From d7137bb8ce8615bb6d2837b3f17eb2fd38dbd244 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Wed, 18 Dec 2024 16:05:48 -0300 Subject: [PATCH] fix: cache line width on setcontent --- viewport/viewport.go | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/viewport/viewport.go b/viewport/viewport.go index cfa6295..184f1ec 100644 --- a/viewport/viewport.go +++ b/viewport/viewport.go @@ -62,9 +62,10 @@ type Model struct { // horizontal step represents the step of indent we add with one move left or right. horizontalStep int - indent int - initialized bool - lines []string + indent int + initialized bool + lines []string + longestLineWidth int } func (m *Model) setInitialValues() { @@ -113,6 +114,7 @@ func (m Model) ScrollPercent() float64 { func (m *Model) SetContent(s string) { s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings m.lines = strings.Split(s, "\n") + m.longestLineWidth = findLongestLineWidth(m.lines) if m.YOffset > len(m.lines)-1 { m.GotoBottom() @@ -332,22 +334,12 @@ func (m *Model) MoveLeft() { // MoveRight moves all lines to set runes right. func (m *Model) MoveRight() { // prevents over scrolling to the right - if m.indent >= m.longestLineWidth()-m.Width { + if m.indent >= m.longestLineWidth-m.Width { return } m.indent += m.horizontalStep } -func (m Model) longestLineWidth() int { - w := 0 - for _, l := range m.lines { - if ww := ansi.StringWidth(l); ww > w { - w = ww - } - } - return w -} - // Resets lines indent to zero. func (m *Model) ResetIndent() { m.indent = 0 @@ -487,3 +479,13 @@ func max(a, b int) int { } return b } + +func findLongestLineWidth(lines []string) int { + w := 0 + for _, l := range lines { + if ww := ansi.StringWidth(l); ww > w { + w = ww + } + } + return w +}