Commit ad8eb038e2

ad8eb038e2174783fa236e8812a224e9eb2179fe

parent: 4ebc9dbbc6

Unsigned

Wraient <wraient.911@gmail.com> · 2026-07-22 19:49 UTC

Add VimKeys selection mode and inject new config only on upgrade

Optional VimKeys (default false) enables j/k/h/l navigation and / search
in selection menus. Missing config defaults are no longer rewritten into
the user file on every launch; they are appended once when curd_version
changes, preserving existing options and order.

Layout: unified · split

README.md +2 −1
@@ -378,7 +378,8 @@ If the browser reaches the localhost callback page but curd does not continue au
378378| `AnimeNameLanguage` | Enum | `english`, `romaji` | Sets the preferred language for anime names. |
379379| `MpvArgs` | List | all mpv args eg ["--fullscreen=yes", "--mute=yes"] | Add args to mpv player |
380380| `MpvPlaybackStartTimeout` | Integer | `1` to `600` (seconds) | How long to wait for MPV playback to start before trying another provider. Default: `20` |
381| `AddMissingOptions` | Boolean | `true`, `false` | Automatically adds missing configuration options with default values to the config file. |
381| `AddMissingOptions` | Boolean | `true`, `false` | When `true`, missing options are appended to the config file on **curd version upgrades** (not every launch). Defaults still apply in memory always. |
382| `VimKeys` | Boolean | `true`, `false` | When `true`, selection menus use vim motions: `j`/`k`/`h`/`l` (and arrows) to move, `/` or `?` to search. Default: `false` (type-to-filter immediately). |
382383| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. |
383384| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. |
384385| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. |
cmd/curd/main.go +2 −1
@@ -53,7 +53,7 @@ func main() {
5353 fmt.Println("Error applying storage migration:", migrateErr)
5454 return
5555 } else if updated {
56 fmt.Println("Updated provider settings to the current default fallback stack.")
56 fmt.Println("Updated config for this curd version (new options and/or migrations).")
5757 }
5858 internal.SetGlobalConfig(&userCurdConfig)
5959
@@ -77,6 +77,7 @@ func main() {
7777 flag.BoolVar(&userCurdConfig.SaveMpvSpeed, "save-mpv-speed", userCurdConfig.SaveMpvSpeed, "Save MPV speed setting (true/false)")
7878 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)")
7979 flag.StringVar(&userCurdConfig.DiscordClientId, "discord-client-id", userCurdConfig.DiscordClientId, "Discord client ID for Rich Presence")
80 flag.BoolVar(&userCurdConfig.VimKeys, "vim-keys", userCurdConfig.VimKeys, "Enable vim motions in selection menus (j/k/h/l, / search) (true/false)")
8081 continueLast := flag.Bool("c", false, "Continue last episode")
8182 addNewAnime := flag.Bool("new", false, "Add new anime")
8283 rofiSelection := flag.Bool("rofi", false, "Open selection in rofi")
internal/config.go +40 −21
@@ -62,6 +62,7 @@ type CurdConfig struct {
6262 AlternateScreen bool `config:"AlternateScreen"`
6363 DiscordPresence bool `config:"DiscordPresence"`
6464 DiscordClientId string `config:"DiscordClientId"`
65 VimKeys bool `config:"VimKeys"`
6566 Provider string `config:"Provider"`
6667 DisabledProviders string `config:"DisabledProviders"`
6768 ManualProviderSearch bool `config:"ManualProviderSearch"`
@@ -118,6 +119,7 @@ func defaultConfigMap() map[string]string {
118119 "AlternateScreen": "true",
119120 "DiscordPresence": "true",
120121 "DiscordClientId": "1287457464148820089",
122 "VimKeys": "false",
121123 "Provider": "stacked",
122124 "DisabledProviders": "[]",
123125 "ManualProviderSearch": "false",
@@ -131,6 +133,17 @@ func defaultConfigMap() map[string]string {
131133 }
132134}
133135
136// VimKeysEnabled reports whether selection menus should use vim-style motions.
137func VimKeysEnabled(config *CurdConfig) bool {
138 if config != nil {
139 return config.VimKeys
140 }
141 if globalConfig != nil {
142 return globalConfig.VimKeys
143 }
144 return false
145}
146
134147var globalConfig *CurdConfig
135148
136149func SetGlobalConfig(config *CurdConfig) {
@@ -236,44 +249,50 @@ func LoadConfig(configPath string) (CurdConfig, error) {
236249 _, hadTrackingConfigured := configMap["TrackingConfigured"]
237250 legacyConfig := !createdConfig && !hadTrackingRemote && !hadTrackingConfigured
238251
239 // Add missing fields to the config map
240 updated := false
241 defaultConfigMap := defaultConfigMap()
242 for key, defaultValue := range defaultConfigMap {
243 if _, exists := configMap[key]; !exists {
244 configMap[key] = defaultValue
245 updated = true
252 // fileMap = keys actually present on disk (never bulk-fill with all defaults).
253 // workMap = file keys + in-memory defaults for PopulateConfig.
254 fileMap := configMap
255 workMap := make(map[string]string, len(fileMap)+len(defaultConfigMap()))
256 for key, value := range fileMap {
257 workMap[key] = value
258 }
259 for key, defaultValue := range defaultConfigMap() {
260 if _, exists := workMap[key]; !exists {
261 workMap[key] = defaultValue
246262 }
247263 }
264
265 // One-time legacy tracking migration: only touch tracking keys on disk.
266 updated := false
248267 if legacyConfig {
249 configMap["TrackingLocal"] = "true"
250 configMap["TrackingRemote"] = TrackingRemoteAniList
251 configMap["TrackingConfigured"] = "true"
268 fileMap["TrackingLocal"] = "true"
269 fileMap["TrackingRemote"] = TrackingRemoteAniList
270 fileMap["TrackingConfigured"] = "true"
271 workMap["TrackingLocal"] = "true"
272 workMap["TrackingRemote"] = TrackingRemoteAniList
273 workMap["TrackingConfigured"] = "true"
252274 updated = true
253275 }
254276
255 if providerValue, exists := configMap["Provider"]; exists {
277 if providerValue, exists := fileMap["Provider"]; exists {
256278 normalizedProviderValue := canonicalProviderConfigValue(providerValue)
257279 if normalizedProviderValue != providerValue {
258 configMap["Provider"] = normalizedProviderValue
280 fileMap["Provider"] = normalizedProviderValue
281 workMap["Provider"] = normalizedProviderValue
259282 updated = true
260283 }
261284 }
262285
263 // Write updated config back to file only if AddMissingOptions is true
286 // Persist only real migrations (legacy tracking / provider normalize) — not every
287 // missing default. New defaults are appended once in MigrateOnVersionUpgrade.
264288 if addMissing && updated {
265 if err := SaveConfigToFile(configPath, configMap); err != nil {
289 if err := SaveConfigToFile(configPath, fileMap); err != nil {
266290 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
267291 }
268292 }
269293
270 // Parse string arrays
271 if mpvArgs, exists := configMap["MpvArgs"]; exists {
272 configMap["MpvArgs"] = mpvArgs
273 }
274
275 // Populate the CurdConfig struct from the config map
276 config := PopulateConfig(configMap)
294 // Populate the CurdConfig struct from the complete (in-memory) work map
295 config := PopulateConfig(workMap)
277296 normalizeTrackingConfig(&config)
278297
279298 return config, nil
internal/logic_regression_test.go +72
@@ -121,6 +121,78 @@ func TestSelectionCtrlCSelectsQuit(t *testing.T) {
121121 }
122122}
123123
124func TestVimKeysNormalModeNavigatesWithoutFiltering(t *testing.T) {
125 prev := GetGlobalConfig()
126 SetGlobalConfig(&CurdConfig{VimKeys: true})
127 t.Cleanup(func() { SetGlobalConfig(prev) })
128
129 model := &Model{
130 allOptions: []SelectionOption{
131 {Key: "1", Label: "Alpha"},
132 {Key: "2", Label: "Bravo"},
133 {Key: "3", Label: "Charlie"},
134 },
135 filteredKeys: []SelectionOption{
136 {Key: "1", Label: "Alpha"},
137 {Key: "2", Label: "Bravo"},
138 {Key: "3", Label: "Charlie"},
139 },
140 selected: 0,
141 isHomeMenu: false,
142 }
143
144 // j should move down, not type into filter.
145 updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}})
146 model = updated.(*Model)
147 if model.selected != 1 {
148 t.Fatalf("j should move down, selected=%d", model.selected)
149 }
150 if model.filter != "" {
151 t.Fatalf("j must not enter filter in normal mode, filter=%q", model.filter)
152 }
153
154 // k moves up.
155 updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'k'}})
156 model = updated.(*Model)
157 if model.selected != 0 {
158 t.Fatalf("k should move up, selected=%d", model.selected)
159 }
160
161 // / enters search mode; then typing filters.
162 updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'/'}})
163 model = updated.(*Model)
164 if !model.filterActive {
165 t.Fatal("expected / to enter search mode")
166 }
167 updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'B'}})
168 model = updated.(*Model)
169 if model.filter != "B" {
170 t.Fatalf("expected filter B in search mode, got %q", model.filter)
171 }
172}
173
174func TestLegacyModeStillTypeToFilter(t *testing.T) {
175 prev := GetGlobalConfig()
176 SetGlobalConfig(&CurdConfig{VimKeys: false})
177 t.Cleanup(func() { SetGlobalConfig(prev) })
178
179 model := &Model{
180 allOptions: []SelectionOption{
181 {Key: "1", Label: "Alpha"},
182 {Key: "2", Label: "Bravo"},
183 },
184 filteredKeys: []SelectionOption{
185 {Key: "1", Label: "Alpha"},
186 {Key: "2", Label: "Bravo"},
187 },
188 }
189 updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}})
190 model = updated.(*Model)
191 if model.filter != "j" {
192 t.Fatalf("legacy mode should type-to-filter, got filter=%q", model.filter)
193 }
194}
195
124196func TestSelectionEnterWithNoMatchesDoesNotPanic(t *testing.T) {
125197 model := &Model{filteredKeys: nil, selected: 0}
126198 updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
internal/provider_migrate.go +104 −12
@@ -4,6 +4,7 @@ import (
44 "fmt"
55 "os"
66 "path/filepath"
7 "sort"
78 "strings"
89)
910
@@ -105,7 +106,58 @@ func writeStoredCurdVersion(storagePath, version string) error {
105106 return os.WriteFile(storageVersionFilePath(storagePath), []byte(version+"\n"), 0644)
106107}
107108
109// injectMissingConfigDefaults adds any defaultConfigMap keys that are absent from
110// configMap. Returns the sorted list of newly injected keys.
111func injectMissingConfigDefaults(configMap map[string]string) []string {
112 if configMap == nil {
113 return nil
114 }
115 defaults := defaultConfigMap()
116 keys := make([]string, 0, len(defaults))
117 for key := range defaults {
118 keys = append(keys, key)
119 }
120 sort.Strings(keys)
121
122 added := make([]string, 0)
123 for _, key := range keys {
124 if _, exists := configMap[key]; exists {
125 continue
126 }
127 configMap[key] = defaults[key]
128 added = append(added, key)
129 }
130 return added
131}
132
133// appendConfigKeys appends only the given keys to the config file so existing
134// user options and ordering are left untouched.
135func appendConfigKeys(configPath string, configMap map[string]string, keys []string) error {
136 if strings.TrimSpace(configPath) == "" || len(keys) == 0 {
137 return nil
138 }
139 file, err := os.OpenFile(configPath, os.O_APPEND|os.O_WRONLY, 0644)
140 if err != nil {
141 return err
142 }
143 defer file.Close()
144
145 for _, key := range keys {
146 value, ok := configMap[key]
147 if !ok {
148 continue
149 }
150 if _, err := fmt.Fprintf(file, "%s=%s\n", key, value); err != nil {
151 return err
152 }
153 }
154 return nil
155}
156
108157// MigrateOnVersionUpgrade updates stored state and config when curd is upgraded.
158// On version change it injects any new default config options (append-only) and
159// runs provider migrations. Same-version launches do not rewrite the config file
160// just to fill defaults — that avoids churning user config every start.
109161// Returns whether the config file was updated.
110162func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion string) (bool, error) {
111163 if config == nil {
@@ -125,7 +177,48 @@ func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion s
125177 storedVersion := readStoredCurdVersion(storagePath)
126178 configUpdated := false
127179
128 if storedVersion != appVersion {
180 if storedVersion != appVersion && strings.TrimSpace(configPath) != "" {
181 configMap, err := LoadConfigFromFile(configPath)
182 if err != nil {
183 return false, err
184 }
185
186 // Respect AddMissingOptions=false as a hard opt-out of writing new keys.
187 addMissing := true
188 if config != nil {
189 addMissing = config.AddMissingOptions
190 }
191 if val, exists := configMap["AddMissingOptions"]; exists {
192 if parsed, parseErr := parseConfigBool(val); parseErr == nil {
193 addMissing = parsed
194 }
195 }
196
197 if addMissing {
198 if added := injectMissingConfigDefaults(configMap); len(added) > 0 {
199 if err := appendConfigKeys(configPath, configMap, added); err != nil {
200 return false, fmt.Errorf("append new config options: %w", err)
201 }
202 configUpdated = true
203 Log(fmt.Sprintf("Injected new config options on upgrade to %s: %s", appVersion, strings.Join(added, ", ")))
204 }
205 }
206
207 if nextProvider, changed := migrateProviderConfig(configMap["Provider"]); changed {
208 configMap["Provider"] = nextProvider
209 // Provider value already exists in the file — rewrite the full map once.
210 if err := SaveConfigToFile(configPath, configMap); err != nil {
211 return configUpdated, err
212 }
213 configUpdated = true
214 }
215
216 // Refresh in-memory config so new keys (e.g. VimKeys) apply immediately.
217 next := PopulateConfig(configMap)
218 normalizeTrackingConfig(&next)
219 *config = next
220 } else if storedVersion != appVersion {
221 // No config path, still run in-memory provider migration.
129222 if nextProvider, changed := migrateProviderConfig(config.Provider); changed {
130223 config.Provider = nextProvider
131224 configUpdated = true
@@ -136,19 +229,18 @@ func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion s
136229 return configUpdated, fmt.Errorf("write curd version file: %w", err)
137230 }
138231
139 if !configUpdated || strings.TrimSpace(configPath) == "" {
140 return configUpdated, nil
141 }
232 return configUpdated, nil
233}
142234
143 configMap, err := LoadConfigFromFile(configPath)
144 if err != nil {
145 return configUpdated, err
146 }
147 configMap["Provider"] = config.Provider
148 if err := SaveConfigToFile(configPath, configMap); err != nil {
149 return configUpdated, err
235func parseConfigBool(value string) (bool, error) {
236 switch strings.ToLower(strings.TrimSpace(value)) {
237 case "true", "1", "yes", "y", "on":
238 return true, nil
239 case "false", "0", "no", "n", "off":
240 return false, nil
241 default:
242 return false, fmt.Errorf("invalid bool %q", value)
150243 }
151 return configUpdated, nil
152244}
153245
154246func providerConfigDisplayLabel(raw string) string {
internal/provider_migrate_test.go +78
@@ -114,6 +114,84 @@ func TestMigrateOnVersionUpgradeWritesVersionAndUpdatesProvider(t *testing.T) {
114114 }
115115}
116116
117func TestMigrateOnVersionUpgradeInjectsMissingOptionsOnce(t *testing.T) {
118 tempDir := t.TempDir()
119 configPath := filepath.Join(tempDir, "curd.conf")
120 storagePath := filepath.Join(tempDir, "share")
121 // Minimal pre-upgrade config: no VimKeys, no MpvPlaybackStartTimeout.
122 initial := "StoragePath=" + storagePath + "\n" +
123 "AddMissingOptions=true\n" +
124 "Provider=stacked\n" +
125 "Player=mpv\n"
126 if err := os.WriteFile(configPath, []byte(initial), 0644); err != nil {
127 t.Fatalf("write config: %v", err)
128 }
129
130 config, err := LoadConfig(configPath)
131 if err != nil {
132 t.Fatalf("LoadConfig: %v", err)
133 }
134 // LoadConfig must not rewrite the file just for missing defaults.
135 before, err := os.ReadFile(configPath)
136 if err != nil {
137 t.Fatalf("read config: %v", err)
138 }
139 if strings.Contains(string(before), "VimKeys=") {
140 t.Fatalf("LoadConfig should not inject VimKeys into the file every start:\n%s", before)
141 }
142 // In-memory default still applies.
143 if config.VimKeys {
144 t.Fatal("VimKeys default should be false in memory")
145 }
146
147 updated, err := MigrateOnVersionUpgrade(configPath, &config, "2.0.3")
148 if err != nil {
149 t.Fatalf("MigrateOnVersionUpgrade: %v", err)
150 }
151 if !updated {
152 t.Fatal("expected config file to gain new options on version upgrade")
153 }
154
155 after, err := os.ReadFile(configPath)
156 if err != nil {
157 t.Fatalf("read config after migrate: %v", err)
158 }
159 text := string(after)
160 if !strings.Contains(text, "VimKeys=false") {
161 t.Fatalf("expected VimKeys=false appended on upgrade:\n%s", text)
162 }
163 if !strings.Contains(text, "MpvPlaybackStartTimeout=20") {
164 t.Fatalf("expected MpvPlaybackStartTimeout appended on upgrade:\n%s", text)
165 }
166 // Original keys preserved at the top (append-only for new keys).
167 if !strings.HasPrefix(strings.TrimSpace(text), "StoragePath=") && !strings.Contains(text, "StoragePath="+storagePath) {
168 t.Fatalf("original StoragePath should remain:\n%s", text)
169 }
170
171 // Same version: no further rewrite.
172 updated, err = MigrateOnVersionUpgrade(configPath, &config, "2.0.3")
173 if err != nil {
174 t.Fatalf("second migrate: %v", err)
175 }
176 if updated {
177 t.Fatal("same version must not re-inject options")
178 }
179}
180
181func TestInjectMissingConfigDefaultsIdempotent(t *testing.T) {
182 m := map[string]string{"Player": "mpv"}
183 added := injectMissingConfigDefaults(m)
184 if len(added) == 0 {
185 t.Fatal("expected missing keys to be injected")
186 }
187 if _, ok := m["VimKeys"]; !ok {
188 t.Fatal("expected VimKeys default")
189 }
190 if second := injectMissingConfigDefaults(m); len(second) != 0 {
191 t.Fatalf("second inject should be empty, got %v", second)
192 }
193}
194
117195func TestConfiguredProviderNamesUsesStackedByDefault(t *testing.T) {
118196 withAllProvidersEnabledForTest(t)
119197 got := ConfiguredProviderNames(&CurdConfig{})
internal/selection_menu.go +124 −46
@@ -21,6 +21,7 @@ import (
2121// Model represents the application state for the selection prompt
2222type Model struct {
2323 filter string
24 filterActive bool // when VimKeys is on: true after "/" enters search mode
2425 filteredKeys []SelectionOption
2526 allOptions []SelectionOption
2627 selected int
@@ -83,6 +84,45 @@ func (m Model) Init() tea.Cmd {
8384 return nil
8485}
8586
87func (m *Model) moveSelectionDown() {
88 if m.selected < len(m.filteredKeys)-1 {
89 m.selected++
90 }
91 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
92 m.scrollOffset++
93 }
94}
95
96func (m *Model) moveSelectionUp() {
97 if m.selected > 0 {
98 m.selected--
99 }
100 if m.selected < m.scrollOffset {
101 m.scrollOffset--
102 }
103}
104
105func (m *Model) confirmSelection() tea.Cmd {
106 if len(m.filteredKeys) == 0 {
107 return nil
108 }
109 if m.filteredKeys[m.selected].Key == "add_new" {
110 CurdOut("Adding a new anime...")
111 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
112 }
113 return tea.Quit
114}
115
116func (m *Model) exitMenu() tea.Cmd {
117 if m.isHomeMenu {
118 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
119 } else {
120 m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
121 }
122 m.selected = 0
123 return tea.Quit
124}
125
86126// Update handles user input and updates the model
87127func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
88128 // Handle terminal resize messages
@@ -92,67 +132,90 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
92132 }
93133
94134 updateFilter := false
135 vimKeys := VimKeysEnabled(nil)
95136
96137 switch msg := msg.(type) {
97138 case optionsRefreshedMsg:
98139 m.replaceOptions(msg.options)
99140 return m, nil
100141 case tea.KeyMsg:
101 switch msg.String() {
142 key := msg.String()
143
144 switch key {
102145 case "ctrl+c":
103146 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
104147 m.selected = 0
105148 return m, tea.Quit
106 case "esc":
107 // ESC: quit on home menu, go back on sub-menus
108 if m.isHomeMenu {
109 // Quit
110 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
111 m.selected = 0
112 } else {
113 // Go back
114 m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
115 m.selected = 0
149 }
150
151 // --- Vim-enabled selection: normal mode vs search mode ---
152 if vimKeys {
153 // Search mode: typing filters; j/k/arrows still navigate results.
154 if m.filterActive {
155 switch key {
156 case "esc":
157 // Leave search mode but keep the current filter applied.
158 m.filterActive = false
159 return m, nil
160 case "enter":
161 return m, m.confirmSelection()
162 case "backspace":
163 if len(m.filter) > 0 {
164 m.filter = m.filter[:len(m.filter)-1]
165 updateFilter = true
166 }
167 case "down", "j", "tab", "ctrl+n", "l", "right":
168 m.moveSelectionDown()
169 case "up", "k", "shift+tab", "ctrl+p", "h", "left":
170 m.moveSelectionUp()
171 default:
172 if len(key) == 1 && key >= " " && key <= "~" {
173 m.filter += key
174 updateFilter = true
175 }
176 }
177 break
116178 }
117 return m, tea.Quit
179
180 // Normal mode: motions only; "/" or "?" starts search.
181 switch key {
182 case "/", "?":
183 m.filterActive = true
184 return m, nil
185 case "esc":
186 return m, m.exitMenu()
187 case "enter":
188 return m, m.confirmSelection()
189 case "down", "j", "tab", "ctrl+n", "l", "right":
190 m.moveSelectionDown()
191 case "up", "k", "shift+tab", "ctrl+p", "h", "left":
192 m.moveSelectionUp()
193 case "backspace":
194 // Ignore — filter is only edited in search mode.
195 default:
196 // Do not type into filter in normal mode.
197 }
198 break
199 }
200
201 // --- Legacy behavior: every printable key filters immediately ---
202 switch key {
203 case "esc":
204 return m, m.exitMenu()
118205 case "backspace":
119206 if len(m.filter) > 0 {
120207 m.filter = m.filter[:len(m.filter)-1]
121208 updateFilter = true
122209 }
123210 case "down", "tab", "ctrl+n":
124 // Move the selection cursor down
125 if m.selected < len(m.filteredKeys)-1 {
126 m.selected++
127 }
128
129 // Scroll the view if necessary
130 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
131 m.scrollOffset++
132 }
211 m.moveSelectionDown()
133212 case "up", "shift+tab", "ctrl+p":
134 // Move the selection cursor up
135 if m.selected > 0 {
136 m.selected--
137 }
138
139 // Scroll the view if necessary
140 if m.selected < m.scrollOffset {
141 m.scrollOffset--
142 }
213 m.moveSelectionUp()
143214 case "enter":
144 if len(m.filteredKeys) == 0 {
145 return m, nil
146 }
147 if m.filteredKeys[m.selected].Key == "add_new" {
148 CurdOut("Adding a new anime...")
149 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
150 return m, tea.Quit
151 }
152 return m, tea.Quit
215 return m, m.confirmSelection()
153216 default:
154 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
155 m.filter += msg.String()
217 if len(key) == 1 && key >= " " && key <= "~" {
218 m.filter += key
156219 updateFilter = true
157220 }
158221 }
@@ -214,11 +277,26 @@ func (m Model) View() string {
214277 var b strings.Builder
215278
216279 // Display the search prompt and filter with colors
217 b.WriteString(titleStyle.Render("Search") + " (Press " +
218 quitHintStyle.Render("Ctrl+C") + " to quit):\n")
219
220 b.WriteString(filterLabelStyle.Render("Filter: ") +
221 filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing
280 if VimKeysEnabled(nil) {
281 if m.filterActive {
282 b.WriteString(titleStyle.Render("Search") + " (Esc: leave search · Enter: select · j/k: move):\n")
283 b.WriteString(filterLabelStyle.Render("Filter: ") +
284 filterTextStyle.Render(m.filter+"▌") + "\n\n")
285 } else {
286 b.WriteString(titleStyle.Render("Select") + " (j/k/h/l · / search · Enter · Esc):\n")
287 if m.filter != "" {
288 b.WriteString(filterLabelStyle.Render("Filter: ") +
289 filterTextStyle.Render(m.filter) + "\n\n")
290 } else {
291 b.WriteString(quitHintStyle.Render("Press / to search") + "\n\n")
292 }
293 }
294 } else {
295 b.WriteString(titleStyle.Render("Search") + " (Press " +
296 quitHintStyle.Render("Ctrl+C") + " to quit):\n")
297 b.WriteString(filterLabelStyle.Render("Filter: ") +
298 filterTextStyle.Render(m.filter) + "\n\n")
299 }
222300
223301 if len(m.filteredKeys) == 0 {
224302 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")