Skip to content
Myr

UPGRADE_GUIDE_V2.md

This file

Path

UPGRADE_GUIDE_V2.md

574 lines · 16.9 KiB · Markdown

Last changed by

feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626

History of this file

Take it

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 1–2why, one step back
1# Bubble Tea v2 Upgrade Guide
2

docs: correct whats new linkAyman Bagabasbefore adoptionc751374

line 3why, one step back
3This guide covers everything you need to change when upgrading from Bubble Tea v1 to v2. For a tour of all the exciting new features, check out the [What's New](https://github.com/charmbracelet/bubbletea/releases/tag/v2.0.0) doc.

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 4–100why, one step back
4
5> [!NOTE]6> We don't take API changes lightly and strive to make the upgrade process as simple as possible. If something feels way off, let us know.78## Migration Checklist910Here's the short version — a checklist you can follow top to bottom. Each item links to the relevant section below.1112- [ ] [Update import paths](#import-paths)13- [ ] [Change `View() string` to `View() tea.View`](#view-returns-a-teaview-now)14- [ ] [Replace `tea.KeyMsg` with `tea.KeyPressMsg`](#key-messages)15- [ ] [Update key fields: `msg.Type` / `msg.Runes` / `msg.Alt`](#key-messages)16- [ ] [Replace `case " ":` with `case "space":`](#key-messages)17- [ ] [Update mouse message usage](#mouse-messages)18- [ ] [Rename mouse button constants](#mouse-messages)19- [ ] [Remove old program options → use View fields](#removed-program-options)20- [ ] [Remove imperative commands → use View fields](#removed-commands)21- [ ] [Remove old program methods](#removed-program-methods)22- [ ] [Rename `tea.WindowSize()` → `tea.RequestWindowSize`](#renamed-apis)23- [ ] [Replace `tea.Sequentially(...)` → `tea.Sequence(...)`](#renamed-apis)2425## Import Paths2627The module path changed to a vanity domain. Lip Gloss moved too.2829```go30// Before31import tea "github.com/charmbracelet/bubbletea"32import "github.com/charmbracelet/lipgloss"3334// After35import tea "charm.land/bubbletea/v2"36import "charm.land/lipgloss/v2"37```3839## The Big Idea: Declarative Views4041The single biggest change in v2 is the shift from **imperative commands** to **declarative View fields**. In v1, you'd use program options like `tea.WithAltScreen()` and commands like `tea.EnterAltScreen` to toggle terminal features on and off. In v2, you just set fields on the `tea.View` struct in your `View()` method and Bubble Tea handles the rest.4243This means: no more startup option flags, no more toggle commands, no more fighting over state. Just declare what you want and Bubble Tea will make it so.4445```go46// v1: imperative — scattered across NewProgram, Init, and Update47p := tea.NewProgram(model{}, tea.WithAltScreen(), tea.WithMouseCellMotion())4849// v2: declarative — everything lives in View()50func (m model) View() tea.View {51 v := tea.NewView("Hello!")52 v.AltScreen = true53 v.MouseMode = tea.MouseModeCellMotion54 return v55}56```5758Keep this in mind as you go through the rest of the guide — most of the "removed" things simply moved into View fields.5960## View Returns a `tea.View` Now6162The `View()` method no longer returns a `string`. It returns a `tea.View` struct.6364```go65// Before:66func (m model) View() string {67 return "Hello, world!"68}6970// After:71func (m model) View() tea.View {72 return tea.NewView("Hello, world!")73}74```7576You can also use the longer form if you need to set additional fields:7778```go79func (m model) View() tea.View {80 var v tea.View81 v.SetContent("Hello, world!")82 v.AltScreen = true83 return v84}85```8687The `tea.View` struct has fields for everything that used to be controlled by options and commands:8889| View Field | What It Does |90|---|---|91| `Content` | The rendered string (set via `SetContent()` or `NewView()`) |92| `AltScreen` | Enter/exit the alternate screen buffer |93| `MouseMode` | `MouseModeNone`, `MouseModeCellMotion`, or `MouseModeAllMotion` |94| `ReportFocus` | Enable focus/blur event reporting |95| `DisableBracketedPasteMode` | Disable bracketed paste |96| `WindowTitle` | Set the terminal window title |97| `Cursor` | Control cursor position, shape, color, and blink |98| `ForegroundColor` | Set the terminal foreground color |99| `BackgroundColor` | Set the terminal background color |100| `ProgressBar` | Show a native terminal progress bar |

feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626

line 101why, one step back
101| `ProgramStatus` | Report whether the program is working, waiting on the user, done, or failed (OSC 7501) |

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 102–571why, one step back
102| `KeyboardEnhancements` | Request keyboard enhancement features |
103| `OnMouse` | Intercept mouse messages based on view content |104105## Key Messages106107Key messages got a major overhaul. Here's the quick rundown:108109### `tea.KeyMsg` is now an interface110111In v1, `tea.KeyMsg` was a struct you'd match on for key presses. In v2, it's an **interface** that covers both key presses and releases. For most code, you want `tea.KeyPressMsg`:112113```go114// Before:115case tea.KeyMsg:116 switch msg.String() {117 case "q":118 return m, tea.Quit119 }120121// After:122case tea.KeyPressMsg:123 switch msg.String() {124 case "q":125 return m, tea.Quit126 }127```128129If you want to handle both presses and releases, use `tea.KeyMsg` and type-switch inside:130131```go132case tea.KeyMsg:133 switch key := msg.(type) {134 case tea.KeyPressMsg:135 // key press136 case tea.KeyReleaseMsg:137 // key release138 }139```140141### Key fields changed142143| v1 | v2 | Notes |144|---|---|---|145| `msg.Type` | `msg.Code` | A `rune` — can be `tea.KeyEnter`, `'a'`, etc. |146| `msg.Runes` | `msg.Text` | Now a `string`, not `[]rune` |147| `msg.Alt` | `msg.Mod` | `msg.Mod.Contains(tea.ModAlt)` for alt, etc. |148| `tea.KeyRune` | — | Check `len(msg.Text) > 0` instead |149| `tea.KeyCtrlC` | — | Use `msg.String() == "ctrl+c"` or check `msg.Code` + `msg.Mod` |150151### Space bar changed152153Space bar now returns `"space"` instead of `" "` when using `msg.String()`:154155```go156// Before:157case " ":158159// After:160case "space":161```162163`key.Code` is still `' '` and `key.Text` is still `" "`, but `String()` returns `"space"`.164165### Ctrl+key matching166167```go168// Before:169case tea.KeyCtrlC:170 // ctrl+c171172// After (option A — string matching):173case tea.KeyPressMsg:174 switch msg.String() {175 case "ctrl+c":176 // ctrl+c177 }178179// After (option B — field matching):180case tea.KeyPressMsg:181 if msg.Code == 'c' && msg.Mod == tea.ModCtrl {182 // ctrl+c183 }184```185186### New Key fields187188These are new in v2 and don't have v1 equivalents:189190- **`key.ShiftedCode`** — the shifted key code (e.g., `'B'` when pressing shift+b)191- **`key.BaseCode`** — the key on a US PC-101 layout (handy for international keyboards)192- **`key.IsRepeat`** — whether the key is auto-repeating (Kitty protocol / Windows Console only)193- **`key.Keystroke()`** — like `String()` but always includes modifier info194195## Paste Messages196197Paste events no longer come in as `tea.KeyMsg` with a `Paste` flag. They're now their own message types:198199```go200// Before:201case tea.KeyMsg:202 if msg.Paste {203 m.text += string(msg.Runes)204 }205206// After:207case tea.PasteMsg:208 m.text += msg.Content209case tea.PasteStartMsg:210 // paste started211case tea.PasteEndMsg:212 // paste ended213```214215## Mouse Messages216217### `tea.MouseMsg` is now an interface218219In v1, `tea.MouseMsg` was a struct with `X`, `Y`, `Button`, etc. In v2, it's an **interface**. You get the coordinates by calling `msg.Mouse()`:220221```go222// Before:223case tea.MouseMsg:224 x, y := msg.X, msg.Y225226// After:227case tea.MouseMsg:228 mouse := msg.Mouse()229 x, y := mouse.X, mouse.Y230```231232### Mouse events are split by type233234Instead of checking `msg.Action`, match on specific message types:235236```go237// Before:238case tea.MouseMsg:239 if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft {240 // left click241 }242243// After:244case tea.MouseClickMsg:245 if msg.Button == tea.MouseLeft {246 // left click247 }248case tea.MouseReleaseMsg:249 // release250case tea.MouseWheelMsg:251 // scroll252case tea.MouseMotionMsg:253 // movement254```255256### Button constants renamed257258| v1 | v2 |259|---|---|260| `tea.MouseButtonLeft` | `tea.MouseLeft` |261| `tea.MouseButtonRight` | `tea.MouseRight` |262| `tea.MouseButtonMiddle` | `tea.MouseMiddle` |263| `tea.MouseButtonWheelUp` | `tea.MouseWheelUp` |264| `tea.MouseButtonWheelDown` | `tea.MouseWheelDown` |265| `tea.MouseButtonWheelLeft` | `tea.MouseWheelLeft` |266| `tea.MouseButtonWheelRight` | `tea.MouseWheelRight` |267268### `tea.MouseEvent` → `tea.Mouse`269270The `MouseEvent` struct is gone. The new `Mouse` struct has `X`, `Y`, `Button`, and `Mod` fields.271272### Mouse mode is now a View field273274```go275// Before:276p := tea.NewProgram(model{}, tea.WithMouseCellMotion())277278// After:279func (m model) View() tea.View {280 v := tea.NewView("...")281 v.MouseMode = tea.MouseModeCellMotion282 return v283}284```285286## Removed Program Options287288These options no longer exist. They all moved to View fields.289290| Removed Option | Do This Instead |291|---|---|292| `tea.WithAltScreen()` | `view.AltScreen = true` |293| `tea.WithMouseCellMotion()` | `view.MouseMode = tea.MouseModeCellMotion` |294| `tea.WithMouseAllMotion()` | `view.MouseMode = tea.MouseModeAllMotion` |295| `tea.WithReportFocus()` | `view.ReportFocus = true` |296| `tea.WithoutBracketedPaste()` | `view.DisableBracketedPasteMode = true` |297| `tea.WithInputTTY()` | Just remove it — v2 always opens the TTY for input automatically |298| `tea.WithANSICompressor()` | Just remove it — the new renderer handles optimization automatically |299300## Removed Commands301302These commands no longer exist. Set the corresponding View field instead.303304| Removed Command | Do This Instead |305|---|---|306| `tea.EnterAltScreen` | `view.AltScreen = true` |307| `tea.ExitAltScreen` | `view.AltScreen = false` |308| `tea.EnableMouseCellMotion` | `view.MouseMode = tea.MouseModeCellMotion` |309| `tea.EnableMouseAllMotion` | `view.MouseMode = tea.MouseModeAllMotion` |310| `tea.DisableMouse` | `view.MouseMode = tea.MouseModeNone` |311| `tea.HideCursor` | `view.Cursor = nil` |312| `tea.ShowCursor` | `view.Cursor = &tea.Cursor{...}` or `tea.NewCursor(x, y)` |313| `tea.EnableBracketedPaste` | `view.DisableBracketedPasteMode = false` |314| `tea.DisableBracketedPaste` | `view.DisableBracketedPasteMode = true` |315| `tea.EnableReportFocus` | `view.ReportFocus = true` |316| `tea.DisableReportFocus` | `view.ReportFocus = false` |317| `tea.SetWindowTitle("...")` | `view.WindowTitle = "..."` |318319## Removed Program Methods320321These methods on `*Program` are gone.322323| Removed Method | Do This Instead |324|---|---|325| `p.Start()` | `p.Run()` |326| `p.StartReturningModel()` | `p.Run()` |327| `p.EnterAltScreen()` | `view.AltScreen = true` in `View()` |328| `p.ExitAltScreen()` | `view.AltScreen = false` in `View()` |329| `p.EnableMouseCellMotion()` | `view.MouseMode` in `View()` |330| `p.DisableMouseCellMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |331| `p.EnableMouseAllMotion()` | `view.MouseMode` in `View()` |332| `p.DisableMouseAllMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |333| `p.SetWindowTitle(...)` | `view.WindowTitle` in `View()` |334335## Renamed APIs336337| v1 | v2 | Notes |338|---|---|---|339| `tea.Sequentially(...)` | `tea.Sequence(...)` | `Sequentially` was already deprecated in v1 |340| `tea.WindowSize()` | `tea.RequestWindowSize` | Now returns `Msg` directly, not a `Cmd` |341342## New Program Options343344These are new in v2:345346| Option | What It Does |347|---|---|348| `tea.WithColorProfile(p)` | Force a specific color profile (great for testing) |349| `tea.WithWindowSize(w, h)` | Set initial terminal size (great for testing) |350351## Complete Before & After352353Here's a minimal but complete program showing the most common migration patterns side by side.354355**v1:**356357```go358package main359360import (361 "fmt"362 "os"363364 tea "github.com/charmbracelet/bubbletea"365)366367type model struct {368 count int369}370371func (m model) Init() tea.Cmd {372 return nil373}374375func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {376 switch msg := msg.(type) {377 case tea.KeyMsg:378 switch msg.String() {379 case "q", "ctrl+c":380 return m, tea.Quit381 case " ":382 m.count++383 }384 case tea.MouseMsg:385 if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft {386 m.count++387 }388 }389 return m, nil390}391392func (m model) View() string {393 return fmt.Sprintf("Count: %d\n\nSpace or click to increment. q to quit.\n", m.count)394}395396func main() {397 p := tea.NewProgram(model{}, tea.WithAltScreen(), tea.WithMouseCellMotion())398 if _, err := p.Run(); err != nil {399 fmt.Fprintln(os.Stderr, err)400 os.Exit(1)401 }402}403```404405**v2:**406407```go408package main409410import (411 "fmt"412 "os"413414 tea "charm.land/bubbletea/v2"415)416417type model struct {418 count int419}420421func (m model) Init() tea.Cmd {422 return nil423}424425func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {426 switch msg := msg.(type) {427 case tea.KeyPressMsg:428 switch msg.String() {429 case "q", "ctrl+c":430 return m, tea.Quit431 case "space":432 m.count++433 }434 case tea.MouseClickMsg:435 if msg.Button == tea.MouseLeft {436 m.count++437 }438 }439 return m, nil440}441442func (m model) View() tea.View {443 v := tea.NewView(fmt.Sprintf("Count: %d\n\nSpace or click to increment. q to quit.\n", m.count))444 v.AltScreen = true445 v.MouseMode = tea.MouseModeCellMotion446 return v447}448449func main() {450 p := tea.NewProgram(model{})451 if _, err := p.Run(); err != nil {452 fmt.Fprintln(os.Stderr, err)453 os.Exit(1)454 }455}456```457458Notice how the `NewProgram` call got simpler? All the terminal feature flags moved into `View()` where they belong.459460## Quick Reference461462A flat old → new lookup table. Handy for search-and-replace and LLM-assisted migration.463464### Import Paths465466| v1 | v2 |467|---|---|468| `github.com/charmbracelet/bubbletea` | `charm.land/bubbletea/v2` |469| `github.com/charmbracelet/lipgloss` | `charm.land/lipgloss/v2` |470471### Model Interface472473| v1 | v2 |474|---|---|475| `View() string` | `View() tea.View` |476477### Key Events478479| v1 | v2 |480|---|---|481| `tea.KeyMsg` (struct) | `tea.KeyPressMsg` for presses, `tea.KeyMsg` (interface) for both |482| `msg.Type` | `msg.Code` |483| `msg.Runes` | `msg.Text` (string, not `[]rune`) |484| `msg.Alt` | `msg.Mod.Contains(tea.ModAlt)` |485| `tea.KeyRune` | check `len(msg.Text) > 0` |486| `tea.KeyCtrlC` | `msg.Code == 'c' && msg.Mod == tea.ModCtrl` or `msg.String() == "ctrl+c"` |487| `case " ":` (space) | `case "space":` |488489### Mouse Events490491| v1 | v2 |492|---|---|493| `tea.MouseMsg` (struct) | `tea.MouseMsg` (interface) — call `.Mouse()` for the data |494| `tea.MouseEvent` | `tea.Mouse` |495| `tea.MouseButtonLeft` | `tea.MouseLeft` |496| `tea.MouseButtonRight` | `tea.MouseRight` |497| `tea.MouseButtonMiddle` | `tea.MouseMiddle` |498| `tea.MouseButtonWheelUp` | `tea.MouseWheelUp` |499| `tea.MouseButtonWheelDown` | `tea.MouseWheelDown` |500| `msg.X`, `msg.Y` (direct) | `msg.Mouse().X`, `msg.Mouse().Y` |501502### Options → View Fields503504| v1 Option | v2 View Field |505|---|---|506| `tea.WithAltScreen()` | `view.AltScreen = true` |507| `tea.WithMouseCellMotion()` | `view.MouseMode = tea.MouseModeCellMotion` |508| `tea.WithMouseAllMotion()` | `view.MouseMode = tea.MouseModeAllMotion` |509| `tea.WithReportFocus()` | `view.ReportFocus = true` |510| `tea.WithoutBracketedPaste()` | `view.DisableBracketedPasteMode = true` |511512### Commands → View Fields513514| v1 Command | v2 View Field |515|---|---|516| `tea.EnterAltScreen` / `tea.ExitAltScreen` | `view.AltScreen = true/false` |517| `tea.EnableMouseCellMotion` | `view.MouseMode = tea.MouseModeCellMotion` |518| `tea.EnableMouseAllMotion` | `view.MouseMode = tea.MouseModeAllMotion` |519| `tea.DisableMouse` | `view.MouseMode = tea.MouseModeNone` |520| `tea.HideCursor` / `tea.ShowCursor` | `view.Cursor = nil` / `view.Cursor = &tea.Cursor{...}` |521| `tea.EnableBracketedPaste` / `tea.DisableBracketedPaste` | `view.DisableBracketedPasteMode = false/true` |522| `tea.EnableReportFocus` / `tea.DisableReportFocus` | `view.ReportFocus = true/false` |523| `tea.SetWindowTitle("...")` | `view.WindowTitle = "..."` |524525### Removed Options (No Replacement Needed)526527| v1 Option | What Happened |528|---|---|529| `tea.WithInputTTY()` | v2 always opens the TTY for input automatically |530| `tea.WithANSICompressor()` | The new renderer handles optimization automatically |531532### Removed Program Methods533534| v1 Method | v2 Replacement |535|---|---|536| `p.Start()` | `p.Run()` |537| `p.StartReturningModel()` | `p.Run()` |538| `p.EnterAltScreen()` | `view.AltScreen = true` in `View()` |539| `p.ExitAltScreen()` | `view.AltScreen = false` in `View()` |540| `p.EnableMouseCellMotion()` | `view.MouseMode` in `View()` |541| `p.DisableMouseCellMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |542| `p.EnableMouseAllMotion()` | `view.MouseMode` in `View()` |543| `p.DisableMouseAllMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |544| `p.SetWindowTitle(...)` | `view.WindowTitle` in `View()` |545546### Other Renames547548| v1 | v2 |549|---|---|550| `tea.Sequentially(...)` | `tea.Sequence(...)` |551| `tea.WindowSize()` | `tea.RequestWindowSize` (now returns `Msg`, not `Cmd`) |552553### New Program Options554555| Option | Description |556|---|---|557| `tea.WithColorProfile(p)` | Force a specific color profile |558| `tea.WithWindowSize(w, h)` | Set initial window size (great for testing) |559560## Feedback561562Have thoughts on the v2 upgrade? We'd _love_ to hear about it. Let us know on…563564- [Discord](https://charm.land/chat)565- [Matrix](https://charm.land/matrix)566- [Email](mailto:vt100@charm.land)567568---569570Part of [Charm](https://charm.land).571

docs: upgrade guide: correct badge urlAyman Bagabasbefore adoption736fba2

line 572why, one step back
572<a href="https://charm.land/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 573–574why, one step back
573
574Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة