Files
default-creds-tui/ui/search.go
T
Hadi 624a723b16 init
Signed-off-by: Hadi <[email protected]>
2026-08-27 00:05:08 +02:00

88 lines
2.0 KiB
Go

package ui
import (
"strings"
"time"
"charm.land/bubbles/v2/key"
tea "charm.land/bubbletea/v2"
"github.com/anotherhadi/ilovetui/app"
"github.com/anotherhadi/default-creds-tui/internal/config"
"github.com/anotherhadi/default-creds-tui/internal/creds"
)
const onlineDebounce = 300 * time.Millisecond
var (
downKey = key.NewBinding(key.WithKeys("down", "tab"))
enterKey = key.NewBinding(key.WithKeys("enter"))
ctrlCKey = key.NewBinding(key.WithKeys("ctrl+c"))
)
func (m Model) updateSearch(msg tea.KeyPressMsg) (Model, tea.Cmd) {
gk := config.Global.Keybindings.Global
sk := config.Global.Keybindings.Search
switch {
case key.Matches(msg, ctrlCKey):
return m, app.Quit()
case key.Matches(msg, gk.Escape):
return m.exitSearch()
case key.Matches(msg, downKey), key.Matches(msg, enterKey):
if len(m.list.Items()) > 0 {
return m.exitSearch()
}
case key.Matches(msg, sk.Clear):
m.searchInput.Reset()
return m.applyQuery("")
}
prev := m.searchInput.Value()
var cmd tea.Cmd
m.searchInput, cmd = m.searchInput.Update(msg)
if m.searchInput.Value() == prev {
return m, cmd
}
next, queryCmd := m.applyQuery(m.searchInput.Value())
return next, tea.Batch(cmd, queryCmd)
}
func (m Model) exitSearch() (Model, tea.Cmd) {
m.searching = false
m.searchInput.Blur()
return m, nil
}
func (m Model) applyQuery(query string) (Model, tea.Cmd) {
m.query = query
m.searchGen++
if strings.TrimSpace(query) == "" {
m.loading = false
cmd := m.setEntries(nil)
return m, cmd
}
if m.mode == modeLocal {
cmd := m.runSearch()
return m, cmd
}
m.loading = true
gen := m.searchGen
return m, tea.Tick(onlineDebounce, func(time.Time) tea.Msg {
return searchTickMsg{gen: gen}
})
}
func (m *Model) runSearch() tea.Cmd {
if strings.TrimSpace(m.query) == "" {
return m.setEntries(nil)
}
if m.mode != modeLocal {
return fetchOnlineCmd(m.apiURL, m.query, m.searchGen)
}
matches := creds.Filter(m.allLocal, m.query)
m.totalResults = len(matches)
return m.setEntries(matches)
}