-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.go
355 lines (302 loc) · 7.98 KB
/
prompt.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package core
import (
"bufio"
"context"
"flag"
"os"
"strings"
"time"
"github.com/orochaa/go-clack/core/utils"
"github.com/orochaa/go-clack/core/validator"
"github.com/orochaa/go-clack/third_party/sisteransi"
"golang.org/x/term"
)
type State int
const (
// InitialState is the initial state of the prompt
InitialState State = iota
// ActiveState is set after the user's first action
ActiveState
// ValidateState is set after 400ms of validation (e.g., checking user input)
ValidateState
// ErrorState is set if there is an error during validation
ErrorState
// CancelState is set after the user cancels the prompt
CancelState
// SubmitState is set after the user submits the input
SubmitState
)
type Prompt[TValue any] struct {
context context.Context
listeners map[Event][]EventListener
rl *bufio.Reader
input *os.File
output *os.File
State State
Error string
Value TValue
CursorIndex int
Validate func(value TValue) error
ValidationDuration time.Duration
IsValidating bool
Render func(p *Prompt[TValue]) string
Frame string
}
type PromptParams[TValue any] struct {
Context context.Context
Input *os.File
Output *os.File
InitialValue TValue
CursorIndex int
Validate func(value TValue) error
Render func(p *Prompt[TValue]) string
}
// NewPrompt initializes a new Prompt with the provided parameters.
//
// Parameters:
// - Context (context.Context): The context for the prompt (default: context.Background).
// - Input (*os.File): The input stream for the prompt (default: OSFileSystem).
// - Output (*os.File): The output stream for the prompt (default: OSFileSystem).
// - InitialValue (TValue): The initial value of the prompt (default: zero value of TValue).
// - CursorIndex (int): The initial cursor position in the input (default: 0).
// - Validate (func(value TValue) error): Custom validation function for the input (default: nil).
// - Render (func(p *Prompt[TValue]) string): Custom render function for the prompt (default: nil).
//
// Returns:
// - *Prompt[TValue]: A new instance of Prompt.
func NewPrompt[TValue any](params PromptParams[TValue]) *Prompt[TValue] {
v := validator.NewValidator("Prompt")
v.ValidateRender(params.Render)
if params.Context == nil {
params.Context = context.Background()
}
if params.Input == nil {
params.Input = os.Stdin
}
if params.Output == nil {
params.Output = os.Stdout
}
return &Prompt[TValue]{
context: params.Context,
listeners: make(map[Event][]EventListener),
input: params.Input,
output: params.Output,
rl: bufio.NewReader(params.Input),
State: InitialState,
Value: params.InitialValue,
CursorIndex: params.CursorIndex,
Validate: params.Validate,
Render: params.Render,
}
}
type KeyName string
type Key struct {
Name KeyName
Char string
Shift bool
Ctrl bool
}
const (
UpKey KeyName = "Up"
DownKey KeyName = "Down"
LeftKey KeyName = "Left"
RightKey KeyName = "Right"
HomeKey KeyName = "Home"
EndKey KeyName = "End"
SpaceKey KeyName = "Space"
EnterKey KeyName = "Enter"
CancelKey KeyName = "Cancel"
TabKey KeyName = "Tab"
BackspaceKey KeyName = "Backspace"
EscapeKey KeyName = "Escape"
)
// ParseKey parses a rune into a Key.
func (p *Prompt[TValue]) ParseKey(r rune) *Key {
// TODO: parse Backtab(shift+tab) and other variations of shift and ctrl
switch r {
case '\r', '\n':
return &Key{Name: EnterKey}
case ' ':
return &Key{Name: SpaceKey}
case '\b', 127:
return &Key{Name: BackspaceKey}
case '\t':
return &Key{Name: TabKey}
case 3:
return &Key{Name: CancelKey}
case 27:
readerReady := make(chan bool, 1)
go func() {
_, err := p.rl.Peek(2)
readerReady <- err == nil
}()
select {
case ready := <-readerReady:
if ready {
next, err := p.rl.Peek(2)
if err == nil && len(next) == 2 && next[0] == '[' {
p.rl.ReadByte() // Consume '['
thirdByte, _ := p.rl.ReadByte()
switch thirdByte {
case 'A':
return &Key{Name: UpKey}
case 'B':
return &Key{Name: DownKey}
case 'C':
return &Key{Name: RightKey}
case 'D':
return &Key{Name: LeftKey}
case 'H':
return &Key{Name: HomeKey}
case 'F':
return &Key{Name: EndKey}
}
}
return &Key{}
} else {
return &Key{Name: EscapeKey}
}
case <-time.After(50 * time.Millisecond):
return &Key{Name: EscapeKey}
}
}
char := string(r)
return &Key{Char: char, Name: KeyName(char)}
}
// PressKey handles key press events and updates the state of the prompt.
func (p *Prompt[TValue]) PressKey(key *Key) {
if p.State == InitialState || p.State == ErrorState {
p.State = ActiveState
}
p.Emit(KeyEvent, key)
if action, actionExists := aliases[key.Name]; actionExists {
if action == SubmitAction {
if err := p.validate(); err != nil {
p.State = ErrorState
p.Error = err.Error()
} else {
p.State = SubmitState
}
} else if action == CancelAction {
p.State = CancelState
}
}
if p.State == SubmitState || p.State == CancelState {
p.Emit(FinalizeEvent)
}
p.render()
if p.State == SubmitState {
p.Emit(SubmitEvent)
} else if p.State == CancelState {
p.Emit(CancelEvent)
}
}
// validate performs validation on the current value of the prompt.
func (p *Prompt[TValue]) validate() error {
if p.Validate == nil {
return nil
}
p.State = ValidateState
p.IsValidating = true
p.Emit(ValidateEvent)
go func() {
validationStart := time.Now()
time.Sleep(400 * time.Millisecond)
for p.IsValidating {
p.ValidationDuration = time.Since(validationStart)
p.render()
time.Sleep(125 * time.Millisecond)
}
}()
err := p.Validate(p.Value)
p.IsValidating = false
return err
}
// DiffLines calculates the difference between an old and a new frame.
func (p *Prompt[TValue]) DiffLines(oldFrame, newFrame string) []int {
var diff []int
if oldFrame == newFrame {
return diff
}
oldLines := utils.SplitLines(oldFrame)
newLines := utils.SplitLines(newFrame)
for i := range max(len(oldLines), len(newLines)) {
if i >= len(oldLines) || i >= len(newLines) || oldLines[i] != newLines[i] {
diff = append(diff, i)
}
}
return diff
}
// Size retrieves the width and height of the terminal output.
func (p *Prompt[TValue]) Size() (width int, height int, err error) {
return term.GetSize(int(p.output.Fd()))
}
// render renders a new frame to the output.
func (p *Prompt[TValue]) render() {
frame := p.Render(p)
if p.State == InitialState {
p.output.WriteString(sisteransi.HideCursor())
p.output.WriteString(frame)
p.Frame = frame
return
}
if frame == p.Frame {
return
}
diff := p.DiffLines(frame, p.Frame)
diffLineIndex := diff[0]
prevFrameLines := utils.SplitLines((p.Frame))
// Move to first diff line
p.output.WriteString(sisteransi.MoveCursor(-(len(prevFrameLines) - 1), -999))
p.output.WriteString(sisteransi.MoveCursor(diffLineIndex, 0))
p.output.WriteString(sisteransi.EraseDown())
lines := utils.SplitLines(frame)
newLines := lines[diffLineIndex:]
p.output.WriteString(strings.Join(newLines, "\r\n"))
p.Frame = frame
}
// Run runs the prompt and processes input.
func (p *Prompt[TValue]) Run() (TValue, error) {
if flag.Lookup("test.v") == nil {
oldState, err := term.MakeRaw(int(p.input.Fd()))
if err != nil {
return p.Value, err
}
defer term.Restore(int(p.input.Fd()), oldState)
}
done := make(chan struct{})
closeCb := func(args ...any) {
p.output.WriteString(sisteransi.ShowCursor())
p.output.WriteString("\r\n")
close(done)
}
p.Once(SubmitEvent, closeCb)
p.Once(CancelEvent, closeCb)
p.render()
go func() {
select {
case <-done:
return
case <-p.context.Done():
p.PressKey(&Key{Name: CancelKey})
}
}()
outer:
for {
select {
case <-done:
break outer
default:
r, size, err := p.rl.ReadRune()
if err != nil || size == 0 || p.IsValidating {
continue
}
key := p.ParseKey(r)
p.PressKey(key)
}
}
if p.State == CancelState {
return p.Value, ErrCancelPrompt
}
return p.Value, nil
}