Skip to content

Commit

Permalink
Merge pull request #43 from koki-develop/truncate
Browse files Browse the repository at this point in the history
  • Loading branch information
koki-develop committed Apr 9, 2023
2 parents 3830500 + eeda781 commit 33bb954
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions model.go
Expand Up @@ -35,6 +35,7 @@ type model struct {
matchesStyle lipgloss.Style
cursorLineStyle lipgloss.Style
cursorLineMatchesStyle lipgloss.Style
ellipsisStyle lipgloss.Style

matches Matches
choices []int
Expand Down Expand Up @@ -78,6 +79,7 @@ func newModel(opt *option) *model {
matchesStyle: opt.styles.option.matches,
cursorLineStyle: opt.styles.option.cursorLine,
cursorLineMatchesStyle: lipgloss.NewStyle().Inherit(opt.styles.option.matches).Inherit(opt.styles.option.cursorLine),
ellipsisStyle: lipgloss.NewStyle().Faint(true),

choices: []int{},
// window
Expand Down Expand Up @@ -238,10 +240,54 @@ func (m *model) itemView(match Match, cursorLine bool) string {
_, _ = v.WriteString(stringLinesToSpace(m.findOption.itemPrefixFunc(match.Index)))
}

maxItemWidth := m.windowWidth - lipgloss.Width(v.String())
if maxItemWidth < 1 {
return v.String()
}

runes := []rune(match.Str)
from := 0
to := len(runes)
ellipsis := ".."

// truncate string
itemWidth := lipgloss.Width(match.Str)
if maxItemWidth < itemWidth {
if maxItemWidth <= len(ellipsis)*2 {
ellipsis = "."
}
if maxItemWidth <= len(ellipsis)*2 {
ellipsis = ""
}

if len(match.MatchedIndexes) == 0 {
// truncate end
to = maxItemWidth - len(ellipsis)
} else {
lastMatchedIndex := match.MatchedIndexes[len(match.MatchedIndexes)-1]

if lastMatchedIndex+8+len(ellipsis) < maxItemWidth {
// truncate end
to = maxItemWidth - len(ellipsis)
} else {
v.WriteString(m.ellipsisStyle.Render(ellipsis))

if lastMatchedIndex+1+8+len(ellipsis) < len(runes) {
// truncate both start and end
from = lastMatchedIndex + 1 - maxItemWidth + 8 + len(ellipsis)*2
to = from + maxItemWidth - len(ellipsis)*2
} else {
// truncate start
from = len(runes) - maxItemWidth + len(ellipsis)
}
}
}
}

// write item
for ci, c := range []rune(match.Str) {
for ci, c := range runes[from:to] {
// matches
if intContains(match.MatchedIndexes, ci) {
if intContains(match.MatchedIndexes, ci+from) {
if cursorLine {
_, _ = v.WriteString(m.cursorLineMatchesStyle.Render(string(c)))
} else {
Expand All @@ -254,6 +300,10 @@ func (m *model) itemView(match Match, cursorLine bool) string {
}
}

if to != len(runes) {
v.WriteString(m.ellipsisStyle.Render(ellipsis))
}

return v.String()
}

Expand Down

0 comments on commit 33bb954

Please sign in to comment.