README.md
This file
Path
tutorials/basics/README.md
242 lines · 7.3 KiB · Markdown
Last changed by
docs: fix typos and clean up commentsGlenn Gondabefore adoption4880cf2
History of this fileTake it
The walk stopped after 200 commits: lines older than 3795c03 point at it.
add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 1–4why, one step back1Bubble Tea Basics2=================34Bubble Tea is based on the functional design paradigms of [The Elmdocs(tutorials): fix typo in basics tutorial and move a paragraphChristian Rochabefore adoptiona7d6b5c
lines 5–6why, one step back5Architecture][elm], which happens to work nicely with Go. It's a delightful way6to build applications.add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 7–9why, one step back78This tutorial assumes you have a working knowledge of Go.9docs(tutorials): fix typo in basics tutorial and move a paragraphChristian Rochabefore adoptiona7d6b5c
lines 10–12why, one step back10By the way, the non-annotated source code for this program is available11[on GitHub][tut-source].12add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
line 13why, one step back13[elm]: https://guide.elm-lang.org/architecture/docs(tutorials): fix typo in basics tutorial and move a paragraphChristian Rochabefore adoptiona7d6b5c
line 14why, one step back14[tut-source]:https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basicsadd: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 15–17why, one step back1516## Enough! Let's get to it.17fix: fix typosbashbunnibefore adoptiond0f3e1e
line 18why, one step back18For this tutorial, we're making a shopping list.add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 19–55why, one step back1920To start we'll define our package and import some libraries. Our only external21import will be the Bubble Tea library, which we'll call `tea` for short.2223```go24package main2526import (27 "fmt"28 "os"2930 tea "github.com/charmbracelet/bubbletea"31)32```3334Bubble Tea programs are comprised of a **model** that describes the application35state and three simple methods on that model:3637* **Init**, a function that returns an initial command for the application to run.38* **Update**, a function that handles incoming events and updates the model accordingly.39* **View**, a function that renders the UI based on the data in the model.4041## The Model4243So let's start by defining our model which will store our application's state.44It can be any type, but a `struct` usually makes the most sense.4546```go47type model struct {48 choices []string // items on the to-do list49 cursor int // which to-do list item our cursor is pointing at50 selected map[int]struct{} // which to-do items are selected51}52```5354## Initialization55fix: fix typosbashbunnibefore adoptiond0f3e1e
lines 56–57why, one step back56Next, we’ll define our application’s initial state. In this case, we’re defining57a function to return our initial model, however, we could just as easily defineadd: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 58–62why, one step back58the initial model as a variable elsewhere, too.5960```go61func initialModel() model {62 return model{docs: readme improvements (#448)Christian Rochabefore adoptionbf39962
line 63why, one step back63 // Our to-do list is a grocery listadd: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 64–66why, one step back64 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},6566 // A map which indicates which choices are selected. We're usingdocs: fix typos and clean up commentsGlenn Gondabefore adoption4880cf2
line 67why, one step back67 // the map like a mathematical set. The keys refer to the indexesadd: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 68–73why, one step back68 // of the `choices` slice, above.69 selected: make(map[int]struct{}),70 }71}72```73fix: fix typosbashbunnibefore adoptiond0f3e1e
lines 74–75why, one step back74Next, we define the `Init` method. `Init` can return a `Cmd` that could perform75some initial I/O. For now, we don't need to do any I/O, so for the command,add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 76–155why, one step back76we'll just return `nil`, which translates to "no command."7778```go79func (m model) Init() tea.Cmd {80 // Just return `nil`, which means "no I/O right now, please."81 return nil82}83```8485## The Update Method8687Next up is the update method. The update function is called when ”things88happen.” Its job is to look at what has happened and return an updated model in89response. It can also return a `Cmd` to make more things happen, but for now90don't worry about that part.9192In our case, when a user presses the down arrow, `Update`’s job is to notice93that the down arrow was pressed and move the cursor accordingly (or not).9495The “something happened” comes in the form of a `Msg`, which can be any type.96Messages are the result of some I/O that took place, such as a keypress, timer97tick, or a response from a server.9899We usually figure out which type of `Msg` we received with a type switch, but100you could also use a type assertion.101102For now, we'll just deal with `tea.KeyMsg` messages, which are automatically103sent to the update function when keys are pressed.104105```go106func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {107 switch msg := msg.(type) {108109 // Is it a key press?110 case tea.KeyMsg:111112 // Cool, what was the actual key pressed?113 switch msg.String() {114115 // These keys should exit the program.116 case "ctrl+c", "q":117 return m, tea.Quit118119 // The "up" and "k" keys move the cursor up120 case "up", "k":121 if m.cursor > 0 {122 m.cursor--123 }124125 // The "down" and "j" keys move the cursor down126 case "down", "j":127 if m.cursor < len(m.choices)-1 {128 m.cursor++129 }130131 // The "enter" key and the spacebar (a literal space) toggle132 // the selected state for the item that the cursor is pointing at.133 case "enter", " ":134 _, ok := m.selected[m.cursor]135 if ok {136 delete(m.selected, m.cursor)137 } else {138 m.selected[m.cursor] = struct{}{}139 }140 }141 }142143 // Return the updated model to the Bubble Tea runtime for processing.144 // Note that we're not returning a command.145 return m, nil146}147```148149You may have noticed that <kbd>ctrl+c</kbd> and <kbd>q</kbd> above return150a `tea.Quit` command with the model. That’s a special command which instructs151the Bubble Tea runtime to quit, exiting the program.152153## The View Method154155At last, it’s time to render our UI. Of all the methods, the view is thefix: fix typosbashbunnibefore adoptiond0f3e1e
line 156why, one step back156simplest. We look at the model in its current state and use it to returndocs: fix typos and clean up commentsGlenn Gondabefore adoption4880cf2
line 157why, one step back157a `string`. That string is our UI!add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 158–202why, one step back158159Because 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```go164func (m model) View() string {165 // The header166 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 rendering191 return s192}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())chore: rename StartReturningModel to RunChristian Muehlhaeuserbefore adoption6b77c8f
line 203why, one step back203 if _, err := p.Run(); err != nil {add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 204–232why, one step back204 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, but213in the real world you'll also need to perform I/O. To learn about that have a214look at the [Command Tutorial][cmd]. It's pretty simple.215216There are also several [Bubble Tea examples][examples] available and, of course,217there are [Go Docs][docs].218219[cmd]: http://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands/220[examples]: http://github.com/charmbracelet/bubbletea/tree/master/examples221[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc222223## Additional Resources224225* [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)227228### Feedback229230We'd love to hear your thoughts on this tutorial. Feel free to drop us a note!231232* [Twitter](https://twitter.com/charmcli)docs: new readme footerChristian Muehlhaeuserbefore adoption3938164
lines 233–234why, one step back233* [The Fediverse](https://mastodon.social/@charmcli)234* [Discord](https://charm.sh/chat)add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 235–239why, one step back235236***237238Part of [Charm](https://charm.sh).239fix: fix typosbashbunnibefore adoptiond0f3e1e
line 240why, one step back240<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 241–242why, one step back241242Charm热爱开源 • Charm loves open source