-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinputter.go
78 lines (65 loc) · 1.47 KB
/
inputter.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
package bubblewrap
import (
"context"
"fmt"
"io"
"os"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// Input prompts for, well, input!
func Input(prompt string) (string, error) {
input, err := NewInputter().input(prompt)
if err != nil {
return "", err
}
return input, nil
}
type inputter struct {
ctx context.Context
modelbase
textinput textinput.Model
stdin io.Reader
stdout io.Writer
}
func NewInputter() *inputter {
return &inputter{
textinput: textinput.New(),
ctx: context.TODO(),
stdin: os.Stdin,
stdout: os.Stdout,
}
}
func (i *inputter) Init() tea.Cmd { return textinput.Blink }
func (i *inputter) View() string {
return i.textinput.View()
}
func (i *inputter) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC, tea.KeyEscape:
i.quitting = true
i.aborted = true
return i, tea.Quit
case tea.KeyEnter:
i.quitting = true
return i, tea.Quit
}
}
var cmd tea.Cmd
i.textinput, cmd = i.textinput.Update(msg)
return i, cmd
}
func (i *inputter) input(prompt string) (string, error) {
i.textinput.Prompt = prompt
i.textinput.Focus()
p := tea.NewProgram(i, tea.WithContext(i.ctx), tea.WithInput(i.stdin), tea.WithOutput(i.stdout))
if _, err := p.Run(); err != nil {
return "", err
}
if i.aborted {
return "", CancelError(fmt.Errorf("user canceled operation"))
}
return i.textinput.Value(), nil
}