Debian Codegraph @

demos/inputfield/autocompleteasync/main.go

raw symbols SCIP
1 package main
2
3 import (
4 "encoding/json"
5 "net/http"
6 "net/url"
7 "strings"
8 "sync"
9
10 "github.com/gdamore/tcell/v2"
11 "github.com/rivo/tview"
12 )
13
14 type company struct {
15 Name string `json:"name"`
16 }
17
18 func main() {
19 app := tview.NewApplication()
20 inputField := tview.NewInputField().
21 SetLabel("Enter a company name: ").
22 SetFieldWidth(30).
23 SetDoneFunc(func(key tcell.Key) {
24 app.Stop()
25 })
26
27 // Set up autocomplete function.
28 var mutex sync.Mutex
29 prefixMap := make(map[string][]string)
30 inputField.SetAutocompleteFunc(func(currentText string) []string {
31 // Ignore empty text.
32 prefix := strings.TrimSpace(strings.ToLower(currentText))
33 if prefix == "" {
34 return nil
35 }
36
37 // Do we have entries for this text already?
38 mutex.Lock()
39 defer mutex.Unlock()
40 entries, ok := prefixMap[prefix]
41 if ok {
42 return entries
43 }
44
45 // No entries yet. Issue a request to the API in a goroutine.
46 go func() {
47 // Ignore errors in this demo.
48 url := "https://autocomplete.clearbit.com/v1/companies/suggest?query=" + url.QueryEscape(prefix)
49 res, err := http.Get(url)
50 if err != nil {
51 return
52 }
53
54 // Store the result in the prefix map.
55 var companies []*company
56 dec := json.NewDecoder(res.Body)
57 if err := dec.Decode(&companies); err != nil {
58 return
59 }
60 entries := make([]string, 0, len(companies))
61 OuterLoop:
62 for _, c := range companies {
63 for _, entry := range entries { // Eliminate duplicates.
64 if strings.EqualFold(entry, c.Name) {
65 continue OuterLoop
66 }
67 }
68 entries = append(entries, c.Name)
69 }
70 mutex.Lock()
71 prefixMap[prefix] = entries
72 mutex.Unlock()
73
74 // Trigger an update to the input field.
75 inputField.Autocomplete()
76
77 // Also redraw the screen.
78 app.Draw()
79 }()
80
81 return nil
82 })
83
84 if err := app.EnableMouse(true).SetRoot(inputField, true).Run(); err != nil {
85 panic(err)
86 }
87 }