Extract function wrapMessageToWidth

This steals even more code from `gocui.lineWrap`.

We'll make use of this in the next commit.
This commit is contained in:
Stefan Haller 2024-06-11 17:23:42 +02:00
parent 6f8244e3fe
commit dbc21af3b1

View file

@ -63,15 +63,20 @@ func (self *ConfirmationHelper) DeactivateConfirmationPrompt() {
// Temporary hack: we're just duplicating the logic in `gocui.lineWrap` // Temporary hack: we're just duplicating the logic in `gocui.lineWrap`
func getMessageHeight(wrap bool, message string, width int) int { func getMessageHeight(wrap bool, message string, width int) int {
return len(wrapMessageToWidth(wrap, message, width))
}
func wrapMessageToWidth(wrap bool, message string, width int) []string {
lines := strings.Split(message, "\n")
if !wrap { if !wrap {
return len(strings.Split(message, "\n")) return lines
} }
lineCount := 0 wrappedLines := make([]string, 0, len(lines))
lines := strings.Split(message, "\n")
for _, line := range lines { for _, line := range lines {
n := 0 n := 0
offset := 0
lastWhitespaceIndex := -1 lastWhitespaceIndex := -1
for i, currChr := range line { for i, currChr := range line {
rw := runewidth.RuneWidth(currChr) rw := runewidth.RuneWidth(currChr)
@ -79,28 +84,38 @@ func getMessageHeight(wrap bool, message string, width int) int {
if n > width { if n > width {
if currChr == ' ' { if currChr == ' ' {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i + 1
n = 0 n = 0
} else if currChr == '-' { } else if currChr == '-' {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i
n = rw n = rw
} else if lastWhitespaceIndex != -1 && lastWhitespaceIndex+1 != i { } else if lastWhitespaceIndex != -1 && lastWhitespaceIndex+1 != i {
if line[lastWhitespaceIndex] == '-' { if line[lastWhitespaceIndex] == '-' {
wrappedLines = append(wrappedLines, line[offset:lastWhitespaceIndex+1])
offset = lastWhitespaceIndex + 1
n = i - lastWhitespaceIndex n = i - lastWhitespaceIndex
} else { } else {
wrappedLines = append(wrappedLines, line[offset:lastWhitespaceIndex])
offset = lastWhitespaceIndex + 1
n = i - lastWhitespaceIndex + 1 n = i - lastWhitespaceIndex + 1
} }
} else { } else {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i
n = rw n = rw
} }
lineCount++
lastWhitespaceIndex = -1 lastWhitespaceIndex = -1
} else if currChr == ' ' || currChr == '-' { } else if currChr == ' ' || currChr == '-' {
lastWhitespaceIndex = i lastWhitespaceIndex = i
} }
} }
lineCount++
wrappedLines = append(wrappedLines, line[offset:])
} }
return lineCount return wrappedLines
} }
func (self *ConfirmationHelper) getPopupPanelDimensions(wrap bool, prompt string) (int, int, int, int) { func (self *ConfirmationHelper) getPopupPanelDimensions(wrap bool, prompt string) (int, int, int, int) {