Debian Codegraph @

group.go

raw symbols SCIP
1 package huh
2
3 import (
4 "strings"
5
6 "github.com/charmbracelet/bubbles/help"
7 "github.com/charmbracelet/bubbles/viewport"
8 tea "github.com/charmbracelet/bubbletea"
9 "github.com/charmbracelet/huh/internal/selector"
10 "github.com/charmbracelet/lipgloss"
11 )
12
13 // Group is a collection of fields that are displayed together with a page of
14 // the form. While a group is displayed the form completer can switch between
15 // fields in the group.
16 //
17 // If any of the fields in a group have errors, the form will not be able to
18 // progress to the next group.
19 type Group struct {
20 // collection of fields
21 selector *selector.Selector[Field]
22
23 // information
24 title string
25 description string
26
27 // navigation
28 viewport viewport.Model
29
30 // help
31 showHelp bool
32 help help.Model
33
34 // errors
35 showErrors bool
36
37 // group options
38 width int
39 height int
40 theme *Theme
41 keymap *KeyMap
42 hide func() bool
43 active bool
44 }
45
46 // NewGroup returns a new group with the given fields.
47 func NewGroup(fields ...Field) *Group {
48 selector := selector.NewSelector(fields)
49 group := &Group{
50 selector: selector,
51 help: help.New(),
52 showHelp: true,
53 showErrors: true,
54 active: false,
55 }
56
57 group.width = 80
58 height := group.rawHeight()
59 v := viewport.New(group.width, height) //nolint:mnd
60 group.viewport = v
61 group.height = height
62
63 return group
64 }
65
66 // Title sets the group's title.
67 func (g *Group) Title(title string) *Group {
68 g.title = title
69 return g
70 }
71
72 // Description sets the group's description.
73 func (g *Group) Description(description string) *Group {
74 g.description = description
75 return g
76 }
77
78 // WithShowHelp sets whether or not the group's help should be shown.
79 func (g *Group) WithShowHelp(show bool) *Group {
80 g.showHelp = show
81 return g
82 }
83
84 // WithShowErrors sets whether or not the group's errors should be shown.
85 func (g *Group) WithShowErrors(show bool) *Group {
86 g.showErrors = show
87 return g
88 }
89
90 // WithTheme sets the theme on a group.
91 func (g *Group) WithTheme(t *Theme) *Group {
92 g.theme = t
93 g.help.Styles = t.Help
94 g.selector.Range(func(_ int, field Field) bool {
95 field.WithTheme(t)
96 return true
97 })
98 if g.height <= 0 {
99 g.WithHeight(g.rawHeight())
100 }
101 return g
102 }
103
104 // WithKeyMap sets the keymap on a group.
105 func (g *Group) WithKeyMap(k *KeyMap) *Group {
106 g.keymap = k
107 g.selector.Range(func(_ int, field Field) bool {
108 field.WithKeyMap(k)
109 return true
110 })
111 return g
112 }
113
114 // WithWidth sets the width on a group.
115 func (g *Group) WithWidth(width int) *Group {
116 g.width = width
117 g.viewport.Width = width
118 g.help.Width = width
119 g.selector.Range(func(_ int, field Field) bool {
120 field.WithWidth(width)
121 return true
122 })
123 return g
124 }
125
126 // WithHeight sets the height on a group.
127 func (g *Group) WithHeight(height int) *Group {
128 g.height = height
129 h := height - g.titleFooterHeight()
130 g.viewport.Height = h
131 g.selector.Range(func(_ int, field Field) bool {
132 // A field height must not exceed the form height.
133 if h < lipgloss.Height(field.View()) {
134 field.WithHeight(h)
135 }
136 return true
137 })
138 return g
139 }
140
141 // WithHide sets whether this group should be skipped.
142 func (g *Group) WithHide(hide bool) *Group {
143 g.WithHideFunc(func() bool { return hide })
144 return g
145 }
146
147 // WithHideFunc sets the function that checks if this group should be skipped.
148 func (g *Group) WithHideFunc(hideFunc func() bool) *Group {
149 g.hide = hideFunc
150 return g
151 }
152
153 // Errors returns the groups' fields' errors.
154 func (g *Group) Errors() []error {
155 var errs []error
156 g.selector.Range(func(_ int, field Field) bool {
157 if err := field.Error(); err != nil {
158 errs = append(errs, err)
159 }
160 return true
161 })
162 return errs
163 }
164
165 // updateFieldMsg is a message to update the fields of a group that is currently
166 // displayed.
167 //
168 // This is used to update all TitleFunc, DescriptionFunc, and ...Func update
169 // methods to make all fields dynamically update based on user input.
170 type updateFieldMsg struct{}
171
172 // nextFieldMsg is a message to move to the next field,
173 //
174 // each field controls when to send this message such that it is able to use
175 // different key bindings or events to trigger group progression.
176 type nextFieldMsg struct{}
177
178 // prevFieldMsg is a message to move to the previous field.
179 //
180 // each field controls when to send this message such that it is able to use
181 // different key bindings or events to trigger group progression.
182 type prevFieldMsg struct{}
183
184 // NextField is the command to move to the next field.
185 func NextField() tea.Msg {
186 return nextFieldMsg{}
187 }
188
189 // PrevField is the command to move to the previous field.
190 func PrevField() tea.Msg {
191 return prevFieldMsg{}
192 }
193
194 // Init initializes the group.
195 func (g *Group) Init() tea.Cmd {
196 var cmds []tea.Cmd
197
198 cmds = append(cmds, func() tea.Msg { return updateFieldMsg{} })
199
200 if g.selector.Selected().Skip() {
201 if g.selector.OnLast() {
202 cmds = append(cmds, g.prevField()...)
203 } else if g.selector.OnFirst() {
204 cmds = append(cmds, g.nextField()...)
205 }
206 return tea.Batch(cmds...)
207 }
208
209 if g.active {
210 cmd := g.selector.Selected().Focus()
211 cmds = append(cmds, cmd)
212 }
213 g.buildView()
214 return tea.Batch(cmds...)
215 }
216
217 // nextField moves to the next field.
218 func (g *Group) nextField() []tea.Cmd {
219 blurCmd := g.selector.Selected().Blur()
220 if g.selector.OnLast() {
221 return []tea.Cmd{blurCmd, nextGroup}
222 }
223 g.selector.Next()
224 for g.selector.Selected().Skip() {
225 if g.selector.OnLast() {
226 return []tea.Cmd{blurCmd, nextGroup}
227 }
228 g.selector.Next()
229 }
230 focusCmd := g.selector.Selected().Focus()
231 return []tea.Cmd{blurCmd, focusCmd}
232 }
233
234 // prevField moves to the previous field.
235 func (g *Group) prevField() []tea.Cmd {
236 blurCmd := g.selector.Selected().Blur()
237 if g.selector.OnFirst() {
238 return []tea.Cmd{blurCmd, prevGroup}
239 }
240 g.selector.Prev()
241 for g.selector.Selected().Skip() {
242 if g.selector.OnFirst() {
243 return []tea.Cmd{blurCmd, prevGroup}
244 }
245 g.selector.Prev()
246 }
247 focusCmd := g.selector.Selected().Focus()
248 return []tea.Cmd{blurCmd, focusCmd}
249 }
250
251 // Update updates the group.
252 func (g *Group) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
253 var cmds []tea.Cmd
254
255 // Update all the fields in the group.
256 g.selector.Range(func(i int, field Field) bool {
257 switch msg := msg.(type) {
258 case tea.KeyMsg:
259 break
260 default:
261 m, cmd := field.Update(msg)
262 g.selector.Set(i, m.(Field))
263 cmds = append(cmds, cmd)
264 }
265 if g.selector.Index() == i {
266 m, cmd := field.Update(msg)
267 g.selector.Set(i, m.(Field))
268 cmds = append(cmds, cmd)
269 }
270 m, cmd := field.Update(updateFieldMsg{})
271 g.selector.Set(i, m.(Field))
272 cmds = append(cmds, cmd)
273 return true
274 })
275
276 switch msg.(type) {
277 case nextFieldMsg:
278 cmds = append(cmds, g.nextField()...)
279 case prevFieldMsg:
280 cmds = append(cmds, g.prevField()...)
281 }
282
283 g.buildView()
284
285 return g, tea.Batch(cmds...)
286 }
287
288 func (g *Group) getTheme() *Theme {
289 if theme := g.theme; theme != nil {
290 return theme
291 }
292 return ThemeCharm()
293 }
294
295 func (g *Group) styles() GroupStyles { return g.getTheme().Group }
296
297 func (g *Group) getContent() (int, string) {
298 var fields strings.Builder
299 offset := 0
300
301 gap := g.getTheme().FieldSeparator.Render()
302
303 // if the focused field is requesting it be zoomed, only show that field.
304 if g.selector.Selected().Zoom() {
305 g.selector.Selected().WithHeight(g.height)
306 fields.WriteString(g.selector.Selected().View())
307 } else {
308 g.selector.Range(func(i int, field Field) bool {
309 fields.WriteString(field.View())
310 if i == g.selector.Index() {
311 offset = lipgloss.Height(fields.String()) - lipgloss.Height(field.View())
312 }
313 if i < g.selector.Total()-1 {
314 fields.WriteString(gap)
315 }
316 return true
317 })
318 }
319
320 return offset, fields.String()
321 }
322
323 func (g *Group) buildView() {
324 offset, content := g.getContent()
325 g.viewport.SetContent(content)
326 g.viewport.SetYOffset(offset)
327 }
328
329 // Header renders the group's header only (no content).
330 func (g *Group) Header() string {
331 styles := g.styles()
332 var parts []string
333 if g.title != "" {
334 parts = append(parts, styles.Title.Render(wrap(g.title, g.width)))
335 }
336 if g.description != "" {
337 parts = append(parts, styles.Description.Render(wrap(g.description, g.width)))
338 }
339 return strings.Join(parts, "\n")
340 }
341
342 // titleFooterHeight returns the height of the footer + header.
343 func (g *Group) titleFooterHeight() int {
344 h := 0
345 if s := g.Header(); s != "" {
346 h += lipgloss.Height(s)
347 }
348 if s := g.Footer(); s != "" {
349 h += lipgloss.Height(s)
350 }
351 return h
352 }
353
354 // rawHeight returns the full height of the group, without using a viewport.
355 func (g *Group) rawHeight() int {
356 return lipgloss.Height(g.Content()) + g.titleFooterHeight()
357 }
358
359 // View renders the group.
360 func (g *Group) View() string {
361 var parts []string
362 if s := g.Header(); s != "" {
363 parts = append(parts, s)
364 }
365 parts = append(parts, g.viewport.View())
366 if s := g.Footer(); s != "" {
367 // append an empty line, and the footer (usually the help).
368 parts = append(parts, "", s)
369 }
370 if len(parts) > 0 {
371 // Trim suffix spaces from the last part as it can accidentally
372 // scroll the view up on some terminals (like Apple's Terminal.app)
373 // when we right to the bottom rightmost corner cell.
374 lastIdx := len(parts) - 1
375 parts[lastIdx] = strings.TrimSuffix(parts[lastIdx], " ")
376 }
377 return strings.Join(parts, "\n")
378 }
379
380 // Content renders the group's content only (no footer).
381 func (g *Group) Content() string {
382 _, content := g.getContent()
383 return content
384 }
385
386 // Footer renders the group's footer only (no content).
387 func (g *Group) Footer() string {
388 var parts []string
389 errors := g.Errors()
390 if g.showHelp && len(errors) <= 0 {
391 parts = append(parts, g.help.ShortHelpView(g.selector.Selected().KeyBinds()))
392 }
393 if g.showErrors {
394 for _, err := range errors {
395 parts = append(parts, wrap(
396 g.getTheme().Focused.ErrorMessage.Render(err.Error()),
397 g.width,
398 ))
399 }
400 }
401 return g.styles().Base.
402 Render(strings.Join(parts, "\n"))
403 }