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
378| `AnimeNameLanguage` | Enum | `english`, `romaji` | Sets the preferred language for anime names. | 378| `AnimeNameLanguage` | Enum | `english`, `romaji` | Sets the preferred language for anime names. |
379| `MpvArgs` | List | all mpv args eg ["--fullscreen=yes", "--mute=yes"] | Add args to mpv player | 379| `MpvArgs` | List | all mpv args eg ["--fullscreen=yes", "--mute=yes"] | Add args to mpv player |
380| `MpvPlaybackStartTimeout` | Integer | `1` to `600` (seconds) | How long to wait for MPV playback to start before trying another provider. Default: `20` | 380| `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). |
382| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. | 383| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. |
383| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. | 384| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. |
384| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. | 385| `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() {
53 fmt.Println("Error applying storage migration:", migrateErr) 53 fmt.Println("Error applying storage migration:", migrateErr)
54 return 54 return
55 } else if updated { 55 } 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).")
57 } 57 }
58 internal.SetGlobalConfig(&userCurdConfig) 58 internal.SetGlobalConfig(&userCurdConfig)
59 59
@@ -77,6 +77,7 @@ func main() {
77 flag.BoolVar(&userCurdConfig.SaveMpvSpeed, "save-mpv-speed", userCurdConfig.SaveMpvSpeed, "Save MPV speed setting (true/false)") 77 flag.BoolVar(&userCurdConfig.SaveMpvSpeed, "save-mpv-speed", userCurdConfig.SaveMpvSpeed, "Save MPV speed setting (true/false)")
78 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)") 78 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)")
79 flag.StringVar(&userCurdConfig.DiscordClientId, "discord-client-id", userCurdConfig.DiscordClientId, "Discord client ID for Rich Presence") 79 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)")
80 continueLast := flag.Bool("c", false, "Continue last episode") 81 continueLast := flag.Bool("c", false, "Continue last episode")
81 addNewAnime := flag.Bool("new", false, "Add new anime") 82 addNewAnime := flag.Bool("new", false, "Add new anime")
82 rofiSelection := flag.Bool("rofi", false, "Open selection in rofi") 83 rofiSelection := flag.Bool("rofi", false, "Open selection in rofi")
internal/config.go +40 −21
@@ -62,6 +62,7 @@ type CurdConfig struct {
62 AlternateScreen bool `config:"AlternateScreen"` 62 AlternateScreen bool `config:"AlternateScreen"`
63 DiscordPresence bool `config:"DiscordPresence"` 63 DiscordPresence bool `config:"DiscordPresence"`
64 DiscordClientId string `config:"DiscordClientId"` 64 DiscordClientId string `config:"DiscordClientId"`
65 VimKeys bool `config:"VimKeys"`
65 Provider string `config:"Provider"` 66 Provider string `config:"Provider"`
66 DisabledProviders string `config:"DisabledProviders"` 67 DisabledProviders string `config:"DisabledProviders"`
67 ManualProviderSearch bool `config:"ManualProviderSearch"` 68 ManualProviderSearch bool `config:"ManualProviderSearch"`
@@ -118,6 +119,7 @@ func defaultConfigMap() map[string]string {
118 "AlternateScreen": "true", 119 "AlternateScreen": "true",
119 "DiscordPresence": "true", 120 "DiscordPresence": "true",
120 "DiscordClientId": "1287457464148820089", 121 "DiscordClientId": "1287457464148820089",
122 "VimKeys": "false",
121 "Provider": "stacked", 123 "Provider": "stacked",
122 "DisabledProviders": "[]", 124 "DisabledProviders": "[]",
123 "ManualProviderSearch": "false", 125 "ManualProviderSearch": "false",
@@ -131,6 +133,17 @@ func defaultConfigMap() map[string]string {
131 } 133 }
132} 134}
133 135
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
134var globalConfig *CurdConfig 147var globalConfig *CurdConfig
135 148
136func SetGlobalConfig(config *CurdConfig) { 149func SetGlobalConfig(config *CurdConfig) {
@@ -236,44 +249,50 @@ func LoadConfig(configPath string) (CurdConfig, error) {
236 _, hadTrackingConfigured := configMap["TrackingConfigured"] 249 _, hadTrackingConfigured := configMap["TrackingConfigured"]
237 legacyConfig := !createdConfig && !hadTrackingRemote && !hadTrackingConfigured 250 legacyConfig := !createdConfig && !hadTrackingRemote && !hadTrackingConfigured
238 251
239 // Add missing fields to the config map 252 // fileMap = keys actually present on disk (never bulk-fill with all defaults).
240 updated := false 253 // workMap = file keys + in-memory defaults for PopulateConfig.
241 defaultConfigMap := defaultConfigMap() 254 fileMap := configMap
242 for key, defaultValue := range defaultConfigMap { 255 workMap := make(map[string]string, len(fileMap)+len(defaultConfigMap()))
243 if _, exists := configMap[key]; !exists { 256 for key, value := range fileMap {
244 configMap[key] = defaultValue 257 workMap[key] = value
245 updated = true 258 }
259 for key, defaultValue := range defaultConfigMap() {
260 if _, exists := workMap[key]; !exists {
261 workMap[key] = defaultValue
246 } 262 }
247 } 263 }
264
265 // One-time legacy tracking migration: only touch tracking keys on disk.
266 updated := false
248 if legacyConfig { 267 if legacyConfig {
249 configMap["TrackingLocal"] = "true" 268 fileMap["TrackingLocal"] = "true"
250 configMap["TrackingRemote"] = TrackingRemoteAniList 269 fileMap["TrackingRemote"] = TrackingRemoteAniList
251 configMap["TrackingConfigured"] = "true" 270 fileMap["TrackingConfigured"] = "true"
271 workMap["TrackingLocal"] = "true"
272 workMap["TrackingRemote"] = TrackingRemoteAniList
273 workMap["TrackingConfigured"] = "true"
252 updated = true 274 updated = true
253 } 275 }
254 276
255 if providerValue, exists := configMap["Provider"]; exists { 277 if providerValue, exists := fileMap["Provider"]; exists {
256 normalizedProviderValue := canonicalProviderConfigValue(providerValue) 278 normalizedProviderValue := canonicalProviderConfigValue(providerValue)
257 if normalizedProviderValue != providerValue { 279 if normalizedProviderValue != providerValue {
258 configMap["Provider"] = normalizedProviderValue 280 fileMap["Provider"] = normalizedProviderValue
281 workMap["Provider"] = normalizedProviderValue
259 updated = true 282 updated = true
260 } 283 }
261 } 284 }
262 285
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.
264 if addMissing && updated { 288 if addMissing && updated {
265 if err := SaveConfigToFile(configPath, configMap); err != nil { 289 if err := SaveConfigToFile(configPath, fileMap); err != nil {
266 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err) 290 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
267 } 291 }
268 } 292 }
269 293
270 // Parse string arrays 294 // Populate the CurdConfig struct from the complete (in-memory) work map
271 if mpvArgs, exists := configMap["MpvArgs"]; exists { 295 config := PopulateConfig(workMap)
272 configMap["MpvArgs"] = mpvArgs
273 }
274
275 // Populate the CurdConfig struct from the config map
276 config := PopulateConfig(configMap)
277 normalizeTrackingConfig(&config) 296 normalizeTrackingConfig(&config)
278 297
279 return config, nil 298 return config, nil
internal/logic_regression_test.go +72
@@ -121,6 +121,78 @@ func TestSelectionCtrlCSelectsQuit(t *testing.T) {
121 } 121 }
122} 122}
123 123
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
124func TestSelectionEnterWithNoMatchesDoesNotPanic(t *testing.T) { 196func TestSelectionEnterWithNoMatchesDoesNotPanic(t *testing.T) {
125 model := &Model{filteredKeys: nil, selected: 0} 197 model := &Model{filteredKeys: nil, selected: 0}
126 updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyEnter}) 198 updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
internal/provider_migrate.go +104 −12
@@ -4,6 +4,7 @@ import (
4 "fmt" 4 "fmt"
5 "os" 5 "os"
6 "path/filepath" 6 "path/filepath"
7 "sort"
7 "strings" 8 "strings"
8) 9)
9 10
@@ -105,7 +106,58 @@ func writeStoredCurdVersion(storagePath, version string) error {
105 return os.WriteFile(storageVersionFilePath(storagePath), []byte(version+"\n"), 0644) 106 return os.WriteFile(storageVersionFilePath(storagePath), []byte(version+"\n"), 0644)
106} 107}
107 108
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
108// MigrateOnVersionUpgrade updates stored state and config when curd is upgraded. 157// 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.
109// Returns whether the config file was updated. 161// Returns whether the config file was updated.
110func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion string) (bool, error) { 162func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion string) (bool, error) {
111 if config == nil { 163 if config == nil {
@@ -125,7 +177,48 @@ func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion s
125 storedVersion := readStoredCurdVersion(storagePath) 177 storedVersion := readStoredCurdVersion(storagePath)
126 configUpdated := false 178 configUpdated := false
127 179
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.
129 if nextProvider, changed := migrateProviderConfig(config.Provider); changed { 222 if nextProvider, changed := migrateProviderConfig(config.Provider); changed {
130 config.Provider = nextProvider 223 config.Provider = nextProvider
131 configUpdated = true 224 configUpdated = true
@@ -136,19 +229,18 @@ func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion s
136 return configUpdated, fmt.Errorf("write curd version file: %w", err) 229 return configUpdated, fmt.Errorf("write curd version file: %w", err)
137 } 230 }
138 231
139 if !configUpdated || strings.TrimSpace(configPath) == "" { 232 return configUpdated, nil
140 return configUpdated, nil 233}
141 }
142 234
143 configMap, err := LoadConfigFromFile(configPath) 235func parseConfigBool(value string) (bool, error) {
144 if err != nil { 236 switch strings.ToLower(strings.TrimSpace(value)) {
145 return configUpdated, err 237 case "true", "1", "yes", "y", "on":
146 } 238 return true, nil
147 configMap["Provider"] = config.Provider 239 case "false", "0", "no", "n", "off":
148 if err := SaveConfigToFile(configPath, configMap); err != nil { 240 return false, nil
149 return configUpdated, err 241 default:
242 return false, fmt.Errorf("invalid bool %q", value)
150 } 243 }
151 return configUpdated, nil
152} 244}
153 245
154func providerConfigDisplayLabel(raw string) string { 246func providerConfigDisplayLabel(raw string) string {
internal/provider_migrate_test.go +78
@@ -114,6 +114,84 @@ func TestMigrateOnVersionUpgradeWritesVersionAndUpdatesProvider(t *testing.T) {
114 } 114 }
115} 115}
116 116
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
117func TestConfiguredProviderNamesUsesStackedByDefault(t *testing.T) { 195func TestConfiguredProviderNamesUsesStackedByDefault(t *testing.T) {
118 withAllProvidersEnabledForTest(t) 196 withAllProvidersEnabledForTest(t)
119 got := ConfiguredProviderNames(&CurdConfig{}) 197 got := ConfiguredProviderNames(&CurdConfig{})
internal/selection_menu.go +124 −46
@@ -21,6 +21,7 @@ import (
21// Model represents the application state for the selection prompt 21// Model represents the application state for the selection prompt
22type Model struct { 22type Model struct {
23 filter string 23 filter string
24 filterActive bool // when VimKeys is on: true after "/" enters search mode
24 filteredKeys []SelectionOption 25 filteredKeys []SelectionOption
25 allOptions []SelectionOption 26 allOptions []SelectionOption
26 selected int 27 selected int
@@ -83,6 +84,45 @@ func (m Model) Init() tea.Cmd {
83 return nil 84 return nil
84} 85}
85 86
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
86// Update handles user input and updates the model 126// Update handles user input and updates the model
87func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { 127func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
88 // Handle terminal resize messages 128 // Handle terminal resize messages
@@ -92,67 +132,90 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
92 } 132 }
93 133
94 updateFilter := false 134 updateFilter := false
135 vimKeys := VimKeysEnabled(nil)
95 136
96 switch msg := msg.(type) { 137 switch msg := msg.(type) {
97 case optionsRefreshedMsg: 138 case optionsRefreshedMsg:
98 m.replaceOptions(msg.options) 139 m.replaceOptions(msg.options)
99 return m, nil 140 return m, nil
100 case tea.KeyMsg: 141 case tea.KeyMsg:
101 switch msg.String() { 142 key := msg.String()
143
144 switch key {
102 case "ctrl+c": 145 case "ctrl+c":
103 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}} 146 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
104 m.selected = 0 147 m.selected = 0
105 return m, tea.Quit 148 return m, tea.Quit
106 case "esc": 149 }
107 // ESC: quit on home menu, go back on sub-menus 150
108 if m.isHomeMenu { 151 // --- Vim-enabled selection: normal mode vs search mode ---
109 // Quit 152 if vimKeys {
110 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}} 153 // Search mode: typing filters; j/k/arrows still navigate results.
111 m.selected = 0 154 if m.filterActive {
112 } else { 155 switch key {
113 // Go back 156 case "esc":
114 m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}} 157 // Leave search mode but keep the current filter applied.
115 m.selected = 0 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
116 } 178 }
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()
118 case "backspace": 205 case "backspace":
119 if len(m.filter) > 0 { 206 if len(m.filter) > 0 {
120 m.filter = m.filter[:len(m.filter)-1] 207 m.filter = m.filter[:len(m.filter)-1]
121 updateFilter = true 208 updateFilter = true
122 } 209 }
123 case "down", "tab", "ctrl+n": 210 case "down", "tab", "ctrl+n":
124 // Move the selection cursor down 211 m.moveSelectionDown()
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 }
133 case "up", "shift+tab", "ctrl+p": 212 case "up", "shift+tab", "ctrl+p":
134 // Move the selection cursor up 213 m.moveSelectionUp()
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 }
143 case "enter": 214 case "enter":
144 if len(m.filteredKeys) == 0 { 215 return m, m.confirmSelection()
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
153 default: 216 default:
154 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" { 217 if len(key) == 1 && key >= " " && key <= "~" {
155 m.filter += msg.String() 218 m.filter += key
156 updateFilter = true 219 updateFilter = true
157 } 220 }
158 } 221 }
@@ -214,11 +277,26 @@ func (m Model) View() string {
214 var b strings.Builder 277 var b strings.Builder
215 278
216 // Display the search prompt and filter with colors 279 // Display the search prompt and filter with colors
217 b.WriteString(titleStyle.Render("Search") + " (Press " + 280 if VimKeysEnabled(nil) {
218 quitHintStyle.Render("Ctrl+C") + " to quit):\n") 281 if m.filterActive {
219 282 b.WriteString(titleStyle.Render("Search") + " (Esc: leave search · Enter: select · j/k: move):\n")
220 b.WriteString(filterLabelStyle.Render("Filter: ") + 283 b.WriteString(filterLabelStyle.Render("Filter: ") +
221 filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing 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 }
222 300
223 if len(m.filteredKeys) == 0 { 301 if len(m.filteredKeys) == 0 {
224 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n") 302 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")