Skip to content
Myr

Add simple tutorial in Markdown

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent fe15629 · Browse files · 4 files+359 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+359 added−0 removed

  • other:+359 added−0 removed

4 files+359 added−0 removed

added:tutorials/basics/main.go+82 added
1package main23import (4 "fmt"5 "os"67 tea "github.com/charmbracelet/bubbletea"8)910type model struct {11 cursor int12 choices []string13 selected map[int]struct{}14}1516func initialize() (tea.Model, tea.Cmd) {17 return model{18 choices: []string{"Carrots", "Celery", "Kohlrabi"},19 selected: make(map[int]struct{}),20 }, nil21}2223func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {24 m, _ := mdl.(model)2526 switch msg := msg.(type) {27 case tea.KeyMsg:28 switch msg.String() {29 case "ctrl+c", "q":30 return m, tea.Quit31 case "up", "k":32 if m.cursor > 0 {33 m.cursor--34 }35 case "down", "j":36 if m.cursor < len(m.choices)-1 {37 m.cursor++38 }39 case "enter", " ":40 _, ok := m.selected[m.cursor]41 if ok {42 delete(m.selected, m.cursor)43 } else {44 m.selected[m.cursor] = struct{}{}45 }46 }47 }4849 return m, nil50}5152func view(mdl tea.Model) string {53 m, _ := mdl.(model)5455 s := "What should we buy at the market?\n\n"5657 for i, choice := range m.choices {58 cursor := " "59 if m.cursor == i {60 cursor = ">"61 }6263 checked := " "64 if _, ok := m.selected[i]; ok {65 checked = "x"66 }6768 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)69 }7071 s += "\nPress q to quit.\n"7273 return s74}7576func main() {77 p := tea.NewProgram(initialize, update, view)78 if err := p.Start(); err != nil {79 fmt.Printf("Alas, there's been an error: %v", err)80 os.Exit(1)81 }82}
added:tutorials/basics/README.md+235 added
1# Bubble Tea Tutorial23Bubble Tea is based on the functional design paradigms of [The Elm4Architecture][elm]. It might not seem very Go-like at first, but once you get5used to the general structure you'll find that most of the idomatic Go things6you know and love are still relevant and useful here.78By the way, the non-annotated version of of this program is available9[on GitHub](https://github.com/charmbracelet/bubbletea/master/tutorials/basics).1011This tutorial assumes you have a working knowledge of Go.1213[elm]: https://guide.elm-lang.org/architecture/1415## Enough! Let's get to it.1617For this tutorial we're making a to-do list.1819To start we'll define our package and import some libraries. Our only external20import will be the Bubble Tea, library, which we'll call `tea` for short.2122```go23 package main2425 import (26 "fmt"27 "os"2829 tea "github.com/charmbracelet/bubbletea"30 )31```3233Bubble Tea programs are comprised of a model that describes the application34state and three simple functions that are centered around the model:3536Initialize37: A function that returns the model's initial state.38Update39: A function that handles incoming events and updates the model accordingly.40View41: A function that renders the UI based on the data in the model.4243## The Model4445So let's start by defining our application's model. The model is simply the46application's state. It can be any type, but a `struct` usually makes the most47sense.4849```go50 type model struct {51 choices []string // items on the to-do list52 cursor int // which to-do list item our cursor is pointing at53 selected map[int]struct{} // which to-do items are selected54 }55```5657## Initialize5859Next we'll define a function that will initialize our application. An60initialize function returns a model representing our application's initial61state, as well as a `Cmd` that could perform some initial I/O. For now, we62don't need to do any I/O, so for the command we'll just return nil, which63translate to "no command."6465```go66 func initialize() (tea.Model, tea.Cmd) {67 m := model{6869 // Our to-do list is just a grocery list70 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},7172 // A map which indicates which choices are selected. We're using73 // the map like a mathematical set. The keys refer to the indexes74 // of the `choices` slice, above.75 selected: make(map[int]struct{}),76 }7778 // Return the model and `nil`, which means "no I/O right now, please."79 return m, nil80 }81```8283## Update8485Next we'll define the update function. The update function is called when86"things happen." It's job is to look at what has happened and return an87updated model based on whatever happened. It can also return a `Cmd` and make88more things happen, but we'll get into that later.8990In 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 as a `Msg`, which can be any type. Messages94indicate some I/O happened, such as a keypress, timer, or a response from95a server.9697We usually figure out which type of `Msg` we received with a type switch, but98you could also use a type assertion.99100For now, we'll just deal with `tea.KeyMsg`, which are automatically sent to101the update function when keys are pressed.102103```go104 func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {105 m, _ := mdl.(model)106107 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 "ctrl+c" and "q" above return a `tea.Quit` with the150model. That's a special command which instructs the Bubble Tea runtime to exit,151effectively quitting the program.152153## The View154155At last, it's time to render our UI. Of all the functions, the view is the156simplest. A model, in it's current state, comes in and a `string` comes out.157That string is our UI!158159Because the view describes the entire UI of your application, you don't have160to worry about redraw logic and stuff like that. Bubble Tea takes care of it161for you.162163```go164 func view(mdl tea.Model) string {165 m, _ := mdl.(model)166167 // The header168 s := "What should we buy at the market?\n\n"169170 // Iterate over our choices171 for i, choice := range m.choices {172173 // Is the cursor pointing at this choice?174 cursor := " " // no cursor175 if m.cursor == i {176 cursor = ">" // cursor!177 }178179 // Is this choice selected?180 checked := " " // not selected181 if _, ok := m.selected[i]; ok {182 checked = "x" // selected!183 }184185 // Render the row186 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)187 }188189 // The footer190 s += "\nPress q to quit.\n"191192 // Send off the UI to rendered193 return s194 }195```196197## All togeher now198199The last step is to simply run our program. We pass our functions to200`tea.NewProgram` and let it rip:201202```go203 func main() {204 p := tea.NewProgram(initialize, update, view)205 if err := p.Start(); err != nil {206 fmt.Printf("Alas, there's been an error: %v", err)207 os.Exit(1)208 }209 }210```211212## What's next?213214This tutorial covers the basics of building an interactive terminal UI, but215in the real world you'll also need to perform I/O. To learn about that have a216look at the [Cmd Tutorial][cmd]. It's pretty simple.217218There are also several [examples][examples] available. Many of the examples219make use of [Bubbles][bubbles], the little Bubble Tea component library which220includes handy things like a text input component, spinners and a viewport.221222Of course, there are also [Go Docs][docs] for Bubble Tea.223224[cmd]: http://github.com/charmbracelet/bubbletea/tree/master/tutorials/cmds/225[examples]: http://github.com/charmbracelet/bubbletea/tree/master/examples226[bubbles]: https://github.com/charmbracelet/bubbles227[docs]: https://pkg.go.dev/github.com/charmbracelet/glow?tab=doc228229## Feedback230231We'd love to hear your thoughts on this tutorial. Please feel free to reach out232anytime.233234* [Twitter](https://twitter.com/charmcli)235* [The Fediverse](https://mastodon.technology/@charm)
added:tutorials/go.mod+12 added
1module tutorial23go 1.1445require (6 github.com/charmbracelet/bubbletea v0.10.2 // indirect7 github.com/muesli/termenv v0.6.0 // indirect8 golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 // indirect9 golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6 // indirect10)1112replace github.com/charmbracelet/bubbletea => ../
added:tutorials/go.sum+30 added
1github.com/charmbracelet/bubbletea v0.10.2 h1:He5Ybch9TiqErJH2B02JUNkPU36GnPwXCuxwASGZyn4=2github.com/charmbracelet/bubbletea v0.10.2/go.mod h1:wjGGC5pyYvpuls0so+w4Zv+aZQW7RoPvsi9UBcDlSl8=3github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=4github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=5github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=6github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=8github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=9github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=10github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=11github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04 h1:Wr876oXlAk6avTWi0daXAriOr+r5fqIuyDmtNc/KwY0=12github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=13github.com/muesli/termenv v0.6.0 h1:zxvzTBmo4ZcxhNGGWeMz+Tttm51eF5bmPjfy4MCRYlk=14github.com/muesli/termenv v0.6.0/go.mod h1:SohX91w6swWA4AYU+QmPx+aSgXhWO0juiyID9UZmbpA=15github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03 h1:pd4YKIqCB0U7O2I4gWHgEUA2mCEOENmco0l/bM957bU=16github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03/go.mod h1:Z9+Ul5bCbBKnbCvdOWbLqTHhJiYV414CURZJba6L8qA=17golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=18golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=19golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=20golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 h1:DZhuSZLsGlFL4CmhA8BcRA0mnthyA/nZ00AqCUo7vHg=21golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=22golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=23golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=24golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=25golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=26golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 h1:5/PjkGUjvEU5Gl6BxmvKRPpqo2uNMv4rcHBMwzk/st8=27golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=28golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6 h1:X9xIZ1YU8bLZA3l6gqDUHSFiD0GFI9S548h6C8nDtOY=29golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=30golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=