Debian Codegraph @

examples/dynamic/dynamic-bubbletea/main.go

raw symbols SCIP
1 package main
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7
8 tea "github.com/charmbracelet/bubbletea"
9 "github.com/charmbracelet/huh"
10 "github.com/charmbracelet/lipgloss"
11 )
12
13 const maxWidth = 80
14
15 var (
16 red = lipgloss.AdaptiveColor{Light: "#FE5F86", Dark: "#FE5F86"}
17 indigo = lipgloss.AdaptiveColor{Light: "#5A56E0", Dark: "#7571F9"}
18 green = lipgloss.AdaptiveColor{Light: "#02BA84", Dark: "#02BF87"}
19 )
20
21 type Styles struct {
22 Base,
23 HeaderText,
24 Status,
25 StatusHeader,
26 Highlight,
27 ErrorHeaderText,
28 Help lipgloss.Style
29 }
30
31 func NewStyles(lg *lipgloss.Renderer) *Styles {
32 s := Styles{}
33 s.Base = lg.NewStyle().
34 Padding(1, 4, 0, 1)
35 s.HeaderText = lg.NewStyle().
36 Foreground(indigo).
37 Bold(true).
38 Padding(0, 1, 0, 2)
39 s.Status = lg.NewStyle().
40 Border(lipgloss.RoundedBorder()).
41 BorderForeground(indigo).
42 PaddingLeft(1).
43 MarginTop(1)
44 s.StatusHeader = lg.NewStyle().
45 Foreground(green).
46 Bold(true)
47 s.Highlight = lg.NewStyle().
48 Foreground(lipgloss.Color("212"))
49 s.ErrorHeaderText = s.HeaderText.
50 Foreground(red)
51 s.Help = lg.NewStyle().
52 Foreground(lipgloss.Color("240"))
53 return &s
54 }
55
56 type state int
57
58 const (
59 statusNormal state = iota
60 stateDone
61 )
62
63 type Model struct {
64 state state
65 lg *lipgloss.Renderer
66 styles *Styles
67 form *huh.Form
68 width int
69 }
70
71 func NewModel() Model {
72 m := Model{width: maxWidth}
73 m.lg = lipgloss.DefaultRenderer()
74 m.styles = NewStyles(m.lg)
75
76 var class string
77
78 m.form = huh.NewForm(
79 huh.NewGroup(
80 huh.NewSelect[string]().
81 Key("class").
82 Value(&class).
83 Options(huh.NewOptions("Warrior", "Mage", "Rogue")...).
84 Title("Choose your class").
85 Description("This will determine your department"),
86
87 huh.NewSelect[string]().
88 Key("level").
89 OptionsFunc(func() []huh.Option[string] {
90 switch class {
91 case "Warrior":
92 return huh.NewOptions("1", "20", "9999")
93 case "Mage":
94 return huh.NewOptions("10", "100", "1000")
95 }
96 return huh.NewOptions("1", "20", "9999")
97 }, &class).
98 Title("Choose your level").
99 Description("This will determine your benefits package"),
100
101 huh.NewConfirm().
102 Key("done").
103 Title("All done?").
104 Validate(func(v bool) error {
105 if !v {
106 return fmt.Errorf("Welp, finish up then")
107 }
108 return nil
109 }).
110 Affirmative("Yep").
111 Negative("Wait, no"),
112 ),
113 ).
114 WithWidth(45).
115 WithShowHelp(false).
116 WithShowErrors(false)
117 return m
118 }
119
120 func (m Model) Init() tea.Cmd {
121 return m.form.Init()
122 }
123
124 func min(x, y int) int {
125 if x > y {
126 return y
127 }
128 return x
129 }
130
131 func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
132 switch msg := msg.(type) {
133 case tea.WindowSizeMsg:
134 m.width = min(msg.Width, maxWidth) - m.styles.Base.GetHorizontalFrameSize()
135 case tea.KeyMsg:
136 switch msg.String() {
137 case "esc", "ctrl+c", "q":
138 return m, tea.Quit
139 }
140 }
141
142 var cmds []tea.Cmd
143
144 // Process the form
145 form, cmd := m.form.Update(msg)
146 if f, ok := form.(*huh.Form); ok {
147 m.form = f
148 cmds = append(cmds, cmd)
149 }
150
151 if m.form.State == huh.StateCompleted {
152 // Quit when the form is done.
153 cmds = append(cmds, tea.Quit)
154 }
155
156 return m, tea.Batch(cmds...)
157 }
158
159 func (m Model) View() string {
160 s := m.styles
161
162 switch m.form.State {
163 case huh.StateCompleted:
164 title, role := m.getRole()
165 title = s.Highlight.Render(title)
166 var b strings.Builder
167 fmt.Fprintf(&b, "Congratulations, you’re Charm’s newest\n%s!\n\n", title)
168 fmt.Fprintf(&b, "Your job description is as follows:\n\n%s\n\nPlease proceed to HR immediately.", role)
169 return s.Status.Margin(0, 1).Padding(1, 2).Width(48).Render(b.String()) + "\n\n"
170 default:
171
172 var class string
173 if m.form.GetString("class") != "" {
174 class = "Class: " + m.form.GetString("class")
175 }
176
177 // Form (left side)
178 v := strings.TrimSuffix(m.form.View(), "\n\n")
179 form := m.lg.NewStyle().Margin(1, 0).Render(v)
180
181 // Status (right side)
182 var status string
183 {
184 var (
185 buildInfo = "(None)"
186 role string
187 jobDescription string
188 level string
189 )
190
191 if m.form.GetString("level") != "" {
192 level = "Level: " + m.form.GetString("level")
193 role, jobDescription = m.getRole()
194 role = "\n\n" + s.StatusHeader.Render("Projected Role") + "\n" + role
195 jobDescription = "\n\n" + s.StatusHeader.Render("Duties") + "\n" + jobDescription
196 }
197 if m.form.GetString("class") != "" {
198 buildInfo = fmt.Sprintf("%s\n%s", class, level)
199 }
200
201 const statusWidth = 28
202 statusMarginLeft := m.width - statusWidth - lipgloss.Width(form) - s.Status.GetMarginRight()
203 status = s.Status.
204 Height(lipgloss.Height(form)).
205 Width(statusWidth).
206 MarginLeft(statusMarginLeft).
207 Render(s.StatusHeader.Render("Current Build") + "\n" +
208 buildInfo +
209 role +
210 jobDescription)
211 }
212
213 errors := m.form.Errors()
214 header := m.appBoundaryView("Charm Employment Application")
215 if len(errors) > 0 {
216 header = m.appErrorBoundaryView(m.errorView())
217 }
218 body := lipgloss.JoinHorizontal(lipgloss.Left, form, status)
219
220 footer := m.appBoundaryView(m.form.Help().ShortHelpView(m.form.KeyBinds()))
221 if len(errors) > 0 {
222 footer = m.appErrorBoundaryView("")
223 }
224
225 return s.Base.Render(header + "\n" + body + "\n\n" + footer)
226 }
227 }
228
229 func (m Model) errorView() string {
230 var s string
231 for _, err := range m.form.Errors() {
232 s += err.Error()
233 }
234 return s
235 }
236
237 func (m Model) appBoundaryView(text string) string {
238 return lipgloss.PlaceHorizontal(
239 m.width,
240 lipgloss.Left,
241 m.styles.HeaderText.Render(text),
242 lipgloss.WithWhitespaceChars("/"),
243 lipgloss.WithWhitespaceForeground(indigo),
244 )
245 }
246
247 func (m Model) appErrorBoundaryView(text string) string {
248 return lipgloss.PlaceHorizontal(
249 m.width,
250 lipgloss.Left,
251 m.styles.ErrorHeaderText.Render(text),
252 lipgloss.WithWhitespaceChars("/"),
253 lipgloss.WithWhitespaceForeground(red),
254 )
255 }
256
257 func (m Model) getRole() (string, string) {
258 level := m.form.GetString("level")
259 switch m.form.GetString("class") {
260 case "Warrior":
261 switch level {
262 case "1":
263 return "Tank Intern", "Assists with tank-related activities. Paid position."
264 case "9999":
265 return "Tank Manager", "Manages tanks and tank-related activities."
266 default:
267 return "Tank", "General tank. Does damage, takes damage. Responsible for tanking."
268 }
269 case "Mage":
270 switch level {
271 case "1":
272 return "DPS Associate", "Finds DPS deals and passes them on to DPS Manager."
273 case "9999":
274 return "DPS Operating Officer", "Oversees all DPS activities."
275 default:
276 return "DPS", "Does damage and ideally does not take damage. Logs hours in JIRA."
277 }
278 case "Rogue":
279 switch level {
280 case "1":
281 return "Stealth Junior Designer", "Designs rougue-like activities. Reports to Stealth Lead."
282 case "9999":
283 return "Stealth Lead", "Lead designer for all things stealth. Some travel required."
284 default:
285 return "Sneaky Person", "Sneaks around and does sneaky things. Reports to Stealth Lead."
286 }
287 default:
288 return "", ""
289 }
290 }
291
292 func main() {
293 _, err := tea.NewProgram(NewModel()).Run()
294 if err != nil {
295 fmt.Println("Oh no:", err)
296 os.Exit(1)
297 }
298 }