File: group.go

package info (click to toggle)
golang-github-charmbracelet-huh 0.5.2%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 656 kB
  • sloc: makefile: 15
file content (350 lines) | stat: -rw-r--r-- 8,266 bytes parent folder | download
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
package huh

import (
	"strings"

	"github.com/charmbracelet/bubbles/help"
	"github.com/charmbracelet/bubbles/paginator"
	"github.com/charmbracelet/bubbles/viewport"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

// Group is a collection of fields that are displayed together with a page of
// the form. While a group is displayed the form completer can switch between
// fields in the group.
//
// If any of the fields in a group have errors, the form will not be able to
// progress to the next group.
type Group struct {
	// collection of fields
	fields []Field

	// information
	title       string
	description string

	// navigation
	paginator paginator.Model
	viewport  viewport.Model

	// help
	showHelp bool
	help     help.Model

	// errors
	showErrors bool

	// group options
	width  int
	height int
	keymap *KeyMap
	hide   func() bool
	active bool
}

// NewGroup returns a new group with the given fields.
func NewGroup(fields ...Field) *Group {
	p := paginator.New()
	p.SetTotalPages(len(fields))

	group := &Group{
		fields:     fields,
		paginator:  p,
		help:       help.New(),
		showHelp:   true,
		showErrors: true,
		active:     false,
	}

	height := group.fullHeight()
	//nolint:gomnd
	v := viewport.New(80, height)
	group.viewport = v
	group.height = height

	return group
}

// Title sets the group's title.
func (g *Group) Title(title string) *Group {
	g.title = title
	return g
}

// Description sets the group's description.
func (g *Group) Description(description string) *Group {
	g.description = description
	return g
}

// WithShowHelp sets whether or not the group's help should be shown.
func (g *Group) WithShowHelp(show bool) *Group {
	g.showHelp = show
	return g
}

// WithShowErrors sets whether or not the group's errors should be shown.
func (g *Group) WithShowErrors(show bool) *Group {
	g.showErrors = show
	return g
}

// WithTheme sets the theme on a group.
func (g *Group) WithTheme(t *Theme) *Group {
	g.help.Styles = t.Help
	for _, field := range g.fields {
		field.WithTheme(t)
	}
	if g.height <= 0 {
		g.WithHeight(g.fullHeight())
	}
	return g
}

// WithKeyMap sets the keymap on a group.
func (g *Group) WithKeyMap(k *KeyMap) *Group {
	g.keymap = k
	for _, field := range g.fields {
		field.WithKeyMap(k)
	}
	return g
}

// WithWidth sets the width on a group.
func (g *Group) WithWidth(width int) *Group {
	g.width = width
	g.viewport.Width = width
	for _, field := range g.fields {
		field.WithWidth(width)
	}
	return g
}

// WithHeight sets the height on a group.
func (g *Group) WithHeight(height int) *Group {
	g.height = height
	g.viewport.Height = height
	for _, field := range g.fields {
		// A field height must not exceed the form height.
		if height-1 <= lipgloss.Height(field.View()) {
			field.WithHeight(height)
		}
	}
	return g
}

// WithHide sets whether this group should be skipped.
func (g *Group) WithHide(hide bool) *Group {
	g.WithHideFunc(func() bool { return hide })
	return g
}

// WithHideFunc sets the function that checks if this group should be skipped.
func (g *Group) WithHideFunc(hideFunc func() bool) *Group {
	g.hide = hideFunc
	return g
}

// Errors returns the groups' fields' errors.
func (g *Group) Errors() []error {
	var errs []error
	for _, field := range g.fields {
		if err := field.Error(); err != nil {
			errs = append(errs, err)
		}
	}
	return errs
}

// updateFieldMsg is a message to update the fields of a group that is currently
// displayed.
//
// This is used to update all TitleFunc, DescriptionFunc, and ...Func update
// methods to make all fields dynamically update based on user input.
type updateFieldMsg struct{}

// nextFieldMsg is a message to move to the next field,
//
// each field controls when to send this message such that it is able to use
// different key bindings or events to trigger group progression.
type nextFieldMsg struct{}

// prevFieldMsg is a message to move to the previous field.
//
// each field controls when to send this message such that it is able to use
// different key bindings or events to trigger group progression.
type prevFieldMsg struct{}

// NextField is the command to move to the next field.
func NextField() tea.Msg {
	return nextFieldMsg{}
}

// PrevField is the command to move to the previous field.
func PrevField() tea.Msg {
	return prevFieldMsg{}
}

// Init initializes the group.
func (g *Group) Init() tea.Cmd {
	var cmds []tea.Cmd

	if g.fields[g.paginator.Page].Skip() {
		if g.paginator.OnLastPage() {
			cmds = append(cmds, g.prevField()...)
		} else if g.paginator.Page == 0 {
			cmds = append(cmds, g.nextField()...)
		}
		return tea.Batch(cmds...)
	}

	if g.active {
		cmd := g.fields[g.paginator.Page].Focus()
		cmds = append(cmds, cmd)
	}
	g.buildView()
	return tea.Batch(cmds...)
}

// nextField moves to the next field.
func (g *Group) nextField() []tea.Cmd {
	blurCmd := g.fields[g.paginator.Page].Blur()
	if g.paginator.OnLastPage() {
		return []tea.Cmd{blurCmd, nextGroup}
	}
	g.paginator.NextPage()
	for g.fields[g.paginator.Page].Skip() {
		if g.paginator.OnLastPage() {
			return []tea.Cmd{blurCmd, nextGroup}
		}
		g.paginator.NextPage()
	}
	focusCmd := g.fields[g.paginator.Page].Focus()
	return []tea.Cmd{blurCmd, focusCmd}
}

// prevField moves to the previous field.
func (g *Group) prevField() []tea.Cmd {
	blurCmd := g.fields[g.paginator.Page].Blur()
	if g.paginator.Page <= 0 {
		return []tea.Cmd{blurCmd, prevGroup}
	}
	g.paginator.PrevPage()
	for g.fields[g.paginator.Page].Skip() {
		if g.paginator.Page <= 0 {
			return []tea.Cmd{blurCmd, prevGroup}
		}
		g.paginator.PrevPage()
	}
	focusCmd := g.fields[g.paginator.Page].Focus()
	return []tea.Cmd{blurCmd, focusCmd}
}

// Update updates the group.
func (g *Group) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	// Update all the fields in the group.
	for i := range g.fields {
		switch msg := msg.(type) {
		case tea.KeyMsg:
			break
		default:
			m, cmd := g.fields[i].Update(msg)
			g.fields[i] = m.(Field)
			cmds = append(cmds, cmd)
		}
		if g.paginator.Page == i {
			m, cmd := g.fields[i].Update(msg)
			g.fields[i] = m.(Field)
			cmds = append(cmds, cmd)
		}
		m, cmd := g.fields[i].Update(updateFieldMsg{})
		g.fields[i] = m.(Field)
		cmds = append(cmds, cmd)
	}

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		g.WithHeight(min(g.height, min(g.fullHeight(), msg.Height-1)))
	case nextFieldMsg:
		cmds = append(cmds, g.nextField()...)
	case prevFieldMsg:
		cmds = append(cmds, g.prevField()...)
	}

	g.buildView()

	return g, tea.Batch(cmds...)
}

// height returns the full height of the group.
func (g *Group) fullHeight() int {
	height := len(g.fields)
	for _, f := range g.fields {
		height += lipgloss.Height(f.View())
	}
	return height
}

func (g *Group) getContent() (int, string) {
	var fields strings.Builder
	offset := 0
	gap := "\n\n"

	// if the focused field is requesting it be zoomed, only show that field.
	if g.fields[g.paginator.Page].Zoom() {
		g.fields[g.paginator.Page].WithHeight(g.height - 1)
		fields.WriteString(g.fields[g.paginator.Page].View())
	} else {
		for i, field := range g.fields {
			fields.WriteString(field.View())
			if i == g.paginator.Page {
				offset = lipgloss.Height(fields.String()) - lipgloss.Height(field.View())
			}
			if i < len(g.fields)-1 {
				fields.WriteString(gap)
			}
		}
	}

	return offset, fields.String() + "\n"
}

func (g *Group) buildView() {
	offset, content := g.getContent()

	g.viewport.SetContent(content)
	g.viewport.SetYOffset(offset)
}

// View renders the group.
func (g *Group) View() string {
	var view strings.Builder
	view.WriteString(g.viewport.View())
	view.WriteString(g.Footer())
	return view.String()
}

// Content renders the group's content only (no footer).
func (g *Group) Content() string {
	_, content := g.getContent()
	return content
}

// Footer renders the group's footer only (no content).
func (g *Group) Footer() string {
	var view strings.Builder
	view.WriteRune('\n')
	errors := g.Errors()
	if g.showHelp && len(errors) <= 0 {
		view.WriteString(g.help.ShortHelpView(g.fields[g.paginator.Page].KeyBinds()))
	}
	if g.showErrors {
		for _, err := range errors {
			view.WriteString(ThemeCharm().Focused.ErrorMessage.Render(err.Error()))
		}
	}
	return view.String()
}