Debian Codegraph @

field_text.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "fmt"
6 "io"
7 "os"
8 "os/exec"
9 "strings"
10
11 "github.com/charmbracelet/bubbles/key"
12 "github.com/charmbracelet/bubbles/textarea"
13 tea "github.com/charmbracelet/bubbletea"
14 "github.com/charmbracelet/huh/internal/accessibility"
15 "github.com/charmbracelet/lipgloss"
16 )
17
18 // Text is a text field.
19 //
20 // A text box is responsible for getting multi-line input from the user. Use
21 // it to gather longer-form user input. The Text field can be filled with an
22 // EDITOR.
23 type Text struct {
24 accessor Accessor[string]
25 key string
26 id int
27
28 title Eval[string]
29 description Eval[string]
30 placeholder Eval[string]
31
32 externalEditor bool
33 editorCmd string
34 editorArgs []string
35 editorExtension string
36
37 textarea textarea.Model
38
39 focused bool
40 validate func(string) error
41 err error
42
43 accessible bool // Deprecated: use RunAccessible instead.
44 width int
45
46 theme *Theme
47 keymap TextKeyMap
48 }
49
50 // NewText creates a new text field.
51 //
52 // A text box is responsible for getting multi-line input from the user. Use
53 // it to gather longer-form user input. The Text field can be filled with an
54 // EDITOR.
55 func NewText() *Text {
56 text := textarea.New()
57 text.ShowLineNumbers = false
58 text.Prompt = ""
59 text.FocusedStyle.CursorLine = lipgloss.NewStyle()
60
61 editorCmd, editorArgs := getEditor()
62
63 t := &Text{
64 accessor: &EmbeddedAccessor[string]{},
65 id: nextID(),
66 textarea: text,
67 validate: func(string) error { return nil },
68 externalEditor: true,
69 editorCmd: editorCmd,
70 editorArgs: editorArgs,
71 editorExtension: "md",
72 title: Eval[string]{cache: make(map[uint64]string)},
73 description: Eval[string]{cache: make(map[uint64]string)},
74 placeholder: Eval[string]{cache: make(map[uint64]string)},
75 }
76
77 return t
78 }
79
80 // Value sets the value of the text field.
81 func (t *Text) Value(value *string) *Text {
82 return t.Accessor(NewPointerAccessor(value))
83 }
84
85 // Accessor sets the accessor of the text field.
86 func (t *Text) Accessor(accessor Accessor[string]) *Text {
87 t.accessor = accessor
88 t.textarea.SetValue(t.accessor.Get())
89 return t
90 }
91
92 // Key sets the key of the text field.
93 func (t *Text) Key(key string) *Text {
94 t.key = key
95 return t
96 }
97
98 // Title sets the text field's title.
99 //
100 // This title will be static, for dynamic titles use `TitleFunc`.
101 func (t *Text) Title(title string) *Text {
102 t.title.val = title
103 t.title.fn = nil
104 return t
105 }
106
107 // TitleFunc sets the text field's title func.
108 //
109 // The TitleFunc will be re-evaluated when the binding of the TitleFunc changes.
110 // This is useful when you want to display dynamic content and update the title
111 // when another part of your form changes.
112 //
113 // See README#Dynamic for more usage information.
114 func (t *Text) TitleFunc(f func() string, bindings any) *Text {
115 t.title.fn = f
116 t.title.bindings = bindings
117 return t
118 }
119
120 // Description sets the description of the text field.
121 //
122 // This description will be static, for dynamic description use `DescriptionFunc`.
123 func (t *Text) Description(description string) *Text {
124 t.description.val = description
125 t.description.fn = nil
126 return t
127 }
128
129 // DescriptionFunc sets the description func of the text field.
130 //
131 // The DescriptionFunc will be re-evaluated when the binding of the
132 // DescriptionFunc changes. This is useful when you want to display dynamic
133 // content and update the description when another part of your form changes.
134 //
135 // See README#Dynamic for more usage information.
136 func (t *Text) DescriptionFunc(f func() string, bindings any) *Text {
137 t.description.fn = f
138 t.description.bindings = bindings
139 return t
140 }
141
142 // Lines sets the number of lines to show of the text field.
143 func (t *Text) Lines(lines int) *Text {
144 t.textarea.SetHeight(lines)
145 return t
146 }
147
148 // CharLimit sets the character limit of the text field.
149 func (t *Text) CharLimit(charlimit int) *Text {
150 t.textarea.CharLimit = charlimit
151 return t
152 }
153
154 // ShowLineNumbers sets whether or not to show line numbers.
155 func (t *Text) ShowLineNumbers(show bool) *Text {
156 t.textarea.ShowLineNumbers = show
157 return t
158 }
159
160 // Placeholder sets the placeholder of the text field.
161 //
162 // This placeholder will be static, for dynamic placeholders use `PlaceholderFunc`.
163 func (t *Text) Placeholder(str string) *Text {
164 t.textarea.Placeholder = str
165 return t
166 }
167
168 // PlaceholderFunc sets the placeholder func of the text field.
169 //
170 // The PlaceholderFunc will be re-evaluated when the binding of the
171 // PlaceholderFunc changes. This is useful when you want to display dynamic
172 // content and update the placeholder when another part of your form changes.
173 //
174 // See README#Dynamic for more usage information.
175 func (t *Text) PlaceholderFunc(f func() string, bindings any) *Text {
176 t.placeholder.fn = f
177 t.placeholder.bindings = bindings
178 return t
179 }
180
181 // Validate sets the validation function of the text field.
182 func (t *Text) Validate(validate func(string) error) *Text {
183 t.validate = validate
184 return t
185 }
186
187 // ExternalEditor sets whether option to launch an editor is available.
188 func (t *Text) ExternalEditor(enabled bool) *Text {
189 t.externalEditor = enabled
190 return t
191 }
192
193 const defaultEditor = "nano"
194
195 // getEditor returns the editor command and arguments.
196 func getEditor() (string, []string) {
197 editor := strings.Fields(os.Getenv("EDITOR"))
198 if len(editor) > 0 {
199 return editor[0], editor[1:]
200 }
201 return defaultEditor, nil
202 }
203
204 // Editor specifies which editor to use.
205 //
206 // The first argument provided is used as the editor command (vim, nvim, nano, etc...)
207 // The following (optional) arguments provided are passed as arguments to the editor command.
208 func (t *Text) Editor(editor ...string) *Text {
209 if len(editor) > 0 {
210 t.editorCmd = editor[0]
211 }
212 if len(editor) > 1 {
213 t.editorArgs = editor[1:]
214 }
215 return t
216 }
217
218 // EditorExtension specifies arguments to pass into the editor.
219 func (t *Text) EditorExtension(extension string) *Text {
220 t.editorExtension = extension
221 return t
222 }
223
224 // Error returns the error of the text field.
225 func (t *Text) Error() error { return t.err }
226
227 // Skip returns whether the textarea should be skipped or should be blocking.
228 func (*Text) Skip() bool { return false }
229
230 // Zoom returns whether the note should be zoomed.
231 func (*Text) Zoom() bool { return false }
232
233 // Focus focuses the text field.
234 func (t *Text) Focus() tea.Cmd {
235 t.focused = true
236 return t.textarea.Focus()
237 }
238
239 // Blur blurs the text field.
240 func (t *Text) Blur() tea.Cmd {
241 t.focused = false
242 t.accessor.Set(t.textarea.Value())
243 t.textarea.Blur()
244 t.err = t.validate(t.accessor.Get())
245 return nil
246 }
247
248 // KeyBinds returns the help message for the text field.
249 func (t *Text) KeyBinds() []key.Binding {
250 t.keymap.Editor.SetEnabled(t.externalEditor)
251 return []key.Binding{t.keymap.NewLine, t.keymap.Editor, t.keymap.Prev, t.keymap.Submit, t.keymap.Next}
252 }
253
254 type updateValueMsg []byte
255
256 // Init initializes the text field.
257 func (t *Text) Init() tea.Cmd {
258 t.textarea.Blur()
259 return nil
260 }
261
262 // Update updates the text field.
263 func (t *Text) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
264 var cmds []tea.Cmd
265 var cmd tea.Cmd
266
267 switch msg := msg.(type) {
268 case updateValueMsg:
269 t.textarea.SetValue(string(msg))
270 t.textarea, cmd = t.textarea.Update(msg)
271 cmds = append(cmds, cmd)
272 t.accessor.Set(t.textarea.Value())
273 case updateFieldMsg:
274 var cmds []tea.Cmd
275 if ok, hash := t.placeholder.shouldUpdate(); ok {
276 t.placeholder.bindingsHash = hash
277 if t.placeholder.loadFromCache() {
278 t.textarea.Placeholder = t.placeholder.val
279 } else {
280 t.placeholder.loading = true
281 cmds = append(cmds, func() tea.Msg {
282 return updatePlaceholderMsg{id: t.id, placeholder: t.placeholder.fn(), hash: hash}
283 })
284 }
285 }
286 if ok, hash := t.title.shouldUpdate(); ok {
287 t.title.bindingsHash = hash
288 if !t.title.loadFromCache() {
289 cmds = append(cmds, func() tea.Msg {
290 return updateTitleMsg{id: t.id, title: t.title.fn(), hash: hash}
291 })
292 }
293 }
294 if ok, hash := t.description.shouldUpdate(); ok {
295 t.description.bindingsHash = hash
296 if !t.description.loadFromCache() {
297 t.description.loading = true
298 cmds = append(cmds, func() tea.Msg {
299 return updateDescriptionMsg{id: t.id, description: t.description.fn(), hash: hash}
300 })
301 }
302 }
303 return t, tea.Batch(cmds...)
304 case updatePlaceholderMsg:
305 if t.id == msg.id && t.placeholder.bindingsHash == msg.hash {
306 t.placeholder.update(msg.placeholder)
307 t.textarea.Placeholder = msg.placeholder
308 }
309 case updateTitleMsg:
310 if t.id == msg.id && t.title.bindingsHash == msg.hash {
311 t.title.update(msg.title)
312 }
313 case updateDescriptionMsg:
314 if t.id == msg.id && t.description.bindingsHash == msg.hash {
315 t.description.update(msg.description)
316 }
317 case tea.KeyMsg:
318 t.err = nil
319
320 switch {
321 case key.Matches(msg, t.keymap.Editor):
322 ext := strings.TrimPrefix(t.editorExtension, ".")
323 tmpFile, _ := os.CreateTemp(os.TempDir(), "*."+ext)
324 cmd := exec.Command(t.editorCmd, append(t.editorArgs, tmpFile.Name())...) //nolint:gosec
325 _ = os.WriteFile(tmpFile.Name(), []byte(t.textarea.Value()), 0o644) //nolint:mnd,gosec
326 cmds = append(cmds, tea.ExecProcess(cmd, func(error) tea.Msg {
327 content, _ := os.ReadFile(tmpFile.Name())
328 _ = os.Remove(tmpFile.Name())
329 return updateValueMsg(content)
330 }))
331 case key.Matches(msg, t.keymap.Next, t.keymap.Submit):
332 value := t.textarea.Value()
333 t.err = t.validate(value)
334 if t.err != nil {
335 return t, nil
336 }
337 cmds = append(cmds, NextField)
338 case key.Matches(msg, t.keymap.Prev):
339 value := t.textarea.Value()
340 t.err = t.validate(value)
341 if t.err != nil {
342 return t, nil
343 }
344 cmds = append(cmds, PrevField)
345 }
346 }
347
348 t.textarea, cmd = t.textarea.Update(msg)
349 cmds = append(cmds, cmd)
350 t.accessor.Set(t.textarea.Value())
351
352 return t, tea.Batch(cmds...)
353 }
354
355 func (t *Text) activeStyles() *FieldStyles {
356 theme := t.theme
357 if theme == nil {
358 theme = ThemeCharm()
359 }
360 if t.focused {
361 return &theme.Focused
362 }
363 return &theme.Blurred
364 }
365
366 func (t *Text) activeTextAreaStyles() *textarea.Style {
367 if t.theme == nil {
368 return &t.textarea.BlurredStyle
369 }
370 if t.focused {
371 return &t.textarea.FocusedStyle
372 }
373 return &t.textarea.BlurredStyle
374 }
375
376 // View renders the text field.
377 func (t *Text) View() string {
378 styles := t.activeStyles()
379 textareaStyles := t.activeTextAreaStyles()
380
381 // NB: since the method is on a pointer receiver these are being mutated.
382 // Because this runs on every render this shouldn't matter in practice,
383 // however.
384 textareaStyles.Placeholder = styles.TextInput.Placeholder
385 textareaStyles.Text = styles.TextInput.Text
386 textareaStyles.Prompt = styles.TextInput.Prompt
387 textareaStyles.CursorLine = styles.TextInput.Text
388 t.textarea.Cursor.Style = styles.TextInput.Cursor
389 t.textarea.Cursor.TextStyle = styles.TextInput.CursorText
390
391 maxWidth := t.width - styles.Base.GetHorizontalFrameSize()
392 var parts []string
393 if t.title.val != "" || t.title.fn != nil {
394 header := styles.Title.Render(wrap(t.title.val, maxWidth))
395 if t.err != nil {
396 header += styles.ErrorIndicator.String()
397 }
398 parts = append(parts, header)
399 }
400 if t.description.val != "" || t.description.fn != nil {
401 parts = append(parts, styles.Description.Render(wrap(t.description.val, maxWidth)))
402 }
403 parts = append(parts, t.textarea.View())
404
405 return styles.Base.
406 Render(strings.Join(parts, "\n"))
407 }
408
409 // Run runs the text field.
410 func (t *Text) Run() error {
411 if t.accessible { // TODO: remove in a future release.
412 return t.RunAccessible(os.Stdout, os.Stdin)
413 }
414 return Run(t)
415 }
416
417 // RunAccessible runs an accessible text field.
418 func (t *Text) RunAccessible(w io.Writer, r io.Reader) error {
419 styles := t.activeStyles()
420 prompt := styles.Title.
421 PaddingRight(1).
422 Render(cmp.Or(t.title.val, "Input:"))
423 t.accessor.Set(accessibility.PromptString(
424 w,
425 r,
426 prompt,
427 t.GetValue().(string),
428 func(input string) error {
429 if err := t.validate(input); err != nil {
430 // Handle the error from t.validate, return it
431 return err
432 }
433
434 if t.textarea.CharLimit > 0 && len(input) > t.textarea.CharLimit {
435 return fmt.Errorf("Input cannot exceed %d characters", t.textarea.CharLimit)
436 }
437 return nil
438 },
439 ))
440 return nil
441 }
442
443 // WithTheme sets the theme on a text field.
444 func (t *Text) WithTheme(theme *Theme) Field {
445 if t.theme != nil {
446 return t
447 }
448 t.theme = theme
449 return t
450 }
451
452 // WithKeyMap sets the keymap on a text field.
453 func (t *Text) WithKeyMap(k *KeyMap) Field {
454 t.keymap = k.Text
455 t.textarea.KeyMap.InsertNewline.SetKeys(t.keymap.NewLine.Keys()...)
456 return t
457 }
458
459 // WithAccessible sets the accessible mode of the text field.
460 //
461 // Deprecated: you may now call [Text.RunAccessible] directly to run the
462 // field in accessible mode.
463 func (t *Text) WithAccessible(accessible bool) Field {
464 t.accessible = accessible
465 return t
466 }
467
468 // WithWidth sets the width of the text field.
469 func (t *Text) WithWidth(width int) Field {
470 t.width = width
471 t.textarea.SetWidth(width - t.activeStyles().Base.GetHorizontalFrameSize())
472 return t
473 }
474
475 // WithHeight sets the height of the text field.
476 func (t *Text) WithHeight(height int) Field {
477 adjust := 0
478 if t.title.val != "" {
479 adjust++
480 }
481 if t.description.val != "" {
482 adjust++
483 }
484 t.textarea.SetHeight(height - t.activeStyles().Base.GetVerticalFrameSize() - adjust)
485 return t
486 }
487
488 // WithPosition sets the position information of the text field.
489 func (t *Text) WithPosition(p FieldPosition) Field {
490 t.keymap.Prev.SetEnabled(!p.IsFirst())
491 t.keymap.Next.SetEnabled(!p.IsLast())
492 t.keymap.Submit.SetEnabled(p.IsLast())
493 return t
494 }
495
496 // GetKey returns the key of the field.
497 func (t *Text) GetKey() string { return t.key }
498
499 // GetValue returns the value of the field.
500 func (t *Text) GetValue() any {
501 return t.accessor.Get()
502 }