README.md
This file
Path
README.md
402 lines · 14.5 KiB · Markdown
Last changed by
docs(readme): update footer imageChristian Rochabefore adoption640d879
History of this fileTake it
1# Bubble Tea23<p>4 <img src="https://github.com/user-attachments/assets/ad408275-8799-488f-9303-441e7f869535" width="350"><br>5 <a href="https://github.com/charmbracelet/bubbletea/releases"><img src="https://img.shields.io/github/release/charmbracelet/bubbletea.svg" alt="Latest Release"></a>6 <a href="https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc"><img src="https://godoc.org/charm.land/bubbletea/v2?status.svg" alt="GoDoc"></a>7 <a href="https://github.com/charmbracelet/bubbletea/actions"><img src="https://github.com/charmbracelet/bubbletea/actions/workflows/build.yml/badge.svg?branch=main" alt="Build Status"></a>8</p>910The fun, functional and stateful way to build terminal apps. A Go framework11based on [The Elm Architecture][elm]. Bubble Tea is well-suited for simple and12complex terminal applications, either inline, full-window, or a mix of both.1314<p>15 <img src="https://stuff.charm.sh/bubbletea/bubbletea-example.gif" width="100%" alt="Bubble Tea Example">16</p>1718Bubble Tea is in use in production and includes a number of features and19performance optimizations we’ve added along the way. Among those is20a high-performance cell-based renderer, built-in color downsampling,21declarative views, high-fidelity keyboard and mouse handling, native clipboard22support, and more.2324To get started, see the tutorial below, the [examples][examples], the25[docs][docs], and some common [resources](#libraries-we-use-with-bubble-tea).2627> [!TIP]28>29> Upgrading from v1? Check out the [upgrade guide](./UPGRADE_GUIDE_V2.md), or30> point your LLM at it and let it go to town.3132## By the way3334Be sure to check out [Bubbles][bubbles], a library of common UI components for Bubble Tea.3536<p>37 <a href="https://github.com/charmbracelet/bubbles"><img src="https://github.com/user-attachments/assets/b6dc4638-b67a-4bfa-88d0-a8e8833c3ac9" width="172" alt="Bubbles Badge"></a> 38 <a href="https://github.com/charmbracelet/bubbles"><img src="https://stuff.charm.sh/bubbles-examples/textinput.gif" width="400" alt="Text Input Example from Bubbles"></a>39</p>4041---4243## Tutorial4445Bubble Tea is based on the functional design paradigms of [The Elm46Architecture][elm], which happens to work nicely with Go. It's a delightful way47to build applications.4849This tutorial assumes you have a working knowledge of Go.5051By the way, the non-annotated source code for this program is available52[on GitHub][tut-source].5354[elm]: https://guide.elm-lang.org/architecture/55[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics5657### Enough! Let's get to it.5859For this tutorial, we're making a shopping list.6061To start we'll define our package and import some libraries. Our only external62import will be the Bubble Tea library, which we'll call `tea` for short.6364```go65package main6667// These imports will be used later in the tutorial. If you save the file68// now, Go might complain they are unused, but that's fine.69// You may also need to run `go mod tidy` to download bubbletea and its70// dependencies.71import (72 "fmt"73 "os"7475 tea "charm.land/bubbletea/v2"76)77```7879Bubble Tea programs are comprised of a **model** that describes the application80state and three simple methods on that model:8182- **Init**, a function that returns an initial command for the application to run.83- **Update**, a function that handles incoming events and updates the model accordingly.84- **View**, a function that renders the UI based on the data in the model.8586### The Model8788So let's start by defining our model which will store our application's state.89It can be any type, but a `struct` usually makes the most sense.9091```go92type model struct {93 choices []string // items on the to-do list94 cursor int // which to-do list item our cursor is pointing at95 selected map[int]struct{} // which to-do items are selected96}97```9899## Initialization100101Next, we’ll define our application’s initial state. `Init` can return a `Cmd`102that could perform some initial I/O. For now, we don’t need to do any I/O, so103for the command, we’ll just return `nil`, which translates to “no command.”104105```go106func initialModel() model {107 return model{108 // Our to-do list is a grocery list109 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},110111 // A map which indicates which choices are selected. We're using112 // the map like a mathematical set. The keys refer to the indexes113 // of the `choices` slice, above.114 selected: make(map[int]struct{}),115 }116}117```118119After that, we’ll define our application’s initial state in the `Init` method. `Init`120can return a `Cmd` that could perform some initial I/O. For now, we don't need121to do any I/O, so for the command, we'll just return `nil`, which translates to122"no command."123124```go125func (m model) Init() tea.Cmd {126 // Just return `nil`, which means "no I/O right now, please."127 return nil128}129```130131### The Update Method132133Next up is the update method. The update function is called when “things134happen.” Its job is to look at what has happened and return an updated model in135response. It can also return a `Cmd` to make more things happen, but for now136don't worry about that part.137138In our case, when a user presses the down arrow, `Update`’s job is to notice139that the down arrow was pressed and move the cursor accordingly (or not).140141The “something happened” comes in the form of a `Msg`, which can be any type.142Messages are the result of some I/O that took place, such as a keypress, timer143tick, or a response from a server.144145We usually figure out which type of `Msg` we received with a type switch, but146you could also use a type assertion.147148For now, we'll just deal with `tea.KeyPressMsg` messages, which are149automatically sent to the update function when keys are pressed.150151```go152func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {153 switch msg := msg.(type) {154155 // Is it a key press?156 case tea.KeyPressMsg:157158 // Cool, what was the actual key pressed?159 switch msg.String() {160161 // These keys should exit the program.162 case "ctrl+c", "q":163 return m, tea.Quit164165 // The "up" and "k" keys move the cursor up166 case "up", "k":167 if m.cursor > 0 {168 m.cursor--169 }170171 // The "down" and "j" keys move the cursor down172 case "down", "j":173 if m.cursor < len(m.choices)-1 {174 m.cursor++175 }176177 // The "enter" key and the space bar toggle the selected state178 // for the item that the cursor is pointing at.179 case "enter", "space":180 _, ok := m.selected[m.cursor]181 if ok {182 delete(m.selected, m.cursor)183 } else {184 m.selected[m.cursor] = struct{}{}185 }186 }187 }188189 // Return the updated model to the Bubble Tea runtime for processing.190 // Note that we're not returning a command.191 return m, nil192}193```194195You may have noticed that <kbd>ctrl+c</kbd> and <kbd>q</kbd> above return196a `tea.Quit` command with the model. That’s a special command which instructs197the Bubble Tea runtime to quit, exiting the program.198199### The View Method200201At last, it’s time to render our UI. Of all the methods, the view is the202simplest. We look at the model in its current state and use it to build a203`tea.View`. The view declares our UI content and, optionally, terminal features204like alt screen mode, mouse tracking, cursor position, and more.205206Because the view describes the entire UI of your application, you don’t have to207worry about redrawing logic and stuff like that. Bubble Tea takes care of it208for you.209210```go211func (m model) View() tea.View {212 // The header213 s := "What should we buy at the market?\n\n"214215 // Iterate over our choices216 for i, choice := range m.choices {217218 // Is the cursor pointing at this choice?219 cursor := " " // no cursor220 if m.cursor == i {221 cursor = ">" // cursor!222 }223224 // Is this choice selected?225 checked := " " // not selected226 if _, ok := m.selected[i]; ok {227 checked = "x" // selected!228 }229230 // Render the row231 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)232 }233234 // The footer235 s += "\nPress q to quit.\n"236237 // Send the UI for rendering238 return tea.NewView(s)239}240```241242### All Together Now243244The last step is to simply run our program. We pass our initial model to245`tea.NewProgram` and let it rip:246247```go248func main() {249 p := tea.NewProgram(initialModel())250 if _, err := p.Run(); err != nil {251 fmt.Printf("Alas, there's been an error: %v", err)252 os.Exit(1)253 }254}255```256257## What’s Next?258259This tutorial covers the basics of building an interactive terminal UI, but260in the real world you'll also need to perform I/O. To learn about that have a261look at the [Command Tutorial][cmd]. It's pretty simple.262263There are also several [Bubble Tea examples][examples] available and, of course,264there are [Go Docs][docs].265266[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/267[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples268[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc269270## Debugging271272### Debugging with Delve273274Since Bubble Tea apps assume control of stdin and stdout, you’ll need to run275delve in headless mode and then connect to it:276277```bash278# Start the debugger279$ dlv debug --headless --api-version=2 --listen=127.0.0.1:43000 .280API server listening at: 127.0.0.1:43000281282# Connect to it from another terminal283$ dlv connect 127.0.0.1:43000284```285286If you do not explicitly supply the `--listen` flag, the port used will vary287per run, so passing this in makes the debugger easier to use from a script288or your IDE of choice.289290Additionally, we pass in `--api-version=2` because delve defaults to version 1291for backwards compatibility reasons. However, delve recommends using version 2292for all new development and some clients may no longer work with version 1.293For more information, see the [Delve documentation](https://github.com/go-delve/delve/tree/master/Documentation/api).294295### Logging Stuff296297You can’t really log to stdout with Bubble Tea because your TUI is busy298occupying that! You can, however, log to a file by including something like299the following prior to starting your Bubble Tea program:300301```go302if len(os.Getenv("DEBUG")) > 0 {303 f, err := tea.LogToFile("debug.log", "debug")304 if err != nil {305 fmt.Println("fatal:", err)306 os.Exit(1)307 }308 defer f.Close()309}310```311312To see what’s being logged in real time, run `tail -f debug.log` while you run313your program in another window.314315## Libraries we use with Bubble Tea316317- [Bubbles][bubbles]: Common Bubble Tea components such as text inputs, viewports, spinners and so on318- [Lip Gloss][lipgloss]: Style, format and layout tools for terminal applications319- [Harmonica][harmonica]: A spring animation library for smooth, natural motion320- [BubbleZone][bubblezone]: Easy mouse event tracking for Bubble Tea components321- [ntcharts][ntcharts]: A terminal charting library built for Bubble Tea and [Lip Gloss][lipgloss]322323[bubbles]: https://github.com/charmbracelet/bubbles324[lipgloss]: https://github.com/charmbracelet/lipgloss325[harmonica]: https://github.com/charmbracelet/harmonica326[bubblezone]: https://github.com/lrstanley/bubblezone327[ntcharts]: https://github.com/NimbleMarkets/ntcharts328329## Bubble Tea in the Wild330331There are over [18,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.332333### Staff favourites334335- [chezmoi](https://github.com/twpayne/chezmoi): securely manage your dotfiles across multiple machines336- [circumflex](https://github.com/bensadeh/circumflex): read Hacker News in the terminal337- [gh-dash](https://www.github.com/dlvhdr/gh-dash): a GitHub CLI extension for PRs and issues338- [Tetrigo](https://github.com/Broderick-Westrope/tetrigo): Tetris in the terminal339- [Signls](https://github.com/emprcl/signls): a generative midi sequencer designed for composition and live performance340- [Superfile](https://github.com/yorukot/superfile): a super file manager341342### In Industry343344- Microsoft Azure – [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform345- Daytona – [Daytona](https://github.com/daytonaio/daytona): an AI infrastructure platform346- Cockroach Labs – [CockroachDB](https://github.com/cockroachdb/cockroach): a cloud-native, high-availability distributed SQL database347- Truffle Security Co. – [Trufflehog](https://github.com/trufflesecurity/trufflehog): find leaked credentials348- NVIDIA – [container-canary](https://github.com/NVIDIA/container-canary): a container validator349- AWS – [eks-node-viewer](https://github.com/awslabs/eks-node-viewer): a tool for visualizing dynamic node usage within an EKS cluster350- MinIO – [mc](https://github.com/minio/mc): the official [MinIO](https://min.io) client351- Ubuntu – [Authd](https://github.com/ubuntu/authd): an authentication daemon for cloud-based identity providers352353### Charm stuff354355- [Glow](https://github.com/charmbracelet/glow): a markdown reader, browser, and online markdown stash356- [Huh?](https://github.com/charmbracelet/huh): an interactive prompt and form toolkit357- [Mods](https://github.com/charmbracelet/mods): AI on the CLI, built for pipelines358- [Wishlist](https://github.com/charmbracelet/wishlist): an SSH directory (and bastion!)359360### There’s so much more where that came from361362For more applications built with Bubble Tea see [Charm & Friends][community].363Is there something cool you made with Bubble Tea you want to share? [PRs][community] are364welcome!365366## Contributing367368See [contributing][contribute].369370[contribute]: https://github.com/charmbracelet/bubbletea/contribute371372## Feedback373374We’d love to hear your thoughts on this project. Feel free to drop us a note!375376- [Twitter](https://twitter.com/charmcli)377- [The Fediverse](https://mastodon.social/@charmcli)378- [Discord](https://charm.sh/chat)379380## Acknowledgments381382Bubble Tea is based on the paradigms of [The Elm Architecture][elm] by Evan383Czaplicki et alia and the excellent [go-tea][gotea] by TJ Holowaychuk. It’s384inspired by the many great [_Zeichenorientierte Benutzerschnittstellen_][zb]385of days past.386387[elm]: https://guide.elm-lang.org/architecture/388[gotea]: https://github.com/tj/go-tea389[zb]: https://de.wikipedia.org/wiki/Zeichenorientierte_Benutzerschnittstelle390[community]: https://github.com/charm-and-friends/charm-in-the-wild391392## License393394[MIT](https://github.com/charmbracelet/bubbletea/raw/main/LICENSE)395396---397398Part of [Charm](https://charm.sh).399400<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-banner-softy.jpg" width="400"></a>401402Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة