-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_box.go
79 lines (66 loc) · 2.07 KB
/
search_box.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package nve
import (
"log"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
type SearchBox struct {
*tview.InputField
listView *ListBox
contentView *ContentBox
}
func NewSearchBox(listView *ListBox, contentView *ContentBox, notes *Notes) *SearchBox {
res := SearchBox{
InputField: tview.NewInputField(),
listView: listView,
contentView: contentView,
}
// input field attributes
res.SetFieldBackgroundColor(tcell.ColorBlack).
SetPlaceholderStyle(tcell.StyleDefault.Background(tcell.ColorBlack))
// other attributes
res.SetBorder(true).
SetTitle("Search Box").
SetBackgroundColor(tcell.ColorBlack).
SetTitleColor(tcell.ColorYellow).
SetBorderStyle(tcell.StyleDefault.Dim(true)).
SetBorderPadding(0, 0, 1, 1).
SetTitleAlign(tview.AlignLeft)
// input handling
res.SetChangedFunc(func(text string) {
notes.Search(text)
})
res.SetDoneFunc(func(key tcell.Key) {
switch key {
case tcell.KeyEnter:
if len(notes.LastSearchResults) == 0 {
newNote, err := notes.CreateNote(res.GetText())
if err != nil {
log.Println("Error creating new note")
break
}
notes.Search(newNote.DisplayName())
}
}
})
return &res
}
// InputHandler overrides default handling to switch focus away from search box when necessary.
func (sb *SearchBox) InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
return sb.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
if event.Key() == tcell.KeyEnter {
setFocus(sb.contentView)
} else if event.Key() == tcell.KeyDown || event.Key() == tcell.KeyCtrlN {
if handler := sb.listView.InputHandler(); handler != nil {
handler(tcell.NewEventKey(tcell.KeyDown, event.Rune(), event.Modifiers()), setFocus)
}
} else if event.Key() == tcell.KeyUp || event.Key() == tcell.KeyCtrlP {
if handler := sb.listView.InputHandler(); handler != nil {
handler(tcell.NewEventKey(tcell.KeyUp, event.Rune(), event.Modifiers()), setFocus)
}
}
if handler := sb.InputField.InputHandler(); handler != nil {
handler(event, setFocus)
}
})
}