Debian Codegraph @

examples/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 m.form = huh.NewForm(
77 huh.NewGroup(
78 huh.NewSelect[string]().
79 Key("class").
80 Options(huh.NewOptions("Warrior", "Mage", "Rogue")...).
81 Title("Choose your class").
82 Description("This will determine your department"),
83
84 huh.NewSelect[string]().
85 Key("level").
86 Options(huh.NewOptions("1", "20", "9999")...).
87 Title("Choose your level").
88 Description("This will determine your benefits package"),
89
90 huh.NewConfirm().
91 Key("done").
92 Title("All done?").
93 Validate(func(v bool) error {
94 if !v {
95 return fmt.Errorf("Welp, finish up then")
96 }
97 return nil
98 }).
99 Affirmative("Yep").
100 Negative("Wait, no"),
101 ),
102 ).
103 WithWidth(45).
104 WithShowHelp(false).
105 WithShowErrors(false)
106 return m
107 }
108
109 func (m Model) Init() tea.Cmd {
110 return m.form.Init()
111 }
112
113 func min(x, y int) int {
114 if x > y {
115 return y
116 }
117 return x
118 }
119
120 func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
121 switch msg := msg.(type) {
122 case tea.WindowSizeMsg:
123 m.width = min(msg.Width, maxWidth) - m.styles.Base.GetHorizontalFrameSize()
124 case tea.KeyMsg:
125 switch msg.String() {
126 case "ctrl+c":
127 return m, tea.Interrupt
128 case "esc", "q":
129 return m, tea.Quit
130 }
131 }
132
133 var cmds []tea.Cmd
134
135 // Process the form
136 form, cmd := m.form.Update(msg)
137 if f, ok := form.(*huh.Form); ok {
138 m.form = f
139 cmds = append(cmds, cmd)
140 }
141
142 if m.form.State == huh.StateCompleted {
143 // Quit when the form is done.
144 cmds = append(cmds, tea.Quit)
145 }
146
147 return m, tea.Batch(cmds...)
148 }
149
150 func (m Model) View() string {
151 s := m.styles
152
153 switch m.form.State {
154 case huh.StateCompleted:
155 title, role := m.getRole()
156 title = s.Highlight.Render(title)
157 var b strings.Builder
158 fmt.Fprintf(&b, "Congratulations, you’re Charm’s newest\n%s!\n\n", title)
159 fmt.Fprintf(&b, "Your job description is as follows:\n\n%s\n\nPlease proceed to HR immediately.", role)
160 return s.Status.Margin(0, 1).Padding(1, 2).Width(48).Render(b.String()) + "\n\n"
161 default:
162
163 var class string
164 if m.form.GetString("class") != "" {
165 class = "Class: " + m.form.GetString("class")
166 }
167
168 // Form (left side)
169 v := strings.TrimSuffix(m.form.View(), "\n\n")
170 form := m.lg.NewStyle().Margin(1, 0).Render(v)
171
172 // Status (right side)
173 var status string
174 {
175 var (
176 buildInfo = "(None)"
177 role string
178 jobDescription string
179 level string
180 )
181
182 if m.form.GetString("level") != "" {
183 level = "Level: " + m.form.GetString("level")
184 role, jobDescription = m.getRole()
185 role = "\n\n" + s.StatusHeader.Render("Projected Role") + "\n" + role
186 jobDescription = "\n\n" + s.StatusHeader.Render("Duties") + "\n" + jobDescription
187 }
188 if m.form.GetString("class") != "" {
189 buildInfo = fmt.Sprintf("%s\n%s", class, level)
190 }
191
192 const statusWidth = 28
193 statusMarginLeft := m.width - statusWidth - lipgloss.Width(form) - s.Status.GetMarginRight()
194 status = s.Status.
195 Height(lipgloss.Height(form)).
196 Width(statusWidth).
197 MarginLeft(statusMarginLeft).
198 Render(s.StatusHeader.Render("Current Build") + "\n" +
199 buildInfo +
200 role +
201 jobDescription)
202 }
203
204 errors := m.form.Errors()
205 header := m.appBoundaryView("Charm Employment Application")
206 if len(errors) > 0 {
207 header = m.appErrorBoundaryView(m.errorView())
208 }
209 body := lipgloss.JoinHorizontal(lipgloss.Left, form, status)
210
211 footer := m.appBoundaryView(m.form.Help().ShortHelpView(m.form.KeyBinds()))
212 if len(errors) > 0 {
213 footer = m.appErrorBoundaryView("")
214 }
215
216 return s.Base.Render(header + "\n" + body + "\n\n" + footer)
217 }
218 }
219
220 func (m Model) errorView() string {
221 var s string
222 for _, err := range m.form.Errors() {
223 s += err.Error()
224 }
225 return s
226 }
227
228 func (m Model) appBoundaryView(text string) string {
229 return lipgloss.PlaceHorizontal(
230 m.width,
231 lipgloss.Left,
232 m.styles.HeaderText.Render(text),
233 lipgloss.WithWhitespaceChars("/"),
234 lipgloss.WithWhitespaceForeground(indigo),
235 )
236 }
237
238 func (m Model) appErrorBoundaryView(text string) string {
239 return lipgloss.PlaceHorizontal(
240 m.width,
241 lipgloss.Left,
242 m.styles.ErrorHeaderText.Render(text),
243 lipgloss.WithWhitespaceChars("/"),
244 lipgloss.WithWhitespaceForeground(red),
245 )
246 }
247
248 func (m Model) getRole() (string, string) {
249 level := m.form.GetString("level")
250 switch m.form.GetString("class") {
251 case "Warrior":
252 switch level {
253 case "1":
254 return "Tank Intern", "Assists with tank-related activities. Paid position."
255 case "9999":
256 return "Tank Manager", "Manages tanks and tank-related activities."
257 default:
258 return "Tank", "General tank. Does damage, takes damage. Responsible for tanking."
259 }
260 case "Mage":
261 switch level {
262 case "1":
263 return "DPS Associate", "Finds DPS deals and passes them on to DPS Manager."
264 case "9999":
265 return "DPS Operating Officer", "Oversees all DPS activities."
266 default:
267 return "DPS", "Does damage and ideally does not take damage. Logs hours in JIRA."
268 }
269 case "Rogue":
270 switch level {
271 case "1":
272 return "Stealth Junior Designer", "Designs rogue-like activities. Reports to Stealth Lead."
273 case "9999":
274 return "Stealth Lead", "Lead designer for all things stealth. Some travel required."
275 default:
276 return "Sneaky Person", "Sneaks around and does sneaky things. Reports to Stealth Lead."
277 }
278 default:
279 return "", ""
280 }
281 }
282
283 func main() {
284 _, err := tea.NewProgram(NewModel()).Run()
285 if err != nil {
286 fmt.Println("Oh no:", err)
287 os.Exit(1)
288 }
289 }