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 (
55 "fmt"
66 "io"
77 "net/http"
8 "net/url"
89 "os"
910 "path/filepath"
10 "net/url"
1111 // "strings"
1212)
1313
@@ -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 +8 −5
@@ -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 +75 −48
@@ -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 {
@@ -299,42 +299,57 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
299299 }
300300 }
301301 } else {
302 animeListMap = make(map[string]string)
302 animeListOptions = make([]SelectionOption, 0)
303303 // Include anime from all categories
304304 for _, entry := range user.AnimeList.Watching {
305305 title := entry.Media.Title.English
306306 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
307307 title = entry.Media.Title.Romaji
308308 }
309 animeListMap[strconv.Itoa(entry.Media.ID)] = title
309 animeListOptions = append(animeListOptions, SelectionOption{
310 Key: strconv.Itoa(entry.Media.ID),
311 Label: title,
312 })
310313 }
311314 for _, entry := range user.AnimeList.Completed {
312315 title := entry.Media.Title.English
313316 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314317 title = entry.Media.Title.Romaji
315318 }
316 animeListMap[strconv.Itoa(entry.Media.ID)] = title
319 animeListOptions = append(animeListOptions, SelectionOption{
320 Key: strconv.Itoa(entry.Media.ID),
321 Label: title,
322 })
317323 }
318324 for _, entry := range user.AnimeList.Paused {
319325 title := entry.Media.Title.English
320326 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
321327 title = entry.Media.Title.Romaji
322328 }
323 animeListMap[strconv.Itoa(entry.Media.ID)] = title
329 animeListOptions = append(animeListOptions, SelectionOption{
330 Key: strconv.Itoa(entry.Media.ID),
331 Label: title,
332 })
324333 }
325334 for _, entry := range user.AnimeList.Dropped {
326335 title := entry.Media.Title.English
327336 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
328337 title = entry.Media.Title.Romaji
329338 }
330 animeListMap[strconv.Itoa(entry.Media.ID)] = title
339 animeListOptions = append(animeListOptions, SelectionOption{
340 Key: strconv.Itoa(entry.Media.ID),
341 Label: title,
342 })
331343 }
332344 for _, entry := range user.AnimeList.Planning {
333345 title := entry.Media.Title.English
334346 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
335347 title = entry.Media.Title.Romaji
336348 }
337 animeListMap[strconv.Itoa(entry.Media.ID)] = title
349 animeListOptions = append(animeListOptions, SelectionOption{
350 Key: strconv.Itoa(entry.Media.ID),
351 Label: title,
352 })
338353 }
339354 }
340355
@@ -343,7 +358,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
343358 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
344359 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
345360 } else {
346 selectedAnime, err = DynamicSelect(animeListMap)
361 selectedAnime, err = DynamicSelect(animeListOptions)
347362 }
348363 if err != nil {
349364 Log(fmt.Sprintf("Failed to select anime: %v", err))
@@ -369,12 +384,13 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
369384 ClearScreen()
370385 switch updateSelection.Key {
371386 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",
387 categories := []SelectionOption{
388 {Key: "CURRENT", Label: "Currently Watching"},
389 {Key: "COMPLETED", Label: "Completed"},
390 {Key: "PAUSED", Label: "On Hold"},
391 {Key: "DROPPED", Label: "Dropped"},
392 {Key: "PLANNING", Label: "Plan to Watch"},
393 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
378394 }
379395
380396 currentStatus := "None"
@@ -550,7 +566,7 @@ func UpdateCurd(repo, fileName string) error {
550566
551567func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552568 var query string
553 var animeMap map[string]string
569 var animeOptions []SelectionOption
554570 var animeMapPreview map[string]RofiSelectPreview
555571 var err error
556572 var anilistSelectedOption SelectionOption
@@ -578,7 +594,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
578594 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
579595 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
580596 } else {
581 anilistSelectedOption, err = DynamicSelect(animeMap)
597 anilistSelectedOption, err = DynamicSelect(animeOptions)
582598 }
583599
584600 if anilistSelectedOption.Key == "-1" {
@@ -596,12 +612,13 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
596612 }
597613
598614 // Add category selection before adding to list
599 categories := map[string]string{
600 "CURRENT": "Currently Watching",
601 "COMPLETED": "Completed",
602 "PAUSED": "On Hold",
603 "DROPPED": "Dropped",
604 "PLANNING": "Plan to Watch",
615 categories := []SelectionOption{
616 {Key: "CURRENT", Label: "Currently Watching"},
617 {Key: "COMPLETED", Label: "Completed"},
618 {Key: "PAUSED", Label: "On Hold"},
619 {Key: "DROPPED", Label: "Dropped"},
620 {Key: "PLANNING", Label: "Plan to Watch"},
621 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
605622 }
606623
607624 ClearScreen()
@@ -649,7 +666,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
649666 var anilistUserDataPreview map[string]interface{}
650667
651668 // Filter anime list based on selected category
652 var animeListMap map[string]string
669 var animeListOptions []SelectionOption
653670 var animeListMapPreview map[string]RofiSelectPreview
654671
655672 // Get user id, username and Anime list
@@ -716,11 +733,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
716733 }
717734 } else {
718735 // 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)
720741
721 // Select category using DynamicSelect
722 var err error
723 categorySelection, err = DynamicSelect(categories)
724742 if err != nil {
725743 Log(fmt.Sprintf("Failed to select category: %v", err))
726744 ExitCurd(fmt.Errorf("Failed to select category"))
@@ -758,13 +776,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
758776 }
759777 }
760778 } else {
761 animeListMap = make(map[string]string)
779 animeListOptions = make([]SelectionOption, 0)
762780 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
763781 title := entry.Media.Title.English
764782 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
765783 title = entry.Media.Title.Romaji
766784 }
767 animeListMap[strconv.Itoa(entry.Media.ID)] = title
785 animeListOptions = append(animeListOptions, SelectionOption{
786 Key: strconv.Itoa(entry.Media.ID),
787 Label: title,
788 })
768789 }
769790 }
770791 }
@@ -796,10 +817,13 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
796817 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
797818 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
798819 } else {
799 // Add "Add new anime" option to the map
800 animeListMap["add_new"] = "Add new anime"
820 // Add "Add new anime" option to the slice
821 animeListOptions = append(animeListOptions, SelectionOption{
822 Key: "add_new",
823 Label: "Add new anime",
824 })
801825
802 anilistSelectedOption, err = DynamicSelect(animeListMap)
826 anilistSelectedOption, err = DynamicSelect(animeListOptions)
803827 }
804828 if err != nil {
805829 Log(fmt.Sprintf("Error selecting anime: %v", err))
@@ -836,7 +860,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
836860 anime.Title = selectedAnilistAnime.Media.Title
837861 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
838862 anime.Ep.Number = selectedAnilistAnime.Progress + 1
839 var animeList map[string]string
863 var animeList []SelectionOption
840864 userQuery = anime.Title.Romaji
841865
842866 // if anime not found in database, find it in animeList
@@ -900,9 +924,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
900924
901925 if !isInWatchingList {
902926 // Create options for the prompt
903 options := map[string]string{
904 "yes": "Add to watching list",
905 "no": "Continue without adding",
927 options := []SelectionOption{
928 {Key: "yes", Label: "Add to watching list"},
929 {Key: "no", Label: "Continue without adding"},
906930 }
907931
908932 var selectedOption SelectionOption
@@ -970,10 +994,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
970994 if err != nil {
971995 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
972996 } else {
973 for allanimeId, label := range animeList {
974 if allanimeId == anime.AllanimeId {
997 for _, option := range animeList {
998 if option.Key == anime.AllanimeId {
975999 // 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 {
9771001 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
9781002 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
9791003 break
@@ -1211,6 +1235,7 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
12111235 allEntries = append(allEntries, list.Paused...)
12121236 allEntries = append(allEntries, list.Dropped...)
12131237 allEntries = append(allEntries, list.Planning...)
1238 allEntries = append(allEntries, list.Rewatching...)
12141239 return allEntries
12151240 case "CURRENT":
12161241 return list.Watching
@@ -1222,6 +1247,8 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
12221247 return list.Dropped
12231248 case "PLANNING":
12241249 return list.Planning
1250 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1251 return list.Rewatching
12251252 default:
12261253 return []Entry{}
12271254 }
@@ -1238,8 +1265,8 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) {
12381265 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
12391266
12401267 // Create options for the selection
1241 options := map[string]string{
1242 "yes": "Yes, start next episode",
1268 options := []SelectionOption{
1269 {Key: "yes", Label: "Yes, start next episode"},
12431270 // "no": "No, quit",
12441271 }
12451272
@@ -1379,7 +1406,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
13791406 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
13801407
13811408 // 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"}})
13831410 if err != nil {
13841411 ExitCurd(err)
13851412 }
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 +82 −132
@@ -17,22 +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
2922 filter string
3023 filteredKeys []SelectionOption
24 allOptions []SelectionOption
3125 selected int
3226 terminalWidth int
3327 terminalHeight int
34 scrollOffset int // Track the topmost visible item
35 addNewOption bool // Add this field
28 scrollOffset int
29 addNewOption bool
3630}
3731
3832var (
@@ -181,40 +175,36 @@ func (m Model) visibleItemsCount() int {
181175
182176// filterOptions filters and sorts options based on the search term
183177func (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 }
185184
186 for key, value := range m.options {
187 // When the key is " ", compare and display using the value instead
188 if key == " " {
189 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
190 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
191 }
192 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
193 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
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
194191 }
195192 }
196193
197 // Sort the filtered options alphabetically
198 sort.Slice(m.filteredKeys, func(i, j int) bool {
199 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
200 })
194 if !isMenu {
195 sort.Slice(m.filteredKeys, func(i, j int) bool {
196 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
197 })
198 }
201199
202200 // Add "Add new anime" option if enabled
203201 if m.addNewOption {
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{
205 Label: "Add new anime",
206 Key: "add_new",
207 })
202 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
208203 }
209
210 m.filteredKeys = append(m.filteredKeys, SelectionOption{
211 Label: "Quit",
212 Key: "-1",
213 })
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
214205}
215206
216207func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
217 // Pre-download first 14 images in background
218208 go preDownloadImages(options, 14)
219209
220210 userCurdConfig := GetGlobalConfig()
@@ -222,62 +212,46 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
222212 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
223213 }
224214
225 // Prepare Rofi input with anime titles and their cached image paths
226215 var rofiInput strings.Builder
227 for _, option := range options {
228 // Download and get cache path for the image
229 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)
230221 if err != nil {
231222 Log(fmt.Sprintf("Error caching image: %v", err))
232223 continue
233224 }
234
235 // Format: "Title\x00icon\x1f/path/to/cached/image\n"
236 // This tells Rofi to use the image as an icon for this entry
237 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 })
238230 }
239231
240 // Add "Add new anime" and "Quit" options
241232 if addnewoption {
242233 rofiInput.WriteString("Add new anime\n")
243234 }
244235 rofiInput.WriteString("Quit\n")
245236
246 // Get the absolute path to the rasi config
237 // Run rofi
247238 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
248
249 // Create the command with explicit arguments
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())
239 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
240 cmd.Stdin = strings.NewReader(rofiInput.String())
264241 var stdout, stderr bytes.Buffer
265 rofiCmd.Stdout = &stdout
266 rofiCmd.Stderr = &stderr
242 cmd.Stdout = &stdout
243 cmd.Stderr = &stderr
267244
268 // Run the command
269 err := rofiCmd.Run()
270 if err != nil {
271 // Log both stdout and stderr for debugging
245 if err := cmd.Run(); err != nil {
272246 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
273247 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
274248 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
275249 }
276250
277 selectedTitle := strings.TrimSpace(stdout.String())
251 selected := strings.TrimSpace(stdout.String())
278252
279253 // Handle special cases
280 switch selectedTitle {
254 switch selected {
281255 case "":
282256 return SelectionOption{}, fmt.Errorf("no selection made")
283257 case "Add new anime":
@@ -286,13 +260,10 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
286260 return SelectionOption{Label: "Quit", Key: "-1"}, nil
287261 }
288262
289 // Find the selected anime in options
290 for id, option := range options {
291 if option.Title == selectedTitle {
292 return SelectionOption{
293 Label: option.Title,
294 Key: id,
295 }, nil
263 // Find matching option
264 for _, opt := range selectionOptions {
265 if opt.Label == selected {
266 return opt, nil
296267 }
297268 }
298269
@@ -363,116 +334,95 @@ func showCachedImagePreview(imageURL string) error {
363334 return nil
364335}
365336
366func RofiSelect(options map[string]string) (SelectionOption, error) {
337func RofiSelect(options []SelectionOption) (SelectionOption, error) {
367338 userCurdConfig := GetGlobalConfig()
368339 if userCurdConfig.StoragePath == "" {
369340 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
370341 }
371342
372 // Create a slice to store the options in the order we want
343 // Create ordered list of options
373344 var optionsList []string
374 for _, value := range options {
375 optionsList = append(optionsList, value)
345 for _, opt := range options {
346 optionsList = append(optionsList, opt.Label)
376347 }
377348
378 // Sort the options alphabetically
379 sort.Strings(optionsList)
380
381 // Add "Quit" options
349 // Add "Quit" option at the end
382350 optionsList = append(optionsList, "Quit")
383
384 // Join all options into a single string, separated by newlines
385351 optionsString := strings.Join(optionsList, "\n")
386352
387 // Prepare the Rofi command
388 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime")
389
390 // 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")
391356 cmd.Stdin = strings.NewReader(optionsString)
392 var out bytes.Buffer
393 cmd.Stdout = &out
357 var stdout, stderr bytes.Buffer
358 cmd.Stdout = &stdout
359 cmd.Stderr = &stderr
394360
395 // Run the command
396361 err := cmd.Run()
397362 if err != nil {
363 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
364 return SelectionOption{Key: "-1", Label: ""}, nil
365 }
398366 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
399367 }
400368
401 // Get the selected option
402 selected := strings.TrimSpace(out.String())
369 selected := strings.TrimSpace(stdout.String())
403370
404371 // Handle special cases
405372 switch selected {
406373 case "":
407 return SelectionOption{}, fmt.Errorf("no selection made")
374 return SelectionOption{Key: "-1", Label: ""}, nil
408375 case "Quit":
409376 return SelectionOption{Label: "Quit", Key: "-1"}, nil
410377 }
411378
412 // Find the key for the selected value
413 for key, value := range options {
414 if value == selected {
415 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
416383 }
417384 }
418385
419 // If we get here, the selected option wasn't found in the original map
420386 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
421387}
422388
423389// DynamicSelect displays a simple selection prompt without extra features
424func DynamicSelect(options map[string]string) (SelectionOption, error) {
390func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
425391 if GetGlobalConfig().RofiSelection {
426392 return RofiSelect(options)
427393 }
428394
429 // Create a slice to maintain order
430 var orderedOptions []SelectionOption
431
432 // If this is a category selection (contains menu items), use the ordered keys
433 if _, hasMenu := options["ALL"]; hasMenu {
434 // Get the menu order from config
435 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
395 // Sort options if this contains menu categories
396 for _, opt := range options {
397 if opt.Key == "ALL" || opt.Key == "CURRENT" {
398 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
399 optMap := make(map[string]SelectionOption)
400 for _, opt := range options {
401 optMap[opt.Key] = opt
402 }
436403
437 // Add options in the specified order
438 for _, key := range menuOrder {
439 if value, exists := options[key]; exists {
440 orderedOptions = append(orderedOptions, SelectionOption{
441 Key: key,
442 Label: value,
443 })
404 sorted := make([]SelectionOption, 0, len(options))
405 for _, key := range menuOrder {
406 if opt, exists := optMap[key]; exists {
407 sorted = append(sorted, opt)
408 }
444409 }
445 }
446 } else {
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 })
410 options = sorted
411 break
453412 }
454413 }
455414
456415 model := &Model{
457 options: options,
458 filteredKeys: orderedOptions,
416 allOptions: options,
459417 }
418 model.filterOptions() // Initialize filtered options
460419
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
468420 p := tea.NewProgram(model)
469
470421 finalModel, err := p.Run()
471422 if err != nil {
472423 return SelectionOption{}, err
473424 }
474425
475 // Explicitly reset the terminal state
476426 fmt.Print("\033[?25h") // Show cursor
477427 fmt.Print("\033[?7h") // Enable line wrapping
478428
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