Commit e8f271e504

e8f271e504d7bd4793bd4e2625871b6512cc3b34

parent: b08e4daf8f

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-18 09:12 UTC

working stuff

Layout: unified · split

cmd/curd/main.go +90 −2
@@ -1,7 +1,95 @@
11package main
22
3import "fmt"
3import (
4 "fmt"
5 "github.com/wraient/curd/internal"
6 "os"
7)
8
9type Title struct {
10 Romanji_title string
11 English_title string
12 Japanese_title string
13}
14
15type Anime struct {
16 Tit Title
17 Ep Episode
18 Total_episodes int
19 Mal_id int
20 Allanime_id string
21}
22
23type SkipTimes struct {
24 Op int
25 Ed int
26}
27
28type Episode struct {
29 Tit Title
30 Number int
31 Skip_times SkipTimes
32 links []string
33 Is_filler bool
34 Is_recap bool
35 Aired string
36 Synopsis string
37}
438
539func main(){
6 fmt.Println("Great future.")
40 internal.ClearScreen()
41 defer internal.RestoreScreen()
42
43 var userQuery string
44 logFile := "debug.log"
45
46 fmt.Println("Enter anime: ")
47 fmt.Scanln(&userQuery) // Scan input until a newline
48 // fmt.Println("You entered:", input)
49 animeList, err := internal.SearchAnime(string(userQuery), "sub")
50
51 if err != nil {
52 fmt.Println("Failed to get anime list")
53 os.Exit(1)
54 }
55
56 if len(animeList) == 0 {
57 fmt.Println("No results found.")
58 os.Exit(0)
59 }
60 if len(animeList) == 1 {
61 internal.Log("one result", logFile)
62 internal.Log(animeList, logFile)
63 }
64
65 selectedOption, err := internal.DynamicSelect(animeList)
66
67 // Output the selected anime and its internal key
68 if err != nil {
69 fmt.Println("No anime Selected")
70 os.Exit(0)
71 }
72
73 internal.Log(animeList, logFile)
74 internal.Log(selectedOption, logFile)
75
76 episodeList, err := internal.EpisodesList(selectedOption.Key, "sub")
77
78 if err != nil{
79 fmt.Println("No episode list found")
80 }
81
82 internal.Log(episodeList, logFile)
83 var episodeNumber string
84 fmt.Printf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])
85 fmt.Scanln(&episodeNumber)
86
87 link, err := internal.GetEpisodeURL(internal.GetDefaultAllanimeConfig(), selectedOption.Key, episodeNumber)
88
89 if err != nil {
90 fmt.Println("Failed to get episode link")
91 }
92
93 internal.Log(link, logFile)
94
795}
\ No newline at end of file
go.mod added +24
@@ -0,0 +1,24 @@
1module github.com/wraient/curd
2
3go 1.23.2
4
5require github.com/charmbracelet/bubbletea v1.1.1
6
7require (
8 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
9 github.com/charmbracelet/lipgloss v0.13.0 // indirect
10 github.com/charmbracelet/x/ansi v0.2.3 // indirect
11 github.com/charmbracelet/x/term v0.2.0 // indirect
12 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
13 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
14 github.com/mattn/go-isatty v0.0.20 // indirect
15 github.com/mattn/go-localereader v0.0.1 // indirect
16 github.com/mattn/go-runewidth v0.0.15 // indirect
17 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
18 github.com/muesli/cancelreader v0.2.2 // indirect
19 github.com/muesli/termenv v0.15.2 // indirect
20 github.com/rivo/uniseg v0.4.7 // indirect
21 golang.org/x/sync v0.8.0 // indirect
22 golang.org/x/sys v0.24.0 // indirect
23 golang.org/x/text v0.14.0 // indirect
24)
go.sum added +37
@@ -0,0 +1,37 @@
1github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
2github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
3github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY=
4github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4=
5github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw=
6github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY=
7github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY=
8github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
9github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=
10github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
11github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
12github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
13github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
14github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
15github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
16github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
17github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
18github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
19github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
20github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
21github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
22github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
23github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
24github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
25github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
26github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
27github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
28github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
29github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
30golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
31golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
32golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
33golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
34golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
35golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
36golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
37golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
internal/anime_list.go +26 −41
@@ -1,42 +1,41 @@
1package main
1package internal
22
33import (
44 "encoding/json"
55 "fmt"
66 "io/ioutil"
77 "net/http"
8 "os"
9 "strings"
8 // "strings"
109)
1110
12type Anime struct {
11type anime struct {
1312 ID string `json:"_id"`
1413 Name string `json:"name"`
1514 AvailableEpisodes interface{} `json:"availableEpisodes"`
1615}
1716
18type Response struct {
17type response struct {
1918 Data struct {
2019 Shows struct {
21 Edges []Anime `json:"edges"`
20 Edges []anime `json:"edges"`
2221 } `json:"shows"`
2322 } `json:"data"`
2423}
2524
26func main() {
27 // Get environment variables
28 mode := getEnv("ANI_CLI_MODE", "sub")
25// func main() {
26// // Get environment variables
27// mode := "sub"
2928
30 // Query for the anime (from a file in this example)
31 query := "One piece"
29// // Query for the anime (from a file in this example)
30// query := "Death note"
3231
33 // Search anime
34 animeList := searchAnime(string(query), mode)
35 fmt.Println(animeList)
36}
32// // Search anime
33// animeList := searchAnime(string(query), mode)
34// fmt.Println(animeList)
35// }
3736
3837// searchAnime performs the API call and fetches anime information
39func searchAnime(query, mode string) string {
38func SearchAnime(query, mode string) (map[string]string, error) {
4039 const (
4140 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
4241 allanimeRef = "https://allanime.to"
@@ -44,6 +43,9 @@ func searchAnime(query, mode string) string {
4443 allanimeAPI = "https://api." + allanimeBase + "/api"
4544 )
4645
46 // Format and return the anime list
47 animeList := make(map[string]string)
48
4749 searchGql := `query( $search: SearchInput $limit: Int $page: Int $translationType: VaildTranslationTypeEnumType $countryOrigin: VaildCountryOriginEnumType ) { shows( search: $search limit: $limit page: $page translationType: $translationType countryOrigin: $countryOrigin ) { edges { _id name availableEpisodes __typename } } }`
4850
4951 // Build the request URL
@@ -53,7 +55,7 @@ func searchAnime(query, mode string) string {
5355 req, err := http.NewRequest("GET", url, nil)
5456 if err != nil {
5557 fmt.Println("Error creating HTTP request:", err)
56 return ""
58 return animeList, err
5759 }
5860 req.Header.Set("User-Agent", agent)
5961 req.Header.Set("Referer", allanimeRef)
@@ -62,26 +64,24 @@ func searchAnime(query, mode string) string {
6264 resp, err := client.Do(req)
6365 if err != nil {
6466 fmt.Println("Error making HTTP request:", err)
65 return ""
67 return animeList, err
6668 }
6769 defer resp.Body.Close()
6870
6971 body, err := ioutil.ReadAll(resp.Body)
7072 if err != nil {
7173 fmt.Println("Error reading response body:", err)
72 return ""
74 return animeList, err
7375 }
7476
7577 // Parse the JSON response
76 var response Response
78 var response response
7779 err = json.Unmarshal(body, &response)
7880 if err != nil {
7981 fmt.Println("Error parsing JSON:", err)
80 return ""
82 return animeList, err
8183 }
8284
83 // Format and return the anime list
84 var animeList strings.Builder
8585 for _, anime := range response.Data.Shows.Edges {
8686 // availableEpisodes, _ := anime.AvailableEpisodes.Int64() // Converts json.Number to int64
8787
@@ -97,23 +97,8 @@ func searchAnime(query, mode string) string {
9797 default:
9898 episodesStr = "Unknown"
9999 }
100
101
102 animeList.WriteString(fmt.Sprintf("%s\t%s (%s episodes)\n", anime.ID, anime.Name, episodesStr))
103
104 // In the formatting part
105 // animeList.WriteString(fmt.Sprintf("%s\t%s (%d episodes)NEWLINEFROMHERE\n", anime.ID, anime.Name, availableEpisodes))
106
107 // animeList.WriteString(fmt.Sprintf("%s\t%s (%d episodes)NEWLINEFROMHERE\n", anime.ID, anime.Name, anime.AvailableEpisodes))
100 animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", anime.Name, episodesStr)
101 // animeList.WriteString(fmt.Sprintf("%s\t%s (%s episodes)\n", anime.ID, anime.Name, episodesStr))
108102 }
109 return animeList.String()
103 return animeList, nil
110104}
111
112// getEnv returns the value of an environment variable or a default value if it's not set
113func getEnv(key, defaultValue string) string {
114 value := os.Getenv(key)
115 if value == "" {
116 return defaultValue
117 }
118 return value
119}
\ No newline at end of file
internal/curd.go added +54
@@ -0,0 +1,54 @@
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "runtime"
8 "time"
9 // "log"
10)
11
12// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
13func Log(data interface{}, logFile string) error {
14 // Open or create the log file
15 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
16 if err != nil {
17 return err
18 }
19 defer file.Close() // Ensure the file is closed when done
20
21 // Attempt to marshal the data into JSON
22 jsonData, err := json.Marshal(data)
23 if err != nil {
24 return err
25 }
26
27 // Get the caller information
28 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
29 if !ok {
30 return fmt.Errorf("unable to get caller information")
31 }
32
33 // Log the current time and the JSON representation along with caller info
34 currentTime := time.Now().Format("2006/01/02 15:04:05")
35 logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
36 _, err = fmt.Fprint(file, logMessage) // Write to the file
37 if err != nil {
38 return err
39 }
40
41 return nil
42}
43
44
45// ClearScreen clears the terminal screen and saves the state
46func ClearScreen() {
47 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
48 fmt.Print("\033[H") // Move cursor to the top left
49}
50
51// RestoreScreen restores the original terminal state
52func RestoreScreen() {
53 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
54}
\ No newline at end of file
internal/episode_list.go +21 −21
@@ -1,4 +1,4 @@
1package main
1package internal
22
33import (
44 "encoding/json"
@@ -7,10 +7,9 @@ import (
77 "net/http"
88 "sort"
99 "strconv"
10 "strings"
1110)
1211
13type EpisodesResponse struct {
12type episodesResponse struct {
1413 Data struct {
1514 Show struct {
1615 ID string `json:"_id"`
@@ -19,20 +18,20 @@ type EpisodesResponse struct {
1918 } `json:"data"`
2019}
2120
22func main() {
23 // Get environment variables
24 // Read the ID from the file
25 id := "ReooPAxPMsHM4KPMY"
21// func main() {
22// // Get environment variables
23// // Read the ID from the file
24// id := "ReooPAxPMsHM4KPMY"
2625
27 // Fetch episodes list
28 episodeList := episodesList(string(id), "sub")
26// // Fetch episodes list
27// episodeList := episodesList(string(id), "sub")
2928
30 // Write the episode list to a file
31 fmt.Println(episodeList)
32}
29// // Write the episode list to a file
30// fmt.Println(episodeList)
31// }
3332
3433// episodesList performs the API call and fetches the episodes list
35func episodesList(showID, mode string) string {
34func EpisodesList(showID, mode string) ([]string, error) {
3635 const (
3736 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
3837 allanimeRef = "https://allanime.to"
@@ -44,12 +43,13 @@ func episodesList(showID, mode string) string {
4443
4544 // Build the request URL
4645 url := fmt.Sprintf("%s?variables={\"showId\":\"%s\"}&query=%s", allanimeAPI, showID, episodesListGql)
46 episodes := []string{}
4747
4848 // Make the HTTP request
4949 req, err := http.NewRequest("GET", url, nil)
5050 if err != nil {
5151 fmt.Println("Error creating HTTP request:", err)
52 return ""
52 return episodes, err
5353 }
5454 req.Header.Set("User-Agent", agent)
5555 req.Header.Set("Referer", allanimeRef)
@@ -58,27 +58,27 @@ func episodesList(showID, mode string) string {
5858 resp, err := client.Do(req)
5959 if err != nil {
6060 fmt.Println("Error making HTTP request:", err)
61 return ""
61 return episodes, err
6262 }
6363 defer resp.Body.Close()
6464
6565 body, err := ioutil.ReadAll(resp.Body)
6666 if err != nil {
6767 fmt.Println("Error reading response body:", err)
68 return ""
68 return episodes, err
6969 }
7070
7171 // Parse the JSON response
72 var response EpisodesResponse
72 var response episodesResponse
7373 err = json.Unmarshal(body, &response)
7474 if err != nil {
7575 fmt.Println("Error parsing JSON:", err)
76 return ""
76 return episodes, err
7777 }
7878
7979 // Extract and sort the episodes
80 episodes := extractEpisodes(response.Data.Show.AvailableEpisodesDetail, mode)
81 return strings.Join(episodes, "\n")
80 episodes = extractEpisodes(response.Data.Show.AvailableEpisodesDetail, mode)
81 return episodes, nil
8282}
8383
8484// extractEpisodes extracts the episodes list from the availableEpisodesDetail field
@@ -100,7 +100,7 @@ func extractEpisodes(availableEpisodesDetail map[string]interface{}, mode string
100100 // Convert to string and return
101101 var episodesStr []string
102102 for _, ep := range episodes {
103 episodesStr = append(episodesStr, fmt.Sprintf("%.1f", ep))
103 episodesStr = append(episodesStr, fmt.Sprintf("%v", ep))
104104 }
105105 return episodesStr
106106}
internal/episode_url.go +30 −31
@@ -1,4 +1,4 @@
1package main
1package internal
22
33import (
44 "encoding/json"
@@ -6,13 +6,12 @@ import (
66 "io/ioutil"
77 "net/http"
88 "net/url"
9 "os"
109 "regexp"
1110 "strings"
1211 "unicode"
1312)
1413
15type Config struct {
14type config struct {
1615 Agent string
1716 AllanimeRefr string
1817 AllanimeBase string
@@ -21,7 +20,7 @@ type Config struct {
2120 Quality string
2221}
2322
24type AllanimeResponse struct {
23type allanimeResponse struct {
2524 Data struct {
2625 Episode struct {
2726 SourceUrls []struct {
@@ -31,13 +30,13 @@ type AllanimeResponse struct {
3130 } `json:"data"`
3231}
3332
34func getDefaultConfig() Config {
35 return Config{
33func GetDefaultAllanimeConfig() config {
34 return config{
3635 Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0",
3736 AllanimeRefr: "https://allanime.to",
3837 AllanimeBase: "allanime.day",
3938 AllanimeAPI: "https://api.allanime.day",
40 Mode: "dub",
39 Mode: "sub",
4140 Quality: "best",
4241 }
4342}
@@ -125,7 +124,7 @@ func extractLinks(provider_id string) map[string]interface{} {
125124// Returns:
126125// - []string: a list of links for specified episode.
127126// - error: an error if the episode is not found or if there is an issue during the search.
128func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
127func GetEpisodeURL(config config, id, epNo string) ([]string, error) {
129128 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
130129
131130 variables := map[string]string{
@@ -168,7 +167,7 @@ func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
168167 responseStr := string(body)
169168
170169 // Unmarshal the JSON data into the struct
171 var response AllanimeResponse
170 var response allanimeResponse
172171 err = json.Unmarshal([]byte(responseStr), &response)
173172 if err != nil {
174173 fmt.Println("Error parsing JSON: ", err)
@@ -198,25 +197,25 @@ func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
198197 return allinks, nil
199198}
200199
201func main() {
202 config := getDefaultConfig()
203
204 id := "ReooPAxPMsHM4KPMY" // One piece
205 // id := "RezHft5pjutwWcE3B" // Death note
206 epNo := "945"
207
208 links, err := getEpisodeURL(config, id, epNo)
209 if err != nil {
210 fmt.Printf("Error: %v\n", err)
211 if strings.Contains(err.Error(), "no source URLs found") {
212 fmt.Println("Episode not released!")
213 }
214 os.Exit(1)
215 }
216
217 // Print all found links
218 // fmt.Println("links:", links)
219 for _, link := range links {
220 fmt.Println(link)
221 }
222}
\ No newline at end of file
200// func main() {
201// config := getDefaultConfig()
202
203// id := "ReooPAxPMsHM4KPMY" // One piece
204// // id := "RezHft5pjutwWcE3B" // Death note
205// epNo := "945"
206
207// links, err := getEpisodeURL(config, id, epNo)
208// if err != nil {
209// fmt.Printf("Error: %v\n", err)
210// if strings.Contains(err.Error(), "no source URLs found") {
211// fmt.Println("Episode not released!")
212// }
213// os.Exit(1)
214// }
215
216// // Print all found links
217// // fmt.Println("links:", links)
218// for _, link := range links {
219// fmt.Println(link)
220// }
221// }
\ No newline at end of file
internal/selection_menu.go added +123
@@ -0,0 +1,123 @@
1package internal
2
3import (
4 "fmt"
5 "strings"
6 tea "github.com/charmbracelet/bubbletea"
7)
8
9// SelectionOption holds the label and the internal key
10type SelectionOption struct {
11 Label string
12 Key string
13}
14
15// Model represents the application state for the selection prompt
16type Model struct {
17 options map[string]string // Now using a map for options
18 filter string
19 filteredKeys []SelectionOption
20 selected int
21}
22
23// Init initializes the model
24func (m Model) Init() tea.Cmd {
25 return nil
26}
27
28// Update handles user input and updates the model
29func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
30 switch msg := msg.(type) {
31 case tea.KeyMsg:
32 switch msg.String() {
33 case "ctrl+c", "q":
34 return m, tea.Quit
35 case "backspace":
36 if len(m.filter) > 0 {
37 m.filter = m.filter[:len(m.filter)-1]
38 }
39 case "down":
40 if m.selected < len(m.filteredKeys)-1 {
41 m.selected++
42 }
43 case "up":
44 if m.selected > 0 {
45 m.selected--
46 }
47 case "enter":
48 return m, tea.Quit // Or return the selected option
49 default:
50 if msg.String() != "" {
51 m.filter += msg.String()
52 }
53 }
54 m.filterOptions()
55 }
56 return m, nil
57}
58
59// View renders the UI
60func (m Model) View() string {
61 var b strings.Builder
62
63 b.WriteString("Search (Press Ctrl+C to quit):\n\n")
64 b.WriteString("Filter: " + m.filter + "\n\n")
65
66 if len(m.filteredKeys) == 0 {
67 b.WriteString("No matches found.\n")
68 } else {
69 for i, option := range m.filteredKeys {
70 if i == m.selected {
71 b.WriteString(fmt.Sprintf("▶ %s\n", option.Label))
72 } else {
73 b.WriteString(fmt.Sprintf(" %s\n", option.Label))
74 }
75 }
76 }
77
78 return b.String()
79}
80
81// filterOptions filters options based on the search term
82func (m *Model) filterOptions() {
83 m.filteredKeys = nil
84 for key, value := range m.options {
85 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) { // Check values instead of keys
86 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key}) // Set Label to value
87 }
88 }
89}
90
91// DynamicSelect displays a full-screen selection prompt with search
92func DynamicSelect(options map[string]string) (SelectionOption, error) {
93 ClearScreen()
94 defer RestoreScreen()
95 model := &Model{ // Use a pointer to Model
96 options: options,
97 filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
98 }
99
100 // Populate filteredKeys initially
101 model.filterOptions()
102
103 // Create a new Program instance
104 p := tea.NewProgram(model)
105
106 // Run the program and capture the final model and any error
107 finalModel, err := p.Run()
108 if err != nil {
109 return SelectionOption{}, err
110 }
111
112 // Type assert to get the specific model type
113 finalSelectionModel, ok := finalModel.(*Model)
114 if !ok {
115 return SelectionOption{}, fmt.Errorf("unexpected model type")
116 }
117
118 // Return the selected option after quitting
119 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
120 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
121 }
122 return SelectionOption{}, nil
123}