2019-07-08 08:34:06 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
2020-08-30 15:36:03 +00:00
|
|
|
"github.com/gdamore/tcell/v2"
|
2020-01-22 23:28:19 +00:00
|
|
|
"gitlab.com/tslocum/cview"
|
2019-07-08 08:34:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type company struct {
|
2020-01-28 15:08:15 +00:00
|
|
|
Name string `json:"name"`
|
2019-07-08 08:34:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2019-12-30 23:12:17 +00:00
|
|
|
app := cview.NewApplication()
|
|
|
|
inputField := cview.NewInputField().
|
2019-07-08 08:34:06 +00:00
|
|
|
SetLabel("Enter a company name: ").
|
|
|
|
SetFieldWidth(30).
|
|
|
|
SetDoneFunc(func(key tcell.Key) {
|
|
|
|
app.Stop()
|
|
|
|
})
|
|
|
|
|
|
|
|
// Set up autocomplete function.
|
|
|
|
var mutex sync.Mutex
|
2020-09-16 17:55:33 +00:00
|
|
|
prefixMap := make(map[string][]*cview.ListItem)
|
|
|
|
inputField.SetAutocompleteFunc(func(currentText string) []*cview.ListItem {
|
2019-07-08 08:34:06 +00:00
|
|
|
// Ignore empty text.
|
|
|
|
prefix := strings.TrimSpace(strings.ToLower(currentText))
|
|
|
|
if prefix == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do we have entries for this text already?
|
|
|
|
mutex.Lock()
|
|
|
|
defer mutex.Unlock()
|
|
|
|
entries, ok := prefixMap[prefix]
|
|
|
|
if ok {
|
|
|
|
return entries
|
|
|
|
}
|
|
|
|
|
|
|
|
// No entries yet. Issue a request to the API in a goroutine.
|
|
|
|
go func() {
|
|
|
|
// Ignore errors in this demo.
|
|
|
|
url := "https://autocomplete.clearbit.com/v1/companies/suggest?query=" + url.QueryEscape(prefix)
|
|
|
|
res, err := http.Get(url)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store the result in the prefix map.
|
|
|
|
var companies []*company
|
|
|
|
dec := json.NewDecoder(res.Body)
|
|
|
|
if err := dec.Decode(&companies); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2020-09-16 17:55:33 +00:00
|
|
|
entries := make([]*cview.ListItem, 0, len(companies))
|
2019-07-08 08:34:06 +00:00
|
|
|
for _, c := range companies {
|
2020-09-16 17:55:33 +00:00
|
|
|
entries = append(entries, cview.NewListItem(c.Name))
|
2019-07-08 08:34:06 +00:00
|
|
|
}
|
|
|
|
mutex.Lock()
|
|
|
|
prefixMap[prefix] = entries
|
|
|
|
mutex.Unlock()
|
|
|
|
|
|
|
|
// Trigger an update to the input field.
|
|
|
|
inputField.Autocomplete()
|
|
|
|
|
|
|
|
// Also redraw the screen.
|
|
|
|
app.Draw()
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err := app.SetRoot(inputField, true).Run(); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|