Debian Codegraph @

field_note.go

raw symbols SCIP
1 package huh
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "strings"
8
9 "github.com/charmbracelet/bubbles/key"
10 tea "github.com/charmbracelet/bubbletea"
11 )
12
13 // Note is a note field.
14 //
15 // A note is responsible for displaying information to the user. Use it to
16 // provide context around a different field. Generally, the notes are not
17 // interacted with unless the note has a next button `Next(true)`.
18 type Note struct {
19 id int
20
21 title Eval[string]
22 description Eval[string]
23 nextLabel string
24
25 focused bool
26 showNextButton bool
27 skip bool
28
29 accessible bool // Deprecated: use RunAccessible instead.
30 height int
31 width int
32
33 theme *Theme
34 keymap NoteKeyMap
35 }
36
37 // NewNote creates a new note field.
38 //
39 // A note is responsible for displaying information to the user. Use it to
40 // provide context around a different field. Generally, the notes are not
41 // interacted with unless the note has a next button `Next(true)`.
42 func NewNote() *Note {
43 return &Note{
44 id: nextID(),
45 showNextButton: false,
46 skip: true,
47 nextLabel: "Next",
48 title: Eval[string]{cache: make(map[uint64]string)},
49 description: Eval[string]{cache: make(map[uint64]string)},
50 }
51 }
52
53 // Title sets the note field's title.
54 //
55 // This title will be static, for dynamic titles use `TitleFunc`.
56 func (n *Note) Title(title string) *Note {
57 n.title.val = title
58 n.title.fn = nil
59 return n
60 }
61
62 // TitleFunc sets the title func of the note field.
63 //
64 // The TitleFunc will be re-evaluated when the binding of the TitleFunc changes.
65 // This is useful when you want to display dynamic content and update the title
66 // of a note when another part of your form changes.
67 //
68 // See README.md#Dynamic for more usage information.
69 func (n *Note) TitleFunc(f func() string, bindings any) *Note {
70 n.title.fn = f
71 n.title.bindings = bindings
72 return n
73 }
74
75 // Description sets the note field's description.
76 //
77 // This description will be static, for dynamic descriptions use `DescriptionFunc`.
78 func (n *Note) Description(description string) *Note {
79 n.description.val = description
80 n.description.fn = nil
81 return n
82 }
83
84 // DescriptionFunc sets the description func of the note field.
85 //
86 // The DescriptionFunc will be re-evaluated when the binding of the
87 // DescriptionFunc changes. This is useful when you want to display dynamic
88 // content and update the description of a note when another part of your form
89 // changes.
90 //
91 // For example, you can make a dynamic markdown preview with the following Form & Group.
92 //
93 // huh.NewText().Title("Markdown").Value(&md),
94 // huh.NewNote().Height(20).Title("Preview").
95 // DescriptionFunc(func() string {
96 // return md
97 // }, &md),
98 //
99 // Notice the `binding` of the Note is the same as the `Value` of the Text field.
100 // This binds the two values together, so that when the `Value` of the Text
101 // field changes so does the Note description.
102 func (n *Note) DescriptionFunc(f func() string, bindings any) *Note {
103 n.description.fn = f
104 n.description.bindings = bindings
105 return n
106 }
107
108 // Height sets the note field's height.
109 func (n *Note) Height(height int) *Note {
110 n.height = height
111 return n
112 }
113
114 // Next sets whether or not to show the next button.
115 //
116 // Title
117 // Description
118 //
119 // [ Next ]
120 func (n *Note) Next(show bool) *Note {
121 n.showNextButton = show
122 return n
123 }
124
125 // NextLabel sets the next button label.
126 func (n *Note) NextLabel(label string) *Note {
127 n.nextLabel = label
128 return n
129 }
130
131 // Focus focuses the note field.
132 func (n *Note) Focus() tea.Cmd {
133 n.focused = true
134 return nil
135 }
136
137 // Blur blurs the note field.
138 func (n *Note) Blur() tea.Cmd {
139 n.focused = false
140 return nil
141 }
142
143 // Error returns the error of the note field.
144 func (n *Note) Error() error { return nil }
145
146 // Skip returns whether the note should be skipped or should be blocking.
147 func (n *Note) Skip() bool { return n.skip }
148
149 // Zoom returns whether the note should be zoomed.
150 func (n *Note) Zoom() bool { return false }
151
152 // KeyBinds returns the help message for the note field.
153 func (n *Note) KeyBinds() []key.Binding {
154 return []key.Binding{
155 n.keymap.Prev,
156 n.keymap.Submit,
157 n.keymap.Next,
158 }
159 }
160
161 // Init initializes the note field.
162 func (n *Note) Init() tea.Cmd { return nil }
163
164 // Update updates the note field.
165 func (n *Note) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
166 switch msg := msg.(type) {
167 case updateFieldMsg:
168 var cmds []tea.Cmd
169 if ok, hash := n.title.shouldUpdate(); ok {
170 n.title.bindingsHash = hash
171 if !n.title.loadFromCache() {
172 n.title.loading = true
173 cmds = append(cmds, func() tea.Msg {
174 return updateTitleMsg{id: n.id, title: n.title.fn(), hash: hash}
175 })
176 }
177 }
178 if ok, hash := n.description.shouldUpdate(); ok {
179 n.description.bindingsHash = hash
180 if !n.description.loadFromCache() {
181 n.description.loading = true
182 cmds = append(cmds, func() tea.Msg {
183 return updateDescriptionMsg{id: n.id, description: n.description.fn(), hash: hash}
184 })
185 }
186 }
187 return n, tea.Batch(cmds...)
188 case updateTitleMsg:
189 if msg.id == n.id && msg.hash == n.title.bindingsHash {
190 n.title.update(msg.title)
191 }
192 case updateDescriptionMsg:
193 if msg.id == n.id && msg.hash == n.description.bindingsHash {
194 n.description.update(msg.description)
195 }
196 case tea.KeyMsg:
197 switch {
198 case key.Matches(msg, n.keymap.Prev):
199 return n, PrevField
200 case key.Matches(msg, n.keymap.Next, n.keymap.Submit):
201 return n, NextField
202 }
203 return n, NextField
204 }
205 return n, nil
206 }
207
208 func (n *Note) activeStyles() *FieldStyles {
209 theme := n.theme
210 if theme == nil {
211 theme = ThemeCharm()
212 }
213 if n.focused {
214 return &theme.Focused
215 }
216 return &theme.Blurred
217 }
218
219 // View renders the note field.
220 func (n *Note) View() string {
221 styles := n.activeStyles()
222 maxWidth := n.width - styles.Card.GetHorizontalFrameSize()
223 sb := strings.Builder{}
224
225 if n.title.val != "" || n.title.fn != nil {
226 sb.WriteString(styles.NoteTitle.Render(wrap(n.title.val, maxWidth)))
227 }
228 if n.description.val != "" || n.description.fn != nil {
229 sb.WriteRune('\n')
230 sb.WriteString(wrap(render(n.description.val), maxWidth))
231 sb.WriteRune('\n')
232 }
233 if n.showNextButton {
234 sb.WriteRune('\n')
235 sb.WriteString(styles.Next.Render(n.nextLabel))
236 }
237 return styles.Card.
238 Height(n.height).
239 Width(n.width).
240 Render(sb.String())
241 }
242
243 // Run runs the note field.
244 func (n *Note) Run() error {
245 if n.accessible { // TODO: remove in a future release.
246 return n.RunAccessible(os.Stdout, os.Stdin)
247 }
248 return Run(n)
249 }
250
251 // RunAccessible runs an accessible note field.
252 func (n *Note) RunAccessible(w io.Writer, _ io.Reader) error {
253 styles := n.activeStyles()
254 if n.title.val != "" {
255 _, _ = fmt.Fprintln(w, styles.Title.Render(n.title.val))
256 }
257 if n.description.val != "" {
258 _, _ = fmt.Fprintln(w, n.description.val)
259 }
260 return nil
261 }
262
263 // WithTheme sets the theme on a note field.
264 func (n *Note) WithTheme(theme *Theme) Field {
265 if n.theme != nil {
266 return n
267 }
268 n.theme = theme
269 return n
270 }
271
272 // WithKeyMap sets the keymap on a note field.
273 func (n *Note) WithKeyMap(k *KeyMap) Field {
274 n.keymap = k.Note
275 return n
276 }
277
278 // WithAccessible sets the accessible mode of the note field.
279 //
280 // Deprecated: you may now call [Note.RunAccessible] directly to run the
281 // field in accessible mode.
282 func (n *Note) WithAccessible(accessible bool) Field {
283 n.accessible = accessible
284 return n
285 }
286
287 // WithWidth sets the width of the note field.
288 func (n *Note) WithWidth(width int) Field {
289 n.width = width
290 return n
291 }
292
293 // WithHeight sets the height of the note field.
294 func (n *Note) WithHeight(height int) Field {
295 n.Height(height)
296 return n
297 }
298
299 // WithPosition sets the position information of the note field.
300 func (n *Note) WithPosition(p FieldPosition) Field {
301 // if the note is the only field on the screen,
302 // we shouldn't skip the entire group.
303 if p.Field == p.FirstField && p.Field == p.LastField {
304 n.skip = false
305 }
306 n.keymap.Prev.SetEnabled(!p.IsFirst())
307 n.keymap.Next.SetEnabled(!p.IsLast())
308 n.keymap.Submit.SetEnabled(p.IsLast())
309 return n
310 }
311
312 // GetValue satisfies the Field interface, notes do not have values.
313 func (n *Note) GetValue() any { return nil }
314
315 // GetKey satisfies the Field interface, notes do not have keys.
316 func (n *Note) GetKey() string { return "" }
317
318 func render(input string) string {
319 var result strings.Builder
320 var italic, bold, codeblock bool
321 var escape bool
322
323 for _, char := range input {
324 if escape || codeblock {
325 result.WriteRune(char)
326 escape = false
327 continue
328 }
329 switch char {
330 case '\\':
331 escape = true
332 case '_':
333 if !italic {
334 result.WriteString("\033[3m")
335 italic = true
336 } else {
337 result.WriteString("\033[23m")
338 italic = false
339 }
340 case '*':
341 if !bold {
342 result.WriteString("\033[1m")
343 bold = true
344 } else {
345 result.WriteString("\033[22m")
346 bold = false
347 }
348 case '`':
349 if !codeblock {
350 result.WriteString("\033[0;37;40m")
351 result.WriteString(" ")
352 codeblock = true
353 } else {
354 result.WriteString(" ")
355 result.WriteString("\033[0m")
356 codeblock = false
357
358 if bold {
359 result.WriteString("\033[1m")
360 }
361 if italic {
362 result.WriteString("\033[3m")
363 }
364 }
365 default:
366 result.WriteRune(char)
367 }
368 }
369
370 // Reset any open formatting
371 result.WriteString("\033[0m")
372
373 return result.String()
374 }