~/Bubble Tea

Nov 3, 2024


Bubble Tea is a popular Golang framework for building TUI applications. Though the initial learning curve is somewhat steep, the setup amounts to only about 30 lines of code, consider the following example.

 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
package main

import (
	"fmt"
	tea "github.com/charmbracelet/bubbletea"
	"os"
)

type model struct{ x int }

func (m model) Init() tea.Cmd {
	return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg.(type) {
	case tea.KeyMsg:
		m.x++
		if m.x >= 10 {
			return m, tea.Quit
		}
	}
	return m, nil
}
func (m model) View() string {
	return fmt.Sprintf("Hit any key %d/10 times", m.x)
}
func main() {
	p := tea.NewProgram(model{})
	_, err := p.Run()
	if err != nil {
		os.Exit(1)
	}
}

Skipping the self explanatory code, The Init function can be used to run an initial command for your application, here is an example of such a command.

1
2
3
func (m model) Init() tea.Cmd {
	return tea.Quit
}

This may not make much sense as it will exit the application as soon as it begins, lets try another.

1
2
3
func (m model) Init() tea.Cmd {
	return tea.ClearScreen
}

ClearScreen will clear the terminal as part of the Initialization.

Looking at our Update function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg.(type) {
	case tea.KeyMsg:
		m.x++
		if m.x >= 10 {
			return m, tea.Quit
		}
	}
	return m, nil
}

The Update function will simply check if (any) button was pressed and increment the value of x, terminating the application in case the value is 10 or above.

1
2
3
func (m model) View() string {
	return fmt.Sprintf("Hit any key %d/10 times", m.x)
}

I’ll admit this View function is simplistic but it does the job, Here we take a value from our model and populate our….very simple UI to show the number of clicks needed until the program exists. All the View does is return a string that the user views in their terminal with their eyes.

References

Tags: [go] [tutorial] [bubble tea]