From 47b8d9c6a8d67b745a17199b0be3b8168addfc1a Mon Sep 17 00:00:00 2001 From: Christian Rocha Date: Wed, 18 Nov 2020 18:17:27 -0500 Subject: [PATCH] Doc comments, optimizations, and magic number removal --- progress/example/main.go | 5 +++-- progress/progress.go | 15 +++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/progress/example/main.go b/progress/example/main.go index 336880c..6cd6b60 100644 --- a/progress/example/main.go +++ b/progress/example/main.go @@ -11,7 +11,8 @@ import ( ) const ( - stepSize float64 = 1.0 / (60.0 * 2.0) + fps = 60 + stepSize float64 = 1.0 / (float64(fps) * 2.0) padding = 2 maxWidth = 80 ) @@ -75,7 +76,7 @@ func (e example) View() string { } func tickCmd() tea.Cmd { - return tea.Tick(time.Second/60, func(t time.Time) tea.Msg { + return tea.Tick(time.Second/fps, func(t time.Time) tea.Msg { return tickMsg(t) }) } diff --git a/progress/progress.go b/progress/progress.go index e0da642..9b3c3fd 100644 --- a/progress/progress.go +++ b/progress/progress.go @@ -60,6 +60,7 @@ func WithoutPercentage() Option { } } +// Model stores values we'll use when rendering the progress bar. type Model struct { // Total width of the progress bar, including percentage, if set. @@ -106,18 +107,22 @@ func NewModel(opts ...Option) *Model { return m } +// view renders the progress bar as a given percentage. func (m Model) View(percent float64) string { + b := strings.Builder{} if m.ShowPercentage { s := fmt.Sprintf(m.PercentFormat, percent*100) w := ansi.PrintableRuneWidth(s) - return m.bar(percent, w) + s + m.bar(&b, percent, w) + b.WriteString(s) + } else { + m.bar(&b, percent, 0) } - return m.bar(percent, 0) + return b.String() } -func (m Model) bar(percent float64, textWidth int) string { +func (m Model) bar(b *strings.Builder, percent float64, textWidth int) { var ( - b = strings.Builder{} tw = m.Width - textWidth // total width fw = int(float64(tw) * percent) // filled width p float64 @@ -147,8 +152,6 @@ func (m Model) bar(percent float64, textWidth int) string { // Empty fill e := termenv.String(string(m.Empty)).Foreground(color(m.EmptyColor)).String() b.WriteString(strings.Repeat(e, tw-fw)) - - return b.String() } func (m *Model) setRamp(colorA, colorB string, scaled bool) {