/
model_text_input.go
70 lines (58 loc) 路 1.6 KB
/
model_text_input.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
package tui
import (
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// textinput.Model doesn't implement tea.Model interface
type textInput struct {
input textinput.Model
//Since textinput field can be used in multiple places,
//responder is required to determine the receiver of the message emitted by textinput field
responder func(interface{}) tea.Cmd
}
var textInputKeys = keyMap{
Enter: key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("'enter'", "save"),
),
Return: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("'esc'", "return"),
),
}
func initializeTextInput(value string, placeholder string, charLimit int, responder func(interface{}) tea.Cmd) tea.Model {
t := textinput.New()
t.SetValue(value)
t.Cursor.Style = textInputStyle
t.CharLimit = charLimit
t.Focus()
t.PromptStyle = textInputStyle
t.TextStyle = textInputStyle
t.Placeholder = placeholder
m := textInput{
input: t,
responder: responder,
}
return m
}
func (m textInput) Init() tea.Cmd {
return textinput.Blink
}
func (m textInput) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case key.Matches(msg, Keys.Enter):
return m, m.responder(m.input.Value())
}
}
// Placing it outside KeyMsg case is required, otherwise messages like textinput's Blink will be lost
var cmd tea.Cmd
m.input, cmd = m.input.Update(msg)
return m, cmd
}
func (m textInput) View() string {
// Can't just render textinput.Value(), otherwise cursor blinking wouldn't work
return m.input.View()
}