Commit 824b391c23

824b391c23847c23a673e99c5ab8f44512a95812

parent: 1309809bc9

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2025-07-23 18:28 UTC
committer: <noreply@github.com>

Fix bugs and new features (#64)

* Add: rewatching list in show all

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

* Mod: Make functions public

* Fix: Handle last episode scoring and completion

* Fix: Next Episode Prompt

* Add: Logging and new implementation for selectionOption[]

* Remove: Redundant keywords

Layout: unified · split

internal/anilist.go +9 −4
@@ -47,6 +47,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
4747 populateMap(animeList.Paused)
4848 populateMap(animeList.Dropped)
4949 populateMap(animeList.Planning)
50 populateMap(animeList.Rewatching) // Add Rewatching list
5051
5152 return animeMap
5253}
@@ -82,6 +83,7 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
8283 populateMap(animeList.Paused)
8384 populateMap(animeList.Dropped)
8485 populateMap(animeList.Planning)
86 populateMap(animeList.Rewatching) // Add Rewatching list
8587
8688 return animeMap
8789}
@@ -792,13 +794,15 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
792794 case "CURRENT":
793795 animeList.Watching = append(animeList.Watching, animeEntry)
794796 case "COMPLETED":
795 animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
797 animeList.Completed = append(animeList.Completed, animeEntry)
796798 case "PAUSED":
797 animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
799 animeList.Paused = append(animeList.Paused, animeEntry)
798800 case "DROPPED":
799 animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
801 animeList.Dropped = append(animeList.Dropped, animeEntry)
800802 case "PLANNING":
801 animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
803 animeList.Planning = append(animeList.Planning, animeEntry)
804 case "REPEATING": // Anilist uses REPEATING for rewatching
805 animeList.Rewatching = append(animeList.Rewatching, animeEntry)
802806 }
803807 }
804808 }
@@ -820,6 +824,7 @@ func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
820824 list.Paused,
821825 list.Dropped,
822826 list.Planning,
827 list.Rewatching, // Add Rewatching list
823828 }
824829
825830 // Iterate through each category
internal/anime_list.go +6 −3
@@ -41,7 +41,7 @@ type response struct {
4141// fmt.Println(animeList)
4242// }
4343
44func SearchAnime(query, mode string) (map[string]string, error) {
44func SearchAnime(query, mode string) ([]SelectionOption, error) {
4545 userCurdConfig := GetGlobalConfig()
4646 if userCurdConfig == nil {
4747 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
@@ -56,7 +56,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
5656 )
5757
5858 // Prepare the anime list
59 animeList := make(map[string]string)
59 animeList := make([]SelectionOption, 0)
6060
6161 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
6262 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -146,7 +146,10 @@ func SearchAnime(query, mode string) (map[string]string, error) {
146146 displayName = anime.EnglishName
147147 }
148148
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 })
150153 }
151154 return animeList, nil
152155}
internal/config.go +18 −15
@@ -110,7 +110,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
110110 }
111111
112112 // Load the config from file
113 configMap, err := loadConfigFromFile(configPath)
113 configMap, err := LoadConfigFromFile(configPath)
114114 if err != nil {
115115 return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
116116 }
@@ -133,7 +133,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
133133
134134 // Write updated config back to file only if AddMissingOptions is true
135135 if addMissing && updated {
136 if err := saveConfigToFile(configPath, configMap); err != nil {
136 if err := SaveConfigToFile(configPath, configMap); err != nil {
137137 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
138138 }
139139 }
@@ -144,7 +144,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
144144 }
145145
146146 // Populate the CurdConfig struct from the config map
147 config := populateConfig(configMap)
147 config := PopulateConfig(configMap)
148148
149149 return config, nil
150150}
@@ -249,8 +249,8 @@ func ChangeToken(config *CurdConfig, user *User) {
249249 WriteTokenToFile(user.Token, tokenPath)
250250}
251251
252// Load config file from disk into a map (key=value format)
253func loadConfigFromFile(path string) (map[string]string, error) {
252// LoadConfigFromFile loads config file from disk into a map (key=value format)
253func LoadConfigFromFile(path string) (map[string]string, error) {
254254 file, err := os.Open(path)
255255 if err != nil {
256256 return nil, err
@@ -281,8 +281,8 @@ func loadConfigFromFile(path string) (map[string]string, error) {
281281 return configMap, nil
282282}
283283
284// Save updated config map to file in key=value format
285func saveConfigToFile(path string, configMap map[string]string) error {
284// SaveConfigToFile saves updated config map to file in key=value format
285func SaveConfigToFile(path string, configMap map[string]string) error {
286286 file, err := os.Create(path)
287287 if err != nil {
288288 return err
@@ -299,8 +299,8 @@ func saveConfigToFile(path string, configMap map[string]string) error {
299299 return writer.Flush()
300300}
301301
302// Populate the CurdConfig struct from a map
303func populateConfig(configMap map[string]string) CurdConfig {
302// PopulateConfig populates the CurdConfig struct from a map
303func PopulateConfig(configMap map[string]string) CurdConfig {
304304 config := CurdConfig{}
305305 configValue := reflect.ValueOf(&config).Elem()
306306
@@ -334,7 +334,7 @@ func populateConfig(configMap map[string]string) CurdConfig {
334334 return config
335335}
336336
337func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
337func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
338338 // Define the default categories and their labels
339339 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST"}
340340 defaultLabels := map[string]string{
@@ -345,7 +345,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
345345 "CONTINUE_LAST": "Continue Last Session",
346346 }
347347
348 // Create ordered map to store final result
348 // Create ordered list to store final result
349349 finalOrder := make([]string, 0)
350350 seen := make(map[string]bool)
351351
@@ -372,11 +372,14 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
372372 }
373373 }
374374
375 // Create the final ordered map
376 orderedMap := make(map[string]string)
375 // Create the final ordered slice of SelectionOptions
376 orderedCategories := make([]SelectionOption, 0, len(finalOrder))
377377 for _, key := range finalOrder {
378 orderedMap[key] = defaultLabels[key]
378 orderedCategories = append(orderedCategories, SelectionOption{
379 Key: key,
380 Label: defaultLabels[key],
381 })
379382 }
380383
381 return orderedMap
384 return orderedCategories
382385}
internal/curd.go +286 −62
@@ -143,7 +143,7 @@ func ExitCurd(err error) {
143143 RestoreScreen()
144144
145145 anime := GetGlobalAnime()
146 if anime != nil && anime.Ep.Player.SocketPath != "" {
146 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
147147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
148148 if err != nil {
149149 Log("Error closing MPV: " + err.Error())
@@ -223,11 +223,11 @@ func CurdOut(data interface{}) {
223223}
224224
225225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
226 // Create update options map
227 updateOptions := map[string]string{
228 "CATEGORY": "Change Anime Category",
229 "PROGRESS": "Change Progress",
230 "SCORE": "Add/Change Score",
226 // Create update options
227 updateOptions := []SelectionOption{
228 {Key: "CATEGORY", Label: "Change Anime Category"},
229 {Key: "PROGRESS", Label: "Change Progress"},
230 {Key: "SCORE", Label: "Add/Change Score"},
231231 }
232232
233233 // Select update option
@@ -242,7 +242,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
242242 }
243243
244244 // Get user's anime list
245 var animeListMap map[string]string
245 var animeListOptions []SelectionOption
246246 var animeListMapPreview map[string]RofiSelectPreview
247247
248248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -298,43 +298,78 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
298298 CoverImage: entry.CoverImage,
299299 }
300300 }
301 for _, entry := range user.AnimeList.Rewatching {
302 title := entry.Media.Title.English
303 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
304 title = entry.Media.Title.Romaji
305 }
306 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
307 Title: title,
308 CoverImage: entry.CoverImage,
309 }
310 }
301311 } else {
302 animeListMap = make(map[string]string)
312 animeListOptions = make([]SelectionOption, 0)
303313 // Include anime from all categories
304314 for _, entry := range user.AnimeList.Watching {
305315 title := entry.Media.Title.English
306316 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
307317 title = entry.Media.Title.Romaji
308318 }
309 animeListMap[strconv.Itoa(entry.Media.ID)] = title
319 animeListOptions = append(animeListOptions, SelectionOption{
320 Key: strconv.Itoa(entry.Media.ID),
321 Label: title,
322 })
310323 }
311324 for _, entry := range user.AnimeList.Completed {
312325 title := entry.Media.Title.English
313326 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314327 title = entry.Media.Title.Romaji
315328 }
316 animeListMap[strconv.Itoa(entry.Media.ID)] = title
329 animeListOptions = append(animeListOptions, SelectionOption{
330 Key: strconv.Itoa(entry.Media.ID),
331 Label: title,
332 })
317333 }
318334 for _, entry := range user.AnimeList.Paused {
319335 title := entry.Media.Title.English
320336 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
321337 title = entry.Media.Title.Romaji
322338 }
323 animeListMap[strconv.Itoa(entry.Media.ID)] = title
339 animeListOptions = append(animeListOptions, SelectionOption{
340 Key: strconv.Itoa(entry.Media.ID),
341 Label: title,
342 })
324343 }
325344 for _, entry := range user.AnimeList.Dropped {
326345 title := entry.Media.Title.English
327346 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
328347 title = entry.Media.Title.Romaji
329348 }
330 animeListMap[strconv.Itoa(entry.Media.ID)] = title
349 animeListOptions = append(animeListOptions, SelectionOption{
350 Key: strconv.Itoa(entry.Media.ID),
351 Label: title,
352 })
331353 }
332354 for _, entry := range user.AnimeList.Planning {
333355 title := entry.Media.Title.English
334356 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
335357 title = entry.Media.Title.Romaji
336358 }
337 animeListMap[strconv.Itoa(entry.Media.ID)] = title
359 animeListOptions = append(animeListOptions, SelectionOption{
360 Key: strconv.Itoa(entry.Media.ID),
361 Label: title,
362 })
363 }
364 for _, entry := range user.AnimeList.Rewatching {
365 title := entry.Media.Title.English
366 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
367 title = entry.Media.Title.Romaji
368 }
369 animeListOptions = append(animeListOptions, SelectionOption{
370 Key: strconv.Itoa(entry.Media.ID),
371 Label: title,
372 })
338373 }
339374 }
340375
@@ -343,7 +378,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
343378 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
344379 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
345380 } else {
346 selectedAnime, err = DynamicSelect(animeListMap)
381 selectedAnime, err = DynamicSelect(animeListOptions)
347382 }
348383 if err != nil {
349384 Log(fmt.Sprintf("Failed to select anime: %v", err))
@@ -369,17 +404,24 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
369404 ClearScreen()
370405 switch updateSelection.Key {
371406 case "CATEGORY":
372 categories := map[string]string{
373 "CURRENT": "Currently Watching",
374 "COMPLETED": "Completed",
375 "PAUSED": "On Hold",
376 "DROPPED": "Dropped",
377 "PLANNING": "Plan to Watch",
407 categories := []SelectionOption{
408 {Key: "CURRENT", Label: "Currently Watching"},
409 {Key: "COMPLETED", Label: "Completed"},
410 {Key: "PAUSED", Label: "On Hold"},
411 {Key: "DROPPED", Label: "Dropped"},
412 {Key: "PLANNING", Label: "Plan to Watch"},
413 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
378414 }
379415
380416 currentStatus := "None"
381417 if selectedAnilistAnime.Status != "" {
382 currentStatus = categories[selectedAnilistAnime.Status]
418 // Find the label for the current status
419 for _, cat := range categories {
420 if cat.Key == selectedAnilistAnime.Status {
421 currentStatus = cat.Label
422 break
423 }
424 }
383425 }
384426 CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
385427
@@ -550,6 +592,7 @@ func UpdateCurd(repo, fileName string) error {
550592
551593func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552594 var query string
595 var animeOptions []SelectionOption
553596 var animeMapPreview map[string]RofiSelectPreview
554597 var animeOptions []SelectionOption
555598 var err error
@@ -571,7 +614,19 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
571614 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
572615 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
573616 } else {
574 animeOptions, err = SearchAnimeAnilist(query, user.Token)
617 animeMap, err := SearchAnimeAnilist(query, user.Token)
618 if err != nil {
619 Log(fmt.Sprintf("Failed to search anime: %v", err))
620 ExitCurd(fmt.Errorf("Failed to search anime"))
621 }
622 // Convert map to []SelectionOption
623 animeOptions = make([]SelectionOption, 0, len(animeMap))
624 for key, label := range animeMap {
625 animeOptions = append(animeOptions, SelectionOption{
626 Key: key,
627 Label: label,
628 })
629 }
575630 }
576631 if err != nil {
577632 Log(fmt.Sprintf("Failed to search anime: %v", err))
@@ -580,7 +635,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
580635 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
581636 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
582637 } else {
583 anilistSelectedOption, err = DynamicSelectFromSlice(animeOptions)
638 anilistSelectedOption, err = DynamicSelect(animeOptions)
584639 }
585640
586641 if anilistSelectedOption.Key == "-1" {
@@ -598,12 +653,13 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
598653 }
599654
600655 // Add category selection before adding to list
601 categories := map[string]string{
602 "CURRENT": "Currently Watching",
603 "COMPLETED": "Completed",
604 "PAUSED": "On Hold",
605 "DROPPED": "Dropped",
606 "PLANNING": "Plan to Watch",
656 categories := []SelectionOption{
657 {Key: "CURRENT", Label: "Currently Watching"},
658 {Key: "COMPLETED", Label: "Completed"},
659 {Key: "PAUSED", Label: "On Hold"},
660 {Key: "DROPPED", Label: "Dropped"},
661 {Key: "PLANNING", Label: "Plan to Watch"},
662 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
607663 }
608664
609665 ClearScreen()
@@ -651,7 +707,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
651707 var anilistUserDataPreview map[string]interface{}
652708
653709 // Filter anime list based on selected category
654 var animeListMap map[string]string
710 var animeListOptions []SelectionOption
655711 var animeListMapPreview map[string]RofiSelectPreview
656712
657713 // Get user id, username and Anime list
@@ -718,11 +774,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
718774 }
719775 } else {
720776 // Create category selection map
721 categories := getOrderedCategories(userCurdConfig)
777 // Get ordered categories
778 orderedCategories := getOrderedCategories(userCurdConfig)
779
780 // Use DynamicSelect with ordered categories directly
781 categorySelection, err = DynamicSelect(orderedCategories)
722782
723 // Select category using DynamicSelect
724 var err error
725 categorySelection, err = DynamicSelect(categories)
726783 if err != nil {
727784 Log(fmt.Sprintf("Failed to select category: %v", err))
728785 ExitCurd(fmt.Errorf("Failed to select category"))
@@ -760,13 +817,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
760817 }
761818 }
762819 } else {
763 animeListMap = make(map[string]string)
820 animeListOptions = make([]SelectionOption, 0)
764821 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
765822 title := entry.Media.Title.English
766823 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
767824 title = entry.Media.Title.Romaji
768825 }
769 animeListMap[strconv.Itoa(entry.Media.ID)] = title
826 animeListOptions = append(animeListOptions, SelectionOption{
827 Key: strconv.Itoa(entry.Media.ID),
828 Label: title,
829 })
770830 }
771831 }
772832 }
@@ -798,10 +858,13 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
798858 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
799859 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
800860 } else {
801 // Add "Add new anime" option to the map
802 animeListMap["add_new"] = "Add new anime"
861 // Add "Add new anime" option to the slice
862 animeListOptions = append(animeListOptions, SelectionOption{
863 Key: "add_new",
864 Label: "Add new anime",
865 })
803866
804 anilistSelectedOption, err = DynamicSelect(animeListMap)
867 anilistSelectedOption, err = DynamicSelect(animeListOptions)
805868 }
806869 if err != nil {
807870 Log(fmt.Sprintf("Error selecting anime: %v", err))
@@ -838,7 +901,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
838901 anime.Title = selectedAnilistAnime.Media.Title
839902 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
840903 anime.Ep.Number = selectedAnilistAnime.Progress + 1
841 var animeList map[string]string
904 var animeList []SelectionOption
842905 userQuery = anime.Title.Romaji
843906
844907 // if anime not found in database, find it in animeList
@@ -848,7 +911,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
848911 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
849912
850913 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
851 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
852914 if err != nil {
853915 Log(fmt.Sprintf("Failed to select anime: %v", err))
854916 ExitCurd(fmt.Errorf("Failed to select anime"))
@@ -857,10 +919,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
857919 ExitCurd(fmt.Errorf("No results found."))
858920 }
859921
860 // find anime in animeList
861 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
862 if err != nil {
863 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
922 // find anime in animeList by searching through the options
923 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
924 found := false
925 for i, option := range animeList {
926 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s'", i, option.Key, option.Label))
927 if option.Label == targetLabel {
928 anime.AllanimeId = option.Key
929 Log(fmt.Sprintf("Found exact match! Setting AllanimeId to: %s", anime.AllanimeId))
930 found = true
931 break
932 }
933 }
934
935 if !found {
936 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
864937 }
865938
866939 // If unable to get Allanime id automatically get manually
@@ -873,7 +946,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
873946 }
874947
875948 if err != nil {
876 // fmt.Println("No anime available")
877949 ExitCurd(fmt.Errorf("No anime available"))
878950 }
879951 anime.AllanimeId = selectedAllanimeAnime.Key
@@ -902,9 +974,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
902974
903975 if !isInWatchingList {
904976 // Create options for the prompt
905 options := map[string]string{
906 "yes": "Add to watching list",
907 "no": "Continue without adding",
977 options := []SelectionOption{
978 {Key: "yes", Label: "Add to watching list"},
979 {Key: "no", Label: "Continue without adding"},
908980 }
909981
910982 var selectedOption SelectionOption
@@ -972,10 +1044,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
9721044 if err != nil {
9731045 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
9741046 } else {
975 for allanimeId, label := range animeList {
976 if allanimeId == anime.AllanimeId {
1047 for _, option := range animeList {
1048 if option.Key == anime.AllanimeId {
9771049 // Extract total episodes from the label
978 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
1050 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
9791051 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
9801052 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
9811053 break
@@ -1028,6 +1100,33 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10281100 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
10291101 // Ensure the terminal state is clean for the prompt
10301102 fmt.Print("\r\033[K") // Carriage return and clear line
1103 episodeNum := anime.Ep.Number
1104 if !userCurdConfig.RofiSelection {
1105 episodeNum++
1106 }
1107
1108 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1109
1110 // Create options for the selection
1111 options := []SelectionOption{
1112 {Key: "yes", Label: "Yes, start next episode"},
1113 // "no": "No, quit",
1114 }
1115
1116 // Use DynamicSelect for both CLI and Rofi modes
1117 selectedOption, err := DynamicSelect(options)
1118 if err != nil {
1119 ExitCurd(err)
1120 }
1121
1122 if selectedOption.Key == "-1" {
1123 // User selected to quit
1124 fmt.Print("\r\033[K") // Carriage return and clear line
1125 ExitMPV(anime.Ep.Player.SocketPath)
1126 CurdOut("Exiting without starting next episode")
1127 ExitCurd(nil)
1128 return
1129 }
10311130 }
10321131}
10331132
@@ -1052,12 +1151,24 @@ func WriteTokenToFile(token string, filePath string) error {
10521151
10531152func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
10541153
1055 if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1154 // Validate inputs
1155 if anime.AllanimeId == "" {
1156 CurdOut("Error: No anime ID found")
1157 os.Exit(1)
1158 }
1159 if anime.Ep.Number <= 0 {
1160 CurdOut("Error: Invalid episode number")
1161 os.Exit(1)
1162 }
1163
1164 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
10561165 anime.Ep.Links = anime.Ep.NextEpisode.Links
1057 Log("using prefetched next episode link")
10581166 } else {
10591167 // Get episode link
10601168 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1169 if len(link) > 0 {
1170 Log(fmt.Sprintf("Links details: %+v", link))
1171 }
10611172 if err != nil {
10621173 // If unable to get episode link automatically get manually
10631174 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
@@ -1082,7 +1193,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
10821193 CurdOut("Failed to get episode link")
10831194 os.Exit(1)
10841195 }
1085 // anime.Ep.Links = link
1196 } else {
1197 Log(fmt.Sprintf("Successfully retrieved episode link on first try. Links count: %d", len(link)))
10861198 }
10871199 anime.Ep.Links = link
10881200 }
@@ -1090,10 +1202,10 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
10901202 if len(anime.Ep.Links) == 0 {
10911203 CurdOut("No episode links found")
10921204 os.Exit(1)
1205 } else {
1206 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
10931207 }
10941208
1095 Log(anime)
1096
10971209 // Modify the goroutine in main.go where next episode links are fetched
10981210 // Get next episode link in parallel
10991211 go func() {
@@ -1105,14 +1217,15 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
11051217 }
11061218 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
11071219 if err != nil {
1108 Log("Error getting next episode link: " + err.Error())
1220 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
11091221 } else {
11101222 anime.Ep.NextEpisode = NextEpisode{
11111223 Number: nextEpNum,
11121224 Links: nextLinks,
11131225 }
1114 Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
11151226 }
1227 } else {
1228 Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
11161229 }
11171230 }()
11181231
@@ -1213,6 +1326,7 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
12131326 allEntries = append(allEntries, list.Paused...)
12141327 allEntries = append(allEntries, list.Dropped...)
12151328 allEntries = append(allEntries, list.Planning...)
1329 allEntries = append(allEntries, list.Rewatching...)
12161330 return allEntries
12171331 case "CURRENT":
12181332 return list.Watching
@@ -1224,6 +1338,8 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
12241338 return list.Dropped
12251339 case "PLANNING":
12261340 return list.Planning
1341 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1342 return list.Rewatching
12271343 default:
12281344 return []Entry{}
12291345 }
@@ -1231,6 +1347,20 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
12311347
12321348func NextEpisodePrompt(userCurdConfig *CurdConfig) {
12331349 anime := GetGlobalAnime()
1350
1351 // Check if we just completed the last episode
1352 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1353 // Handle scoring and completion for the last episode
1354 HandleLastEpisodeCompletion(userCurdConfig, anime)
1355
1356 // Exit after completing the series
1357 fmt.Print("\r\033[K") // Carriage return and clear line
1358 ExitMPV(anime.Ep.Player.SocketPath)
1359 CurdOut("Series completed!")
1360 ExitCurd(nil)
1361 return
1362 }
1363
12341364 // If in CLI mode (not Rofi), we need to show the next episode number
12351365 episodeNum := anime.Ep.Number
12361366 if !userCurdConfig.RofiSelection {
@@ -1240,8 +1370,8 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) {
12401370 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
12411371
12421372 // Create options for the selection
1243 options := map[string]string{
1244 "yes": "Yes, start next episode",
1373 options := []SelectionOption{
1374 {Key: "yes", Label: "Yes, start next episode"},
12451375 // "no": "No, quit",
12461376 }
12471377
@@ -1364,6 +1494,35 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
13641494 // Save previous episode number for progress update
13651495 prevEpisode := anime.Ep.Number
13661496
1497 // Check if we just completed the last episode
1498 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1499 // Handle scoring and completion for the last episode
1500 HandleLastEpisodeCompletion(userCurdConfig, anime)
1501
1502 // Update Anilist progress for the last episode if not rewatching
1503 if !anime.Rewatching {
1504 user := &User{}
1505 var err error
1506 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1507 if err != nil {
1508 Log("Error reading token for progress update: " + err.Error())
1509 } else {
1510 go func() {
1511 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1512 if err != nil {
1513 Log("Error updating Anilist progress: " + err.Error())
1514 } else {
1515 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1516 }
1517 }()
1518 }
1519 }
1520
1521 CurdOut("Series completed!")
1522 ExitCurd(nil)
1523 return
1524 }
1525
13671526 // Increment episode number
13681527 anime.Ep.Number++
13691528
@@ -1381,7 +1540,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
13811540 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
13821541
13831542 // Simple yes/no selection for the last episode
1384 selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"})
1543 selectedOption, err := DynamicSelect([]SelectionOption{{Key: "yes", Label: "Yes"}})
13851544 if err != nil {
13861545 ExitCurd(err)
13871546 }
@@ -1432,3 +1591,68 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
14321591 // Output message to user
14331592 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
14341593}
1594
1595// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1596func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
1597 // Check if this is the last episode and scoring is enabled
1598 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1599 // Get user token for scoring
1600 user := &User{}
1601
1602 // Get config for storage path
1603 homeDir := ""
1604 if runtime.GOOS == "windows" {
1605 homeDir = os.Getenv("USERPROFILE")
1606 } else {
1607 homeDir = os.Getenv("HOME")
1608 }
1609 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1610 config, err := LoadConfig(configFilePath)
1611 if err != nil {
1612 Log("Error loading config for scoring: " + err.Error())
1613 return
1614 }
1615
1616 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1617 if err != nil {
1618 Log("Error reading token for scoring: " + err.Error())
1619 return
1620 }
1621
1622 // Prompt user to score the anime
1623 CurdOut("You've completed this anime! Would you like to rate it?")
1624
1625 scoreOptions := []SelectionOption{
1626 {Key: "yes", Label: "Yes, rate this anime"},
1627 {Key: "no", Label: "No, skip rating"},
1628 }
1629
1630 selectedOption, err := DynamicSelect(scoreOptions)
1631 if err != nil {
1632 Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1633 return
1634 }
1635
1636 if selectedOption.Key == "yes" {
1637 err = RateAnime(user.Token, anime.AnilistId)
1638 if err != nil {
1639 Log(fmt.Sprintf("Error rating anime: %v", err))
1640 CurdOut("Failed to rate anime")
1641 } else {
1642 CurdOut("Anime rated successfully!")
1643 }
1644 }
1645
1646 // Update anime status to completed on AniList
1647 if !anime.Rewatching {
1648 go func() {
1649 err = UpdateAnimeStatus(user.Token, anime.AnilistId, "COMPLETED")
1650 if err != nil {
1651 Log("Error updating anime status to completed: " + err.Error())
1652 } else {
1653 CurdOut("Anime status updated to completed!")
1654 }
1655 }()
1656 }
1657 }
1658}
internal/discord.go +2 −2
@@ -38,11 +38,11 @@ func DiscordPresence(anime Anime, IsPaused bool) error {
3838 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image
3939 Buttons: []*client.Button{
4040 {
41 Label: "View on AniList", // Button label
41 Label: "View on AniList", // Button label
4242 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link
4343 },
4444 {
45 Label: "View on MAL", // Button label
45 Label: "View on MAL", // Button label
4646 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link
4747 },
4848 },
internal/localTracking.go +1 −1
@@ -250,7 +250,7 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
250250
251251func WatchUntracked(userCurdConfig *CurdConfig) {
252252 var query string
253 var animeList map[string]string
253 var animeList []SelectionOption
254254 var err error
255255 var anime Anime
256256
internal/selection_menu.go +84 −149
@@ -17,24 +17,16 @@ import (
1717 "github.com/charmbracelet/lipgloss"
1818)
1919
20// SelectionOption holds the label and the internal key
21type SelectionOption struct {
22 Label string
23 Key string
24}
25
2620// Model represents the application state for the selection prompt
2721type Model struct {
28 options map[string]string
29 filter string
30 filteredKeys []SelectionOption
31 selected int
32 terminalWidth int
33 terminalHeight int
34 scrollOffset int // Track the topmost visible item
35 addNewOption bool
36 useSliceMode bool // Track if we're using slice-based filtering
37 originalOptions []SelectionOption // Store original options for slice-based filtering
22 filter string
23 filteredKeys []SelectionOption
24 allOptions []SelectionOption
25 selected int
26 terminalWidth int
27 terminalHeight int
28 scrollOffset int
29 addNewOption bool
3830}
3931
4032var (
@@ -183,29 +175,23 @@ func (m Model) visibleItemsCount() int {
183175
184176// filterOptions filters and sorts options based on the search term
185177func (m *Model) filterOptions() {
186 m.filteredKeys = []SelectionOption{}
187
188 if m.useSliceMode {
189 // slice-based filtering, filter from the original options
190 for _, option := range m.originalOptions {
191 if strings.Contains(strings.ToLower(option.Label), strings.ToLower(m.filter)) {
192 m.filteredKeys = append(m.filteredKeys, option)
193 }
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)
194182 }
195 } else {
196 // map-based filtering
197 for key, value := range m.options {
198 // When the key is " ", compare and display using the value instead
199 if key == " " {
200 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
201 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
202 }
203 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
205 }
183 }
184
185 // Sort the filtered options alphabetically unless this is a menu selection
186 isMenu := false
187 for _, opt := range m.allOptions {
188 if opt.Key == "ALL" || opt.Key == "CURRENT" {
189 isMenu = true
190 break
206191 }
192 }
207193
208 // Sort the filtered options alphabetically
194 if !isMenu {
209195 sort.Slice(m.filteredKeys, func(i, j int) bool {
210196 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
211197 })
@@ -213,20 +199,12 @@ func (m *Model) filterOptions() {
213199
214200 // Add "Add new anime" option if enabled
215201 if m.addNewOption {
216 m.filteredKeys = append(m.filteredKeys, SelectionOption{
217 Label: "Add new anime",
218 Key: "add_new",
219 })
202 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
220203 }
221
222 m.filteredKeys = append(m.filteredKeys, SelectionOption{
223 Label: "Quit",
224 Key: "-1",
225 })
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
226205}
227206
228207func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
229 // Pre-download first 14 images in background
230208 go preDownloadImages(options, 14)
231209
232210 userCurdConfig := GetGlobalConfig()
@@ -234,62 +212,46 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
234212 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
235213 }
236214
237 // Prepare Rofi input with anime titles and their cached image paths
238215 var rofiInput strings.Builder
239 for _, option := range options {
240 // Download and get cache path for the image
241 cachePath, err := downloadToCache(option.CoverImage)
216 selectionOptions := make([]SelectionOption, 0, len(options))
217
218 // Prepare options and rofi input
219 for id, opt := range options {
220 cachePath, err := downloadToCache(opt.CoverImage)
242221 if err != nil {
243222 Log(fmt.Sprintf("Error caching image: %v", err))
244223 continue
245224 }
246
247 // Format: "Title\x00icon\x1f/path/to/cached/image\n"
248 // This tells Rofi to use the image as an icon for this entry
249 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath))
225 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath))
226 selectionOptions = append(selectionOptions, SelectionOption{
227 Label: opt.Title,
228 Key: id,
229 })
250230 }
251231
252 // Add "Add new anime" and "Quit" options
253232 if addnewoption {
254233 rofiInput.WriteString("Add new anime\n")
255234 }
256235 rofiInput.WriteString("Quit\n")
257236
258 // Get the absolute path to the rasi config
237 // Run rofi
259238 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
260
261 // Create the command with explicit arguments
262 args := []string{
263 "-dmenu",
264 "-theme", configPath,
265 "-show-icons",
266 "-p", "Select Anime",
267 "-i", // Case-insensitive matching
268 "-no-custom", // Disable custom input
269 }
270
271 // Create the command
272 rofiCmd := exec.Command("rofi", args...)
273
274 // Set up pipes for input/output
275 rofiCmd.Stdin = strings.NewReader(rofiInput.String())
239 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
240 cmd.Stdin = strings.NewReader(rofiInput.String())
276241 var stdout, stderr bytes.Buffer
277 rofiCmd.Stdout = &stdout
278 rofiCmd.Stderr = &stderr
242 cmd.Stdout = &stdout
243 cmd.Stderr = &stderr
279244
280 // Run the command
281 err := rofiCmd.Run()
282 if err != nil {
283 // Log both stdout and stderr for debugging
245 if err := cmd.Run(); err != nil {
284246 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
285247 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
286248 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
287249 }
288250
289 selectedTitle := strings.TrimSpace(stdout.String())
251 selected := strings.TrimSpace(stdout.String())
290252
291253 // Handle special cases
292 switch selectedTitle {
254 switch selected {
293255 case "":
294256 return SelectionOption{}, fmt.Errorf("no selection made")
295257 case "Add new anime":
@@ -298,13 +260,10 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
298260 return SelectionOption{Label: "Quit", Key: "-1"}, nil
299261 }
300262
301 // Find the selected anime in options
302 for id, option := range options {
303 if option.Title == selectedTitle {
304 return SelectionOption{
305 Label: option.Title,
306 Key: id,
307 }, nil
263 // Find matching option
264 for _, opt := range selectionOptions {
265 if opt.Label == selected {
266 return opt, nil
308267 }
309268 }
310269
@@ -375,60 +334,55 @@ func showCachedImagePreview(imageURL string) error {
375334 return nil
376335}
377336
378func RofiSelect(options map[string]string) (SelectionOption, error) {
337func RofiSelect(options []SelectionOption) (SelectionOption, error) {
379338 userCurdConfig := GetGlobalConfig()
380339 if userCurdConfig.StoragePath == "" {
381340 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
382341 }
383342
384 // Create a slice to store the options in the order we want
343 // Create ordered list of options
385344 var optionsList []string
386 for _, value := range options {
387 optionsList = append(optionsList, value)
345 for _, opt := range options {
346 optionsList = append(optionsList, opt.Label)
388347 }
389348
390 // Sort the options alphabetically
391 sort.Strings(optionsList)
392
393 // Add "Quit" options
349 // Add "Quit" option at the end
394350 optionsList = append(optionsList, "Quit")
395
396 // Join all options into a single string, separated by newlines
397351 optionsString := strings.Join(optionsList, "\n")
398352
399 // Prepare the Rofi command
400 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime")
401
402 // Set up pipes for input and output
353 // Prepare and run rofi
354 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
355 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
403356 cmd.Stdin = strings.NewReader(optionsString)
404 var out bytes.Buffer
405 cmd.Stdout = &out
357 var stdout, stderr bytes.Buffer
358 cmd.Stdout = &stdout
359 cmd.Stderr = &stderr
406360
407 // Run the command
408361 err := cmd.Run()
409362 if err != nil {
363 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
364 return SelectionOption{Key: "-1", Label: ""}, nil
365 }
410366 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
411367 }
412368
413 // Get the selected option
414 selected := strings.TrimSpace(out.String())
369 selected := strings.TrimSpace(stdout.String())
415370
416371 // Handle special cases
417372 switch selected {
418373 case "":
419 return SelectionOption{}, fmt.Errorf("no selection made")
374 return SelectionOption{Key: "-1", Label: ""}, nil
420375 case "Quit":
421376 return SelectionOption{Label: "Quit", Key: "-1"}, nil
422377 }
423378
424 // Find the key for the selected value
425 for key, value := range options {
426 if value == selected {
427 return SelectionOption{Label: value, Key: key}, nil
379 // Find the matching SelectionOption
380 for _, opt := range options {
381 if opt.Label == selected {
382 return opt, nil
428383 }
429384 }
430385
431 // If we get here, the selected option wasn't found in the original map
432386 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
433387}
434388
@@ -482,61 +436,42 @@ func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error)
482436}
483437
484438// DynamicSelect displays a simple selection prompt without extra features
485func DynamicSelect(options map[string]string) (SelectionOption, error) {
439func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
486440 if GetGlobalConfig().RofiSelection {
487441 return RofiSelect(options)
488442 }
489443
490 // Create a slice to maintain order
491 var orderedOptions []SelectionOption
444 // Sort options if this contains menu categories
445 for _, opt := range options {
446 if opt.Key == "ALL" || opt.Key == "CURRENT" {
447 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
448 optMap := make(map[string]SelectionOption)
449 for _, opt := range options {
450 optMap[opt.Key] = opt
451 }
492452
493 // If this is a category selection (contains menu items), use the ordered keys
494 if _, hasMenu := options["ALL"]; hasMenu {
495 // Get the menu order from config
496 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
497
498 // Add options in the specified order
499 for _, key := range menuOrder {
500 if value, exists := options[key]; exists {
501 orderedOptions = append(orderedOptions, SelectionOption{
502 Key: key,
503 Label: value,
504 })
453 sorted := make([]SelectionOption, 0, len(options))
454 for _, key := range menuOrder {
455 if opt, exists := optMap[key]; exists {
456 sorted = append(sorted, opt)
457 }
505458 }
506 }
507 } else {
508 // For other selections, preserve the order as passed in
509 // Since Go maps don't preserve insertion order, we need to handle this differently
510 // For now, we'll use the order as it comes from the map iteration
511 // (This will be random, but it's better than alphabetical sorting for search results)
512 for key, value := range options {
513 orderedOptions = append(orderedOptions, SelectionOption{
514 Key: key,
515 Label: value,
516 })
459 options = sorted
460 break
517461 }
518462 }
519463
520464 model := &Model{
521 options: options,
522 filteredKeys: orderedOptions,
465 allOptions: options,
523466 }
467 model.filterOptions() // Initialize filtered options
524468
525 model.filteredKeys = append(model.filteredKeys, SelectionOption{
526 Label: "Quit",
527 Key: "-1",
528 })
529
530 // Create a program with altScreen option turned off to maintain the terminal state
531 // This prevents the terminal from switching to an alternate screen
532469 p := tea.NewProgram(model)
533
534470 finalModel, err := p.Run()
535471 if err != nil {
536472 return SelectionOption{}, err
537473 }
538474
539 // Explicitly reset the terminal state
540475 fmt.Print("\033[?25h") // Show cursor
541476 fmt.Print("\033[?7h") // Enable line wrapping
542477
internal/structs.go +18 −5
@@ -106,14 +106,27 @@ type Entry struct {
106106}
107107
108108type AnimeList struct {
109 Watching []Entry `json:"watching"`
110 Completed []Entry `json:"completed"`
111 Paused []Entry `json:"paused"`
112 Dropped []Entry `json:"dropped"`
113 Planning []Entry `json:"planning"`
109 Watching []Entry `json:"watching"`
110 Completed []Entry `json:"completed"`
111 Paused []Entry `json:"paused"`
112 Dropped []Entry `json:"dropped"`
113 Planning []Entry `json:"planning"`
114 Rewatching []Entry `json:"rewatching"`
114115}
115116
116117type RofiSelectPreview struct {
117118 Title string `json:"title"`
118119 CoverImage string `json:"coverImage"`
119120}
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