Intro
Bubbletea is a framework with a philosophy based on The Elm Architecture: Making it simple, it breaks into three parts:
- Model: the state of your application
- View: a way to turn your state into something to display
- Update: a way to update your state based on messages
The framework’s runtime manages everything else: from messages orchestration to low-level rendering details.
Example
Let’s say you want to create the classic to-do list:
your model will be a struct holding a list of tasks, and a flag to mark them “Done”
type model struct { tasks []string // items on the to-do list done []bool // which to-do items are done }
your view will be a function that takes the model and return a string representation of the task list
func (m model) View() string { var s strings.Builder // Iterate over our choices for i, tasks := range m.tasks { // Is this task done? if m.done[i] { s.WriteString("[x] ") } else { s.WriteString("[ ] ") } s.WriteString(tasks[i]+"\n") } return s.String() }
your update will be a function that takes a message that comes from the framework and reacts to it, for example a keypress, a mouse click or a window resize. Check the docs for details.
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { // here you need to process events from the framework // and return an updated model plus optionally a new Command to execute } }
As a final step, you only need to pass the model to the framework:
func main() { p := tea.NewProgram(model{}) if _, err := p.Run(); err != nil { fmt.Printf("There's been an error: %v", err) os.Exit(1) } }
Something fun
Instead of the boring to-do list, as another example I implemented the classic “bouncing ball” with the walls that can be resizeable; you can see the program reacts to the window resize and acts accordingly.
The source code is rather simple:
|
|
The only big difference here is a custom message type, used to send periodic events to the application in order to update itself without user interaction. Sounds like one can also write some games 😉 !
Of course you can find lots of examples in the library’s repository.
Wrapping up
With Bubbletea I can also recommend some ideal “companion” libraries, all from https://github.com/charmbracelet/:
- Bubbles for ready made “components”
- Lipgloss for colorization, layout and styling, more or less “CSS for the terminal”
Have fun!