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
Provenance
- Commit
e4243bd- Tree
6398657- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
fe15629
4 files changed+359 added−0 removed
added:tutorials/basics/main.go+82 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "github.com/charmbracelet/bubbletea"8+)9+10+type model struct {11+ cursor int12+ choices []string13+ selected map[int]struct{}14+}15+16+func initialize() (tea.Model, tea.Cmd) {17+ return model{18+ choices: []string{"Carrots", "Celery", "Kohlrabi"},19+ selected: make(map[int]struct{}),20+ }, nil21+}22+23+func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {24+ m, _ := mdl.(model)25+26+ 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+ }48+49+ return m, nil50+}51+52+func view(mdl tea.Model) string {53+ m, _ := mdl.(model)54+55+ s := "What should we buy at the market?\n\n"56+57+ for i, choice := range m.choices {58+ cursor := " "59+ if m.cursor == i {60+ cursor = ">"61+ }62+63+ checked := " "64+ if _, ok := m.selected[i]; ok {65+ checked = "x"66+ }67+68+ s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)69+ }70+71+ s += "\nPress q to quit.\n"72+73+ return s74+}75+76+func 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 Tutorial2+3+Bubble Tea is based on the functional design paradigms of [The Elm4+Architecture][elm]. It might not seem very Go-like at first, but once you get5+used to the general structure you'll find that most of the idomatic Go things6+you know and love are still relevant and useful here.7+8+By the way, the non-annotated version of of this program is available9+[on GitHub](https://github.com/charmbracelet/bubbletea/master/tutorials/basics).10+11+This tutorial assumes you have a working knowledge of Go.12+13+[elm]: https://guide.elm-lang.org/architecture/14+15+## Enough! Let's get to it.16+17+For this tutorial we're making a to-do list.18+19+To start we'll define our package and import some libraries. Our only external20+import will be the Bubble Tea, library, which we'll call `tea` for short.21+22+```go23+ package main24+25+ import (26+ "fmt"27+ "os"28+29+ tea "github.com/charmbracelet/bubbletea"30+ )31+```32+33+Bubble Tea programs are comprised of a model that describes the application34+state and three simple functions that are centered around the model:35+36+Initialize37+: A function that returns the model's initial state.38+Update39+: A function that handles incoming events and updates the model accordingly.40+View41+: A function that renders the UI based on the data in the model.42+43+## The Model44+45+So let's start by defining our application's model. The model is simply the46+application's state. It can be any type, but a `struct` usually makes the most47+sense.48+49+```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+```56+57+## Initialize58+59+Next we'll define a function that will initialize our application. An60+initialize function returns a model representing our application's initial61+state, as well as a `Cmd` that could perform some initial I/O. For now, we62+don't need to do any I/O, so for the command we'll just return nil, which63+translate to "no command."64+65+```go66+ func initialize() (tea.Model, tea.Cmd) {67+ m := model{68+69+ // Our to-do list is just a grocery list70+ choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},71+72+ // 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+ }77+78+ // Return the model and `nil`, which means "no I/O right now, please."79+ return m, nil80+ }81+```82+83+## Update84+85+Next 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 an87+updated model based on whatever happened. It can also return a `Cmd` and make88+more things happen, but we'll get into that later.89+90+In our case, when a user presses the down arrow `update`'s job is to notice91+that the down arrow was pressed and move the cursor accordingly (or not).92+93+The "something happened" comes in as a `Msg`, which can be any type. Messages94+indicate some I/O happened, such as a keypress, timer, or a response from95+a server.96+97+We usually figure out which type of `Msg` we received with a type switch, but98+you could also use a type assertion.99+100+For now, we'll just deal with `tea.KeyMsg`, which are automatically sent to101+the update function when keys are pressed.102+103+```go104+ func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {105+ m, _ := mdl.(model)106+107+ switch msg := msg.(type) {108+109+ // Is it a key press?110+ case tea.KeyMsg:111+112+ // Cool, what was the actual key pressed?113+ switch msg.String() {114+115+ // These keys should exit the program.116+ case "ctrl+c", "q":117+ return m, tea.Quit118+119+ // The "up" and "k" keys move the cursor up120+ case "up", "k":121+ if m.cursor > 0 {122+ m.cursor--123+ }124+125+ // The "down" and "j" keys move the cursor down126+ case "down", "j":127+ if m.cursor < len(m.choices)-1 {128+ m.cursor++129+ }130+131+ // 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+ }142+143+ // 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+```148+149+You may have noticed that "ctrl+c" and "q" above return a `tea.Quit` with the150+model. That's a special command which instructs the Bubble Tea runtime to exit,151+effectively quitting the program.152+153+## The View154+155+At last, it's time to render our UI. Of all the functions, the view is the156+simplest. A model, in it's current state, comes in and a `string` comes out.157+That string is our UI!158+159+Because the view describes the entire UI of your application, you don't have160+to worry about redraw logic and stuff like that. Bubble Tea takes care of it161+for you.162+163+```go164+ func view(mdl tea.Model) string {165+ m, _ := mdl.(model)166+167+ // The header168+ s := "What should we buy at the market?\n\n"169+170+ // Iterate over our choices171+ for i, choice := range m.choices {172+173+ // Is the cursor pointing at this choice?174+ cursor := " " // no cursor175+ if m.cursor == i {176+ cursor = ">" // cursor!177+ }178+179+ // Is this choice selected?180+ checked := " " // not selected181+ if _, ok := m.selected[i]; ok {182+ checked = "x" // selected!183+ }184+185+ // Render the row186+ s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)187+ }188+189+ // The footer190+ s += "\nPress q to quit.\n"191+192+ // Send off the UI to rendered193+ return s194+ }195+```196+197+## All togeher now198+199+The last step is to simply run our program. We pass our functions to200+`tea.NewProgram` and let it rip:201+202+```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+```211+212+## What's next?213+214+This tutorial covers the basics of building an interactive terminal UI, but215+in the real world you'll also need to perform I/O. To learn about that have a216+look at the [Cmd Tutorial][cmd]. It's pretty simple.217+218+There are also several [examples][examples] available. Many of the examples219+make use of [Bubbles][bubbles], the little Bubble Tea component library which220+includes handy things like a text input component, spinners and a viewport.221+222+Of course, there are also [Go Docs][docs] for Bubble Tea.223+224+[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=doc228+229+## Feedback230+231+We'd love to hear your thoughts on this tutorial. Please feel free to reach out232+anytime.233+234+* [Twitter](https://twitter.com/charmcli)235+* [The Fediverse](https://mastodon.technology/@charm)added:tutorials/go.mod+12 added
1+module tutorial2+3+go 1.144+5+require (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+)11+12+replace github.com/charmbracelet/bubbletea => ../added:tutorials/go.sum+30 added
1+github.com/charmbracelet/bubbletea v0.10.2 h1:He5Ybch9TiqErJH2B02JUNkPU36GnPwXCuxwASGZyn4=2+github.com/charmbracelet/bubbletea v0.10.2/go.mod h1:wjGGC5pyYvpuls0so+w4Zv+aZQW7RoPvsi9UBcDlSl8=3+github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=4+github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=5+github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=6+github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=8+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=9+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=10+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=11+github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04 h1:Wr876oXlAk6avTWi0daXAriOr+r5fqIuyDmtNc/KwY0=12+github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=13+github.com/muesli/termenv v0.6.0 h1:zxvzTBmo4ZcxhNGGWeMz+Tttm51eF5bmPjfy4MCRYlk=14+github.com/muesli/termenv v0.6.0/go.mod h1:SohX91w6swWA4AYU+QmPx+aSgXhWO0juiyID9UZmbpA=15+github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03 h1:pd4YKIqCB0U7O2I4gWHgEUA2mCEOENmco0l/bM957bU=16+github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03/go.mod h1:Z9+Ul5bCbBKnbCvdOWbLqTHhJiYV414CURZJba6L8qA=17+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=18+golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=19+golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=20+golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 h1:DZhuSZLsGlFL4CmhA8BcRA0mnthyA/nZ00AqCUo7vHg=21+golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=22+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=23+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=24+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=25+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=26+golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 h1:5/PjkGUjvEU5Gl6BxmvKRPpqo2uNMv4rcHBMwzk/st8=27+golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=28+golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6 h1:X9xIZ1YU8bLZA3l6gqDUHSFiD0GFI9S548h6C8nDtOY=29+golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=30+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=