filter.go
This file
Path
filter/filter.go
563 lines · 14.7 KiB · Go
Last changed by
chore: update to bubbletea v2 (#1112)Drew Smirnoffbefore adoptionf6dd28e
History of this fileTake it
1// Package filter provides a fuzzy searching text input to allow filtering a2// list of options to select one option.3//4// By default it will list all the files (recursively) in the current directory5// for the user to choose one, but the script (or user) can provide different6// new-line separated options to choose from.7//8// I.e. let's pick from a list of gum flavors:9//10// $ cat flavors.text | gum filter11package filter1213import (14 "strings"1516 "charm.land/bubbles/v2/help"17 "charm.land/bubbles/v2/key"18 "charm.land/bubbles/v2/textinput"19 "charm.land/bubbles/v2/viewport"20 tea "charm.land/bubbletea/v2"21 "charm.land/lipgloss/v2"22 "github.com/charmbracelet/x/exp/ordered"23 "github.com/rivo/uniseg"24 "github.com/sahilm/fuzzy"25)2627func defaultKeymap() keymap {28 return keymap{29 Down: key.NewBinding(30 key.WithKeys("down", "ctrl+j", "ctrl+n"),31 ),32 Up: key.NewBinding(33 key.WithKeys("up", "ctrl+k", "ctrl+p"),34 ),35 NDown: key.NewBinding(36 key.WithKeys("j"),37 ),38 NUp: key.NewBinding(39 key.WithKeys("k"),40 ),41 Home: key.NewBinding(42 key.WithKeys("g", "home"),43 ),44 End: key.NewBinding(45 key.WithKeys("G", "end"),46 ),47 ToggleAndNext: key.NewBinding(48 key.WithKeys("tab"),49 key.WithHelp("tab", "toggle"),50 key.WithDisabled(),51 ),52 ToggleAndPrevious: key.NewBinding(53 key.WithKeys("shift+tab"),54 key.WithHelp("shift+tab", "toggle"),55 key.WithDisabled(),56 ),57 Toggle: key.NewBinding(58 key.WithKeys("ctrl+@"),59 key.WithHelp("ctrl+@", "toggle"),60 key.WithDisabled(),61 ),62 ToggleAll: key.NewBinding(63 key.WithKeys("ctrl+a"),64 key.WithHelp("ctrl+a", "select all"),65 key.WithDisabled(),66 ),67 FocusInSearch: key.NewBinding(68 key.WithKeys("/"),69 key.WithHelp("/", "search"),70 ),71 FocusOutSearch: key.NewBinding(72 key.WithKeys("esc"),73 key.WithHelp("esc", "blur search"),74 ),75 Quit: key.NewBinding(76 key.WithKeys("esc"),77 key.WithHelp("esc", "quit"),78 ),79 Abort: key.NewBinding(80 key.WithKeys("ctrl+c"),81 key.WithHelp("ctrl+c", "abort"),82 ),83 Submit: key.NewBinding(84 key.WithKeys("enter", "ctrl+q"),85 key.WithHelp("enter", "submit"),86 ),87 }88}8990type keymap struct {91 FocusInSearch,92 FocusOutSearch,93 Down,94 Up,95 NDown,96 NUp,97 Home,98 End,99 ToggleAndNext,100 ToggleAndPrevious,101 ToggleAll,102 Toggle,103 Abort,104 Quit,105 Submit key.Binding106}107108// FullHelp implements help.KeyMap.109func (k keymap) FullHelp() [][]key.Binding { return nil }110111// ShortHelp implements help.KeyMap.112func (k keymap) ShortHelp() []key.Binding {113 return []key.Binding{114 key.NewBinding(115 key.WithKeys("up", "down"),116 key.WithHelp("↓↑", "navigate"),117 ),118 k.FocusInSearch,119 k.FocusOutSearch,120 k.ToggleAndNext,121 k.ToggleAll,122 k.Submit,123 }124}125126type model struct {127 textinput textinput.Model128 viewport *viewport.Model129 choices map[string]string130 filteringChoices []string131 matches []fuzzy.Match132 cursor int133 header string134 selected map[string]struct{}135 limit int136 numSelected int137 indicator string138 selectedPrefix string139 unselectedPrefix string140 height int141 padding []int142 quitting bool143 headerStyle lipgloss.Style144 matchStyle lipgloss.Style145 textStyle lipgloss.Style146 cursorTextStyle lipgloss.Style147 indicatorStyle lipgloss.Style148 selectedPrefixStyle lipgloss.Style149 unselectedPrefixStyle lipgloss.Style150 reverse bool151 fuzzy bool152 sort bool153 showHelp bool154 keymap keymap155 help help.Model156 strict bool157 submitted bool158}159160func (m model) Init() tea.Cmd { return textinput.Blink }161162func (m model) View() tea.View {163 if m.quitting {164 return tea.NewView("")165 }166167 var s strings.Builder168 var lineTextStyle lipgloss.Style169170 // For reverse layout, if the number of matches is less than the viewport171 // height, we need to offset the matches so that the first match is at the172 // bottom edge of the viewport instead of in the middle.173 if m.reverse && len(m.matches) < m.viewport.Height() {174 s.WriteString(strings.Repeat("\n", m.viewport.Height()-len(m.matches)))175 }176177 // Since there are matches, display them so that the user can see, in real178 // time, what they are searching for.179 last := len(m.matches) - 1180 for i := range m.matches {181 // For reverse layout, the matches are displayed in reverse order.182 if m.reverse {183 i = last - i184 }185 match := m.matches[i]186187 // If this is the current selected index, we add a small indicator to188 // represent it. Otherwise, simply pad the string.189 // The line's text style is set depending on whether or not the cursor190 // points to this line.191 if i == m.cursor {192 s.WriteString(m.indicatorStyle.Render(m.indicator))193 lineTextStyle = m.cursorTextStyle194 } else {195 s.WriteString(strings.Repeat(" ", lipgloss.Width(m.indicator)))196 lineTextStyle = m.textStyle197 }198199 // If there are multiple selections mark them, otherwise leave an empty space200 if _, ok := m.selected[match.Str]; ok {201 s.WriteString(m.selectedPrefixStyle.Render(m.selectedPrefix))202 } else if m.limit > 1 {203 s.WriteString(m.unselectedPrefixStyle.Render(m.unselectedPrefix))204 } else {205 s.WriteString(" ")206 }207208 styledOption := m.choices[match.Str]209 if len(match.MatchedIndexes) == 0 {210 // No matches, just render the text.211 s.WriteString(lineTextStyle.Render(styledOption))212 s.WriteRune('\n')213 continue214 }215216 var ranges []lipgloss.Range217 for _, rng := range matchedRanges(match.MatchedIndexes) {218 // ansi.Cut is grapheme and ansi sequence aware, we match against a ansi.Stripped string, but we might still have graphemes.219 // all that to say that rng is byte positions, but we need to pass it down to ansi.Cut as char positions.220 // so we need to adjust it here:221 start, stop := bytePosToVisibleCharPos(match.Str, rng)222 ranges = append(ranges, lipgloss.NewRange(start, stop+1, m.matchStyle))223 }224225 s.WriteString(lineTextStyle.Render(lipgloss.StyleRanges(styledOption, ranges...)))226227 // We have finished displaying the match with all of its matched228 // characters highlighted and the rest filled in.229 // Move on to the next match.230 s.WriteRune('\n')231 }232233 m.viewport.SetContent(s.String())234235 // View the input and the filtered choices236 header := m.headerStyle.Render(m.header)237 var content string238 if m.reverse {239 content = m.reverseView(header)240 } else {241 content = m.normalView(header)242 }243 v := tea.NewView(content)244 v.ReportFocus = true245 if m.height == 0 {246 v.AltScreen = true247 }248 return v249}250251func (m model) reverseView(header string) string {252 view := m.viewport.View()253 if m.header != "" {254 view += "\n" + header255 }256 view += "\n" + m.textinput.View()257 if m.showHelp {258 view += m.helpView()259 }260 return lipgloss.NewStyle().261 Padding(m.padding...).262 Render(view)263}264265func (m model) normalView(header string) string {266 view := m.textinput.View() + "\n" + m.viewport.View()267 if m.showHelp {268 view += m.helpView()269 }270 if m.header != "" {271 return lipgloss.NewStyle().272 Padding(m.padding...).273 Render(header + "\n" + view)274 }275 return lipgloss.NewStyle().276 Padding(m.padding...).277 Render(view)278}279280func (m model) helpView() string {281 return "\n\n" + m.help.View(m.keymap)282}283284func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {285 var cmd, icmd tea.Cmd286 m.textinput, icmd = m.textinput.Update(msg)287 switch msg := msg.(type) {288 case tea.WindowSizeMsg:289 if m.height == 0 || m.height > msg.Height {290 m.viewport.SetHeight(msg.Height - lipgloss.Height(m.textinput.View()))291 }292 // Include the header in the height calculation.293 if m.header != "" {294 m.viewport.SetHeight(m.viewport.Height() - lipgloss.Height(m.headerStyle.Render(m.header)))295 }296 // Include the help in the total height calculation.297 if m.showHelp {298 m.viewport.SetHeight(m.viewport.Height() - lipgloss.Height(m.helpView()))299 }300 m.viewport.SetHeight(m.viewport.Height() - m.padding[0] - m.padding[2])301 m.viewport.SetWidth(msg.Width - m.padding[1] - m.padding[3])302 m.textinput.SetWidth(msg.Width - m.padding[1] - m.padding[3])303 if m.reverse {304 m.viewport.SetYOffset(ordered.Clamp(len(m.matches)-m.viewport.Height(), 0, len(m.matches)))305 }306 case tea.KeyPressMsg:307 km := m.keymap308 switch {309 case key.Matches(msg, km.FocusInSearch):310 m.textinput.Focus()311 case key.Matches(msg, km.FocusOutSearch):312 m.textinput.Blur()313 case key.Matches(msg, km.Quit):314 m.quitting = true315 return m, tea.Quit316 case key.Matches(msg, km.Abort):317 m.quitting = true318 return m, tea.Interrupt319 case key.Matches(msg, km.Submit):320 m.quitting = true321 m.submitted = true322 return m, tea.Quit323 case key.Matches(msg, km.Down, km.NDown):324 m.CursorDown()325 case key.Matches(msg, km.Up, km.NUp):326 m.CursorUp()327 case key.Matches(msg, km.Home):328 m.cursor = 0329 m.viewport.GotoTop()330 case key.Matches(msg, km.End):331 m.cursor = len(m.choices) - 1332 m.viewport.GotoBottom()333 case key.Matches(msg, km.ToggleAndNext):334 if m.limit == 1 {335 break // no op336 }337 m.ToggleSelection()338 m.CursorDown()339 case key.Matches(msg, km.ToggleAndPrevious):340 if m.limit == 1 {341 break // no op342 }343 m.ToggleSelection()344 m.CursorUp()345 case key.Matches(msg, km.Toggle):346 if m.limit == 1 {347 break // no op348 }349 m.ToggleSelection()350 case key.Matches(msg, km.ToggleAll):351 if m.limit <= 1 {352 break353 }354 if m.numSelected < len(m.matches) && m.numSelected < m.limit {355 m = m.selectAll()356 } else {357 m = m.deselectAll()358 }359 default:360 // yOffsetFromBottom is the number of lines from the bottom of the361 // list to the top of the viewport. This is used to keep the viewport362 // at a constant position when the number of matches are reduced363 // in the reverse layout.364 var yOffsetFromBottom int365 if m.reverse {366 yOffsetFromBottom = max(0, len(m.matches)-m.viewport.YOffset())367 }368369 // A character was entered, this likely means that the text input has370 // changed. This suggests that the matches are outdated, so update them.371 var choices []string372 if !m.strict {373 choices = append(choices, m.textinput.Value())374 }375 choices = append(choices, m.filteringChoices...)376 if m.fuzzy {377 if m.sort {378 m.matches = fuzzy.Find(m.textinput.Value(), choices)379 } else {380 m.matches = fuzzy.FindNoSort(m.textinput.Value(), choices)381 }382 } else {383 m.matches = exactMatches(m.textinput.Value(), choices)384 }385386 // If the search field is empty, let's not display the matches387 // (none), but rather display all possible choices.388 if m.textinput.Value() == "" {389 m.matches = matchAll(m.filteringChoices)390 }391392 // For reverse layout, we need to offset the viewport so that the393 // it remains at a constant position relative to the cursor.394 if m.reverse {395 maxYOffset := max(0, len(m.matches)-m.viewport.Height())396 m.viewport.SetYOffset(ordered.Clamp(len(m.matches)-yOffsetFromBottom, 0, maxYOffset))397 }398 }399 }400401 m.keymap.FocusInSearch.SetEnabled(!m.textinput.Focused())402 m.keymap.FocusOutSearch.SetEnabled(m.textinput.Focused())403 m.keymap.NUp.SetEnabled(!m.textinput.Focused())404 m.keymap.NDown.SetEnabled(!m.textinput.Focused())405 m.keymap.Home.SetEnabled(!m.textinput.Focused())406 m.keymap.End.SetEnabled(!m.textinput.Focused())407408 // It's possible that filtering items have caused fewer matches. So, ensure409 // that the selected index is within the bounds of the number of matches.410 m.cursor = ordered.Clamp(m.cursor, 0, len(m.matches)-1)411 return m, tea.Batch(cmd, icmd)412}413414func (m *model) CursorUp() {415 if len(m.matches) == 0 {416 return417 }418 if m.reverse { //nolint:nestif419 m.cursor = (m.cursor + 1) % len(m.matches)420 if len(m.matches)-m.cursor <= m.viewport.YOffset() {421 m.viewport.ScrollUp(1)422 }423 if len(m.matches)-m.cursor > m.viewport.Height()+m.viewport.YOffset() {424 m.viewport.SetYOffset(len(m.matches) - m.viewport.Height())425 }426 } else {427 m.cursor = (m.cursor - 1 + len(m.matches)) % len(m.matches)428 if m.cursor < m.viewport.YOffset() {429 m.viewport.ScrollUp(1)430 }431 if m.cursor >= m.viewport.YOffset()+m.viewport.Height() {432 m.viewport.SetYOffset(len(m.matches) - m.viewport.Height())433 }434 }435}436437func (m *model) CursorDown() {438 if len(m.matches) == 0 {439 return440 }441 if m.reverse { //nolint:nestif442 m.cursor = (m.cursor - 1 + len(m.matches)) % len(m.matches)443 if len(m.matches)-m.cursor > m.viewport.Height()+m.viewport.YOffset() {444 m.viewport.ScrollDown(1)445 }446 if len(m.matches)-m.cursor <= m.viewport.YOffset() {447 m.viewport.GotoTop()448 }449 } else {450 m.cursor = (m.cursor + 1) % len(m.matches)451 if m.cursor >= m.viewport.YOffset()+m.viewport.Height() {452 m.viewport.ScrollDown(1)453 }454 if m.cursor < m.viewport.YOffset() {455 m.viewport.GotoTop()456 }457 }458}459460func (m *model) ToggleSelection() {461 if _, ok := m.selected[m.matches[m.cursor].Str]; ok {462 delete(m.selected, m.matches[m.cursor].Str)463 m.numSelected--464 } else if m.numSelected < m.limit {465 m.selected[m.matches[m.cursor].Str] = struct{}{}466 m.numSelected++467 }468}469470func (m model) selectAll() model {471 for i := range m.matches {472 if m.numSelected >= m.limit {473 break // do not exceed given limit474 }475 if _, ok := m.selected[m.matches[i].Str]; ok {476 continue477 }478 m.selected[m.matches[i].Str] = struct{}{}479 m.numSelected++480 }481 return m482}483484func (m model) deselectAll() model {485 m.selected = make(map[string]struct{})486 m.numSelected = 0487 return m488}489490func matchAll(options []string) []fuzzy.Match {491 matches := make([]fuzzy.Match, len(options))492 for i, option := range options {493 matches[i] = fuzzy.Match{Str: option}494 }495 return matches496}497498func exactMatches(search string, choices []string) []fuzzy.Match {499 matches := fuzzy.Matches{}500 for i, choice := range choices {501 search = strings.ToLower(search)502 matchedString := strings.ToLower(choice)503504 index := strings.Index(matchedString, search)505 if index >= 0 {506 matchedIndexes := make([]int, 0, len(search))507 for s := range search {508 matchedIndexes = append(matchedIndexes, index+s)509 }510 matches = append(matches, fuzzy.Match{511 Str: choice,512 Index: i,513 MatchedIndexes: matchedIndexes,514 })515 }516 }517518 return matches519}520521func matchedRanges(in []int) [][2]int {522 if len(in) == 0 {523 return [][2]int{}524 }525 current := [2]int{in[0], in[0]}526 if len(in) == 1 {527 return [][2]int{current}528 }529 var out [][2]int530 for i := 1; i < len(in); i++ {531 if in[i] == current[1]+1 {532 current[1] = in[i]533 } else {534 out = append(out, current)535 current = [2]int{in[i], in[i]}536 }537 }538 out = append(out, current)539 return out540}541542func bytePosToVisibleCharPos(str string, rng [2]int) (int, int) {543 bytePos, byteStart, byteStop := 0, rng[0], rng[1]544 pos, start, stop := 0, 0, 0545 gr := uniseg.NewGraphemes(str)546 for byteStart > bytePos {547 if !gr.Next() {548 break549 }550 bytePos += len(gr.Str())551 pos += max(1, gr.Width())552 }553 start = pos554 for byteStop > bytePos {555 if !gr.Next() {556 break557 }558 bytePos += len(gr.Str())559 pos += max(1, gr.Width())560 }561 stop = pos562 return start, stop563}