Commit a99fd31522

a99fd31522a7fb3385d6b328dd54a180f5698ed6

parent: 4b47c44bf4

Unregistered key

AlpinDale <52078762+AlpinDale@users.noreply.github.com> · 2025-07-03 19:23 UTC
committer: <noreply@github.com>

fix: whitespace getting ignored in search + fuzzy matching (#63)

* Fix anime search with fuzzy matching and full input support
* fix search result filtering

Layout: unified · split

internal/anilist.go +99 −17
@@ -8,6 +8,7 @@ import (
88 "net/http"
99 "os"
1010 "path/filepath"
11 "sort"
1112 "strconv"
1213 "strings"
1314)
@@ -85,13 +86,61 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
8586 return animeMap
8687}
8788
89// fuzzy matching w/ Levenshtein distance
90func levenshtein(a, b string) int {
91 a = strings.ToLower(a)
92 b = strings.ToLower(b)
93 ar, br := []rune(a), []rune(b)
94 alen, blen := len(ar), len(br)
95 if alen == 0 {
96 return blen
97 }
98 if blen == 0 {
99 return alen
100 }
101 matrix := make([][]int, alen+1)
102 for i := range matrix {
103 matrix[i] = make([]int, blen+1)
104 }
105 for i := 0; i <= alen; i++ {
106 matrix[i][0] = i
107 }
108 for j := 0; j <= blen; j++ {
109 matrix[0][j] = j
110 }
111 for i := 1; i <= alen; i++ {
112 for j := 1; j <= blen; j++ {
113 cost := 0
114 if ar[i-1] != br[j-1] {
115 cost = 1
116 }
117 matrix[i][j] = min3(
118 matrix[i-1][j]+1,
119 matrix[i][j-1]+1,
120 matrix[i-1][j-1]+cost,
121 )
122 }
123 }
124 return matrix[alen][blen]
125}
126
127func min3(a, b, c int) int {
128 if a < b && a < c {
129 return a
130 }
131 if b < c {
132 return b
133 }
134 return c
135}
136
88137// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
89138func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
90139 url := "https://graphql.anilist.co"
91140
92141 queryString := `
93142 query ($search: String) {
94 Page(page: 1, perPage: 10) {
143 Page(page: 1, perPage: 50) {
95144 media(search: $search, type: ANIME) {
96145 id
97146 title {
@@ -149,29 +198,45 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
149198 animeList := responseData["data"].Page.Media
150199 animeDict := make(map[string]RofiSelectPreview)
151200
152 // Map titles and cover images to their IDs
201 type scoredAnime struct {
202 id string
203 title string
204 cover string
205 score int
206 }
207 var scored []scoredAnime
153208 for _, anime := range animeList {
154209 idStr := strconv.Itoa(anime.ID)
155210 title := anime.Title.English
156211 if title == "" {
157212 title = anime.Title.Romaji
158213 }
159 animeDict[idStr] = RofiSelectPreview{
160 Title: title,
161 CoverImage: anime.CoverImage.Large,
214 cover := anime.CoverImage.Large
215 score := levenshtein(title, query)
216 scored = append(scored, scoredAnime{idStr, title, cover, score})
217 }
218 sort.Slice(scored, func(i, j int) bool {
219 return scored[i].score < scored[j].score
220 })
221 for i, s := range scored {
222 if i >= 10 {
223 break
224 }
225 animeDict[s.id] = RofiSelectPreview{
226 Title: s.title,
227 CoverImage: s.cover,
162228 }
163229 }
164
165230 return animeDict, nil
166231}
167232
168233// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
169func SearchAnimeAnilist(query, token string) (map[string]string, error) {
234func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
170235 url := "https://graphql.anilist.co"
171236
172237 queryString := `
173238 query ($search: String) {
174 Page(page: 1, perPage: 10) {
239 Page(page: 1, perPage: 50) {
175240 media(search: $search, type: ANIME) {
176241 id
177242 title {
@@ -224,19 +289,36 @@ func SearchAnimeAnilist(query, token string) (map[string]string, error) {
224289 }
225290
226291 animeList := responseData["data"].Page.Media
227 animeDict := make(map[string]string)
292 var results []SelectionOption
228293
229 // Map titles to their IDs as strings
294 type scoredAnime struct {
295 id string
296 title string
297 score int
298 }
299 var scored []scoredAnime
230300 for _, anime := range animeList {
231 idStr := strconv.Itoa(anime.ID) // Convert ID to string
232 if anime.Title.English != "" {
233 animeDict[idStr] = anime.Title.English
234 } else {
235 animeDict[idStr] = anime.Title.Romaji
301 idStr := strconv.Itoa(anime.ID)
302 title := anime.Title.English
303 if title == "" {
304 title = anime.Title.Romaji
236305 }
306 score := levenshtein(title, query)
307 scored = append(scored, scoredAnime{idStr, title, score})
237308 }
238
239 return animeDict, nil
309 sort.Slice(scored, func(i, j int) bool {
310 return scored[i].score < scored[j].score
311 })
312 for i, s := range scored {
313 if i >= 10 {
314 break
315 }
316 results = append(results, SelectionOption{
317 Key: s.id,
318 Label: s.title,
319 })
320 }
321 return results, nil
240322}
241323
242324// Function to get AniList user ID and username
internal/curd.go +7 −5
@@ -14,7 +14,7 @@ import (
1414 "strconv"
1515 "strings"
1616 "time"
17
17 "bufio"
1818 "github.com/gen2brain/beeep"
1919)
2020
@@ -550,8 +550,8 @@ func UpdateCurd(repo, fileName string) error {
550550
551551func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552552 var query string
553 var animeMap map[string]string
554553 var animeMapPreview map[string]RofiSelectPreview
554 var animeOptions []SelectionOption
555555 var err error
556556 var anilistSelectedOption SelectionOption
557557
@@ -564,12 +564,14 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
564564 query = userInput
565565 } else {
566566 CurdOut("Enter the anime name:")
567 fmt.Scanln(&query)
567 reader := bufio.NewReader(os.Stdin)
568 input, _ := reader.ReadString('\n')
569 query = strings.TrimSpace(input)
568570 }
569571 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
570572 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
571573 } else {
572 animeMap, err = SearchAnimeAnilist(query, user.Token)
574 animeOptions, err = SearchAnimeAnilist(query, user.Token)
573575 }
574576 if err != nil {
575577 Log(fmt.Sprintf("Failed to search anime: %v", err))
@@ -578,7 +580,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
578580 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
579581 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
580582 } else {
581 anilistSelectedOption, err = DynamicSelect(animeMap)
583 anilistSelectedOption, err = DynamicSelectFromSlice(animeOptions)
582584 }
583585
584586 if anilistSelectedOption.Key == "-1" {
internal/selection_menu.go +83 −19
@@ -25,14 +25,16 @@ type SelectionOption struct {
2525
2626// Model represents the application state for the selection prompt
2727type 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 // Add this field
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
3638}
3739
3840var (
@@ -183,21 +185,31 @@ func (m Model) visibleItemsCount() int {
183185func (m *Model) filterOptions() {
184186 m.filteredKeys = []SelectionOption{}
185187
186 for key, value := range m.options {
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 }
194 }
195 } else {
196 // map-based filtering
197 for key, value := range m.options {
187198 // 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)) {
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)) {
190204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
191205 }
192 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
193 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
194206 }
195 }
196207
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 })
208 // Sort the filtered options alphabetically
209 sort.Slice(m.filteredKeys, func(i, j int) bool {
210 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
211 })
212 }
201213
202214 // Add "Add new anime" option if enabled
203215 if m.addNewOption {
@@ -420,6 +432,55 @@ func RofiSelect(options map[string]string) (SelectionOption, error) {
420432 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
421433}
422434
435func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
436 if GetGlobalConfig().RofiSelection {
437 optionsMap := make(map[string]string)
438 for _, option := range options {
439 optionsMap[option.Key] = option.Label
440 }
441 return RofiSelect(optionsMap)
442 }
443
444 // slice to maintain order
445 var orderedOptions []SelectionOption
446 for _, option := range options {
447 orderedOptions = append(orderedOptions, option)
448 }
449
450 model := &Model{
451 options: make(map[string]string), // empty map since we're using slice
452 filteredKeys: orderedOptions,
453 useSliceMode: true, // slice-based filtering
454 originalOptions: orderedOptions, // store original options for filtering
455 }
456
457 model.filteredKeys = append(model.filteredKeys, SelectionOption{
458 Label: "Quit",
459 Key: "-1",
460 })
461
462 p := tea.NewProgram(model)
463
464 finalModel, err := p.Run()
465 if err != nil {
466 return SelectionOption{}, err
467 }
468
469 // resetting terminal state
470 fmt.Print("\033[?25h") // show cursor
471 fmt.Print("\033[?7h") // line wrapping
472
473 finalSelectionModel, ok := finalModel.(*Model)
474 if !ok {
475 return SelectionOption{}, fmt.Errorf("unexpected model type")
476 }
477
478 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
479 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
480 }
481 return SelectionOption{}, nil
482}
483
423484// DynamicSelect displays a simple selection prompt without extra features
424485func DynamicSelect(options map[string]string) (SelectionOption, error) {
425486 if GetGlobalConfig().RofiSelection {
@@ -444,7 +505,10 @@ func DynamicSelect(options map[string]string) (SelectionOption, error) {
444505 }
445506 }
446507 } else {
447 // For other selections, maintain alphabetical order
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)
448512 for key, value := range options {
449513 orderedOptions = append(orderedOptions, SelectionOption{
450514 Key: key,