-
Notifications
You must be signed in to change notification settings - Fork 12
/
textinputhelper.go
97 lines (79 loc) · 2.05 KB
/
textinputhelper.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"strings"
"github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/companyzero/bisonrelay/internal/strescape"
)
type textInputHelperOption func(model *textinput.Model)
func tihWithPrompt(prompt string) textInputHelperOption {
return func(model *textinput.Model) {
model.Prompt = prompt
}
}
func tihWithValue(value string) textInputHelperOption {
return func(model *textinput.Model) {
model.SetValue(value)
}
}
// textInputHelper is a helper to work around textinput.Model quirks and to
// ease creating forms.
type textInputHelper struct {
initless
textinput.Model
styles *theme
}
func (input *textInputHelper) clear() {
input.Model.SetValue("")
}
func (input *textInputHelper) Focus() tea.Cmd {
input.Model.PromptStyle = input.styles.focused
input.Model.TextStyle = input.styles.focused
return input.Model.Focus()
}
func (input *textInputHelper) Blur() tea.Cmd {
input.Model.PromptStyle = input.styles.noStyle
input.Model.TextStyle = input.styles.noStyle
input.Model.Blur()
return nil
}
func (input *textInputHelper) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
default:
hasLN := strings.ContainsAny(msg.String(), "\n\r")
if hasLN {
lines := strescape.CannonicalizeNL(msg.String())
msg := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(lines)}
input.Model, cmd = input.Model.Update(msg)
cmds = appendCmd(cmds, cmd)
} else {
input.Model, cmd = input.Model.Update(msg)
cmds = appendCmd(cmds, cmd)
}
}
}
return input, batchCmds(cmds)
}
func newTextInputHelper(styles *theme, opts ...textInputHelperOption) *textInputHelper {
// TODO: parametrize based on styles.blink
c := cursor.New()
c.Style = styles.cursor
c.SetMode(cursor.CursorBlink)
model := textinput.New()
model.Cursor = c
input := textInputHelper{
styles: styles,
Model: model,
}
for _, opt := range opts {
opt(&input.Model)
}
return &input
}