fix: cache line width on setcontent

This commit is contained in:
Carlos Alexandro Becker
2024-12-18 16:05:48 -03:00
parent 4a8cae34fa
commit d7137bb8ce
+16 -14
View File
@@ -62,9 +62,10 @@ type Model struct {
// horizontal step represents the step of indent we add with one move left or right. // horizontal step represents the step of indent we add with one move left or right.
horizontalStep int horizontalStep int
indent int indent int
initialized bool initialized bool
lines []string lines []string
longestLineWidth int
} }
func (m *Model) setInitialValues() { func (m *Model) setInitialValues() {
@@ -113,6 +114,7 @@ func (m Model) ScrollPercent() float64 {
func (m *Model) SetContent(s string) { func (m *Model) SetContent(s string) {
s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings
m.lines = strings.Split(s, "\n") m.lines = strings.Split(s, "\n")
m.longestLineWidth = findLongestLineWidth(m.lines)
if m.YOffset > len(m.lines)-1 { if m.YOffset > len(m.lines)-1 {
m.GotoBottom() m.GotoBottom()
@@ -332,22 +334,12 @@ func (m *Model) MoveLeft() {
// MoveRight moves all lines to set runes right. // MoveRight moves all lines to set runes right.
func (m *Model) MoveRight() { func (m *Model) MoveRight() {
// prevents over scrolling to the right // prevents over scrolling to the right
if m.indent >= m.longestLineWidth()-m.Width { if m.indent >= m.longestLineWidth-m.Width {
return return
} }
m.indent += m.horizontalStep 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. // Resets lines indent to zero.
func (m *Model) ResetIndent() { func (m *Model) ResetIndent() {
m.indent = 0 m.indent = 0
@@ -487,3 +479,13 @@ func max(a, b int) int {
} }
return b return b
} }
func findLongestLineWidth(lines []string) int {
w := 0
for _, l := range lines {
if ww := ansi.StringWidth(l); ww > w {
w = ww
}
}
return w
}