vendor/github.com/charmbracelet/bubbletea/README.md
396 lines · 14802 bytes
1# Bubble Tea
2
3<p>
4 <a href="https://stuff.charm.sh/bubbletea/bubbletea-4k.png"><img src="https://github.com/charmbracelet/bubbletea/assets/25087/108d4fdb-d554-4910-abed-2a5f5586a60e" width="313" alt="Bubble Tea Title Treatment"></a><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/github.com/charmbracelet/bubbletea?tab=doc"><img src="https://godoc.org/github.com/charmbracelet/bubbletea?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" alt="Build Status"></a>
8 <a href="https://www.phorm.ai/query?projectId=a0e324b6-b706-4546-b951-6671ea60c13f"><img src="https://stuff.charm.sh/misc/phorm-badge.svg" alt="phorm.ai"></a>
9</p>
10
11The fun, functional and stateful way to build terminal apps. A Go framework
12based on [The Elm Architecture][elm]. Bubble Tea is well-suited for simple and
13complex terminal applications, either inline, full-window, or a mix of both.
14
15<p>
16 <img src="https://stuff.charm.sh/bubbletea/bubbletea-example.gif" width="100%" alt="Bubble Tea Example">
17</p>
18
19Bubble Tea is in use in production and includes a number of features and
20performance optimizations we’ve added along the way. Among those is
21a framerate-based renderer, mouse support, focus reporting and more.
22
23To get started, see the tutorial below, the [examples][examples], the
24[docs][docs], the [video tutorials][youtube] and some common [resources](#libraries-we-use-with-bubble-tea).
25
26[youtube]: https://charm.sh/yt
27
28## By the way
29
30Be sure to check out [Bubbles][bubbles], a library of common UI components for Bubble Tea.
31
32<p>
33 <a href="https://github.com/charmbracelet/bubbles"><img src="https://stuff.charm.sh/bubbles/bubbles-badge.png" width="174" alt="Bubbles Badge"></a>
34 <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>
35</p>
36
37---
38
39## Tutorial
40
41Bubble Tea is based on the functional design paradigms of [The Elm
42Architecture][elm], which happens to work nicely with Go. It's a delightful way
43to build applications.
44
45This tutorial assumes you have a working knowledge of Go.
46
47By the way, the non-annotated source code for this program is available
48[on GitHub][tut-source].
49
50[elm]: https://guide.elm-lang.org/architecture/
51[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics
52
53### Enough! Let's get to it.
54
55For this tutorial, we're making a shopping list.
56
57To start we'll define our package and import some libraries. Our only external
58import will be the Bubble Tea library, which we'll call `tea` for short.
59
60```go
61package main
62
63// These imports will be used later on the tutorial. If you save the file
64// now, Go might complain they are unused, but that's fine.
65// You may also need to run `go mod tidy` to download bubbletea and its
66// dependencies.
67import (
68 "fmt"
69 "os"
70
71 tea "github.com/charmbracelet/bubbletea"
72)
73```
74
75Bubble Tea programs are comprised of a **model** that describes the application
76state and three simple methods on that model:
77
78- **Init**, a function that returns an initial command for the application to run.
79- **Update**, a function that handles incoming events and updates the model accordingly.
80- **View**, a function that renders the UI based on the data in the model.
81
82### The Model
83
84So let's start by defining our model which will store our application's state.
85It can be any type, but a `struct` usually makes the most sense.
86
87```go
88type model struct {
89 choices []string // items on the to-do list
90 cursor int // which to-do list item our cursor is pointing at
91 selected map[int]struct{} // which to-do items are selected
92}
93```
94
95### Initialization
96
97Next, we’ll define our application’s initial state. In this case, we’re defining
98a function to return our initial model, however, we could just as easily define
99the initial model as a variable elsewhere, too.
100
101```go
102func initialModel() model {
103 return model{
104 // Our to-do list is a grocery list
105 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},
106
107 // A map which indicates which choices are selected. We're using
108 // the map like a mathematical set. The keys refer to the indexes
109 // of the `choices` slice, above.
110 selected: make(map[int]struct{}),
111 }
112}
113```
114
115Next, we define the `Init` method. `Init` can return a `Cmd` that could perform
116some initial I/O. For now, we don't need to do any I/O, so for the command,
117we'll just return `nil`, which translates to "no command."
118
119```go
120func (m model) Init() tea.Cmd {
121 // Just return `nil`, which means "no I/O right now, please."
122 return nil
123}
124```
125
126### The Update Method
127
128Next up is the update method. The update function is called when ”things
129happen.” Its job is to look at what has happened and return an updated model in
130response. It can also return a `Cmd` to make more things happen, but for now
131don't worry about that part.
132
133In our case, when a user presses the down arrow, `Update`’s job is to notice
134that the down arrow was pressed and move the cursor accordingly (or not).
135
136The “something happened” comes in the form of a `Msg`, which can be any type.
137Messages are the result of some I/O that took place, such as a keypress, timer
138tick, or a response from a server.
139
140We usually figure out which type of `Msg` we received with a type switch, but
141you could also use a type assertion.
142
143For now, we'll just deal with `tea.KeyMsg` messages, which are automatically
144sent to the update function when keys are pressed.
145
146```go
147func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
148 switch msg := msg.(type) {
149
150 // Is it a key press?
151 case tea.KeyMsg:
152
153 // Cool, what was the actual key pressed?
154 switch msg.String() {
155
156 // These keys should exit the program.
157 case "ctrl+c", "q":
158 return m, tea.Quit
159
160 // The "up" and "k" keys move the cursor up
161 case "up", "k":
162 if m.cursor > 0 {
163 m.cursor--
164 }
165
166 // The "down" and "j" keys move the cursor down
167 case "down", "j":
168 if m.cursor < len(m.choices)-1 {
169 m.cursor++
170 }
171
172 // The "enter" key and the spacebar (a literal space) toggle
173 // the selected state for the item that the cursor is pointing at.
174 case "enter", " ":
175 _, ok := m.selected[m.cursor]
176 if ok {
177 delete(m.selected, m.cursor)
178 } else {
179 m.selected[m.cursor] = struct{}{}
180 }
181 }
182 }
183
184 // Return the updated model to the Bubble Tea runtime for processing.
185 // Note that we're not returning a command.
186 return m, nil
187}
188```
189
190You may have noticed that <kbd>ctrl+c</kbd> and <kbd>q</kbd> above return
191a `tea.Quit` command with the model. That’s a special command which instructs
192the Bubble Tea runtime to quit, exiting the program.
193
194### The View Method
195
196At last, it’s time to render our UI. Of all the methods, the view is the
197simplest. We look at the model in its current state and use it to return
198a `string`. That string is our UI!
199
200Because the view describes the entire UI of your application, you don’t have to
201worry about redrawing logic and stuff like that. Bubble Tea takes care of it
202for you.
203
204```go
205func (m model) View() string {
206 // The header
207 s := "What should we buy at the market?\n\n"
208
209 // Iterate over our choices
210 for i, choice := range m.choices {
211
212 // Is the cursor pointing at this choice?
213 cursor := " " // no cursor
214 if m.cursor == i {
215 cursor = ">" // cursor!
216 }
217
218 // Is this choice selected?
219 checked := " " // not selected
220 if _, ok := m.selected[i]; ok {
221 checked = "x" // selected!
222 }
223
224 // Render the row
225 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)
226 }
227
228 // The footer
229 s += "\nPress q to quit.\n"
230
231 // Send the UI for rendering
232 return s
233}
234```
235
236### All Together Now
237
238The last step is to simply run our program. We pass our initial model to
239`tea.NewProgram` and let it rip:
240
241```go
242func main() {
243 p := tea.NewProgram(initialModel())
244 if _, err := p.Run(); err != nil {
245 fmt.Printf("Alas, there's been an error: %v", err)
246 os.Exit(1)
247 }
248}
249```
250
251## What’s Next?
252
253This tutorial covers the basics of building an interactive terminal UI, but
254in the real world you'll also need to perform I/O. To learn about that have a
255look at the [Command Tutorial][cmd]. It's pretty simple.
256
257There are also several [Bubble Tea examples][examples] available and, of course,
258there are [Go Docs][docs].
259
260[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/
261[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples
262[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc
263
264## Debugging
265
266### Debugging with Delve
267
268Since Bubble Tea apps assume control of stdin and stdout, you’ll need to run
269delve in headless mode and then connect to it:
270
271```bash
272# Start the debugger
273$ dlv debug --headless --api-version=2 --listen=127.0.0.1:43000 .
274API server listening at: 127.0.0.1:43000
275
276# Connect to it from another terminal
277$ dlv connect 127.0.0.1:43000
278```
279
280If you do not explicitly supply the `--listen` flag, the port used will vary
281per run, so passing this in makes the debugger easier to use from a script
282or your IDE of choice.
283
284Additionally, we pass in `--api-version=2` because delve defaults to version 1
285for backwards compatibility reasons. However, delve recommends using version 2
286for all new development and some clients may no longer work with version 1.
287For more information, see the [Delve documentation](https://github.com/go-delve/delve/tree/master/Documentation/api).
288
289### Logging Stuff
290
291You can’t really log to stdout with Bubble Tea because your TUI is busy
292occupying that! You can, however, log to a file by including something like
293the following prior to starting your Bubble Tea program:
294
295```go
296if len(os.Getenv("DEBUG")) > 0 {
297 f, err := tea.LogToFile("debug.log", "debug")
298 if err != nil {
299 fmt.Println("fatal:", err)
300 os.Exit(1)
301 }
302 defer f.Close()
303}
304```
305
306To see what’s being logged in real time, run `tail -f debug.log` while you run
307your program in another window.
308
309## Libraries we use with Bubble Tea
310
311- [Bubbles][bubbles]: Common Bubble Tea components such as text inputs, viewports, spinners and so on
312- [Lip Gloss][lipgloss]: Style, format and layout tools for terminal applications
313- [Harmonica][harmonica]: A spring animation library for smooth, natural motion
314- [BubbleZone][bubblezone]: Easy mouse event tracking for Bubble Tea components
315- [ntcharts][ntcharts]: A terminal charting library built for Bubble Tea and [Lip Gloss][lipgloss]
316
317[bubbles]: https://github.com/charmbracelet/bubbles
318[lipgloss]: https://github.com/charmbracelet/lipgloss
319[harmonica]: https://github.com/charmbracelet/harmonica
320[bubblezone]: https://github.com/lrstanley/bubblezone
321[ntcharts]: https://github.com/NimbleMarkets/ntcharts
322
323## Bubble Tea in the Wild
324
325There are over [10,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.
326
327### Staff favourites
328
329- [chezmoi](https://github.com/twpayne/chezmoi): securely manage your dotfiles across multiple machines
330- [circumflex](https://github.com/bensadeh/circumflex): read Hacker News in the terminal
331- [gh-dash](https://www.github.com/dlvhdr/gh-dash): a GitHub CLI extension for PRs and issues
332- [Tetrigo](https://github.com/Broderick-Westrope/tetrigo): Tetris in the terminal
333- [Signls](https://github.com/emprcl/signls): a generative midi sequencer designed for composition and live performance
334- [Superfile](https://github.com/yorukot/superfile): a super file manager
335
336### In Industry
337
338- Microsoft Azure – [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform
339- Daytona – [Daytona](https://github.com/daytonaio/daytona): open source dev environment manager
340- Cockroach Labs – [CockroachDB](https://github.com/cockroachdb/cockroach): a cloud-native, high-availability distributed SQL database
341- Truffle Security Co. – [Trufflehog](https://github.com/trufflesecurity/trufflehog): find leaked credentials
342- NVIDIA – [container-canary](https://github.com/NVIDIA/container-canary): a container validator
343- AWS – [eks-node-viewer](https://github.com/awslabs/eks-node-viewer): a tool for visualizing dynamic node usage within an EKS cluster
344- MinIO – [mc](https://github.com/minio/mc): the official [MinIO](https://min.io) client
345- Ubuntu – [Authd](https://github.com/ubuntu/authd): an authentication daemon for cloud-based identity providers
346
347### Charm stuff
348
349- [Glow](https://github.com/charmbracelet/glow): a markdown reader, browser, and online markdown stash
350- [Huh?](https://github.com/charmbracelet/huh): an interactive prompt and form toolkit
351- [Mods](https://github.com/charmbracelet/mods): AI on the CLI, built for pipelines
352- [Wishlist](https://github.com/charmbracelet/wishlist): an SSH directory (and bastion!)
353
354### There’s so much more where that came from
355
356For more applications built with Bubble Tea see [Charm & Friends][community].
357Is there something cool you made with Bubble Tea you want to share? [PRs][community] are
358welcome!
359
360## Contributing
361
362See [contributing][contribute].
363
364[contribute]: https://github.com/charmbracelet/bubbletea/contribute
365
366## Feedback
367
368We’d love to hear your thoughts on this project. Feel free to drop us a note!
369
370- [Twitter](https://twitter.com/charmcli)
371- [The Fediverse](https://mastodon.social/@charmcli)
372- [Discord](https://charm.sh/chat)
373
374## Acknowledgments
375
376Bubble Tea is based on the paradigms of [The Elm Architecture][elm] by Evan
377Czaplicki et alia and the excellent [go-tea][gotea] by TJ Holowaychuk. It’s
378inspired by the many great [_Zeichenorientierte Benutzerschnittstellen_][zb]
379of days past.
380
381[elm]: https://guide.elm-lang.org/architecture/
382[gotea]: https://github.com/tj/go-tea
383[zb]: https://de.wikipedia.org/wiki/Zeichenorientierte_Benutzerschnittstelle
384[community]: https://github.com/charm-and-friends/charm-in-the-wild
385
386## License
387
388[MIT](https://github.com/charmbracelet/bubbletea/raw/main/LICENSE)
389
390---
391
392Part of [Charm](https://charm.sh).
393
394<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
395
396Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة