Skip to content

Commit

Permalink
feat(filter): ctrl+a to toggle select all (#770)
Browse files Browse the repository at this point in the history
closes #388
  • Loading branch information
caarlos0 authored Dec 12, 2024
1 parent f921ebd commit 74c1079
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions filter/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func (o Options) Run() error {
km.Toggle.SetEnabled(true)
km.ToggleAndPrevious.SetEnabled(true)
km.ToggleAndNext.SetEnabled(true)
km.ToggleAll.SetEnabled(true)
}

p := tea.NewProgram(model{
Expand Down
38 changes: 37 additions & 1 deletion filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ func defaultKeymap() keymap {
key.WithHelp("ctrl+@", "toggle"),
key.WithDisabled(),
),
ToggleAll: key.NewBinding(
key.WithKeys("ctrl+a"),
key.WithHelp("ctrl+a", "select all"),
key.WithDisabled(),
),
Quit: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "quit"),
Expand All @@ -65,6 +70,7 @@ type keymap struct {
Up,
ToggleAndNext,
ToggleAndPrevious,
ToggleAll,
Toggle,
Abort,
Quit,
Expand All @@ -77,11 +83,12 @@ func (k keymap) FullHelp() [][]key.Binding { return nil }
// ShortHelp implements help.KeyMap.
func (k keymap) ShortHelp() []key.Binding {
return []key.Binding{
k.ToggleAndNext,
key.NewBinding(
key.WithKeys("up", "down"),
key.WithHelp("↓↑", "navigate"),
),
k.ToggleAndNext,
k.ToggleAll,
k.Submit,
}
}
Expand Down Expand Up @@ -286,6 +293,15 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
break // no op
}
m.ToggleSelection()
case key.Matches(msg, km.ToggleAll):
if m.limit <= 1 {
break
}
if m.numSelected < len(m.matches) && m.numSelected < m.limit {
m = m.selectAll()
} else {
m = m.deselectAll()
}
default:
// yOffsetFromBottom is the number of lines from the bottom of the
// list to the top of the viewport. This is used to keep the viewport
Expand Down Expand Up @@ -390,6 +406,26 @@ func (m *model) ToggleSelection() {
}
}

func (m model) selectAll() model {
for i := range m.matches {
if m.numSelected >= m.limit {
break // do not exceed given limit
}
if _, ok := m.selected[m.matches[i].Str]; ok {
continue
}
m.selected[m.matches[i].Str] = struct{}{}
m.numSelected++
}
return m
}

func (m model) deselectAll() model {
m.selected = make(map[string]struct{})
m.numSelected = 0
return m
}

func matchAll(options []string) []fuzzy.Match {
matches := make([]fuzzy.Match, len(options))
for i, option := range options {
Expand Down

0 comments on commit 74c1079

Please sign in to comment.