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
The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.
feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1–3why, one step back1# Bubble Tea23<p>docs(readme): update header imageChristian Rochabefore adoption3499dac
line 4why, one step back4 <img src="https://github.com/user-attachments/assets/ad408275-8799-488f-9303-441e7f869535" width="350"><br>feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 5why, one step back5 <a href="https://github.com/charmbracelet/bubbletea/releases"><img src="https://img.shields.io/github/release/charmbracelet/bubbletea.svg" alt="Latest Release"></a>Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 6why, one step back6 <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>docs: show the correct branch in the build badgeAyman Bagabasbefore adoptionf01583b
line 7why, one step back7 <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>feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 8–18why, one step back8</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 anddocs(readme): additional readme tiyding upChristian Rochabefore adoption1bf1886
line 19why, one step back19performance optimizations we’ve added along the way. Among those isMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 20–22why, one step back20a high-performance cell-based renderer, built-in color downsampling,21declarative views, high-fidelity keyboard and mouse handling, native clipboard22support, and more.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 23–24why, one step back2324To get started, see the tutorial below, the [examples][examples], theMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 25why, one step back25[docs][docs], and some common [resources](#libraries-we-use-with-bubble-tea).feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 26why, one step back26Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 27–30why, one step back27> [!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.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 31–36why, one step back3132## By the way3334Be sure to check out [Bubbles][bubbles], a library of common UI components for Bubble Tea.3536<p>docs(readme): update bubbles callout imageChristian Rochabefore adoption07a69fb
line 37why, one step back37 <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> feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 38–54why, one step back38 <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/Update README.md references to main branchSimon Nordbergbefore adoptioneb7e3d0
line 55why, one step back55[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basicsfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 56–66why, one step back5657### 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 main66docs: fix README wording (#1624)Rohan Santhosh Kumarbefore adoptione19d255
line 67why, one step back67// These imports will be used later in the tutorial. If you save the filedocs(readme): additional readme tiyding upChristian Rochabefore adoption1bf1886
line 68why, one step back68// now, Go might complain they are unused, but that's fine.docs: clarify imports in the readme (#1234)Carlos Alexandro Beckerbefore adoption39f9fae
lines 69–70why, one step back69// You may also need to run `go mod tidy` to download bubbletea and its70// dependencies.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 71–74why, one step back71import (72 "fmt"73 "os"74Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 75why, one step back75 tea "charm.land/bubbletea/v2"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 76–98why, one step back76)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```98Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 99why, one step back99## Initializationfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 100why, one step back100Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 101–103why, one step back101Next, 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.”feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 104–118why, one step back104105```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```118Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 119–122why, one step back119After 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."feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 123–132why, one step back123124```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 Method132Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 133why, one step back133Next up is the update method. The update function is called when “thingsfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 134–147why, one step back134happen.” 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.147Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 148–149why, one step back148For now, we'll just deal with `tea.KeyPressMsg` messages, which are149automatically sent to the update function when keys are pressed.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 150–155why, one step back150151```go152func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {153 switch msg := msg.(type) {154155 // Is it a key press?Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 156why, one step back156 case tea.KeyPressMsg:feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 157–176why, one step back157158 // 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 }176Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 177–179why, one step back177 // The "enter" key and the space bar toggle the selected state178 // for the item that the cursor is pointing at.179 case "enter", "space":feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 180–201why, one step back180 _, 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 theMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 202–204why, one step back202simplest. 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.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 205–210why, one step back205206Because 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```goMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 211why, one step back211func (m model) View() tea.View {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 212–237why, one step back212 // 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 renderingMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 238why, one step back238 return tea.NewView(s)feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 239–265why, one step back239}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].265Update README.md references to main branchSimon Nordbergbefore adoptioneb7e3d0
lines 266–267why, one step back266[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/267[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examplesMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 268why, one step back268[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=docfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 269–330why, one step back269270## 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 Wild330Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 331why, one step back331There are over [18,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 332–338why, one step back332333### 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 terminaldocs(readme): add more stuff to "In the Wild"Christian Rochabefore adoption07288b1
lines 339–340why, one step back339- [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 managerfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 341–343why, one step back341342### In Industry343Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 344–345why, one step back344- Microsoft Azure – [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform345- Daytona – [Daytona](https://github.com/daytonaio/daytona): an AI infrastructure platformdocs(readme): fix tiny typo in readmeChristian Rochabefore adoption79cc2fb
line 346why, one step back346- Cockroach Labs – [CockroachDB](https://github.com/cockroachdb/cockroach): a cloud-native, high-availability distributed SQL databaseMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 347–351why, one step back347- 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 providersfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 352–393why, one step back352353### 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## License393Update README.md references to main branchSimon Nordbergbefore adoptioneb7e3d0
line 394why, one step back394[MIT](https://github.com/charmbracelet/bubbletea/raw/main/LICENSE)feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 395–399why, one step back395396---397398Part of [Charm](https://charm.sh).399docs(readme): update footer imageChristian Rochabefore adoption640d879
line 400why, one step back400<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-banner-softy.jpg" width="400"></a>feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 401–402why, one step back401402Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة