aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel A. Giovanini <mail@gabrielgio.me>2024-04-25 22:15:30 +0200
committerGabriel A. Giovanini <mail@gabrielgio.me>2024-04-25 22:15:30 +0200
commitb7ca1117b18e228b84dd62a677a0a2ca52b3c549 (patch)
tree45e232058c0238d60459371f17679aafcf768a81
parenta26f850c2372718d2b69d6b258d686c68ddba5ff (diff)
downloaddict-b7ca1117b18e228b84dd62a677a0a2ca52b3c549.tar.gz
dict-b7ca1117b18e228b84dd62a677a0a2ca52b3c549.tar.bz2
dict-b7ca1117b18e228b84dd62a677a0a2ca52b3c549.zip
feat: Add async request
-rw-r--r--cmd/ui/ui.go63
1 files changed, 42 insertions, 21 deletions
diff --git a/cmd/ui/ui.go b/cmd/ui/ui.go
index b5f2f2f..50b8543 100644
--- a/cmd/ui/ui.go
+++ b/cmd/ui/ui.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ "sync"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
@@ -47,30 +48,52 @@ func Run(ctx context.Context, name string) error {
SetDynamicColors(true).
SetRegions(true)
+ app := tview.NewApplication()
+
+ search := ""
+ tx := sync.Mutex{}
+
input := tview.NewInputField().
SetChangedFunc(func(v string) {
- textView.Clear()
- words, err := db.SelectDict(ctx, v, 100)
- if err != nil {
- return
- }
+ tx.Lock()
+ defer tx.Unlock()
+ search = v
- lastWord := ""
- for _, w := range words {
-
- if lastWord == w.Word {
- fmt.Fprintf(textView, "%s\n", w.Line)
- } else if lastWord == "" {
- fmt.Fprintf(textView, "[bold]%s[normal]\n", w.Word)
- fmt.Fprintf(textView, "%s\n", w.Line)
- } else {
- fmt.Fprintf(textView, "\n[bold]%s[normal]\n", w.Word)
- fmt.Fprintf(textView, "%s\n", w.Line)
+ go func(v string) {
+ words, err := db.SelectDict(ctx, v, 100)
+ if err != nil {
+ return
}
- lastWord = w.Word
- }
+ tx.Lock()
+ if search != v {
+ tx.Unlock()
+ return
+ }
+ tx.Unlock()
+
+ textView.Clear()
+ lastWord := ""
+ for _, w := range words {
+ w.Word = tview.Escape(w.Word)
+ w.Line = tview.Escape(w.Line)
+
+ if lastWord == w.Word {
+ fmt.Fprintf(textView, "%s\n", w.Line)
+ } else if lastWord == "" {
+ fmt.Fprintf(textView, "[::bu]%s[-:-:-]\n", w.Word)
+ fmt.Fprintf(textView, "%s\n", w.Line)
+ } else {
+ fmt.Fprintf(textView, "\n[::bu]%s[-:-:-]\n", w.Word)
+ fmt.Fprintf(textView, "%s\n", w.Line)
+ }
+
+ lastWord = w.Word
+ }
+
+ app.Draw()
+ }(v)
}).
SetAutocompleteFunc(func(v string) []string {
if len(v) == 0 {
@@ -98,10 +121,8 @@ func Run(ctx context.Context, name string) error {
AddItem(input, 0, 0, 1, 3, 0, 0, false).
AddItem(textView, 1, 0, 1, 3, 0, 0, false)
- err = tview.NewApplication().
+ return app.
SetRoot(grid, true).
SetFocus(input).
Run()
-
- return err
}