Skip to content
Myr

README.md

This file

Path

tutorials/basics/README.md

242 lines · 7.3 KiB · Markdown

Last changed by

docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b

History of this file

Take it

The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 1why, one step back
1# Bubble Tea Basics

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 2–3why, one step back
2
3Bubble Tea is based on the functional design paradigms of [The Elm

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 4why, one step back
4Architecture][elm], which happens to work nicely with Go. It’s a delightful way

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 5–12why, one step back
5to build applications.
67This tutorial assumes you have a working knowledge of Go.89By the way, the non-annotated source code for this program is available10[on GitHub][tut-source].1112[elm]: https://guide.elm-lang.org/architecture/

docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b

line 13why, one step back
13[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 14why, one step back
14

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 15why, one step back
15## Enough! Let’s get to it.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 16why, one step back
16

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 17why, one step back
17For this tutorial, we’re making a shopping list.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 18why, one step back
18

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 19–20why, one step back
19To start we’ll define our package and import some libraries. Our only external
20import will be the Bubble Tea library, which we’ll call `tea` for short.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 21–28why, one step back
21
22```go23package main2425import (26 "fmt"27 "os"28

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 29why, one step back
29 tea "charm.land/bubbletea/v2"

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 30–35why, one step back
30)
31```3233Bubble Tea programs are comprised of a **model** that describes the application34state and three simple methods on that model:35

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 36–38why, one step back
36- **Init**, a function that returns an initial command for the application to run.
37- **Update**, a function that handles incoming events and updates the model accordingly.38- **View**, a function that renders the UI based on the data in the model.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 39–41why, one step back
39
40## The Model41

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 42why, one step back
42So let’s start by defining our model which will store our application’s state.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 43–72why, one step back
43It can be any type, but a `struct` usually makes the most sense.
4445```go46type model struct {47 choices []string // items on the to-do list48 cursor int // which to-do list item our cursor is pointing at49 selected map[int]struct{} // which to-do items are selected50}51```5253## Initialization5455Next, we’ll define our application’s initial state. In this case, we’re defining56a function to return our initial model, however, we could just as easily define57the initial model as a variable elsewhere, too.5859```go60func initialModel() model {61 return model{62 // Our to-do list is a grocery list63 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},6465 // A map which indicates which choices are selected. We're using66 // the map like a mathematical set. The keys refer to the indexes67 // of the `choices` slice, above.68 selected: make(map[int]struct{}),69 }70}71```72

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 73–75why, one step back
73After that, we’ll define the `Init` method. `Init` can return a `Cmd` that
74could perform some initial I/O. For now, we don’t need to do any I/O, so for75the command, we’ll just return `nil`, which translates to "no command."

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 76–84why, one step back
76
77```go78func (m model) Init() tea.Cmd {79 return nil80}81```8283## The Update Method84

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 85why, one step back
85Next up is the update method. The update function is called when “things

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 86–87why, one step back
86happen.” Its job is to look at what has happened and return an updated model in
87response. It can also return a `Cmd` to make more things happen, but for now

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 88why, one step back
88don’t worry about that part.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 89–99why, one step back
89
90In our case, when a user presses the down arrow, `Update`’s job is to notice91that the down arrow was pressed and move the cursor accordingly (or not).9293The “something happened” comes in the form of a `Msg`, which can be any type.94Messages are the result of some I/O that took place, such as a keypress, timer95tick, or a response from a server.9697We usually figure out which type of `Msg` we received with a type switch, but98you could also use a type assertion.99

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 100–101why, one step back
100For now, we’ll just deal with `tea.KeyPressMsg` messages, which are
101automatically sent to the update function when keys are pressed.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 102–107why, one step back
102
103```go104func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {105 switch msg := msg.(type) {106107 // Is it a key press?

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 108why, one step back
108 case tea.KeyPressMsg:

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 109–128why, one step back
109
110 // Cool, what was the actual key pressed?111 switch msg.String() {112113 // These keys should exit the program.114 case "ctrl+c", "q":115 return m, tea.Quit116117 // The "up" and "k" keys move the cursor up118 case "up", "k":119 if m.cursor > 0 {120 m.cursor--121 }122123 // The "down" and "j" keys move the cursor down124 case "down", "j":125 if m.cursor < len(m.choices)-1 {126 m.cursor++127 }128

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 129–131why, one step back
129 // The enter key and the space bar toggle the selected state for the
130 // item that the cursor is pointing at.131 case "enter", "space":

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 132–154why, one step back
132 _, ok := m.selected[m.cursor]
133 if ok {134 delete(m.selected, m.cursor)135 } else {136 m.selected[m.cursor] = struct{}{}137 }138 }139 }140141 // Return the updated model to the Bubble Tea runtime for processing.142 // Note that we're not returning a command.143 return m, nil144}145```146147You may have noticed that <kbd>ctrl+c</kbd> and <kbd>q</kbd> above return148a `tea.Quit` command with the model. That’s a special command which instructs149the Bubble Tea runtime to quit, exiting the program.150151## The View Method152153At last, it’s time to render our UI. Of all the methods, the view is the154simplest. We look at the model in its current state and use it to return

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 155–157why, one step back
155a `tea.View`. The view declares our UI content and, optionally, terminal
156features like full-window mode (aka, altscreen mode), mouse tracking, cursor157position, and more.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 158–163why, one step back
158
159Because the view describes the entire UI of your application, you don’t have to160worry about redrawing logic and stuff like that. Bubble Tea takes care of it161for you.162163```go

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 164why, one step back
164func (m model) View() tea.View {

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 165–190why, one step back
165 // The header
166 s := "What should we buy at the market?\n\n"167168 // Iterate over our choices169 for i, choice := range m.choices {170171 // Is the cursor pointing at this choice?172 cursor := " " // no cursor173 if m.cursor == i {174 cursor = ">" // cursor!175 }176177 // Is this choice selected?178 checked := " " // not selected179 if _, ok := m.selected[i]; ok {180 checked = "x" // selected!181 }182183 // Render the row184 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)185 }186187 // The footer188 s += "\nPress q to quit.\n"189190 // Send the UI for rendering

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 191why, one step back
191 return tea.NewView(s)

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 192–212why, one step back
192}
193```194195## All Together Now196197The last step is to simply run our program. We pass our initial model to198`tea.NewProgram` and let it rip:199200```go201func main() {202 p := tea.NewProgram(initialModel())203 if _, err := p.Run(); err != nil {204 fmt.Printf("Alas, there's been an error: %v", err)205 os.Exit(1)206 }207}208```209210## What’s Next?211212This tutorial covers the basics of building an interactive terminal UI, but

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 213–214why, one step back
213in the real world you’ll also need to perform I/O. To learn about that have a
214look at the [Command Tutorial][cmd]. It’s pretty simple.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 215–218why, one step back
215
216There are also several [Bubble Tea examples][examples] available and, of course,217there are [Go Docs][docs].218

docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b

lines 219–220why, one step back
219[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/
220[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 221why, one step back
221[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 222–224why, one step back
222
223## Additional Resources224

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 225–226why, one step back
225- [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)
226- [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 227–229why, one step back
227
228### Feedback229

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 230why, one step back
230We’d love to hear your thoughts on this tutorial. Feel free to drop us a note!

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 231why, one step back
231

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 232–234why, one step back
232- [Twitter](https://twitter.com/charmcli)
233- [The Fediverse](https://mastodon.social/@charmcli)234- [Discord](https://charm.sh/chat)

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 235why, one step back
235

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 236why, one step back
236---

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 237–242why, one step back
237
238Part of [Charm](https://charm.sh).239240<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>241242Charm热爱开源 • Charm loves open source