Commit d8d078535a

d8d078535a5a9aedda863d6b036c9a818faa3708

parent: 96ea30e758

Unsigned

Wraient <wraient.911@gmail.com> · 2025-07-23 11:59 UTC

Mod: Change [string]string to SelectionOption for maintaining order and consistency

Layout: unified · split

internal/anime_list.go +7 −4
@@ -5,9 +5,9 @@ import (
5 "fmt" 5 "fmt"
6 "io" 6 "io"
7 "net/http" 7 "net/http"
8 "net/url"
8 "os" 9 "os"
9 "path/filepath" 10 "path/filepath"
10 "net/url"
11 // "strings" 11 // "strings"
12) 12)
13 13
@@ -41,7 +41,7 @@ type response struct {
41// fmt.Println(animeList) 41// fmt.Println(animeList)
42// } 42// }
43 43
44func SearchAnime(query, mode string) (map[string]string, error) { 44func SearchAnime(query, mode string) ([]SelectionOption, error) {
45 userCurdConfig := GetGlobalConfig() 45 userCurdConfig := GetGlobalConfig()
46 if userCurdConfig == nil { 46 if userCurdConfig == nil {
47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log") 47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
@@ -56,7 +56,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
56 ) 56 )
57 57
58 // Prepare the anime list 58 // Prepare the anime list
59 animeList := make(map[string]string) 59 animeList := make([]SelectionOption, 0)
60 60
61 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) { 61 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
62 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) { 62 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -146,7 +146,10 @@ func SearchAnime(query, mode string) (map[string]string, error) {
146 displayName = anime.EnglishName 146 displayName = anime.EnglishName
147 } 147 }
148 148
149 animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", displayName, episodesStr) 149 animeList = append(animeList, SelectionOption{
150 Key: anime.ID,
151 Label: fmt.Sprintf("%s (%s episodes)", displayName, episodesStr),
152 })
150 } 153 }
151 return animeList, nil 154 return animeList, nil
152} 155}
internal/config.go +8 −5
@@ -345,7 +345,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
345 "CONTINUE_LAST": "Continue Last Session", 345 "CONTINUE_LAST": "Continue Last Session",
346 } 346 }
347 347
348 // Create ordered map to store final result 348 // Create ordered list to store final result
349 finalOrder := make([]string, 0) 349 finalOrder := make([]string, 0)
350 seen := make(map[string]bool) 350 seen := make(map[string]bool)
351 351
@@ -372,11 +372,14 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
372 } 372 }
373 } 373 }
374 374
375 // Create the final ordered map 375 // Create the final ordered slice of SelectionOptions
376 orderedMap := make(map[string]string) 376 orderedCategories := make([]SelectionOption, 0, len(finalOrder))
377 for _, key := range finalOrder { 377 for _, key := range finalOrder {
378 orderedMap[key] = defaultLabels[key] 378 orderedCategories = append(orderedCategories, SelectionOption{
379 Key: key,
380 Label: defaultLabels[key],
381 })
379 } 382 }
380 383
381 return orderedMap 384 return orderedCategories
382} 385}
internal/curd.go +75 −48
@@ -143,7 +143,7 @@ func ExitCurd(err error) {
143 RestoreScreen() 143 RestoreScreen()
144 144
145 anime := GetGlobalAnime() 145 anime := GetGlobalAnime()
146 if anime != nil && anime.Ep.Player.SocketPath != "" { 146 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
148 if err != nil { 148 if err != nil {
149 Log("Error closing MPV: " + err.Error()) 149 Log("Error closing MPV: " + err.Error())
@@ -223,11 +223,11 @@ func CurdOut(data interface{}) {
223} 223}
224 224
225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) { 225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
226 // Create update options map 226 // Create update options
227 updateOptions := map[string]string{ 227 updateOptions := []SelectionOption{
228 "CATEGORY": "Change Anime Category", 228 {Key: "CATEGORY", Label: "Change Anime Category"},
229 "PROGRESS": "Change Progress", 229 {Key: "PROGRESS", Label: "Change Progress"},
230 "SCORE": "Add/Change Score", 230 {Key: "SCORE", Label: "Add/Change Score"},
231 } 231 }
232 232
233 // Select update option 233 // Select update option
@@ -242,7 +242,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
242 } 242 }
243 243
244 // Get user's anime list 244 // Get user's anime list
245 var animeListMap map[string]string 245 var animeListOptions []SelectionOption
246 var animeListMapPreview map[string]RofiSelectPreview 246 var animeListMapPreview map[string]RofiSelectPreview
247 247
248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -299,42 +299,57 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
299 } 299 }
300 } 300 }
301 } else { 301 } else {
302 animeListMap = make(map[string]string) 302 animeListOptions = make([]SelectionOption, 0)
303 // Include anime from all categories 303 // Include anime from all categories
304 for _, entry := range user.AnimeList.Watching { 304 for _, entry := range user.AnimeList.Watching {
305 title := entry.Media.Title.English 305 title := entry.Media.Title.English
306 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 306 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
307 title = entry.Media.Title.Romaji 307 title = entry.Media.Title.Romaji
308 } 308 }
309 animeListMap[strconv.Itoa(entry.Media.ID)] = title 309 animeListOptions = append(animeListOptions, SelectionOption{
310 Key: strconv.Itoa(entry.Media.ID),
311 Label: title,
312 })
310 } 313 }
311 for _, entry := range user.AnimeList.Completed { 314 for _, entry := range user.AnimeList.Completed {
312 title := entry.Media.Title.English 315 title := entry.Media.Title.English
313 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 316 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314 title = entry.Media.Title.Romaji 317 title = entry.Media.Title.Romaji
315 } 318 }
316 animeListMap[strconv.Itoa(entry.Media.ID)] = title 319 animeListOptions = append(animeListOptions, SelectionOption{
320 Key: strconv.Itoa(entry.Media.ID),
321 Label: title,
322 })
317 } 323 }
318 for _, entry := range user.AnimeList.Paused { 324 for _, entry := range user.AnimeList.Paused {
319 title := entry.Media.Title.English 325 title := entry.Media.Title.English
320 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 326 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
321 title = entry.Media.Title.Romaji 327 title = entry.Media.Title.Romaji
322 } 328 }
323 animeListMap[strconv.Itoa(entry.Media.ID)] = title 329 animeListOptions = append(animeListOptions, SelectionOption{
330 Key: strconv.Itoa(entry.Media.ID),
331 Label: title,
332 })
324 } 333 }
325 for _, entry := range user.AnimeList.Dropped { 334 for _, entry := range user.AnimeList.Dropped {
326 title := entry.Media.Title.English 335 title := entry.Media.Title.English
327 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 336 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
328 title = entry.Media.Title.Romaji 337 title = entry.Media.Title.Romaji
329 } 338 }
330 animeListMap[strconv.Itoa(entry.Media.ID)] = title 339 animeListOptions = append(animeListOptions, SelectionOption{
340 Key: strconv.Itoa(entry.Media.ID),
341 Label: title,
342 })
331 } 343 }
332 for _, entry := range user.AnimeList.Planning { 344 for _, entry := range user.AnimeList.Planning {
333 title := entry.Media.Title.English 345 title := entry.Media.Title.English
334 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 346 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
335 title = entry.Media.Title.Romaji 347 title = entry.Media.Title.Romaji
336 } 348 }
337 animeListMap[strconv.Itoa(entry.Media.ID)] = title 349 animeListOptions = append(animeListOptions, SelectionOption{
350 Key: strconv.Itoa(entry.Media.ID),
351 Label: title,
352 })
338 } 353 }
339 } 354 }
340 355
@@ -343,7 +358,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
343 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 358 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
344 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false) 359 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
345 } else { 360 } else {
346 selectedAnime, err = DynamicSelect(animeListMap) 361 selectedAnime, err = DynamicSelect(animeListOptions)
347 } 362 }
348 if err != nil { 363 if err != nil {
349 Log(fmt.Sprintf("Failed to select anime: %v", err)) 364 Log(fmt.Sprintf("Failed to select anime: %v", err))
@@ -369,12 +384,13 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
369 ClearScreen() 384 ClearScreen()
370 switch updateSelection.Key { 385 switch updateSelection.Key {
371 case "CATEGORY": 386 case "CATEGORY":
372 categories := map[string]string{ 387 categories := []SelectionOption{
373 "CURRENT": "Currently Watching", 388 {Key: "CURRENT", Label: "Currently Watching"},
374 "COMPLETED": "Completed", 389 {Key: "COMPLETED", Label: "Completed"},
375 "PAUSED": "On Hold", 390 {Key: "PAUSED", Label: "On Hold"},
376 "DROPPED": "Dropped", 391 {Key: "DROPPED", Label: "Dropped"},
377 "PLANNING": "Plan to Watch", 392 {Key: "PLANNING", Label: "Plan to Watch"},
393 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
378 } 394 }
379 395
380 currentStatus := "None" 396 currentStatus := "None"
@@ -550,7 +566,7 @@ func UpdateCurd(repo, fileName string) error {
550 566
551func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption { 567func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552 var query string 568 var query string
553 var animeMap map[string]string 569 var animeOptions []SelectionOption
554 var animeMapPreview map[string]RofiSelectPreview 570 var animeMapPreview map[string]RofiSelectPreview
555 var err error 571 var err error
556 var anilistSelectedOption SelectionOption 572 var anilistSelectedOption SelectionOption
@@ -578,7 +594,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
578 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 594 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
579 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false) 595 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
580 } else { 596 } else {
581 anilistSelectedOption, err = DynamicSelect(animeMap) 597 anilistSelectedOption, err = DynamicSelect(animeOptions)
582 } 598 }
583 599
584 if anilistSelectedOption.Key == "-1" { 600 if anilistSelectedOption.Key == "-1" {
@@ -596,12 +612,13 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
596 } 612 }
597 613
598 // Add category selection before adding to list 614 // Add category selection before adding to list
599 categories := map[string]string{ 615 categories := []SelectionOption{
600 "CURRENT": "Currently Watching", 616 {Key: "CURRENT", Label: "Currently Watching"},
601 "COMPLETED": "Completed", 617 {Key: "COMPLETED", Label: "Completed"},
602 "PAUSED": "On Hold", 618 {Key: "PAUSED", Label: "On Hold"},
603 "DROPPED": "Dropped", 619 {Key: "DROPPED", Label: "Dropped"},
604 "PLANNING": "Plan to Watch", 620 {Key: "PLANNING", Label: "Plan to Watch"},
621 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
605 } 622 }
606 623
607 ClearScreen() 624 ClearScreen()
@@ -649,7 +666,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
649 var anilistUserDataPreview map[string]interface{} 666 var anilistUserDataPreview map[string]interface{}
650 667
651 // Filter anime list based on selected category 668 // Filter anime list based on selected category
652 var animeListMap map[string]string 669 var animeListOptions []SelectionOption
653 var animeListMapPreview map[string]RofiSelectPreview 670 var animeListMapPreview map[string]RofiSelectPreview
654 671
655 // Get user id, username and Anime list 672 // Get user id, username and Anime list
@@ -716,11 +733,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
716 } 733 }
717 } else { 734 } else {
718 // Create category selection map 735 // Create category selection map
719 categories := getOrderedCategories(userCurdConfig) 736 // Get ordered categories
737 orderedCategories := getOrderedCategories(userCurdConfig)
738
739 // Use DynamicSelect with ordered categories directly
740 categorySelection, err = DynamicSelect(orderedCategories)
720 741
721 // Select category using DynamicSelect
722 var err error
723 categorySelection, err = DynamicSelect(categories)
724 if err != nil { 742 if err != nil {
725 Log(fmt.Sprintf("Failed to select category: %v", err)) 743 Log(fmt.Sprintf("Failed to select category: %v", err))
726 ExitCurd(fmt.Errorf("Failed to select category")) 744 ExitCurd(fmt.Errorf("Failed to select category"))
@@ -758,13 +776,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
758 } 776 }
759 } 777 }
760 } else { 778 } else {
761 animeListMap = make(map[string]string) 779 animeListOptions = make([]SelectionOption, 0)
762 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) { 780 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
763 title := entry.Media.Title.English 781 title := entry.Media.Title.English
764 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 782 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
765 title = entry.Media.Title.Romaji 783 title = entry.Media.Title.Romaji
766 } 784 }
767 animeListMap[strconv.Itoa(entry.Media.ID)] = title 785 animeListOptions = append(animeListOptions, SelectionOption{
786 Key: strconv.Itoa(entry.Media.ID),
787 Label: title,
788 })
768 } 789 }
769 } 790 }
770 } 791 }
@@ -796,10 +817,13 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
796 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 817 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
797 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true) 818 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
798 } else { 819 } else {
799 // Add "Add new anime" option to the map 820 // Add "Add new anime" option to the slice
800 animeListMap["add_new"] = "Add new anime" 821 animeListOptions = append(animeListOptions, SelectionOption{
822 Key: "add_new",
823 Label: "Add new anime",
824 })
801 825
802 anilistSelectedOption, err = DynamicSelect(animeListMap) 826 anilistSelectedOption, err = DynamicSelect(animeListOptions)
803 } 827 }
804 if err != nil { 828 if err != nil {
805 Log(fmt.Sprintf("Error selecting anime: %v", err)) 829 Log(fmt.Sprintf("Error selecting anime: %v", err))
@@ -836,7 +860,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
836 anime.Title = selectedAnilistAnime.Media.Title 860 anime.Title = selectedAnilistAnime.Media.Title
837 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 861 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
838 anime.Ep.Number = selectedAnilistAnime.Progress + 1 862 anime.Ep.Number = selectedAnilistAnime.Progress + 1
839 var animeList map[string]string 863 var animeList []SelectionOption
840 userQuery = anime.Title.Romaji 864 userQuery = anime.Title.Romaji
841 865
842 // if anime not found in database, find it in animeList 866 // if anime not found in database, find it in animeList
@@ -900,9 +924,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
900 924
901 if !isInWatchingList { 925 if !isInWatchingList {
902 // Create options for the prompt 926 // Create options for the prompt
903 options := map[string]string{ 927 options := []SelectionOption{
904 "yes": "Add to watching list", 928 {Key: "yes", Label: "Add to watching list"},
905 "no": "Continue without adding", 929 {Key: "no", Label: "Continue without adding"},
906 } 930 }
907 931
908 var selectedOption SelectionOption 932 var selectedOption SelectionOption
@@ -970,10 +994,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
970 if err != nil { 994 if err != nil {
971 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 995 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
972 } else { 996 } else {
973 for allanimeId, label := range animeList { 997 for _, option := range animeList {
974 if allanimeId == anime.AllanimeId { 998 if option.Key == anime.AllanimeId {
975 // Extract total episodes from the label 999 // Extract total episodes from the label
976 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 { 1000 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
977 anime.TotalEpisodes, _ = strconv.Atoi(matches[1]) 1001 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
978 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes)) 1002 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
979 break 1003 break
@@ -1211,6 +1235,7 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1211 allEntries = append(allEntries, list.Paused...) 1235 allEntries = append(allEntries, list.Paused...)
1212 allEntries = append(allEntries, list.Dropped...) 1236 allEntries = append(allEntries, list.Dropped...)
1213 allEntries = append(allEntries, list.Planning...) 1237 allEntries = append(allEntries, list.Planning...)
1238 allEntries = append(allEntries, list.Rewatching...)
1214 return allEntries 1239 return allEntries
1215 case "CURRENT": 1240 case "CURRENT":
1216 return list.Watching 1241 return list.Watching
@@ -1222,6 +1247,8 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1222 return list.Dropped 1247 return list.Dropped
1223 case "PLANNING": 1248 case "PLANNING":
1224 return list.Planning 1249 return list.Planning
1250 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1251 return list.Rewatching
1225 default: 1252 default:
1226 return []Entry{} 1253 return []Entry{}
1227 } 1254 }
@@ -1238,8 +1265,8 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1238 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum)) 1265 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1239 1266
1240 // Create options for the selection 1267 // Create options for the selection
1241 options := map[string]string{ 1268 options := []SelectionOption{
1242 "yes": "Yes, start next episode", 1269 {Key: "yes", Label: "Yes, start next episode"},
1243 // "no": "No, quit", 1270 // "no": "No, quit",
1244 } 1271 }
1245 1272
@@ -1379,7 +1406,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1379 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number)) 1406 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
1380 1407
1381 // Simple yes/no selection for the last episode 1408 // Simple yes/no selection for the last episode
1382 selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"}) 1409 selectedOption, err := DynamicSelect([]SelectionOption{{Key: "yes", Label: "Yes"}})
1383 if err != nil { 1410 if err != nil {
1384 ExitCurd(err) 1411 ExitCurd(err)
1385 } 1412 }
internal/localTracking.go +1 −1
@@ -250,7 +250,7 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
250 250
251func WatchUntracked(userCurdConfig *CurdConfig) { 251func WatchUntracked(userCurdConfig *CurdConfig) {
252 var query string 252 var query string
253 var animeList map[string]string 253 var animeList []SelectionOption
254 var err error 254 var err error
255 var anime Anime 255 var anime Anime
256 256
internal/selection_menu.go +82 −132
@@ -17,22 +17,16 @@ import (
17 "github.com/charmbracelet/lipgloss" 17 "github.com/charmbracelet/lipgloss"
18) 18)
19 19
20// SelectionOption holds the label and the internal key
21type SelectionOption struct {
22 Label string
23 Key string
24}
25
26// Model represents the application state for the selection prompt 20// Model represents the application state for the selection prompt
27type Model struct { 21type Model struct {
28 options map[string]string
29 filter string 22 filter string
30 filteredKeys []SelectionOption 23 filteredKeys []SelectionOption
24 allOptions []SelectionOption
31 selected int 25 selected int
32 terminalWidth int 26 terminalWidth int
33 terminalHeight int 27 terminalHeight int
34 scrollOffset int // Track the topmost visible item 28 scrollOffset int
35 addNewOption bool // Add this field 29 addNewOption bool
36} 30}
37 31
38var ( 32var (
@@ -181,40 +175,36 @@ func (m Model) visibleItemsCount() int {
181 175
182// filterOptions filters and sorts options based on the search term 176// filterOptions filters and sorts options based on the search term
183func (m *Model) filterOptions() { 177func (m *Model) filterOptions() {
184 m.filteredKeys = []SelectionOption{} 178 m.filteredKeys = nil
179 for _, opt := range m.allOptions {
180 if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
181 m.filteredKeys = append(m.filteredKeys, opt)
182 }
183 }
185 184
186 for key, value := range m.options { 185 // Sort the filtered options alphabetically unless this is a menu selection
187 // When the key is " ", compare and display using the value instead 186 isMenu := false
188 if key == " " { 187 for _, opt := range m.allOptions {
189 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) { 188 if opt.Key == "ALL" || opt.Key == "CURRENT" {
190 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key}) 189 isMenu = true
191 } 190 break
192 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
193 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
194 } 191 }
195 } 192 }
196 193
197 // Sort the filtered options alphabetically 194 if !isMenu {
198 sort.Slice(m.filteredKeys, func(i, j int) bool { 195 sort.Slice(m.filteredKeys, func(i, j int) bool {
199 return m.filteredKeys[i].Label < m.filteredKeys[j].Label 196 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
200 }) 197 })
198 }
201 199
202 // Add "Add new anime" option if enabled 200 // Add "Add new anime" option if enabled
203 if m.addNewOption { 201 if m.addNewOption {
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{ 202 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
205 Label: "Add new anime",
206 Key: "add_new",
207 })
208 } 203 }
209 204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
210 m.filteredKeys = append(m.filteredKeys, SelectionOption{
211 Label: "Quit",
212 Key: "-1",
213 })
214} 205}
215 206
216func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) { 207func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
217 // Pre-download first 14 images in background
218 go preDownloadImages(options, 14) 208 go preDownloadImages(options, 14)
219 209
220 userCurdConfig := GetGlobalConfig() 210 userCurdConfig := GetGlobalConfig()
@@ -222,62 +212,46 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
222 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 212 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
223 } 213 }
224 214
225 // Prepare Rofi input with anime titles and their cached image paths
226 var rofiInput strings.Builder 215 var rofiInput strings.Builder
227 for _, option := range options { 216 selectionOptions := make([]SelectionOption, 0, len(options))
228 // Download and get cache path for the image 217
229 cachePath, err := downloadToCache(option.CoverImage) 218 // Prepare options and rofi input
219 for id, opt := range options {
220 cachePath, err := downloadToCache(opt.CoverImage)
230 if err != nil { 221 if err != nil {
231 Log(fmt.Sprintf("Error caching image: %v", err)) 222 Log(fmt.Sprintf("Error caching image: %v", err))
232 continue 223 continue
233 } 224 }
234 225 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath))
235 // Format: "Title\x00icon\x1f/path/to/cached/image\n" 226 selectionOptions = append(selectionOptions, SelectionOption{
236 // This tells Rofi to use the image as an icon for this entry 227 Label: opt.Title,
237 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath)) 228 Key: id,
229 })
238 } 230 }
239 231
240 // Add "Add new anime" and "Quit" options
241 if addnewoption { 232 if addnewoption {
242 rofiInput.WriteString("Add new anime\n") 233 rofiInput.WriteString("Add new anime\n")
243 } 234 }
244 rofiInput.WriteString("Quit\n") 235 rofiInput.WriteString("Quit\n")
245 236
246 // Get the absolute path to the rasi config 237 // Run rofi
247 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi") 238 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
248 239 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
249 // Create the command with explicit arguments 240 cmd.Stdin = strings.NewReader(rofiInput.String())
250 args := []string{
251 "-dmenu",
252 "-theme", configPath,
253 "-show-icons",
254 "-p", "Select Anime",
255 "-i", // Case-insensitive matching
256 "-no-custom", // Disable custom input
257 }
258
259 // Create the command
260 rofiCmd := exec.Command("rofi", args...)
261
262 // Set up pipes for input/output
263 rofiCmd.Stdin = strings.NewReader(rofiInput.String())
264 var stdout, stderr bytes.Buffer 241 var stdout, stderr bytes.Buffer
265 rofiCmd.Stdout = &stdout 242 cmd.Stdout = &stdout
266 rofiCmd.Stderr = &stderr 243 cmd.Stderr = &stderr
267 244
268 // Run the command 245 if err := cmd.Run(); err != nil {
269 err := rofiCmd.Run()
270 if err != nil {
271 // Log both stdout and stderr for debugging
272 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String())) 246 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
273 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String())) 247 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
274 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err) 248 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
275 } 249 }
276 250
277 selectedTitle := strings.TrimSpace(stdout.String()) 251 selected := strings.TrimSpace(stdout.String())
278 252
279 // Handle special cases 253 // Handle special cases
280 switch selectedTitle { 254 switch selected {
281 case "": 255 case "":
282 return SelectionOption{}, fmt.Errorf("no selection made") 256 return SelectionOption{}, fmt.Errorf("no selection made")
283 case "Add new anime": 257 case "Add new anime":
@@ -286,13 +260,10 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
286 return SelectionOption{Label: "Quit", Key: "-1"}, nil 260 return SelectionOption{Label: "Quit", Key: "-1"}, nil
287 } 261 }
288 262
289 // Find the selected anime in options 263 // Find matching option
290 for id, option := range options { 264 for _, opt := range selectionOptions {
291 if option.Title == selectedTitle { 265 if opt.Label == selected {
292 return SelectionOption{ 266 return opt, nil
293 Label: option.Title,
294 Key: id,
295 }, nil
296 } 267 }
297 } 268 }
298 269
@@ -363,116 +334,95 @@ func showCachedImagePreview(imageURL string) error {
363 return nil 334 return nil
364} 335}
365 336
366func RofiSelect(options map[string]string) (SelectionOption, error) { 337func RofiSelect(options []SelectionOption) (SelectionOption, error) {
367 userCurdConfig := GetGlobalConfig() 338 userCurdConfig := GetGlobalConfig()
368 if userCurdConfig.StoragePath == "" { 339 if userCurdConfig.StoragePath == "" {
369 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 340 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
370 } 341 }
371 342
372 // Create a slice to store the options in the order we want 343 // Create ordered list of options
373 var optionsList []string 344 var optionsList []string
374 for _, value := range options { 345 for _, opt := range options {
375 optionsList = append(optionsList, value) 346 optionsList = append(optionsList, opt.Label)
376 } 347 }
377 348
378 // Sort the options alphabetically 349 // Add "Quit" option at the end
379 sort.Strings(optionsList)
380
381 // Add "Quit" options
382 optionsList = append(optionsList, "Quit") 350 optionsList = append(optionsList, "Quit")
383
384 // Join all options into a single string, separated by newlines
385 optionsString := strings.Join(optionsList, "\n") 351 optionsString := strings.Join(optionsList, "\n")
386 352
387 // Prepare the Rofi command 353 // Prepare and run rofi
388 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime") 354 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
389 355 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
390 // Set up pipes for input and output
391 cmd.Stdin = strings.NewReader(optionsString) 356 cmd.Stdin = strings.NewReader(optionsString)
392 var out bytes.Buffer 357 var stdout, stderr bytes.Buffer
393 cmd.Stdout = &out 358 cmd.Stdout = &stdout
359 cmd.Stderr = &stderr
394 360
395 // Run the command
396 err := cmd.Run() 361 err := cmd.Run()
397 if err != nil { 362 if err != nil {
363 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
364 return SelectionOption{Key: "-1", Label: ""}, nil
365 }
398 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err) 366 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
399 } 367 }
400 368
401 // Get the selected option 369 selected := strings.TrimSpace(stdout.String())
402 selected := strings.TrimSpace(out.String())
403 370
404 // Handle special cases 371 // Handle special cases
405 switch selected { 372 switch selected {
406 case "": 373 case "":
407 return SelectionOption{}, fmt.Errorf("no selection made") 374 return SelectionOption{Key: "-1", Label: ""}, nil
408 case "Quit": 375 case "Quit":
409 return SelectionOption{Label: "Quit", Key: "-1"}, nil 376 return SelectionOption{Label: "Quit", Key: "-1"}, nil
410 } 377 }
411 378
412 // Find the key for the selected value 379 // Find the matching SelectionOption
413 for key, value := range options { 380 for _, opt := range options {
414 if value == selected { 381 if opt.Label == selected {
415 return SelectionOption{Label: value, Key: key}, nil 382 return opt, nil
416 } 383 }
417 } 384 }
418 385
419 // If we get here, the selected option wasn't found in the original map
420 return SelectionOption{}, fmt.Errorf("selected option not found in original list") 386 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
421} 387}
422 388
423// DynamicSelect displays a simple selection prompt without extra features 389// DynamicSelect displays a simple selection prompt without extra features
424func DynamicSelect(options map[string]string) (SelectionOption, error) { 390func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
425 if GetGlobalConfig().RofiSelection { 391 if GetGlobalConfig().RofiSelection {
426 return RofiSelect(options) 392 return RofiSelect(options)
427 } 393 }
428 394
429 // Create a slice to maintain order 395 // Sort options if this contains menu categories
430 var orderedOptions []SelectionOption 396 for _, opt := range options {
431 397 if opt.Key == "ALL" || opt.Key == "CURRENT" {
432 // If this is a category selection (contains menu items), use the ordered keys 398 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
433 if _, hasMenu := options["ALL"]; hasMenu { 399 optMap := make(map[string]SelectionOption)
434 // Get the menu order from config 400 for _, opt := range options {
435 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",") 401 optMap[opt.Key] = opt
402 }
436 403
437 // Add options in the specified order 404 sorted := make([]SelectionOption, 0, len(options))
438 for _, key := range menuOrder { 405 for _, key := range menuOrder {
439 if value, exists := options[key]; exists { 406 if opt, exists := optMap[key]; exists {
440 orderedOptions = append(orderedOptions, SelectionOption{ 407 sorted = append(sorted, opt)
441 Key: key, 408 }
442 Label: value,
443 })
444 } 409 }
445 } 410 options = sorted
446 } else { 411 break
447 // For other selections, maintain alphabetical order
448 for key, value := range options {
449 orderedOptions = append(orderedOptions, SelectionOption{
450 Key: key,
451 Label: value,
452 })
453 } 412 }
454 } 413 }
455 414
456 model := &Model{ 415 model := &Model{
457 options: options, 416 allOptions: options,
458 filteredKeys: orderedOptions,
459 } 417 }
418 model.filterOptions() // Initialize filtered options
460 419
461 model.filteredKeys = append(model.filteredKeys, SelectionOption{
462 Label: "Quit",
463 Key: "-1",
464 })
465
466 // Create a program with altScreen option turned off to maintain the terminal state
467 // This prevents the terminal from switching to an alternate screen
468 p := tea.NewProgram(model) 420 p := tea.NewProgram(model)
469
470 finalModel, err := p.Run() 421 finalModel, err := p.Run()
471 if err != nil { 422 if err != nil {
472 return SelectionOption{}, err 423 return SelectionOption{}, err
473 } 424 }
474 425
475 // Explicitly reset the terminal state
476 fmt.Print("\033[?25h") // Show cursor 426 fmt.Print("\033[?25h") // Show cursor
477 fmt.Print("\033[?7h") // Enable line wrapping 427 fmt.Print("\033[?7h") // Enable line wrapping
478 428
internal/structs.go +18 −5
@@ -106,14 +106,27 @@ type Entry struct {
106} 106}
107 107
108type AnimeList struct { 108type AnimeList struct {
109 Watching []Entry `json:"watching"` 109 Watching []Entry `json:"watching"`
110 Completed []Entry `json:"completed"` 110 Completed []Entry `json:"completed"`
111 Paused []Entry `json:"paused"` 111 Paused []Entry `json:"paused"`
112 Dropped []Entry `json:"dropped"` 112 Dropped []Entry `json:"dropped"`
113 Planning []Entry `json:"planning"` 113 Planning []Entry `json:"planning"`
114 Rewatching []Entry `json:"rewatching"`
114} 115}
115 116
116type RofiSelectPreview struct { 117type RofiSelectPreview struct {
117 Title string `json:"title"` 118 Title string `json:"title"`
118 CoverImage string `json:"coverImage"` 119 CoverImage string `json:"coverImage"`
119} 120}
121
122type SelectionOptionImage struct {
123 Key string
124 Label string
125 CoverImage string
126}
127
128// SelectionOption holds the label and the internal key
129type SelectionOption struct {
130 Label string
131 Key string
132}\ No newline at end of file