feat: use shift+tab to toggle selection and move up (#167)

* feat: use `shift+tab` to toggle selection and move up

* refactor: extract CursorUp, CursorDown, ToggleSelection methods

Co-authored-by: Maas Lalani <maas@lalani.dev>
This commit is contained in:
Dhruv Manilawala 2022-10-02 22:17:41 +05:30 committed by GitHub
parent 9b0f5f015b
commit 5c98432070
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -119,34 +119,21 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.quitting = true m.quitting = true
return m, tea.Quit return m, tea.Quit
case "ctrl+n", "ctrl+j", "down": case "ctrl+n", "ctrl+j", "down":
m.cursor = clamp(0, len(m.matches)-1, m.cursor+1) m.CursorDown()
if m.cursor >= m.viewport.YOffset+m.viewport.Height {
m.viewport.LineDown(1)
}
case "ctrl+p", "ctrl+k", "up": case "ctrl+p", "ctrl+k", "up":
m.cursor = clamp(0, len(m.matches)-1, m.cursor-1) m.CursorUp()
if m.cursor < m.viewport.YOffset {
m.viewport.SetYOffset(m.cursor)
}
case "tab": case "tab":
if m.limit == 1 { if m.limit == 1 {
break // no op break // no op
} }
m.ToggleSelection()
// Tab is used to toggle selection of current item in the list m.CursorDown()
if _, ok := m.selected[m.matches[m.cursor].Str]; ok { case "shift+tab":
delete(m.selected, m.matches[m.cursor].Str) if m.limit == 1 {
m.numSelected-- break // no op
} else if m.numSelected < m.limit {
m.selected[m.matches[m.cursor].Str] = struct{}{}
m.numSelected++
}
// Go down by one line
m.cursor = clamp(0, len(m.matches)-1, m.cursor+1)
if m.cursor >= m.viewport.YOffset+m.viewport.Height {
m.viewport.LineDown(1)
} }
m.ToggleSelection()
m.CursorUp()
default: default:
m.textinput, cmd = m.textinput.Update(msg) m.textinput, cmd = m.textinput.Update(msg)
@ -170,6 +157,30 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, cmd return m, cmd
} }
func (m *model) CursorUp() {
m.cursor = clamp(0, len(m.matches)-1, m.cursor-1)
if m.cursor < m.viewport.YOffset {
m.viewport.SetYOffset(m.cursor)
}
}
func (m *model) CursorDown() {
m.cursor = clamp(0, len(m.matches)-1, m.cursor+1)
if m.cursor >= m.viewport.YOffset+m.viewport.Height {
m.viewport.LineDown(1)
}
}
func (m *model) ToggleSelection() {
if _, ok := m.selected[m.matches[m.cursor].Str]; ok {
delete(m.selected, m.matches[m.cursor].Str)
m.numSelected--
} else if m.numSelected < m.limit {
m.selected[m.matches[m.cursor].Str] = struct{}{}
m.numSelected++
}
}
func matchAll(options []string) []fuzzy.Match { func matchAll(options []string) []fuzzy.Match {
var matches = make([]fuzzy.Match, len(options)) var matches = make([]fuzzy.Match, len(options))
for i, option := range options { for i, option := range options {