Merge pull request #1118 from charmbracelet/v2-exp
Before adoption: this commit came in with the history the project adopted, so no landing records it.
(v2) Bubble Tea v2
authored by Ayman Bagabas · committed by GitHub · parents 13d882c, 1b79985 · Browse files · 145 files·+7056 added−6397 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
145 files+7056 added−6397 removed
- other:+7056 added−6397 removed
Provenance
- Commit
d1c8c97- Tree
bd71f1e- Author
Ayman Bagabas <ayman.bagabas@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
13d882c- Parent 2
1b79985
145 files changed+7056 added−6397 removed
modified:.github/workflows/lint.yml+4 added
4 unmodified lines567891011124 unmodified lines
jobs: lint: uses: charmbracelet/meta/.github/workflows/lint.yml@main with: golangci_path: .golangci.yml golangci_version: v2.9 timeout: 10mmodified:examples/altscreen-toggle/main.go+15 added-14 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- tea "github.com/charmbracelet/bubbletea"8- "github.com/charmbracelet/lipgloss"7+ tea "charm.land/bubbletea/v2"8+ "charm.land/lipgloss/v2"9 )10 11 var (12 keywordStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("204")).Background(lipgloss.Color("235"))14 unmodified lines27 switch msg := msg.(type) {28 case tea.ResumeMsg:29 m.suspending = false30 return m, nil31- case tea.KeyMsg:31+ case tea.KeyPressMsg:32 switch msg.String() {33 case "q", "ctrl+c", "esc":34 m.quitting = true35 return m, tea.Quit36 case "ctrl+z":37 m.suspending = true38 return m, tea.Suspend39- case " ":39+ case "space":40 var cmd tea.Cmd41- if m.altscreen {42- cmd = tea.ExitAltScreen43- } else {44- cmd = tea.EnterAltScreen45- }41 m.altscreen = !m.altscreen42 return m, cmd43 }44 }45 return m, nil46 }47 53-func (m model) View() string {48+func (m model) View() tea.View {49 if m.suspending {50+ v := tea.NewView("")51+ v.AltScreen = m.altscreen55- return ""52+ return v53 }54 55 if m.quitting {59- return "Bye!\n"56+ v := tea.NewView("Bye!\n")57+ v.AltScreen = m.altscreen58+ return v59 }60 61 const (62 altscreenMode = " altscreen mode "6 unmodified lines69 } else {70 mode = inlineMode71 }72 74- return fmt.Sprintf("\n\n You're in %s\n\n\n", keywordStyle.Render(mode)) +75- helpStyle.Render(" space: switch modes • ctrl-z: suspend • q: exit\n")73+ v := tea.NewView(fmt.Sprintf("\n\n You're in %s\n\n\n", keywordStyle.Render(mode)) +74+ helpStyle.Render(" space: switch modes • ctrl-z: suspend • q: exit\n"))75+ v.AltScreen = m.altscreen76+ return v77 }78 79 func main() {80 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesmodified:examples/autocomplete/main.go+81 added-30 removed
1 package main2 3 import (4 "encoding/json"5- "fmt"5 "io"6 "log"7 "net/http"8 10- "github.com/charmbracelet/bubbles/help"11- "github.com/charmbracelet/bubbles/key"12- "github.com/charmbracelet/bubbles/textinput"13- tea "github.com/charmbracelet/bubbletea"14- "github.com/charmbracelet/lipgloss"9+ "charm.land/bubbles/v2/help"10+ "charm.land/bubbles/v2/key"11+ "charm.land/bubbles/v2/textinput"12+ tea "charm.land/bubbletea/v2"13+ "charm.land/lipgloss/v2"14 )15 16 func main() {17 p := tea.NewProgram(initialModel())1 unmodified line19 log.Fatal(err)20 }21 }22 23+type (24-type gotReposSuccessMsg []repo25-type gotReposErrMsg error24+ gotReposSuccessMsg []repo25+ gotReposErrMsg error26+)27 28 type repo struct {29 Name string `json:"name"`30 }35 unmodified lines66 help help.Model67 keymap keymap68 }69 69-type keymap struct{}70+type keymap struct {71+ complete, next, prev, quit key.Binding72+}73 74 func (k keymap) ShortHelp() []key.Binding {75 return []key.Binding{73- key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "complete")),74- key.NewBinding(key.WithKeys("ctrl+n"), key.WithHelp("ctrl+n", "next")),75- key.NewBinding(key.WithKeys("ctrl+p"), key.WithHelp("ctrl+p", "prev")),76- key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "quit")),76+ k.complete,77+ k.next,78+ k.prev,79+ k.quit,80 }81 }82+83 func (k keymap) FullHelp() [][]key.Binding {84 return [][]key.Binding{k.ShortHelp()}85 }86 87 func initialModel() model {88 ti := textinput.New()85- ti.Placeholder = "repository"89 ti.Prompt = "charmbracelet/"87- ti.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))88- ti.Cursor.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))90+91+ s := ti.Styles()92+ s.Focused.Prompt = lipgloss.NewStyle().Foreground(lipgloss.Color("63")).MarginLeft(2)93+ s.Cursor.Color = lipgloss.Color("63")94+ ti.SetStyles(s)95+96+ ti.SetVirtualCursor(false)97 ti.Focus()98 ti.CharLimit = 5091- ti.Width = 2099+ ti.SetWidth(20)100 ti.ShowSuggestions = true101 94- h := help.New()102+ km := keymap{103+ // XXX: we should be using the keybindings on the textinput model.104+ complete: key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "complete"), key.WithDisabled()),105+ next: key.NewBinding(key.WithKeys("ctrl+n"), key.WithHelp("ctrl+n", "next"), key.WithDisabled()),106+ prev: key.NewBinding(key.WithKeys("ctrl+p"), key.WithHelp("ctrl+p", "prev"), key.WithDisabled()),107 96- km := keymap{}108+ quit: key.NewBinding(key.WithKeys("enter", "ctrl+c", "esc"), key.WithHelp("esc", "quit")),109+ }110 98- return model{textInput: ti, help: h, keymap: km}111+ return model{112+ textInput: ti,113+ keymap: km,114+ help: help.New(),115+ }116 }117 118 func (m model) Init() tea.Cmd {119 return tea.Batch(getRepos, textinput.Blink)120 }121 122+func (m model) Cursor() *tea.Cursor {123+ c := m.textInput.Cursor()124+ if c != nil {125+ c.Y += lipgloss.Height(m.headerView())126+ }127+ return c128+}129+130 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {131 switch msg := msg.(type) {107- case tea.KeyMsg:108- switch msg.Type {109- case tea.KeyEnter, tea.KeyCtrlC, tea.KeyEsc:110- return m, tea.Quit111- }132+133 case gotReposSuccessMsg:134 var suggestions []string135 for _, r := range msg {136 suggestions = append(suggestions, r.Name)137 }138 m.textInput.SetSuggestions(suggestions)139+140+ case tea.KeyPressMsg:141+ switch {142+ case key.Matches(msg, m.keymap.quit):143+ return m, tea.Quit144+ }145 }146 147 var cmd tea.Cmd148 m.textInput, cmd = m.textInput.Update(msg)149+150+ // Determine whether to show completion keybindings.151+ //152+ // XXX: we should be using the keybindings on the textinput model.153+ hasChoices := len(m.textInput.MatchedSuggestions()) > 1154+ m.keymap.complete.SetEnabled(hasChoices)155+ m.keymap.next.SetEnabled(hasChoices)156+ m.keymap.prev.SetEnabled(hasChoices)157+158 return m, cmd159 }160 125-func (m model) View() string {126- return fmt.Sprintf(127- "Pick a Charm™ repo:\n\n %s\n\n%s\n\n",161+func (m model) View() tea.View {162+ if len(m.textInput.AvailableSuggestions()) < 1 {163+ return tea.NewView("One sec, we're fetching completions...")164+ }165+166+ v := tea.NewView(lipgloss.JoinVertical(167+ lipgloss.Left,168+ m.headerView(),169 m.textInput.View(),129- m.help.View(m.keymap),130- )170+ m.footerView(),171+ ))172+173+ c := m.textInput.Cursor()174+ if c != nil {175+ c.Y += lipgloss.Height(m.headerView())176+ }177+ v.Cursor = c178+ return v179 }180+181+func (m model) headerView() string { return "Enter a Charm™ repo:\n" }182+func (m model) footerView() string { return "\n" + m.help.View(m.keymap) }added:examples/canvas/main.go+95 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "charm.land/bubbletea/v2"8+ "charm.land/lipgloss/v2"9+ "github.com/charmbracelet/x/exp/charmtone"10+)11+12+type model struct {13+ width int14+ flip bool15+ quitting bool16+}17+18+func (m model) Init() tea.Cmd {19+ return nil20+}21+22+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {23+ switch msg := msg.(type) {24+ case tea.WindowSizeMsg:25+ m.width = msg.Width26+ return m, nil27+ case tea.KeyPressMsg:28+ switch msg.String() {29+ case "q", "ctrl+c", "esc":30+ m.quitting = true31+ return m, tea.Quit32+ default:33+ m.flip = !m.flip34+ }35+ }36+ return m, nil37+}38+39+func (m model) View() tea.View {40+ var view tea.View41+ if m.quitting {42+ return view43+ }44+45+ z := []int{0, 1}46+ if m.flip {47+ z = reverse(z)48+ }49+50+ footer := lipgloss.NewStyle().51+ Height(13).52+ Foreground(charmtone.Oyster).53+ AlignVertical(lipgloss.Bottom).54+ Render("Press any key to swap the cards, or q to quit.")55+56+ cardA := newCard("Hello").Z(z[0])57+ cardB := newCard("Goodbye").Z(z[1])58+ comp := lipgloss.NewCompositor(59+ lipgloss.NewLayer(footer),60+ cardA,61+ cardB.X(10).Y(2),62+ )63+ view.SetContent(comp.Render())64+65+ return view66+}67+68+func newCard(str string) *lipgloss.Layer {69+ return lipgloss.NewLayer(70+ lipgloss.NewStyle().71+ Width(20).72+ Height(10).73+ Border(lipgloss.RoundedBorder()).74+ BorderForeground(charmtone.Charple).75+ Align(lipgloss.Center, lipgloss.Center).76+ Render(str),77+ )78+}79+80+// Reverse a slice, returning a new slice.81+func reverse[T any](s []T) []T {82+ n := len(s)83+ r := make([]T, n)84+ for i, v := range s {85+ r[n-1-i] = v86+ }87+ return r88+}89+90+func main() {91+ if _, err := tea.NewProgram(model{}).Run(); err != nil {92+ fmt.Fprintln(os.Stderr, "Urgh:", err)93+ os.Exit(1)94+ }95+}added:examples/capability/main.go+76 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ "charm.land/bubbles/v2/textinput"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10+)11+12+type model struct {13+ input textinput.Model14+ width int15+}16+17+var _ tea.Model = model{}18+19+// Init implements tea.Model.20+func (m model) Init() tea.Cmd {21+ return m.input.Focus()22+}23+24+// Update implements tea.Model.25+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {26+ var cmd tea.Cmd27+ switch msg := msg.(type) {28+ case tea.WindowSizeMsg:29+ m.width = msg.Width30+ case tea.KeyPressMsg:31+ switch msg.String() {32+ case "ctrl+c", "esc":33+ return m, tea.Quit34+ case "enter":35+ input := m.input.Value()36+ m.input.Reset()37+ return m, tea.RequestCapability(input)38+ }39+ case tea.CapabilityMsg:40+ return m, tea.Printf("Got capability: %s", msg)41+ }42+ m.input, cmd = m.input.Update(msg)43+ return m, cmd44+}45+46+// View implements tea.Model.47+func (m model) View() tea.View {48+ w := min(m.width, 60)49+50+ instructions := lipgloss.NewStyle().51+ Width(w).52+ Render("Query for terminal capabilities. You can enter things like 'TN', 'RGB', 'cols', and so on. This will not work in all terminals and multiplexers.")53+54+ return tea.NewView("\n" + instructions + "\n\n" +55+ m.input.View() +56+ "\n\nPress enter to request capability, or ctrl+c to quit.")57+}58+59+func main() {60+ m := model{}61+ m.input = textinput.New()62+ m.input.Placeholder = "Enter capability name to request"63+ m.input.Focus()64+65+ if _, err := tea.NewProgram(m).Run(); err != nil {66+ fmt.Fprintln(os.Stderr, "Uh oh:", err)67+ os.Exit(1)68+ }69+}70+71+func min(a, b int) int {72+ if a < b {73+ return a74+ }75+ return b76+}modified:examples/cellbuffer/main.go+17 added-8 removed
8 unmodified lines9 "os"10 "strings"11 "time"12 13- tea "github.com/charmbracelet/bubbletea"13+ tea "charm.land/bubbletea/v2"14 "github.com/charmbracelet/harmonica"15 )16 17 const (98 unmodified lines116 }117 118 func (c cellbuffer) String() string {119 var b strings.Builder120- for i := 0; i < len(c.cells); i++ {120+ for i := range c.cells {121 if i > 0 && i%c.stride == 0 && i < len(c.cells)-1 {122 b.WriteRune('\n')123 }124 b.WriteString(c.cells[i])22 unmodified lines147 }148 149 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {150 switch msg := msg.(type) {151- case tea.KeyMsg:151+ case tea.KeyPressMsg:152 return m, tea.Quit153 case tea.WindowSizeMsg:154 if !m.cells.ready() {155 m.targetX, m.targetY = float64(msg.Width)/2, float64(msg.Height)/2156 }157 m.cells.init(msg.Width, msg.Height)158 return m, nil159 case tea.MouseMsg:160+ switch msg.(type) {161+ case tea.MouseClickMsg, tea.MouseMotionMsg:162+ default:163+ break164+ }165 if !m.cells.ready() {166 return m, nil167 }168+ mouse := msg.Mouse()163- m.targetX, m.targetY = float64(msg.X), float64(msg.Y)169+ m.targetX, m.targetY = float64(mouse.X), float64(mouse.Y)170 return m, nil171 172 case frameMsg:173 if !m.cells.ready() {9 unmodified lines183 return m, nil184 }185 }186 181-func (m model) View() string {182- return m.cells.String()187+func (m model) View() tea.View {188+ v := tea.NewView(m.cells.String())189+ v.AltScreen = true190+ v.MouseMode = tea.MouseModeCellMotion191+ return v192 }193 194 func main() {195 m := model{196 spring: harmonica.NewSpring(harmonica.FPS(fps), frequency, damping),197 }198 190- p := tea.NewProgram(m, tea.WithAltScreen(), tea.WithMouseCellMotion())199+ p := tea.NewProgram(m)200 if _, err := p.Run(); err != nil {192- fmt.Println("Uh oh:", err)201+ fmt.Fprintln(os.Stderr, "Uh oh:", err)202 os.Exit(1)203 }204 }modified:examples/chat/main.go+44 added-43 removed
3 unmodified lines4 // component library.5 6 import (7 "fmt"8- "log"8+ "os"9 "strings"10 11- "github.com/charmbracelet/bubbles/textarea"12- "github.com/charmbracelet/bubbles/viewport"13- tea "github.com/charmbracelet/bubbletea"14- "github.com/charmbracelet/lipgloss"11+ "charm.land/bubbles/v2/cursor"12+ "charm.land/bubbles/v2/textarea"13+ "charm.land/bubbles/v2/viewport"14+ tea "charm.land/bubbletea/v2"15+ "charm.land/lipgloss/v2"16 )17 17-const gap = "\n\n"18-18 func main() {19 p := tea.NewProgram(initialModel())21-20 if _, err := p.Run(); err != nil {23- log.Fatal(err)21+ fmt.Fprintf(os.Stderr, "Oof: %v\n", err)22 }23 }24 27-type (28- errMsg error29-)30-25 type model struct {26 viewport viewport.Model27 messages []string28 textarea textarea.Model3 unmodified lines32 33 func initialModel() model {34 ta := textarea.New()35 ta.Placeholder = "Send a message..."36+ ta.SetVirtualCursor(false)37 ta.Focus()38 39 ta.Prompt = "┃ "40 ta.CharLimit = 2801 unmodified line42 ta.SetWidth(30)43 ta.SetHeight(3)44 45 // Remove cursor line styling46+ s := ta.Styles()51- ta.FocusedStyle.CursorLine = lipgloss.NewStyle()47+ s.Focused.CursorLine = lipgloss.NewStyle()48+ ta.SetStyles(s)49 50 ta.ShowLineNumbers = false51 55- vp := viewport.New(30, 5)52+ vp := viewport.New(viewport.WithWidth(30), viewport.WithHeight(5))53 vp.SetContent(`Welcome to the chat room!54 Type a message and press Enter to send.`)55+ vp.KeyMap.Left.SetEnabled(false)56+ vp.KeyMap.Right.SetEnabled(false)57 58 ta.KeyMap.InsertNewline.SetEnabled(false)59 60 return model{9 unmodified lines70 return textarea.Blink71 }72 73 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {75- var (76- tiCmd tea.Cmd77- vpCmd tea.Cmd78- )79-80- m.textarea, tiCmd = m.textarea.Update(msg)81- m.viewport, vpCmd = m.viewport.Update(msg)82-74 switch msg := msg.(type) {75 case tea.WindowSizeMsg:85- m.viewport.Width = msg.Width76+ m.viewport.SetWidth(msg.Width)77 m.textarea.SetWidth(msg.Width)87- m.viewport.Height = msg.Height - m.textarea.Height() - lipgloss.Height(gap)78+ m.viewport.SetHeight(msg.Height - m.textarea.Height())79 80 if len(m.messages) > 0 {81 // Wrap content before setting it.91- m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width).Render(strings.Join(m.messages, "\n")))82+ m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width()).Render(strings.Join(m.messages, "\n")))83 }84 m.viewport.GotoBottom()94- case tea.KeyMsg:95- switch msg.Type {96- case tea.KeyCtrlC, tea.KeyEsc:85+ case tea.KeyPressMsg:86+ switch msg.String() {87+ case "ctrl+c", "esc":88 fmt.Println(m.textarea.Value())89 return m, tea.Quit99- case tea.KeyEnter:90+ case "enter":91 m.messages = append(m.messages, m.senderStyle.Render("You: ")+m.textarea.Value())101- m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width).Render(strings.Join(m.messages, "\n")))92+ m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width()).Render(strings.Join(m.messages, "\n")))93 m.textarea.Reset()94 m.viewport.GotoBottom()95+ return m, nil96+ default:97+ // Send all other keypresses to the textarea.98+ var cmd tea.Cmd99+ m.textarea, cmd = m.textarea.Update(msg)100+ return m, cmd101 }102 106- // We handle errors just like any other message107- case errMsg:108- m.err = msg109- return m, nil103+ case cursor.BlinkMsg:104+ // Textarea should also process cursor blinks.105+ var cmd tea.Cmd106+ m.textarea, cmd = m.textarea.Update(msg)107+ return m, cmd108 }109 112- return m, tea.Batch(tiCmd, vpCmd)110+ return m, nil111 }112 115-func (m model) View() string {116- return fmt.Sprintf(117- "%s%s%s",118- m.viewport.View(),119- gap,120- m.textarea.View(),121- )113+func (m model) View() tea.View {114+ viewportView := m.viewport.View()115+ v := tea.NewView(viewportView + "\n" + m.textarea.View())116+ c := m.textarea.Cursor()117+ if c != nil {118+ c.Y += lipgloss.Height(viewportView)119+ }120+ v.Cursor = c121+ v.AltScreen = true122+ return v123 }added:examples/clickable/main.go+369 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "charm.land/bubbletea/v2"8+ "charm.land/lipgloss/v2"9+ "github.com/segmentio/ksuid"10+)11+12+// LayerHitMsg is a message that is sent to the program when a layer is hit by13+// a mouse event. This is used to determine which layer in a compostable view14+// was hit by the mouse event. The layer is identified by its ID, which is a15+// string that is unique to the layer.16+type LayerHitMsg struct {17+ ID string18+ Mouse tea.MouseMsg19+}20+21+const maxDialogs = 99922+23+// Styles24+var (25+ bgTextStyle = lipgloss.NewStyle().26+ Foreground(lipgloss.Color("239")).27+ Padding(1, 2)28+29+ bgWhitespace = []lipgloss.WhitespaceOption{30+ lipgloss.WithWhitespaceChars("/"),31+ lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("238"))),32+ }33+34+ dialogWordStyle = lipgloss.NewStyle().35+ Foreground(lipgloss.Color("#E7E1CC"))36+37+ dialogStyle = dialogWordStyle.38+ Width(36).39+ Height(8).40+ Padding(1, 3).41+ Border(lipgloss.RoundedBorder()).42+ BorderForeground(lipgloss.Color("#874BFD"))43+44+ hoveredDialogStyle = dialogStyle.45+ BorderForeground(lipgloss.Color("#F25D94"))46+47+ specialWordLightColor = lipgloss.Color("#43BF6D")48+ specialWordDarkColor = lipgloss.Color("#73F59F")49+50+ buttonStyle = lipgloss.NewStyle().51+ Padding(0, 3).52+ Foreground(lipgloss.Color("#FFF7DB")).53+ Background(lipgloss.Color("#6124DF"))54+55+ hoveredButtonStyle = buttonStyle.56+ Background(lipgloss.Color("#FF5F87"))57+)58+59+// Model60+61+type model struct {62+ specialWordStyle lipgloss.Style63+ width, height int64+ dialogs []dialog65+ mouseDown bool66+ pressID string67+ dragID string68+ dragOffsetX int69+ dragOffsetY int70+}71+72+func (m model) Init() tea.Cmd {73+ return tea.Batch(74+ tea.RequestBackgroundColor,75+ )76+}77+78+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {79+ switch msg := msg.(type) {80+ case tea.WindowSizeMsg:81+ m.width, m.height = msg.Width, msg.Height82+83+ case tea.BackgroundColorMsg:84+ if msg.IsDark() {85+ m.specialWordStyle = m.specialWordStyle.Foreground(specialWordDarkColor)86+ } else {87+ m.specialWordStyle = m.specialWordStyle.Foreground(specialWordLightColor)88+ }89+90+ case tea.KeyPressMsg:91+ switch msg.String() {92+ case "q", "ctrl+c", "esc":93+ return m, tea.Quit94+ }95+96+ case LayerHitMsg:97+ mouse := msg.Mouse.Mouse()98+99+ switch msg.Mouse.(type) {100+ case tea.MouseClickMsg:101+ if mouse.Button != tea.MouseLeft {102+ break103+ }104+105+ // Initial press106+ if !m.mouseDown {107+ m.mouseDown = true108+ m.pressID = msg.ID109+110+ // Did we press on a dialog box?111+ for i, d := range m.dialogs {112+ if d.id != msg.ID {113+ continue114+ }115+116+ // Init drag117+ m.dragID = msg.ID118+ m.dragOffsetX = mouse.X - d.x119+ m.dragOffsetY = mouse.Y - d.y120+121+ if len(m.dialogs) < 2 {122+ break123+ }124+125+ // Move the one we're going to drag to the end of the slice126+ // so that it gets the highest z-index when we do127+ // compositing later. There are, of course, lots of other128+ // ways you could manage the z-index, too.129+ m.dialogs = m.removeDialog(i)130+ m.dialogs = append(m.dialogs, d)131+ break132+ }133+134+ break135+ }136+137+ // MouseMotion events are send when the mouse has moved and a mouse138+ // button is not pressed.139+ case tea.MouseMotionMsg:140+ // Dragging141+ if m.mouseDown && m.dragID != "" {142+ // Find the dialog box we're dragging143+ for i := range m.dialogs {144+ d := &m.dialogs[i]145+ if d.id != m.dragID {146+ continue147+ }148+149+ // Move the dialog box with the cursor150+ if m.dragID == d.id {151+ d.x = clamp(mouse.X-(m.dragOffsetX), 0, m.width-lipgloss.Width(d.windowView()))152+ d.y = clamp(mouse.Y-(m.dragOffsetY), 0, m.height-lipgloss.Height(d.windowView()))153+ }154+155+ break156+ }157+ }158+159+ // Are we hoving over a dialog box?160+ for i := range m.dialogs {161+162+ d := &m.dialogs[i]163+ d.hovering = false164+ d.hoveringButton = false165+166+ if d.id == msg.ID {167+ d.hovering = true168+ continue169+ }170+ if d.buttonID == msg.ID {171+ d.hovering = true172+ d.hoveringButton = true173+ continue174+ }175+ }176+177+ case tea.MouseReleaseMsg:178+179+ // Make sure we're releasing on something with an ID. A successful180+ // click is a press and release.181+ if m.pressID == "" {182+ break183+ }184+185+ // Did we click a button?186+ for i, d := range m.dialogs {187+ if msg.ID == d.buttonID && m.pressID == d.buttonID {188+ // "Close" the window189+ m.dialogs = m.removeDialog(i)190+ break191+ }192+ }193+194+ // Clicking the background spawns a new dialog195+ if msg.ID == "bg" && m.pressID == "bg" {196+ if len(m.dialogs) < maxDialogs {197+ m.dialogs = append(m.dialogs, m.newDialog(mouse.X, mouse.Y))198+ }199+ }200+201+ m.mouseDown = false202+ m.dragID = ""203+ m.pressID = ""204+ }205+ }206+207+ return m, nil208+}209+210+func (m model) View() tea.View {211+ var v tea.View212+ var body string213+214+ n := len(m.dialogs)215+ if n > 0 {216+ body += "Drag to move. "217+ }218+ if n == 0 && n < maxDialogs {219+ body += "Click to spawn."220+ } else if n >= 1 && n < maxDialogs {221+ body += fmt.Sprintf("Click to spawn up to %d more.", maxDialogs-len(m.dialogs))222+ }223+ body += "\n\nPress q to quit."224+225+ bg := lipgloss.Place(226+ m.width,227+ m.height,228+ lipgloss.Top,229+ lipgloss.Left,230+ bgTextStyle.Render(body),231+ bgWhitespace...,232+ )233+234+ root := lipgloss.NewLayer(bg).ID("bg")235+ for i, d := range m.dialogs {236+ root.AddLayers(d.view().Z(i + 1))237+ }238+239+ comp := lipgloss.NewCompositor(root)240+241+ v.MouseMode = tea.MouseModeAllMotion242+ v.AltScreen = true243+ v.OnMouse = func(msg tea.MouseMsg) tea.Cmd {244+ return func() tea.Msg {245+ mouse := msg.Mouse()246+ x, y := mouse.X, mouse.Y247+ if id := comp.Hit(x, y).ID(); id != "" {248+ return LayerHitMsg{249+ ID: id,250+ Mouse: msg,251+ }252+ }253+ return nil254+ }255+ }256+ v.SetContent(comp.Render())257+258+ return v259+}260+261+func (m *model) newDialog(x, y int) (d dialog) {262+ d.specialWordStyle = &m.specialWordStyle263+ dummyView := d.windowView()264+ w := lipgloss.Width(dummyView)265+ h := lipgloss.Height(dummyView)266+ d.x = clamp(x-w/2, 0, m.width-w)267+ d.y = clamp(y-h/2, 0, m.height-h)268+ d.text = nextRandomWord()269+ d.id = ksuid.New().String()270+ d.buttonID = ksuid.New().String()271+ return d272+}273+274+func (m model) removeDialog(index int) []dialog {275+ d := m.dialogs276+277+ if len(d) <= index {278+ return m.dialogs279+ }280+281+ copy(d[index:], d[index+1:]) // shift282+ d[len(d)-1] = dialog{} // nullify283+ return d[:len(d)-1] // truncate284+}285+286+// Dialog Windows287+288+type dialog struct {289+ specialWordStyle *lipgloss.Style290+ id string291+ buttonID string292+ x, y int293+ text string294+ hovering bool295+ hoveringButton bool296+}297+298+func (d dialog) buttonView() string {299+ const label = "Run Away"300+301+ if d.hoveringButton {302+ return hoveredButtonStyle.Render(label)303+ }304+ return buttonStyle.Render(label)305+}306+307+func (d dialog) windowView() string {308+ var style lipgloss.Style309+ if d.hovering {310+ style = hoveredDialogStyle311+ } else {312+ style = dialogStyle313+ }314+315+ s := d.specialWordStyle.Render(d.text) + dialogWordStyle.Render(" draws near. Command?")316+ return style.Render(s)317+}318+319+func (d dialog) view() *lipgloss.Layer {320+ const hGap, vGap = 3, 1321+322+ window := d.windowView()323+ button := d.buttonView()324+325+ buttonX := lipgloss.Width(window) - lipgloss.Width(button) - 1 - hGap326+ buttonY := lipgloss.Height(window) - lipgloss.Height(button) - 1 - vGap327+328+ buttonLayer := lipgloss.NewLayer(button).329+ ID(d.buttonID).330+ X(buttonX).331+ Y(buttonY)332+333+ return lipgloss.NewLayer(window).334+ ID(d.id).335+ X(d.x).336+ Y(d.y).337+ AddLayers(buttonLayer)338+}339+340+// Main341+342+func main() {343+ ksuid.SetRand(ksuid.FastRander)344+345+ path := os.Getenv("TEA_LOGFILE")346+ if path != "" {347+ f, err := tea.LogToFile(path, "layers")348+ if err != nil {349+ fmt.Println("could not open logfile:", err)350+ os.Exit(1)351+ }352+ defer f.Close()353+ }354+355+ if _, err := tea.NewProgram(model{}).Run(); err != nil {356+ fmt.Println("Error while running program:", err)357+ os.Exit(1)358+ }359+}360+361+func clamp(n, min, max int) int {362+ if n < min {363+ return min364+ }365+ if n > max {366+ return max367+ }368+ return n369+}added:examples/clickable/words.go+77 added
1+package main2+3+import (4+ "math/rand"5+ "strings"6+ "sync"7+)8+9+const uncapitalized = " of a an and ’n’ "10+11+var (12+ adjectives = []string{13+ "a hot", "a cute", "a fresh", "a nice", "a lovely",14+ "an eager", "a soft", "an expensive", "a new", "an old", "a happy",15+ "a messy", "a good", "a bad", "a cheesy", "a friendly", "a free",16+ "a cold", "a gorgeous", "a glamorous", "a handsome", "an exquisite",17+ "a tantalizing", "a suspicious", "an american", "a wooden", "a golden",18+ "a dirty", "a hairy", "a lukewarm", "a burning hot", "a shiny",19+ "a rogue", "a green", "a late night", "a mass produced", "a handmade",20+ "a wild", "a clean", "a rugged", "the #1", "the best", "the worst",21+ "a famous", "an infamous", "a clever", "a microwaved", "a 3D printed",22+ "your favorite", "your least favorite", "someone’s", "a precious",23+ "a fake", "a genuine", "a bejeweled", "a good-smelling",24+ }25+26+ nouns = []string{27+ "pear", "banana", "bowl of ramen", "currywurst", "quince",28+ "pie", "cake", "burrito", "sushi", "basket of fish ’n’ chips", "burger",29+ "kohlrabi", "pineapple", "cantaloupe", "sausage roll", "yuzu",30+ "grapefruit", "espresso shot", "sandwich", "bowl of chow mein", "lemon",31+ "cup of coffee", "bottle of hot sauce", "can of beer", "glass of wine",32+ "muffin", "bagel", "glass of champagne", "bottle of rosé", "pengu",33+ "badger", "mango", "okonomiyaki", "meatball", "box of wine",34+ "artichoke", "TUI", "linux distro", "dotfile", "weißwurst", "computer",35+ }36+37+ shuffle sync.Once38+ nextWordMtx sync.Mutex39+)40+41+func nextRandomWord() string {42+ shuffle.Do(shuffleWords)43+44+ nextWordMtx.Lock()45+ defer nextWordMtx.Unlock()46+47+ adjectives = cycle(adjectives)48+ nouns = cycle(nouns)49+50+ return capitalize(adjectives[0] + " " + nouns[0])51+}52+53+func shuffleWords() {54+ shuf := func(x []string) {55+ rand.Shuffle(len(x), func(i, j int) { x[i], x[j] = x[j], x[i] })56+ }57+ shuf(adjectives)58+ shuf(nouns)59+}60+61+func capitalize(s string) string {62+ words := strings.Fields(s)63+64+ for i, w := range words {65+ if i > 0 && strings.Contains(uncapitalized, " "+w+" ") {66+ words[i] = w67+ } else {68+ words[i] = strings.Title(w)69+ }70+ }71+72+ return strings.Join(words, " ")73+}74+75+func cycle(stack []string) []string {76+ return append(stack[1:], stack[0])77+}added:examples/colorprofile/main.go+53 added
1+package main2+3+import (4+ "image/color"5+ "log"6+7+ tea "charm.land/bubbletea/v2"8+ "github.com/charmbracelet/colorprofile"9+ "github.com/charmbracelet/x/ansi"10+ "github.com/lucasb-eyer/go-colorful"11+)12+13+var myFancyColor color.Color14+15+type model struct{}16+17+var _ tea.Model = model{}18+19+// Init implements tea.Model.20+func (m model) Init() tea.Cmd {21+ return tea.Batch(22+ tea.RequestCapability("RGB"),23+ tea.RequestCapability("Tc"),24+ )25+}26+27+// Update implements tea.Model.28+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {29+ switch msg := msg.(type) {30+ case tea.KeyMsg:31+ return m, tea.Quit32+ case tea.ColorProfileMsg:33+ return m, tea.Println("Color profile manually set to ", msg)34+ }35+ return m, nil36+}37+38+// View implements tea.Model.39+func (m model) View() tea.View {40+ return tea.NewView("This will produce the wrong colors on Apple Terminal :)\n\n" +41+ ansi.Style{}.ForegroundColor(myFancyColor).Styled("Howdy!") +42+ "\n\n" +43+ "Press any key to exit.")44+}45+46+func main() {47+ myFancyColor, _ = colorful.Hex("#6b50ff")48+49+ p := tea.NewProgram(model{}, tea.WithColorProfile(colorprofile.TrueColor))50+ if _, err := p.Run(); err != nil {51+ log.Fatal(err)52+ }53+}modified:examples/composable-views/main.go+14 added-13 removed
1 unmodified line2 3 import (4 "fmt"5 "log"6+ "strings"7 "time"8 8- "github.com/charmbracelet/bubbles/spinner"9- "github.com/charmbracelet/bubbles/timer"10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"9+ "charm.land/bubbles/v2/spinner"10+ "charm.land/bubbles/v2/timer"11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13 )14 15 /*16 This example assumes an existing understanding of commands and messages. If you16-haven't already read our tutorials on the basics of Bubble Tea and working17-with commands, we recommend reading those first.17+haven't already read our tutorials on the basics of Bubble Tea and working with18+commands, we recommend reading those first.19 20 Find them at:21 https://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands22 https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics58 unmodified lines81 func (m mainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {82 var cmd tea.Cmd83 var cmds []tea.Cmd84 switch msg := msg.(type) {84- case tea.KeyMsg:85+ case tea.KeyPressMsg:86 switch msg.String() {87 case "ctrl+c", "q":88 return m, tea.Quit89 case "tab":30 unmodified lines120 }121 return m, tea.Batch(cmds...)122 }123 123-func (m mainModel) View() string {124- var s string124+func (m mainModel) View() tea.View {125+ var s strings.Builder126 model := m.currentFocusedModel()127 if m.state == timerView {127- s += lipgloss.JoinHorizontal(lipgloss.Top, focusedModelStyle.Render(fmt.Sprintf("%4s", m.timer.View())), modelStyle.Render(m.spinner.View()))128+ s.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, focusedModelStyle.Render(fmt.Sprintf("%4s", m.timer.View())), modelStyle.Render(m.spinner.View())))129 } else {129- s += lipgloss.JoinHorizontal(lipgloss.Top, modelStyle.Render(fmt.Sprintf("%4s", m.timer.View())), focusedModelStyle.Render(m.spinner.View()))130+ s.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, modelStyle.Render(fmt.Sprintf("%4s", m.timer.View())), focusedModelStyle.Render(m.spinner.View())))131 }131- s += helpStyle.Render(fmt.Sprintf("\ntab: focus next • n: new %s • q: exit\n", model))132- return s132+ s.WriteString(helpStyle.Render(fmt.Sprintf("\ntab: focus next • n: new %s • q: exit\n", model)))133+ return tea.NewView(s.String())134 }135 136 func (m mainModel) currentFocusedModel() string {137 if m.state == timerView {26 unmodified linesdeleted:examples/credit-card-form/credit-card-form.gifbinary
A binary file, deleted.
deleted:examples/credit-card-form/main.go-202 removed
1-package main2-3-import (4- "fmt"5- "log"6- "strconv"7- "strings"8-9- "github.com/charmbracelet/bubbles/textinput"10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"12-)13-14-func main() {15- p := tea.NewProgram(initialModel())16-17- if _, err := p.Run(); err != nil {18- log.Fatal(err)19- }20-}21-22-type (23- errMsg error24-)25-26-const (27- ccn = iota28- exp29- cvv30-)31-32-const (33- hotPink = lipgloss.Color("#FF06B7")34- darkGray = lipgloss.Color("#767676")35-)36-37-var (38- inputStyle = lipgloss.NewStyle().Foreground(hotPink)39- continueStyle = lipgloss.NewStyle().Foreground(darkGray)40-)41-42-type model struct {43- inputs []textinput.Model44- focused int45- err error46-}47-48-// Validator functions to ensure valid input49-func ccnValidator(s string) error {50- // Credit Card Number should a string less than 20 digits51- // It should include 16 integers and 3 spaces52- if len(s) > 16+3 {53- return fmt.Errorf("CCN is too long")54- }55-56- if len(s) == 0 || len(s)%5 != 0 && (s[len(s)-1] < '0' || s[len(s)-1] > '9') {57- return fmt.Errorf("CCN is invalid")58- }59-60- // The last digit should be a number unless it is a multiple of 4 in which61- // case it should be a space62- if len(s)%5 == 0 && s[len(s)-1] != ' ' {63- return fmt.Errorf("CCN must separate groups with spaces")64- }65-66- // The remaining digits should be integers67- c := strings.ReplaceAll(s, " ", "")68- _, err := strconv.ParseInt(c, 10, 64)69-70- return err71-}72-73-func expValidator(s string) error {74- // The 3 character should be a slash (/)75- // The rest should be numbers76- e := strings.ReplaceAll(s, "/", "")77- _, err := strconv.ParseInt(e, 10, 64)78- if err != nil {79- return fmt.Errorf("EXP is invalid")80- }81-82- // There should be only one slash and it should be in the 2nd index (3rd character)83- if len(s) >= 3 && (strings.Index(s, "/") != 2 || strings.LastIndex(s, "/") != 2) {84- return fmt.Errorf("EXP is invalid")85- }86-87- return nil88-}89-90-func cvvValidator(s string) error {91- // The CVV should be a number of 3 digits92- // Since the input will already ensure that the CVV is a string of length 3,93- // All we need to do is check that it is a number94- _, err := strconv.ParseInt(s, 10, 64)95- return err96-}97-98-func initialModel() model {99- var inputs []textinput.Model = make([]textinput.Model, 3)100- inputs[ccn] = textinput.New()101- inputs[ccn].Placeholder = "4505 **** **** 1234"102- inputs[ccn].Focus()103- inputs[ccn].CharLimit = 20104- inputs[ccn].Width = 30105- inputs[ccn].Prompt = ""106- inputs[ccn].Validate = ccnValidator107-108- inputs[exp] = textinput.New()109- inputs[exp].Placeholder = "MM/YY "110- inputs[exp].CharLimit = 5111- inputs[exp].Width = 5112- inputs[exp].Prompt = ""113- inputs[exp].Validate = expValidator114-115- inputs[cvv] = textinput.New()116- inputs[cvv].Placeholder = "XXX"117- inputs[cvv].CharLimit = 3118- inputs[cvv].Width = 5119- inputs[cvv].Prompt = ""120- inputs[cvv].Validate = cvvValidator121-122- return model{123- inputs: inputs,124- focused: 0,125- err: nil,126- }127-}128-129-func (m model) Init() tea.Cmd {130- return textinput.Blink131-}132-133-func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {134- var cmds []tea.Cmd = make([]tea.Cmd, len(m.inputs))135-136- switch msg := msg.(type) {137- case tea.KeyMsg:138- switch msg.Type {139- case tea.KeyEnter:140- if m.focused == len(m.inputs)-1 {141- return m, tea.Quit142- }143- m.nextInput()144- case tea.KeyCtrlC, tea.KeyEsc:145- return m, tea.Quit146- case tea.KeyShiftTab, tea.KeyCtrlP:147- m.prevInput()148- case tea.KeyTab, tea.KeyCtrlN:149- m.nextInput()150- }151- for i := range m.inputs {152- m.inputs[i].Blur()153- }154- m.inputs[m.focused].Focus()155-156- // We handle errors just like any other message157- case errMsg:158- m.err = msg159- return m, nil160- }161-162- for i := range m.inputs {163- m.inputs[i], cmds[i] = m.inputs[i].Update(msg)164- }165- return m, tea.Batch(cmds...)166-}167-168-func (m model) View() string {169- return fmt.Sprintf(170- ` Total: $21.50:171-172- %s173- %s174-175- %s %s176- %s %s177-178- %s179-`,180- inputStyle.Width(30).Render("Card Number"),181- m.inputs[ccn].View(),182- inputStyle.Width(6).Render("EXP"),183- inputStyle.Width(6).Render("CVV"),184- m.inputs[exp].View(),185- m.inputs[cvv].View(),186- continueStyle.Render("Continue ->"),187- ) + "\n"188-}189-190-// nextInput focuses the next input field191-func (m *model) nextInput() {192- m.focused = (m.focused + 1) % len(m.inputs)193-}194-195-// prevInput focuses the previous input field196-func (m *model) prevInput() {197- m.focused--198- // Wrap around199- if m.focused < 0 {200- m.focused = len(m.inputs) - 1201- }202-}deleted:examples/credit-card-form/README.md-3 removed
1-# Credit Card Form2-3-<img width="800" src="./credit-card-form.gif" />added:examples/cursor-style/main.go+79 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "charm.land/bubbletea/v2"8+)9+10+type model struct {11+ cursor tea.Cursor12+ blink bool13+}14+15+func (m model) Init() tea.Cmd {16+ return nil17+}18+19+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {20+ switch msg := msg.(type) {21+ case tea.KeyPressMsg:22+ switch msg.String() {23+ case "ctrl+c", "q":24+ return m, tea.Quit25+ case "h", "left":26+ m.cursor.Shape--27+ if m.cursor.Shape < tea.CursorBlock {28+ m.cursor.Shape = tea.CursorBar29+ }30+ case "l", "right":31+ m.cursor.Shape++32+ if m.cursor.Shape > tea.CursorBar {33+ m.cursor.Shape = tea.CursorBlock34+ }35+ }36+ }37+ m.blink = !m.blink38+ return m, nil39+}40+41+func (m model) View() tea.View {42+ v := tea.NewView("Press left/right to change the cursor style, q or ctrl+c to quit." +43+ "\n\n" +44+ " <- This is the cursor (a " + m.describeCursor() + ")")45+ c := tea.NewCursor(0, 2)46+ c.Shape = m.cursor.Shape47+ c.Blink = m.blink48+ v.Cursor = c49+ return v50+}51+52+func (m model) describeCursor() string {53+ var adj, noun string54+55+ if m.blink {56+ adj = "blinking"57+ } else {58+ adj = "steady"59+ }60+61+ switch m.cursor.Shape {62+ case tea.CursorBlock:63+ noun = "block"64+ case tea.CursorUnderline:65+ noun = "underline"66+ case tea.CursorBar:67+ noun = "bar"68+ }69+70+ return fmt.Sprintf("%s %s", adj, noun)71+}72+73+func main() {74+ p := tea.NewProgram(model{blink: true})75+ if _, err := p.Run(); err != nil {76+ fmt.Fprintf(os.Stderr, "Error: %v", err)77+ os.Exit(1)78+ }79+}modified:examples/debounce/main.go+5 added-5 removed
13 unmodified lines14 "fmt"15 "os"16 "time"17 18- tea "github.com/charmbracelet/bubbletea"18+ tea "charm.land/bubbletea/v2"19 )20 21 const debounceDuration = time.Second22 8 unmodified lines31 }32 33 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {34 switch msg := msg.(type) {35- case tea.KeyMsg:35+ case tea.KeyPressMsg:36 // Increment the tag on the model...37 m.tag++38 return m, tea.Tick(debounceDuration, func(_ time.Time) tea.Msg {39 // ...and include a copy of that tag value in the message.12 unmodified lines52 53 return m, nil54 }55 56-func (m model) View() string {57- return fmt.Sprintf("Key presses: %d", m.tag) +58- "\nTo exit press any key, then wait for one second without pressing anything."56+func (m model) View() tea.View {57+ return tea.NewView(fmt.Sprintf("Key presses: %d", m.tag) +58+ "\nTo exit press any key, then wait for one second without pressing anything.")59 }60 61 func main() {62 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesadded:examples/doom-fire/main.go+133 added
1+package main2+3+import (4+ "fmt"5+ "math/rand"6+ "strings"7+ "time"8+9+ tea "charm.land/bubbletea/v2"10+ "charm.land/lipgloss/v2"11+)12+13+// This Doom Fire implementation was ported from @const-void's Node version.14+// See https://github.com/const-void/DOOM-fire-node15+16+var whiteFg = lipgloss.NewStyle().Foreground(lipgloss.White)17+18+type model struct {19+ screenBuf []int20+ width int21+ height int22+ firePalette []int23+ startTime time.Time24+}25+26+func (m model) Init() tea.Cmd {27+ return tick28+}29+30+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {31+ switch msg := msg.(type) {32+ case tea.KeyPressMsg:33+ if msg.String() == "q" || msg.String() == "ctrl+c" {34+ return m, tea.Quit35+ }36+ case tickMsg:37+ m.spreadFire()38+ return m, tick39+ case tea.WindowSizeMsg:40+ m.width = msg.Width41+ m.height = msg.Height * 2 // Double height for half-block characters42+ m.screenBuf = make([]int, m.width*m.height)43+ // Initialize the bottom row with white (maximum intensity)44+ for i := range m.width {45+ m.screenBuf[(m.height-1)*m.width+i] = len(m.firePalette) - 146+ }47+ }48+ return m, nil49+}50+51+func (m model) View() tea.View {52+ if m.width == 0 {53+ return tea.NewView("Initializing...")54+ }55+56+ var s strings.Builder57+58+ for y := 0; y < m.height-2; y += 2 {59+ for x := range m.width {60+ pixelHi := m.screenBuf[y*m.width+x]61+ pixelLo := m.screenBuf[(y+1)*m.width+x]62+63+ hiColor := m.firePalette[pixelHi]64+ loColor := m.firePalette[pixelLo]65+66+ s.WriteString(lipgloss.NewStyle().67+ Foreground(lipgloss.ANSIColor(hiColor)).68+ Background(lipgloss.ANSIColor(loColor)).69+ Render("▀"))70+ }71+ if y < m.height-2 {72+ s.WriteByte('\n')73+ }74+ }75+76+ elapsed := time.Since(m.startTime)77+ s.WriteString(whiteFg.Render("Press q or ctrl+c to quit. " + fmt.Sprintf("Elapsed: %s", elapsed.Round(time.Second))))78+ v := tea.NewView(s.String())79+ v.AltScreen = true80+ return v81+}82+83+func (m *model) spreadFire() {84+ for x := range m.width {85+ for y := range m.height {86+ m.spreadPixel(y*m.width + x)87+ }88+ }89+}90+91+func (m *model) spreadPixel(idx int) {92+ if idx < m.width {93+ return94+ }95+96+ pixel := m.screenBuf[idx]97+ if pixel == 0 {98+ m.screenBuf[idx-m.width] = 099+ return100+ }101+102+ rnd := rand.Intn(3)103+ dst := idx - rnd + 1104+ if dst-m.width >= 0 && dst-m.width < len(m.screenBuf) {105+ decay := rnd & 1106+ newValue := max(pixel-decay, 0)107+ m.screenBuf[dst-m.width] = newValue108+ }109+}110+111+type tickMsg time.Time112+113+func tick() tea.Msg {114+ time.Sleep(time.Millisecond * 50)115+ return tickMsg(time.Now())116+}117+118+func initialModel() model {119+ // Same color palette as the original120+ palette := []int{0, 233, 234, 52, 53, 88, 89, 94, 95, 96, 130, 131, 132, 133, 172, 214, 215, 220, 220, 221, 3, 226, 227, 230, 231, 7}121+122+ return model{123+ firePalette: palette,124+ startTime: time.Now(),125+ }126+}127+128+func main() {129+ p := tea.NewProgram(initialModel())130+ if _, err := p.Run(); err != nil {131+ fmt.Printf("Error running program: %v", err)132+ }133+}modified:examples/exec/main.go+12 added-14 removed
1 package main2 3 import (4+ "cmp"5 "fmt"6 "os"7 "os/exec"8 8- tea "github.com/charmbracelet/bubbletea"9+ tea "charm.land/bubbletea/v2"10 )11 12 type editorFinishedMsg struct{ err error }13 14 func openEditor() tea.Cmd {14- editor := os.Getenv("EDITOR")15- if editor == "" {16- editor = "vim"17- }15+ editor := cmp.Or(os.Getenv("EDITOR"), "vim")16 c := exec.Command(editor) //nolint:gosec17 return tea.ExecProcess(c, func(err error) tea.Msg {18 return editorFinishedMsg{err}19 })9 unmodified lines29 }30 31 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {32 switch msg := msg.(type) {35- case tea.KeyMsg:33+ case tea.KeyPressMsg:34 switch msg.String() {35 case "a":36 m.altscreenActive = !m.altscreenActive39- cmd := tea.EnterAltScreen40- if !m.altscreenActive {41- cmd = tea.ExitAltScreen42- }43- return m, cmd37+ return m, nil38 case "e":39 return m, openEditor()40 case "ctrl+c", "q":41 return m, tea.Quit6 unmodified lines48 }49 return m, nil50 }51 58-func (m model) View() string {52+func (m model) View() tea.View {53 if m.err != nil {60- return "Error: " + m.err.Error() + "\n"54+ v := tea.NewView("Error: " + m.err.Error() + "\n")55+ v.AltScreen = m.altscreenActive56+ return v57 }62- return "Press 'e' to open your EDITOR.\nPress 'a' to toggle the altscreen\nPress 'q' to quit.\n"58+ v := tea.NewView("Press 'e' to open your EDITOR.\nPress 'a' to toggle the altscreen\nPress 'q' to quit.\n")59+ v.AltScreen = m.altscreenActive60+ return v61 }62 63 func main() {64 m := model{}5 unmodified linesmodified:examples/eyes/main.go+13 added-10 removed
6 unmodified lines7 "math/rand"8 "strings"9 "time"10 11- tea "github.com/charmbracelet/bubbletea"12- "github.com/charmbracelet/lipgloss"11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13 )14 15 const (16 // Eye dimensions (corresponding to original EYE_WIDTH and EYE_HEIGHT)26 unmodified lines43 44 type tickMsg time.Time45 46 func main() {47- p := tea.NewProgram(initialModel(), tea.WithAltScreen())47+ p := tea.NewProgram(initialModel())48 if _, err := p.Run(); err != nil {49 fmt.Printf("Error running program: %v\n", err)50 }51 }20 unmodified lines72 m.eyePositions[1] = startX + eyeSpacing73 }74 75 func (m model) Init() tea.Cmd {76- return tea.Batch(77- tickCmd(),78- tea.EnterAltScreen,79- )76+ return tickCmd()77 }78 79 func tickCmd() tea.Cmd {80 return tea.Tick(50*time.Millisecond, func(t time.Time) tea.Msg {3 unmodified lines84 85 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {86 switch msg := msg.(type) {87 case tea.KeyMsg:91- if msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyEsc {88+ switch msg.String() {89+ case "ctrl+c", "esc":90 return m, tea.Quit91 }92 93 case tea.WindowSizeMsg:27 unmodified lines121 122 return m, tickCmd()123 }124 127-func (m model) View() string {125+func (m model) View() tea.View {126+ var v tea.View127+ v.AltScreen = true // Use alternate screen buffer128+129 // Create empty canvas130 canvas := make([][]string, m.height)131 for y := range canvas {132 canvas[y] = make([]string, m.width)37 unmodified lines170 // Style output171 style := lipgloss.NewStyle().172 Foreground(lipgloss.Color("#F0F0F0"))173 173- return style.Render(s.String())174+ v.SetContent(style.Render(s.String()))175+176+ return v177 }178 179 func drawEllipse(canvas [][]string, x0, y0, rx, ry int) {180 // Improved ellipse drawing algorithm with better angles17 unmodified linesmodified:examples/file-picker/main.go+10 added-10 removed
5 unmodified lines6 "os"7 "strings"8 "time"9 10- "github.com/charmbracelet/bubbles/filepicker"11- tea "github.com/charmbracelet/bubbletea"10+ "charm.land/bubbles/v2/filepicker"11+ tea "charm.land/bubbletea/v2"12 )13 14 type model struct {15 filepicker filepicker.Model15 unmodified lines31 }32 33 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {34 switch msg := msg.(type) {35- case tea.KeyMsg:35+ case tea.KeyPressMsg:36 switch msg.String() {37 case "ctrl+c", "q":38 m.quitting = true39 return m, tea.Quit22 unmodified lines62 63 return m, cmd64 }65 66-func (m model) View() string {66+func (m model) View() tea.View {67 if m.quitting {68- return ""68+ return tea.NewView("")69 }70 var s strings.Builder71 s.WriteString("\n ")72 if m.err != nil {3 unmodified lines76 } else {77 s.WriteString("Selected file: " + m.filepicker.Styles.Selected.Render(m.selectedFile))78 }79 s.WriteString("\n\n" + m.filepicker.View() + "\n")80- return s.String()80+ v := tea.NewView(s.String())81+ v.AltScreen = true82+ return v83 }84 85 func main() {86 fp := filepicker.New()87 fp.AllowedTypes = []string{".mod", ".sum", ".go", ".txt", ".md"}88 fp.CurrentDirectory, _ = os.UserHomeDir()89 88- m := model{89- filepicker: fp,90- }91- tm, _ := tea.NewProgram(&m).Run()90+ m := model{filepicker: fp}91+ tm, _ := tea.NewProgram(m).Run()92 mm := tm.(model)93 fmt.Println("\n You selected: " + m.filepicker.Styles.Selected.Render(mm.selectedFile) + "\n")94 }modified:examples/focus-blur/main.go+7 added-6 removed
3 unmodified lines4 5 import (6 "log"7 8- tea "github.com/charmbracelet/bubbletea"8+ tea "charm.land/bubbletea/v2"9 )10 11 func main() {12 p := tea.NewProgram(model{13- // assume we start focused...13 focused: true,14 reporting: true,16- }, tea.WithReportFocus())15+ })16 if _, err := p.Run(); err != nil {17 log.Fatal(err)18 }19 }12 unmodified lines32 case tea.FocusMsg:33 m.focused = true34 case tea.BlurMsg:35 m.focused = false37- case tea.KeyMsg:36+ case tea.KeyPressMsg:37 switch msg.String() {38 case "t":39 m.reporting = !m.reporting40 case "ctrl+c", "q":3 unmodified lines44 45 return m, nil46 }47 49-func (m model) View() string {48+func (m model) View() tea.View {49 s := "Hi. Focus report is currently "50 if m.reporting {51 s += "enabled"52 } else {7 unmodified lines60 } else {61 s += "This program is currently blurred!"62 }63 }65- return s + "\n\nTo quit sooner press ctrl-c, or t to toggle focus reporting...\n"64+ v := tea.NewView(s + "\n\nTo quit sooner press ctrl-c, or t to toggle focus reporting...\n")65+ v.ReportFocus = m.reporting66+ return v67 }modified:examples/fullscreen/main.go+7 added-5 removed
6 unmodified lines7 "fmt"8 "log"9 "time"10 11- tea "github.com/charmbracelet/bubbletea"11+ tea "charm.land/bubbletea/v2"12 )13 14 type model int15 16 type tickMsg time.Time17 18 func main() {19- p := tea.NewProgram(model(5), tea.WithAltScreen())19+ p := tea.NewProgram(model(5))20 if _, err := p.Run(); err != nil {21 log.Fatal(err)22 }23 }3 unmodified lines27 }28 29 func (m model) Update(message tea.Msg) (tea.Model, tea.Cmd) {30 switch msg := message.(type) {31- case tea.KeyMsg:31+ case tea.KeyPressMsg:32 switch msg.String() {33 case "q", "esc", "ctrl+c":34 return m, tea.Quit35 }8 unmodified lines44 45 return m, nil46 }47 48-func (m model) View() string {49- return fmt.Sprintf("\n\n Hi. This program will exit in %d seconds...", m)48+func (m model) View() tea.View {49+ v := tea.NewView(fmt.Sprintf("\n\n Hi. This program will exit in %d seconds...", m))50+ v.AltScreen = true51+ return v52 }53 54 func tick() tea.Cmd {55 return tea.Tick(time.Second, func(t time.Time) tea.Msg {3 unmodified linesmodified:examples/glamour/main.go+25 added-15 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/viewport"8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/glamour"10- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/viewport"8+ tea "charm.land/bubbletea/v2"9+ "github.com/charmbracelet/glamour/v2"10+ "github.com/charmbracelet/glamour/v2/styles"11+ "charm.land/lipgloss/v2"12 )13 14 const content = `15 # Today’s Menu22 unmodified lines38 | Dorayaki | $4 | Looks good on rabbits |39 | Banana Split | $5 | A classic |40 | Cream Puff | $3 | Pretty creamy! |41 41-All our dishes are made in-house by Karen, our chef. Most of our ingredients42-are from our garden or the fish market down the street.42+All our dishes are made in-house by Karen, our chef. Most of our ingredients are from our garden or the fish market down the street.43 44 Some famous people that have eaten here lately:45 46 * [x] René Redzepi8 unmodified lines55 type example struct {56 viewport viewport.Model57 }58 59-func newExample() (*example, error) {60- const width = 7859+func newExample(isDark bool) (*example, error) {60+ const (61+ width = 7862+ height = 2063+ )64 62- vp := viewport.New(width, 20)65+ vp := viewport.New()66+ vp.SetWidth(width)67+ vp.SetHeight(height)68 vp.Style = lipgloss.NewStyle().69 BorderStyle(lipgloss.RoundedBorder()).70 BorderForeground(lipgloss.Color("62")).71 PaddingRight(2)5 unmodified lines77 // * The viewport padding78 // * The viewport margins79 // * The gutter glamour applies to the left side of the content80 //76- const glamourGutter = 281+ const glamourGutter = 382 glamourRenderWidth := width - vp.Style.GetHorizontalFrameSize() - glamourGutter83 84+ style := styles.DarkStyleConfig85+ if !isDark {86+ style = styles.LightStyleConfig87+ }88 renderer, err := glamour.NewTermRenderer(80- glamour.WithAutoStyle(),89+ glamour.WithStyles(style),90 glamour.WithWordWrap(glamourRenderWidth),91 )92 if err != nil {93 return nil, err16 unmodified lines110 }111 112 func (e example) Update(msg tea.Msg) (tea.Model, tea.Cmd) {113 switch msg := msg.(type) {105- case tea.KeyMsg:114+ case tea.KeyPressMsg:115 switch msg.String() {116 case "q", "ctrl+c", "esc":117 return e, tea.Quit118 default:5 unmodified lines124 return e, nil125 }126 }127 119-func (e example) View() string {120- return e.viewport.View() + e.helpView()128+func (e example) View() tea.View {129+ return tea.NewView(e.viewport.View() + e.helpView())130 }131 132 func (e example) helpView() string {133 return helpStyle("\n ↑/↓: Navigate • q: Quit\n")134 }135 136 func main() {137+ hasDarkBg := lipgloss.HasDarkBackground(os.Stdin, os.Stdout)128- model, err := newExample()138+ model, err := newExample(hasDarkBg)139 if err != nil {140 fmt.Println("Could not initialize Bubble Tea model:", err)141 os.Exit(1)142 }6 unmodified linesmodified:examples/help/main.go+8 added-8 removed
3 unmodified lines4 "fmt"5 "os"6 "strings"7 8- "github.com/charmbracelet/bubbles/help"9- "github.com/charmbracelet/bubbles/key"10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"8+ "charm.land/bubbles/v2/help"9+ "charm.land/bubbles/v2/key"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12 )13 14 // keyMap defines a set of keybindings. To work for help it must satisfy15 // key.Map. It could also very easily be a map[string]key.Binding.74 unmodified lines90 // If we set a width on the help menu it can gracefully truncate91 // its view as needed.92 m.help.Width = msg.Width93 94- case tea.KeyMsg:94+ case tea.KeyPressMsg:95 switch {96 case key.Matches(msg, m.keys.Up):97 m.lastKey = "↑"98 case key.Matches(msg, m.keys.Down):12 unmodified lines111 112 return m, nil113 }114 115-func (m model) View() string {115+func (m model) View() tea.View {116 if m.quitting {117- return "Bye!\n"117+ return tea.NewView("Bye!\n")118 }119 120 var status string121 if m.lastKey == "" {4 unmodified lines126 127 helpView := m.help.View(m.keys)128 height := 8 - strings.Count(status, "\n") - strings.Count(helpView, "\n")129 130- return "\n" + status + strings.Repeat("\n", height) + helpView130+ return tea.NewView(status + strings.Repeat("\n", height) + helpView)131 }132 133 func main() {134 if os.Getenv("HELP_DEBUG") != "" {13 unmodified linesmodified:examples/http/main.go+4 added-4 removed
6 unmodified lines7 "log"8 "net/http"9 "time"10 11- tea "github.com/charmbracelet/bubbletea"11+ tea "charm.land/bubbletea/v2"12 )13 14 const url = "https://charm.sh/"15 20 unmodified lines36 }37 38 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {39 switch msg := msg.(type) {40- case tea.KeyMsg:40+ case tea.KeyPressMsg:41 switch msg.String() {42 case "q", "ctrl+c", "esc":43 return m, tea.Quit44 default:12 unmodified lines57 return m, nil58 }59 }60 61-func (m model) View() string {61+func (m model) View() tea.View {62 s := fmt.Sprintf("Checking %s...", url)63 if m.err != nil {64 s += fmt.Sprintf("something went wrong: %s", m.err)65 } else if m.status != 0 {66 s += fmt.Sprintf("%d %s", m.status, http.StatusText(m.status))67 }68- return s + "\n"68+ return tea.NewView(s + "\n")69 }70 71 func checkServer() tea.Msg {72 c := &http.Client{10 unmodified linesadded:examples/isbn-form/isbn-form.gifbinary
A binary file, added.
added:examples/isbn-form/isbn-form.tape+16 added
1+Type "go run ./isbn-form"2+Enter3+Sleep 2s4+Type "9783548372570"5+Sleep 500ms6+Sleep 1s7+Down8+Sleep 500ms9+Type "my book title"10+Sleep 500ms11+Backspace 1012+Type "title"13+Sleep 500ms14+Enter15+Sleep 3s16+Output isbn-form.gifadded:examples/isbn-form/main.go+245 added
1+package main2+3+import (4+ "fmt"5+ "log"6+ "strings"7+ "unicode"8+9+ "charm.land/bubbles/v2/textinput"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12+ "github.com/charmbracelet/x/exp/charmtone"13+)14+15+func main() {16+ p := tea.NewProgram(initialModel())17+18+ if _, err := p.Run(); err != nil {19+ log.Fatal(err)20+ }21+}22+23+type (24+ errMsg error25+)26+27+var (28+ inputStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Tang.Hex()))29+ continueStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Anchovy.Hex()))30+ validStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Guac.Hex()))31+ errStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Cherry.Hex()))32+)33+34+type model struct {35+ isbnInput textinput.Model36+ titleInput textinput.Model37+ focusedInput int38+ err error39+}40+41+// canFindBook returns whether the find button is to be pressed42+func (m model) canFindBook() bool {43+ correctIsbnGiven := m.isbnInput.Err == nil && len(m.isbnInput.Value()) != 044+ correctTitleGiven := m.titleInput.Err == nil && len(m.titleInput.Value()) != 045+46+ return correctIsbnGiven && correctTitleGiven47+}48+49+// Validator function to ensure valid input50+func isbn13Validator(s string) error {51+ // A valid ISBN looks like this:52+ // 978-3-548-37257-0 or53+ // 9783548372570 without any spaces54+55+ // Remove dashes56+ s = strings.ReplaceAll(s, "-", "")57+ if len(s) != 13 {58+ return fmt.Errorf("ISBN is of wrong length")59+ }60+61+ for _, c := range s {62+ if !unicode.IsDigit(c) {63+ return fmt.Errorf("ISBN contains invalid characters")64+ }65+ }66+67+ gs1Prefix := s[:3]68+ switch gs1Prefix {69+ case "978", "979":70+ break71+ default:72+ return fmt.Errorf("ISBN has invalid GS1 prefix")73+ }74+75+ // The last digit, the check digit,76+ // must make the checksum a multiple of 10.77+ // All digits are added up after being multiplied78+ // by either 1 or 3 alternately.79+ // So 9x1 + 7x3 + 8x1 + ... + 0 must be a multiple of 10.80+81+ sum := 082+ for i, c := range s {83+ // Convert rune to int84+ n := int(c - '0')85+86+ // Multiply the uneven indices by 387+ if i%2 != 0 {88+ n *= 389+ }90+91+ sum += n92+ }93+94+ if sum%10 != 0 {95+ return fmt.Errorf("ISBN has invalid check digit")96+ }97+98+ return nil99+}100+101+var bannedTitleWords = []string{102+ "very",103+ "bad",104+ "words",105+ "that",106+ "should",107+ "not",108+ "appear",109+ "in",110+ "book",111+ "titles",112+}113+114+func bookTitleValidator(s string) error {115+ s = strings.TrimSpace(s)116+117+ if len(s) == 0 {118+ return fmt.Errorf("Book title is empty")119+ }120+121+ for _, bannedWord := range bannedTitleWords {122+ if strings.Contains(s, bannedWord) {123+ return fmt.Errorf("Book title contains banned word %q", bannedWord)124+ }125+ }126+127+ return nil128+}129+130+func initialModel() model {131+ isbnInput := textinput.New()132+ isbnInput.Focus()133+ isbnInput.Placeholder = "978-X-XXX-XXXXX-X"134+ isbnInput.CharLimit = 17135+ isbnInput.SetWidth(30)136+ isbnInput.Prompt = ""137+ isbnInput.Validate = isbn13Validator138+139+ titleInput := textinput.New()140+ titleInput.Blur()141+ titleInput.Placeholder = "Title"142+ titleInput.CharLimit = 100143+ titleInput.SetWidth(100)144+ titleInput.Prompt = ""145+ titleInput.Validate = bookTitleValidator146+147+ return model{148+ isbnInput: isbnInput,149+ titleInput: titleInput,150+ focusedInput: 0,151+ err: nil,152+ }153+}154+155+func (m model) Init() tea.Cmd {156+ return textinput.Blink157+}158+159+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {160+ switch msg := msg.(type) {161+ case tea.KeyPressMsg:162+ switch msg.String() {163+ case "up", "down":164+ // Switch between text inputs165+ switch m.focusedInput {166+ case 0:167+ m.focusedInput = 1168+ m.titleInput.Focus()169+ m.isbnInput.Blur()170+ case 1:171+ m.focusedInput = 0172+ m.isbnInput.Focus()173+ m.titleInput.Blur()174+ }175+ case "enter":176+ // Enter is blocked until all inputs are ok177+ if m.canFindBook() {178+ return m, tea.Quit179+ }180+ case "ctrl+c", "esc":181+ return m, tea.Quit182+ }183+184+ // We handle errors just like any other message185+ case errMsg:186+ m.err = msg187+ return m, nil188+ }189+190+ var isbnCommand tea.Cmd191+ m.isbnInput, isbnCommand = m.isbnInput.Update(msg)192+193+ var titleCommand tea.Cmd194+ m.titleInput, titleCommand = m.titleInput.Update(msg)195+196+ return m, tea.Batch(isbnCommand, titleCommand)197+}198+199+func (m model) View() tea.View {200+ var continueText string201+ if m.canFindBook() {202+ continueText = continueStyle.Render("Find ->")203+ }204+205+ var isbnErrorText string206+ if m.isbnInput.Value() != "" {207+ if m.isbnInput.Err != nil {208+ isbnErrorText = errStyle.Render(m.isbnInput.Err.Error())209+ } else {210+ isbnErrorText = validStyle.Render("Valid ISBN")211+ }212+ }213+214+ var titleErrorText string215+ if m.titleInput.Value() != "" {216+ if m.titleInput.Err != nil {217+ titleErrorText = errStyle.Render(m.titleInput.Err.Error())218+ } else {219+ titleErrorText = validStyle.Render("Valid title")220+ }221+ }222+223+ return tea.NewView(fmt.Sprintf(224+ ` Search book:225+ %s226+ %s227+ %s228+229+ %s230+ %s231+ %s232+233+ %s234+`,235+ inputStyle.Width(30).Render("ISBN"),236+ m.isbnInput.View(),237+ isbnErrorText,238+239+ inputStyle.Width(30).Render("Title"),240+ m.titleInput.View(),241+ titleErrorText,242+243+ continueText,244+ ) + "\n")245+}added:examples/keyboard-enhancements/main.go+109 added
1+package main2+3+// This is a simple example illustrating how to enable enhanced keyboard4+// support.5+6+import (7+ "fmt"8+ "os"9+ "strings"10+11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13+)14+15+type styles struct {16+ ui lipgloss.Style17+}18+19+type model struct {20+ supportsDisambiguation bool21+ supportsEventTypes bool22+ styles styles23+}24+25+func (m model) Init() tea.Cmd {26+ return tea.RequestBackgroundColor27+}28+29+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {30+ switch msg := msg.(type) {31+ // Bubble Tea will send a [tea.KeyboardEnhancementsMsg] on startup if the32+ // terminal supports keyboard enhancements features.33+ //34+ // These features extend the capabilities of keyboard input beyond the basic legacy35+ // support found in most terminals. This includes features like:36+ // - Key disambiguation: Improved ability to distinguish between certain key presses37+ // like "enter" and "shift+enter" or "tab" and "ctrl+i".38+ // - Key event types: The ability to report different types of key events such as39+ // key presses and key releases.40+ //41+ // This allows for more nuanced input handling in terminal applications.42+ // You can ask Bubble Tea to request additional keyboard enhancements43+ // features by setting fields on the [tea.View.KeyboardEnhancements] struct44+ // in your [tea.View] method.45+ case tea.KeyboardEnhancementsMsg:46+ // Check which features were able to be enabled.47+ m.supportsDisambiguation = true // This is always enabled when this msg is received.48+ m.supportsEventTypes = msg.SupportsEventTypes()49+50+ case tea.KeyPressMsg:51+ switch msg.String() {52+ case "ctrl+c":53+ return m, tea.Quit54+ default:55+ return m, tea.Println(" press: " + msg.String())56+ }57+58+ case tea.KeyReleaseMsg:59+ return m, tea.Printf("release: %s", msg.String())60+61+ case tea.BackgroundColorMsg:62+ // Initialize styles.63+ m.updateStyles(msg.IsDark())64+ }65+ return m, nil66+}67+68+func (m model) View() tea.View {69+ var v tea.View70+ var b strings.Builder71+ fmt.Fprintf(&b, "Terminal supports key releases: %v\n", m.supportsEventTypes)72+ fmt.Fprintf(&b, "Terminal supports key disambiguation: %v\n", m.supportsDisambiguation)73+ fmt.Fprint(&b, "This demo logs key events. Press ctrl+c to quit.")74+ v.SetContent(b.String() + "\n")75+76+ // Attempt to enable reporting key event types (key presses and key77+ // releases). By default, only key disambiguation is enabled which improves78+ // the ability to distinguish between certain key presses like "enter" and79+ // "shift+enter" or "tab" and "ctrl+i".80+ v.KeyboardEnhancements.ReportEventTypes = true81+82+ return v83+}84+85+func (m *model) updateStyles(isDark bool) {86+ // Initialize styles.87+ lightDark := lipgloss.LightDark(isDark)88+ grey := lightDark(lipgloss.Color("239"), lipgloss.Color("245"))89+ darkGray := lightDark(lipgloss.Color("245"), lipgloss.Color("239"))90+91+ m.styles.ui = lipgloss.NewStyle().92+ Foreground(grey).93+ Border(lipgloss.NormalBorder(), true, false, false, false).94+ BorderForeground(darkGray)95+}96+97+func initialModel() model {98+ m := model{}99+ m.updateStyles(true) // default to dark styles.100+ return m101+}102+103+func main() {104+ p := tea.NewProgram(initialModel())105+ if _, err := p.Run(); err != nil {106+ fmt.Fprintf(os.Stderr, "Urgh: %v\n", err)107+ os.Exit(1)108+ }109+}modified:examples/list-default/main.go+9 added-7 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/list"8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/list"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10 )11 12 var docStyle = lipgloss.NewStyle().Margin(1, 2)13 14 unmodified lines28 }29 30 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {31 switch msg := msg.(type) {32- case tea.KeyMsg:32+ case tea.KeyPressMsg:33 if msg.String() == "ctrl+c" {34 return m, tea.Quit35 }36 case tea.WindowSizeMsg:5 unmodified lines42 m.list, cmd = m.list.Update(msg)43 return m, cmd44 }45 46-func (m model) View() string {47- return docStyle.Render(m.list.View())46+func (m model) View() tea.View {47+ v := tea.NewView(docStyle.Render(m.list.View()))48+ v.AltScreen = true49+ return v50 }51 52 func main() {53 items := []list.Item{24 unmodified lines78 79 m := model{list: list.New(items, list.NewDefaultDelegate(), 0, 0)}80 m.list.Title = "My Fave Things"81 80- p := tea.NewProgram(m, tea.WithAltScreen())82+ p := tea.NewProgram(m)83 84 if _, err := p.Run(); err != nil {85 fmt.Println("Error running program:", err)86 os.Exit(1)2 unmodified linesmodified:examples/list-fancy/delegate.go+7 added-7 removed
1 package main2 3 import (4- "github.com/charmbracelet/bubbles/key"5- "github.com/charmbracelet/bubbles/list"6- tea "github.com/charmbracelet/bubbletea"4+ "charm.land/bubbles/v2/key"5+ "charm.land/bubbles/v2/list"6+ tea "charm.land/bubbletea/v2"7 )8 9-func newItemDelegate(keys *delegateKeyMap) list.DefaultDelegate {9+func newItemDelegate(keys *delegateKeyMap, styles *styles) list.DefaultDelegate {10 d := list.NewDefaultDelegate()11 12 d.UpdateFunc = func(msg tea.Msg, m *list.Model) tea.Cmd {13 var title string4 unmodified lines18 return nil19 }20 21 switch msg := msg.(type) {22- case tea.KeyMsg:22+ case tea.KeyPressMsg:23 switch {24 case key.Matches(msg, keys.choose):25- return m.NewStatusMessage(statusMessageStyle("You chose " + title))25+ return m.NewStatusMessage(styles.statusMessage.Render("You chose " + title))26 27 case key.Matches(msg, keys.remove):28 index := m.Index()29 m.RemoveItem(index)30 if len(m.Items()) == 0 {31 keys.remove.SetEnabled(false)32 }33- return m.NewStatusMessage(statusMessageStyle("Deleted " + title))33+ return m.NewStatusMessage(styles.statusMessage.Render("Deleted " + title))34 }35 }36 37 return nil52 unmodified linesmodified:examples/list-fancy/main.go+94 added-61 removed
1 package main2 3 import (4 "fmt"5- "math/rand"5 "os"7- "time"6+ "sync"7 9- "github.com/charmbracelet/bubbles/key"10- "github.com/charmbracelet/bubbles/list"11- tea "github.com/charmbracelet/bubbletea"12- "github.com/charmbracelet/lipgloss"8+ "charm.land/bubbles/v2/key"9+ "charm.land/bubbles/v2/list"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12 )13 15-var (16- appStyle = lipgloss.NewStyle().Padding(1, 2)14+type styles struct {15+ app lipgloss.Style16+ title lipgloss.Style17+ statusMessage lipgloss.Style18+}19 20+func newStyles(darkBG bool) styles {21+ lightDark := lipgloss.LightDark(darkBG)22+23+ return styles{24+ app: lipgloss.NewStyle().25+ Padding(1, 2),18- titleStyle = lipgloss.NewStyle().26+ title: lipgloss.NewStyle().27 Foreground(lipgloss.Color("#FFFDF5")).28 Background(lipgloss.Color("#25A065")).21- Padding(0, 1)29+ Padding(0, 1),30+ statusMessage: lipgloss.NewStyle().31+ Foreground(lightDark(lipgloss.Color("#04B575"), lipgloss.Color("#04B575"))),32+ }33+}34 23- statusMessageStyle = lipgloss.NewStyle().24- Foreground(lipgloss.AdaptiveColor{Light: "#04B575", Dark: "#04B575"}).25- Render26-)27-35 type item struct {36 title string37 description string38 }40 unmodified lines79 }80 }81 82 type model struct {83+ styles styles84+ darkBG bool85+ width, height int86+ once *sync.Once87 list list.Model88 itemGenerator *randomItemGenerator89 keys *listKeyMap90 delegateKeys *delegateKeyMap91 }92 82-func newModel() model {83- var (84- itemGenerator randomItemGenerator85- delegateKeys = newDelegateKeyMap()86- listKeys = newListKeyMap()93+func (m model) Init() tea.Cmd {94+ return tea.Batch(95+ tea.RequestBackgroundColor,96 )97+}98 89- // Make initial list of items90- const numItems = 2491- items := make([]list.Item, numItems)92- for i := 0; i < numItems; i++ {93- items[i] = itemGenerator.next()94- }99+func (m *model) updateListProperties() {100+ // Update list size.101+ h, v := m.styles.app.GetFrameSize()102+ m.list.SetSize(m.width-h, m.height-v)103 96- // Setup list97- delegate := newItemDelegate(delegateKeys)98- groceryList := list.New(items, delegate, 0, 0)99- groceryList.Title = "Groceries"100- groceryList.Styles.Title = titleStyle101- groceryList.AdditionalFullHelpKeys = func() []key.Binding {102- return []key.Binding{103- listKeys.toggleSpinner,104- listKeys.insertItem,105- listKeys.toggleTitleBar,106- listKeys.toggleStatusBar,107- listKeys.togglePagination,108- listKeys.toggleHelpMenu,109- }110- }111-112- return model{113- list: groceryList,114- keys: listKeys,115- delegateKeys: delegateKeys,116- itemGenerator: &itemGenerator,117- }104+ // Update the model and list styles.105+ m.styles = newStyles(m.darkBG)106+ m.list.Styles.Title = m.styles.title107 }108 120-func (m model) Init() tea.Cmd {121- return nil122-}123-109 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {110 var cmds []tea.Cmd111 112 switch msg := msg.(type) {113+ case tea.BackgroundColorMsg:114+ m.darkBG = msg.IsDark()115+ m.updateListProperties()116+ return m, nil117+118 case tea.WindowSizeMsg:129- h, v := appStyle.GetFrameSize()130- m.list.SetSize(msg.Width-h, msg.Height-v)119+ m.width, m.height = msg.Width, msg.Height120+ m.updateListProperties()121+ return m, nil122+ }123 124+ switch msg := msg.(type) {132- case tea.KeyMsg:125+ case tea.KeyPressMsg:126 // Don't match any of the keys below if we're actively filtering.127 if m.list.FilterState() == list.Filtering {128 break129 }25 unmodified lines155 case key.Matches(msg, m.keys.insertItem):156 m.delegateKeys.remove.SetEnabled(true)157 newItem := m.itemGenerator.next()158 insCmd := m.list.InsertItem(0, newItem)166- statusCmd := m.list.NewStatusMessage(statusMessageStyle("Added " + newItem.Title()))159+ statusCmd := m.list.NewStatusMessage(m.styles.statusMessage.Render("Added " + newItem.Title()))160 return m, tea.Batch(insCmd, statusCmd)161 }162 }163 4 unmodified lines168 169 return m, tea.Batch(cmds...)170 }171 179-func (m model) View() string {180- return appStyle.Render(m.list.View())172+func (m model) View() tea.View {173+ v := tea.NewView(m.styles.app.Render(m.list.View()))174+ v.AltScreen = true175+ return v176 }177 183-func main() {184- rand.Seed(time.Now().UTC().UnixNano())178+func initialModel() model {179+ // Initialize the model and list.180+ m := model{}181+ m.styles = newStyles(false) // default to dark background styles182 183+ delegateKeys := newDelegateKeyMap()184+ listKeys := newListKeyMap()185+186+ // Make initial list of items.187+ var itemGenerator randomItemGenerator188+ const numItems = 24189+ items := make([]list.Item, numItems)190+ for i := range numItems {191+ items[i] = itemGenerator.next()192+ }193+194+ // Setup list.195+ delegate := newItemDelegate(delegateKeys, &m.styles)196+ groceryList := list.New(items, delegate, 0, 0)197+ groceryList.Title = "Groceries"198+ groceryList.Styles.Title = m.styles.title199+ groceryList.AdditionalFullHelpKeys = func() []key.Binding {200+ return []key.Binding{201+ listKeys.toggleSpinner,202+ listKeys.insertItem,203+ listKeys.toggleTitleBar,204+ listKeys.toggleStatusBar,205+ listKeys.togglePagination,206+ listKeys.toggleHelpMenu,207+ }208+ }209+210+ m.list = groceryList211+ m.keys = listKeys212+ m.delegateKeys = delegateKeys213+ m.itemGenerator = &itemGenerator214+215+ return m216+}217+218+func main() {186- if _, err := tea.NewProgram(newModel(), tea.WithAltScreen()).Run(); err != nil {219+ if _, err := tea.NewProgram(initialModel()).Run(); err != nil {220 fmt.Println("Error running program:", err)221 os.Exit(1)222 }223 }modified:examples/list-simple/main.go+68 added-45 removed
4 unmodified lines5 "io"6 "os"7 "strings"8 9- "github.com/charmbracelet/bubbles/list"10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"9+ "charm.land/bubbles/v2/list"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12 )13 14 const listHeight = 1415 16-var (17- titleStyle = lipgloss.NewStyle().MarginLeft(2)18- itemStyle = lipgloss.NewStyle().PaddingLeft(4)19- selectedItemStyle = lipgloss.NewStyle().PaddingLeft(2).Foreground(lipgloss.Color("170"))20- paginationStyle = list.DefaultStyles().PaginationStyle.PaddingLeft(4)21- helpStyle = list.DefaultStyles().HelpStyle.PaddingLeft(4).PaddingBottom(1)22- quitTextStyle = lipgloss.NewStyle().Margin(1, 0, 2, 4)23-)16+type styles struct {17+ title lipgloss.Style18+ item lipgloss.Style19+ selectedItem lipgloss.Style20+ pagination lipgloss.Style21+ help lipgloss.Style22+ quitText lipgloss.Style23+}24 25+func newStyles(darkBG bool) styles {26+ var s styles27+ s.title = lipgloss.NewStyle().MarginLeft(2)28+ s.item = lipgloss.NewStyle().PaddingLeft(4)29+ s.selectedItem = lipgloss.NewStyle().PaddingLeft(2).Foreground(lipgloss.Color("170"))30+ s.pagination = list.DefaultStyles(darkBG).PaginationStyle.PaddingLeft(4)31+ s.help = list.DefaultStyles(darkBG).HelpStyle.PaddingLeft(4).PaddingBottom(1)32+ s.quitText = lipgloss.NewStyle().Margin(1, 0, 2, 4)33+ return s34+}35+36 type item string37 38 func (i item) FilterValue() string { return "" }39 29-type itemDelegate struct{}40+type itemDelegate struct {41+ styles *styles42+}43 44 func (d itemDelegate) Height() int { return 1 }45 func (d itemDelegate) Spacing() int { return 0 }46 func (d itemDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }4 unmodified lines51 }52 53 str := fmt.Sprintf("%d. %s", index+1, i)54 42- fn := itemStyle.Render55+ fn := d.styles.item.Render56 if index == m.Index() {57 fn = func(s ...string) string {45- return selectedItemStyle.Render("> " + strings.Join(s, " "))58+ return d.styles.selectedItem.Render("> " + strings.Join(s, " "))59 }60 }61 62 fmt.Fprint(w, fn(str))1 unmodified line64 65 type model struct {66 list list.Model67 choice string68+ styles styles69 quitting bool70 }71 72+func initialModel() model {73+ items := []list.Item{74+ item("Ramen"),75+ item("Tomato Soup"),76+ item("Hamburgers"),77+ item("Cheeseburgers"),78+ item("Currywurst"),79+ item("Okonomiyaki"),80+ item("Pasta"),81+ item("Fillet Mignon"),82+ item("Caviar"),83+ item("Just Wine"),84+ }85+86+ const defaultWidth = 2087+88+ l := list.New(items, itemDelegate{}, defaultWidth, listHeight)89+ l.Title = "What do you want for dinner?"90+ l.SetShowStatusBar(false)91+ l.SetFilteringEnabled(false)92+93+ m := model{list: l}94+ m.updateStyles(true) // default to dark styles.95+ return m96+}97+98+func (m *model) updateStyles(isDark bool) {99+ m.styles = newStyles(isDark)100+ m.list.Styles.Title = m.styles.title101+ m.list.Styles.PaginationStyle = m.styles.pagination102+ m.list.Styles.HelpStyle = m.styles.help103+ m.list.SetDelegate(itemDelegate{styles: &m.styles})104+}105+106 func (m model) Init() tea.Cmd {107 return nil108 }109 2 unmodified lines112 case tea.WindowSizeMsg:113 m.list.SetWidth(msg.Width)114 return m, nil115 68- case tea.KeyMsg:116+ case tea.KeyPressMsg:117 switch keypress := msg.String(); keypress {118 case "q", "ctrl+c":119 m.quitting = true120 return m, tea.Quit11 unmodified lines132 m.list, cmd = m.list.Update(msg)133 return m, cmd134 }135 88-func (m model) View() string {136+func (m model) View() tea.View {137 if m.choice != "" {90- return quitTextStyle.Render(fmt.Sprintf("%s? Sounds good to me.", m.choice))138+ return tea.NewView(m.styles.quitText.Render(fmt.Sprintf("%s? Sounds good to me.", m.choice)))139 }140 if m.quitting {93- return quitTextStyle.Render("Not hungry? That’s cool.")141+ return tea.NewView(m.styles.quitText.Render("Not hungry? That’s cool."))142 }95- return "\n" + m.list.View()143+ return tea.NewView("\n" + m.list.View())144 }145 146 func main() {99- items := []list.Item{100- item("Ramen"),101- item("Tomato Soup"),102- item("Hamburgers"),103- item("Cheeseburgers"),104- item("Currywurst"),105- item("Okonomiyaki"),106- item("Pasta"),107- item("Fillet Mignon"),108- item("Caviar"),109- item("Just Wine"),110- }111-112- const defaultWidth = 20113-114- l := list.New(items, itemDelegate{}, defaultWidth, listHeight)115- l.Title = "What do you want for dinner?"116- l.SetShowStatusBar(false)117- l.SetFilteringEnabled(false)118- l.Styles.Title = titleStyle119- l.Styles.PaginationStyle = paginationStyle120- l.Styles.HelpStyle = helpStyle121-122- m := model{list: l}123-124- if _, err := tea.NewProgram(m).Run(); err != nil {147+ if _, err := tea.NewProgram(initialModel()).Run(); err != nil {148 fmt.Println("Error running program:", err)149 os.Exit(1)150 }151 }modified:examples/mouse/main.go+10 added-11 removed
4 unmodified lines5 6 import (7 "log"8 9- tea "github.com/charmbracelet/bubbletea"9+ tea "charm.land/bubbletea/v2"10 )11 12 func main() {13- p := tea.NewProgram(model{}, tea.WithMouseAllMotion())13+ p := tea.NewProgram(model{})14 if _, err := p.Run(); err != nil {15 log.Fatal(err)16 }17 }18 19-type model struct {20- mouseEvent tea.MouseEvent21-}19+type model struct{}20 21 func (m model) Init() tea.Cmd {22 return nil23 }24 25 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {26 switch msg := msg.(type) {29- case tea.KeyMsg:27+ case tea.KeyPressMsg:28 if s := msg.String(); s == "ctrl+c" || s == "q" || s == "esc" {29 return m, tea.Quit30 }31 32 case tea.MouseMsg:33+ mouse := msg.Mouse()35- return m, tea.Printf("(X: %d, Y: %d) %s", msg.X, msg.Y, tea.MouseEvent(msg))34+ return m, tea.Printf("(X: %d, Y: %d) %s", mouse.X, mouse.Y, mouse)35 }36 37 return m, nil38 }39 41-func (m model) View() string {42- s := "Do mouse stuff. When you're done press q to quit.\n"43-44- return s40+func (m model) View() tea.View {41+ v := tea.NewView("Do mouse stuff. When you're done press q to quit.\n")42+ v.MouseMode = tea.MouseModeAllMotion43+ return v44 }modified:examples/package-manager/main.go+11 added-13 removed
5 unmodified lines6 "os"7 "strings"8 "time"9 10- "github.com/charmbracelet/bubbles/progress"11- "github.com/charmbracelet/bubbles/spinner"12- tea "github.com/charmbracelet/bubbletea"13- "github.com/charmbracelet/lipgloss"10+ "charm.land/bubbles/v2/progress"11+ "charm.land/bubbles/v2/spinner"12+ tea "charm.land/bubbletea/v2"13+ "charm.land/lipgloss/v2"14 )15 16 type model struct {17 packages []string12 unmodified lines30 )31 32 func newModel() model {33 p := progress.New(34- progress.WithDefaultGradient(),34+ progress.WithDefaultBlend(),35 progress.WithWidth(40),36 progress.WithoutPercentage(),37 )38 s := spinner.New()12 unmodified lines51 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {52 switch msg := msg.(type) {53 case tea.WindowSizeMsg:54 m.width, m.height = msg.Width, msg.Height55- case tea.KeyMsg:55+ case tea.KeyPressMsg:56 switch msg.String() {57 case "ctrl+c", "esc", "q":58 return m, tea.Quit59 }21 unmodified lines81 var cmd tea.Cmd82 m.spinner, cmd = m.spinner.Update(msg)83 return m, cmd84 case progress.FrameMsg:85- newModel, cmd := m.progress.Update(msg)86- if newModel, ok := newModel.(progress.Model); ok {87- m.progress = newModel88- }85+ var cmd tea.Cmd86+ m.progress, cmd = m.progress.Update(msg)87 return m, cmd88 }89 return m, nil90 }91 94-func (m model) View() string {92+func (m model) View() tea.View {93 n := len(m.packages)94 w := lipgloss.Width(fmt.Sprintf("%d", n))95 96 if m.done {99- return doneStyle.Render(fmt.Sprintf("Done! Installed %d packages.\n", n))97+ return tea.NewView(doneStyle.Render(fmt.Sprintf("Done! Installed %d packages.\n", n)))98 }99 100 pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n)101 6 unmodified lines108 109 cellsRemaining := max(0, m.width-lipgloss.Width(spin+info+prog+pkgCount))110 gap := strings.Repeat(" ", cellsRemaining)111 114- return spin + info + gap + prog + pkgCount112+ return tea.NewView(spin + info + gap + prog + pkgCount)113 }114 115 type installedPkgMsg string116 15 unmodified linesmodified:examples/pager/main.go+32 added-15 removed
4 unmodified lines5 6 import (7 "fmt"8 "os"9+ "regexp"10 "strings"11 11- "github.com/charmbracelet/bubbles/viewport"12- tea "github.com/charmbracelet/bubbletea"13- "github.com/charmbracelet/lipgloss"12+ "charm.land/bubbles/v2/viewport"13+ tea "charm.land/bubbletea/v2"14+ "charm.land/lipgloss/v2"15 )16 17 var (18 titleStyle = func() lipgloss.Style {25 unmodified lines44 cmds []tea.Cmd45 )46 47 switch msg := msg.(type) {47- case tea.KeyMsg:48+ case tea.KeyPressMsg:49 if k := msg.String(); k == "ctrl+c" || k == "q" || k == "esc" {50 return m, tea.Quit51 }52 7 unmodified lines60 // need to wait until we've received the window dimensions before61 // we can initialize the viewport. The initial dimensions come in62 // quickly, though asynchronously, which is why we wait for them63 // here.63- m.viewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)64+ m.viewport = viewport.New(viewport.WithWidth(msg.Width), viewport.WithHeight(msg.Height-verticalMarginHeight))65 m.viewport.YPosition = headerHeight66+ m.viewport.LeftGutterFunc = func(info viewport.GutterContext) string {67+ if info.Soft {68+ return " │ "69+ }70+ if info.Index >= info.TotalLines {71+ return " ~ │ "72+ }73+ return fmt.Sprintf("%4d │ ", info.Index+1)74+ }75+ m.viewport.HighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("238")).Background(lipgloss.Color("34"))76+ m.viewport.SelectedHighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("238")).Background(lipgloss.Color("47"))77 m.viewport.SetContent(m.content)78+ m.viewport.SetHighlights(regexp.MustCompile("artichoke").FindAllStringIndex(m.content, -1))79+ m.viewport.HighlightNext()80 m.ready = true81 } else {68- m.viewport.Width = msg.Width69- m.viewport.Height = msg.Height - verticalMarginHeight82+ m.viewport.SetWidth(msg.Width)83+ m.viewport.SetHeight(msg.Height - verticalMarginHeight)84 }85 }86 87 // Handle keyboard and mouse events in the viewport2 unmodified lines90 91 return m, tea.Batch(cmds...)92 }93 80-func (m model) View() string {94+func (m model) View() tea.View {95+ var v tea.View96+ v.AltScreen = true // use the full size of the terminal in its "alternate screen buffer"97+ v.MouseMode = tea.MouseModeCellMotion // turn on mouse support so we can track the mouse wheel98 if !m.ready {82- return "\n Initializing..."99+ v.SetContent("\n Initializing...")100+ } else {101+ v.SetContent(fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.viewport.View(), m.footerView()))102 }84- return fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.viewport.View(), m.footerView())103+ return v104 }105 106 func (m model) headerView() string {107 title := titleStyle.Render("Mr. Pager")89- line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(title)))108+ line := strings.Repeat("─", max(0, m.viewport.Width()-lipgloss.Width(title)))109 return lipgloss.JoinHorizontal(lipgloss.Center, title, line)110 }111 112 func (m model) footerView() string {94- info := infoStyle.Render(fmt.Sprintf("%3.f%%", m.viewport.ScrollPercent()*100))95- line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(info)))113+ info := infoStyle.Render(fmt.Sprintf("%3.f%%:%3.f%%", m.viewport.ScrollPercent()*100, m.viewport.HorizontalScrollPercent()*100))114+ line := strings.Repeat("─", max(0, m.viewport.Width()-lipgloss.Width(info)))115 return lipgloss.JoinHorizontal(lipgloss.Center, line, info)116 }117 118 func main() {5 unmodified lines124 }125 126 p := tea.NewProgram(127 model{content: string(content)},109- tea.WithAltScreen(), // use the full size of the terminal in its "alternate screen buffer"110- tea.WithMouseCellMotion(), // turn on mouse support so we can track the mouse wheel128 )129 130 if _, err := p.Run(); err != nil {131 fmt.Println("could not run program:", err)3 unmodified linesmodified:examples/paginator/main.go+36 added-13 removed
6 unmodified lines7 "fmt"8 "log"9 "strings"10 11- "github.com/charmbracelet/bubbles/paginator"12- "github.com/charmbracelet/lipgloss"11+ "charm.land/bubbles/v2/paginator"12+ "charm.land/lipgloss/v2"13 14- tea "github.com/charmbracelet/bubbletea"14+ tea "charm.land/bubbletea/v2"15 )16 17+type styles struct {18+ activeDot lipgloss.Style19+ inactiveDot lipgloss.Style20+}21+22+func newStyles(bgIsDark bool) (s styles) {23+ lightDark := lipgloss.LightDark(bgIsDark)24+25+ s.activeDot = lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("235"), lipgloss.Color("252"))).SetString("•")26+ s.inactiveDot = s.activeDot.Foreground(lightDark(lipgloss.Color("250"), lipgloss.Color("238"))).SetString("•")27+ return s28+}29+30+type model struct {31+ items []string32+ paginator paginator.Model33+}34+35 func newModel() model {36 var items []string37 for i := 1; i < 101; i++ {38 text := fmt.Sprintf("Item %d", i)2 unmodified lines41 42 p := paginator.New()43 p.Type = paginator.Dots44 p.PerPage = 1027- p.ActiveDot = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "235", Dark: "252"}).Render("•")28- p.InactiveDot = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "250", Dark: "238"}).Render("•")45 p.SetTotalPages(len(items))46 31- return model{47+ m := model{48 paginator: p,49 items: items,50 }51+52+ m.updateStyles(true) // default to dark styles53+ return m54 }55 37-type model struct {38- items []string39- paginator paginator.Model56+func (m *model) updateStyles(isDark bool) {57+ styles := newStyles(isDark)58+ m.paginator.ActiveDot = styles.activeDot.String()59+ m.paginator.InactiveDot = styles.inactiveDot.String()60 }61 62 func (m model) Init() tea.Cmd {43- return nil63+ return tea.RequestBackgroundColor64 }65 66 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {67 var cmd tea.Cmd68 switch msg := msg.(type) {49- case tea.KeyMsg:69+ case tea.BackgroundColorMsg:70+ m.updateStyles(msg.IsDark())71+ return m, nil72+ case tea.KeyPressMsg:73 switch msg.String() {74 case "q", "esc", "ctrl+c":75 return m, tea.Quit76 }1 unmodified line78 m.paginator, cmd = m.paginator.Update(msg)79 return m, cmd80 }81 59-func (m model) View() string {82+func (m model) View() tea.View {83 var b strings.Builder84 b.WriteString("\n Paginator Example\n\n")85 start, end := m.paginator.GetSliceBounds(len(m.items))86 for _, item := range m.items[start:end] {87 b.WriteString(" • " + item + "\n\n")88 }89 b.WriteString(" " + m.paginator.View())90 b.WriteString("\n\n h/l ←/→ page • q: quit\n")68- return b.String()91+ return tea.NewView(b.String())92 }93 94 func main() {95 p := tea.NewProgram(newModel())4 unmodified linesmodified:examples/pipe/main.go+15 added-11 removed
10 unmodified lines11 "io"12 "os"13 "strings"14 15- "github.com/charmbracelet/bubbles/textinput"16- tea "github.com/charmbracelet/bubbletea"17- "github.com/charmbracelet/lipgloss"15+ "charm.land/bubbles/v2/textinput"16+ tea "charm.land/bubbletea/v2"17+ "charm.land/lipgloss/v2"18 )19 20 func main() {21 stat, err := os.Stdin.Stat()35 unmodified lines57 58 func newModel(initialValue string) (m model) {59 i := textinput.New()60 i.Prompt = ""61- i.Cursor.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))62- i.Width = 4861+62+ s := i.Styles()63+ s.Cursor.Color = lipgloss.Color("63")64+ i.SetStyles(s)65+66+ i.SetWidth(48)67 i.SetValue(initialValue)68 i.CursorEnd()69 i.Focus()70 71 m.userInput = i68- return72+ return m73 }74 75 func (m model) Init() tea.Cmd {76 return textinput.Blink77 }78 79 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {80 if key, ok := msg.(tea.KeyMsg); ok {77- switch key.Type {78- case tea.KeyCtrlC, tea.KeyEscape, tea.KeyEnter:81+ switch key.String() {82+ case "ctrl+c", "esc", "enter":83 return m, tea.Quit84 }85 }86 1 unmodified line88 m.userInput, cmd = m.userInput.Update(msg)89 return m, cmd90 }91 88-func (m model) View() string {89- return fmt.Sprintf(92+func (m model) View() tea.View {93+ return tea.NewView(fmt.Sprintf(94 "\nYou piped in: %s\n\nPress ^C to exit",95 m.userInput.View(),92- )96+ ))97 }modified:examples/prevent-quit/main.go+16 added-16 removed
4 unmodified lines5 import (6 "fmt"7 "log"8 9- "github.com/charmbracelet/bubbles/help"10- "github.com/charmbracelet/bubbles/key"11- "github.com/charmbracelet/bubbles/textarea"12- tea "github.com/charmbracelet/bubbletea"13- "github.com/charmbracelet/lipgloss"9+ "charm.land/bubbles/v2/help"10+ "charm.land/bubbles/v2/key"11+ "charm.land/bubbles/v2/textarea"12+ tea "charm.land/bubbletea/v2"13+ "charm.land/lipgloss/v2"14 )15 16 var (17 choiceStyle = lipgloss.NewStyle().PaddingLeft(1).Foreground(lipgloss.Color("241"))18 saveTextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("170"))19- quitViewStyle = lipgloss.NewStyle().Padding(1).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("170"))19+ quitViewStyle = lipgloss.NewStyle().Padding(1, 3).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("170"))20 )21 22 func main() {23 p := tea.NewProgram(initialModel(), tea.WithFilter(filter))67 unmodified lines91 var cmds []tea.Cmd92 var cmd tea.Cmd93 94 switch msg := msg.(type) {95- case tea.KeyMsg:95+ case tea.KeyPressMsg:96 m.saveText = ""97 switch {98 case key.Matches(msg, m.keymap.save):99 m.saveText = "Changes saved!"100 m.hasChanges = false101 case key.Matches(msg, m.keymap.quit):102 m.quitting = true103 return m, tea.Quit104- case msg.Type == tea.KeyRunes:104+ case len(msg.Text) > 0:105 m.saveText = ""106 m.hasChanges = true107 fallthrough108 default:9 unmodified lines118 }119 120 func (m model) updatePromptView(msg tea.Msg) (tea.Model, tea.Cmd) {121 switch msg := msg.(type) {122- case tea.KeyMsg:122+ case tea.KeyPressMsg:123 // For simplicity's sake, we'll treat any key besides "y" as "no"124 if key.Matches(msg, m.keymap.quit) || msg.String() == "y" {125 m.hasChanges = false126 return m, tea.Quit3 unmodified lines130 131 return m, nil132 }133 134-func (m model) View() string {134+func (m model) View() tea.View {135 if m.quitting {136 if m.hasChanges {137- text := lipgloss.JoinHorizontal(lipgloss.Top, "You have unsaved changes. Quit without saving?", choiceStyle.Render("[yn]"))138- return quitViewStyle.Render(text)137+ text := lipgloss.JoinHorizontal(lipgloss.Top, "You have unsaved changes. Quit without saving?", choiceStyle.Render("[yN]"))138+ return tea.NewView(quitViewStyle.Render(text))139 }140- return "Very important, thank you\n"140+ return tea.NewView("Very important. Thank you.\n")141 }142 143 helpView := m.help.ShortHelpView([]key.Binding{144 m.keymap.save,145 m.keymap.quit,146 })147 148- return fmt.Sprintf(149- "\nType some important things.\n\n%s\n\n %s\n %s",148+ return tea.NewView(fmt.Sprintf(149+ "Type some important things.\n%s\n %s\n %s",150 m.textarea.View(),151 saveTextStyle.Render(m.saveText),152 helpView,153- ) + "\n\n"153+ ) + "\n\n")154 }added:examples/print-key/main.go+51 added
1+package main2+3+import (4+ "log"5+6+ tea "charm.land/bubbletea/v2"7+)8+9+type model struct{}10+11+func (m model) Init() tea.Cmd {12+ return nil13+}14+15+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {16+ switch msg := msg.(type) {17+ case tea.KeyboardEnhancementsMsg:18+ return m, tea.Printf("Keyboard enhancements: EventTypes: %v\n",19+ msg.SupportsEventTypes())20+ case tea.KeyMsg:21+ key := msg.Key()22+ switch msg := msg.(type) {23+ case tea.KeyPressMsg:24+ switch msg.String() {25+ case "ctrl+c":26+ return m, tea.Quit27+ }28+ }29+ format := "(%T) You pressed: %s"30+ args := []any{msg, msg.String()}31+ if len(key.Text) > 0 {32+ format += " (text: %q)"33+ args = append(args, key.Text)34+ }35+ return m, tea.Printf(format, args...)36+ }37+ return m, nil38+}39+40+func (m model) View() tea.View {41+ v := tea.NewView("Press any key to see its details printed to the terminal. Press 'ctrl+c' to quit.")42+ v.KeyboardEnhancements.ReportEventTypes = true43+ return v44+}45+46+func main() {47+ p := tea.NewProgram(model{})48+ if _, err := p.Run(); err != nil {49+ log.Printf("Error running program: %v", err)50+ }51+}modified:examples/progress-animated/main.go+13 added-13 removed
11 unmodified lines12 "os"13 "strings"14 "time"15 16- "github.com/charmbracelet/bubbles/progress"17- tea "github.com/charmbracelet/bubbletea"18- "github.com/charmbracelet/lipgloss"16+ "charm.land/bubbles/v2/progress"17+ tea "charm.land/bubbletea/v2"18+ "charm.land/lipgloss/v2"19 )20 21 const (22 padding = 23 unmodified lines26 var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render27 28 func main() {29 m := model{30- progress: progress.New(progress.WithDefaultGradient()),30+ progress: progress.New(progress.WithDefaultBlend()),31 }32 33 if _, err := tea.NewProgram(m).Run(); err != nil {34 fmt.Println("Oh no!", err)12 unmodified lines47 }48 49 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {50 switch msg := msg.(type) {51- case tea.KeyMsg:51+ case tea.KeyPressMsg:52 return m, tea.Quit53 54 case tea.WindowSizeMsg:55- m.progress.Width = msg.Width - padding*2 - 456- if m.progress.Width > maxWidth {57- m.progress.Width = maxWidth55+ m.progress.SetWidth(msg.Width - padding*2 - 4)56+ if m.progress.Width() > maxWidth {57+ m.progress.SetWidth(maxWidth)58 }59 return m, nil60 61 case tickMsg:7 unmodified lines69 return m, tea.Batch(tickCmd(), cmd)70 71 // FrameMsg is sent when the progress bar wants to animate itself72 case progress.FrameMsg:73- progressModel, cmd := m.progress.Update(msg)74- m.progress = progressModel.(progress.Model)73+ var cmd tea.Cmd74+ m.progress, cmd = m.progress.Update(msg)75 return m, cmd76 77 default:78 return m, nil79 }80 }81 82-func (m model) View() string {82+func (m model) View() tea.View {83 pad := strings.Repeat(" ", padding)84- return "\n" +84+ return tea.NewView("\n" +85 pad + m.progress.View() + "\n\n" +86- pad + helpStyle("Press any key to quit")86+ pad + helpStyle("Press any key to quit"))87 }88 89 func tickCmd() tea.Cmd {90 return tea.Tick(time.Second*1, func(t time.Time) tea.Msg {3 unmodified linesadded:examples/progress-bar/main.go+65 added
1+package main2+3+import (4+ "log"5+6+ tea "charm.land/bubbletea/v2"7+ "charm.land/lipgloss/v2"8+)9+10+var body = lipgloss.NewStyle().Padding(1, 2)11+12+type model struct {13+ value int14+ width int15+ state tea.ProgressBarState16+}17+18+func (m model) Init() tea.Cmd {19+ return nil20+}21+22+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {23+ switch msg := msg.(type) {24+ case tea.WindowSizeMsg:25+ m.width = msg.Width26+ case tea.KeyPressMsg:27+ switch msg.String() {28+ case "q", "ctrl+c":29+ return m, tea.Quit30+ case "up", "k":31+ if m.value < 100 {32+ m.value += 1033+ }34+ case "down", "j":35+ if m.value > 0 {36+ m.value -= 1037+ }38+ case "left", "h":39+ if m.state > 0 {40+ m.state--41+ }42+ case "right", "l":43+ if m.state < 4 {44+ m.state++45+ }46+ }47+ }48+ return m, nil49+}50+51+func (m model) View() tea.View {52+ s := body.Width(m.width - body.GetHorizontalPadding()).Render(53+ "This demo requires a terminal emulator that supports an indeterminate progress bar, such a Windows Terminal or Ghostty. In other terminals (including tmux in a supporting terminal) nothing will happen.\n\nPress up/down to change value, left/right to change state, q to quit.",54+ )55+ v := tea.NewView(s)56+ v.ProgressBar = tea.NewProgressBar(m.state, m.value)57+ return v58+}59+60+func main() {61+ p := tea.NewProgram(model{value: 50, state: tea.ProgressBarIndeterminate})62+ if _, err := p.Run(); err != nil {63+ log.Fatalf("Error: %v", err)64+ }65+}modified:examples/progress-download/main.go+3 added-3 removed
7 unmodified lines8 "net/http"9 "os"10 "path/filepath"11 12- "github.com/charmbracelet/bubbles/progress"13- tea "github.com/charmbracelet/bubbletea"12+ "charm.land/bubbles/v2/progress"13+ tea "charm.land/bubbletea/v2"14 )15 16 var p *tea.Program17 73 unmodified lines91 }92 93 m := model{94 pw: pw,95- progress: progress.New(progress.WithDefaultGradient()),95+ progress: progress.New(progress.WithDefaultBlend()),96 }97 // Start Bubble Tea98 p = tea.NewProgram(m)99 8 unmodified linesmodified:examples/progress-download/tui.go+13 added-13 removed
2 unmodified lines3 import (4 "strings"5 "time"6 7- "github.com/charmbracelet/bubbles/progress"8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/progress"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10 )11 12 var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render13 23 unmodified lines37 }38 39 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {40 switch msg := msg.(type) {41- case tea.KeyMsg:41+ case tea.KeyPressMsg:42 return m, tea.Quit43 44 case tea.WindowSizeMsg:45- m.progress.Width = msg.Width - padding*2 - 446- if m.progress.Width > maxWidth {47- m.progress.Width = maxWidth45+ m.progress.SetWidth(msg.Width - padding*2 - 4)46+ if m.progress.Width() > maxWidth {47+ m.progress.SetWidth(maxWidth)48 }49 return m, nil50 51 case progressErrMsg:11 unmodified lines63 return m, tea.Batch(cmds...)64 65 // FrameMsg is sent when the progress bar wants to animate itself66 case progress.FrameMsg:67- progressModel, cmd := m.progress.Update(msg)68- m.progress = progressModel.(progress.Model)67+ var cmd tea.Cmd68+ m.progress, cmd = m.progress.Update(msg)69 return m, cmd70 71 default:72 return m, nil73 }74 }75 76-func (m model) View() string {76+func (m model) View() tea.View {77 if m.err != nil {78- return "Error downloading: " + m.err.Error() + "\n"78+ return tea.NewView("Error downloading: " + m.err.Error() + "\n")79 }80 81 pad := strings.Repeat(" ", padding)82- return "\n" +82+ return tea.NewView("\n" +83 pad + m.progress.View() + "\n\n" +84- pad + helpStyle("Press any key to quit")84+ pad + helpStyle("Press any key to quit"))85 }modified:examples/progress-static/main.go+16 added-12 removed
20 unmodified lines21 "os"22 "strings"23 "time"24 25- "github.com/charmbracelet/bubbles/progress"26- tea "github.com/charmbracelet/bubbletea"27- "github.com/charmbracelet/lipgloss"25+ "charm.land/bubbles/v2/progress"26+ tea "charm.land/bubbletea/v2"27+ "charm.land/lipgloss/v2"28 )29 30 const (31 padding = 232 maxWidth = 8033 )34 35+var (35-var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render36+ helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render37+ yellow = lipgloss.Color("#FDFF8C")38+ pink = lipgloss.Color("#FF7CCB")39+)40 41 func main() {38- prog := progress.New(progress.WithScaledGradient("#FF7CCB", "#FDFF8C"))42+ prog := progress.New(progress.WithScaled(true), progress.WithColors(pink, yellow))43 44 if _, err := tea.NewProgram(model{progress: prog}).Run(); err != nil {45 fmt.Println("Oh no!", err)46 os.Exit(1)12 unmodified lines59 }60 61 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {62 switch msg := msg.(type) {59- case tea.KeyMsg:63+ case tea.KeyPressMsg:64 return m, tea.Quit65 66 case tea.WindowSizeMsg:63- m.progress.Width = msg.Width - padding*2 - 464- if m.progress.Width > maxWidth {65- m.progress.Width = maxWidth67+ m.progress.SetWidth(msg.Width - padding*2 - 4)68+ if m.progress.Width() > maxWidth {69+ m.progress.SetWidth(maxWidth)70 }71 return m, nil72 73 case tickMsg:8 unmodified lines82 return m, nil83 }84 }85 82-func (m model) View() string {86+func (m model) View() tea.View {87 pad := strings.Repeat(" ", padding)84- return "\n" +88+ return tea.NewView("\n" +89 pad + m.progress.ViewAs(m.percent) + "\n\n" +86- pad + helpStyle("Press any key to quit")90+ pad + helpStyle("Press any key to quit"))91 }92 93 func tickCmd() tea.Cmd {94 return tea.Tick(time.Second, func(t time.Time) tea.Msg {3 unmodified linesadded:examples/query-term/main.go+102 added
1+// This example uses a textinput to send the terminal ANSI sequences to query2+// it for capabilities.3+package main4+5+import (6+ "fmt"7+ "io"8+ "log"9+ "os"10+ "strconv"11+ "strings"12+ "unicode"13+14+ "charm.land/bubbles/v2/textinput"15+ tea "charm.land/bubbletea/v2"16+)17+18+func newModel() model {19+ ti := textinput.New()20+ ti.Focus()21+ ti.CharLimit = 15622+ ti.SetWidth(20)23+ ti.SetVirtualCursor(false)24+ return model{input: ti}25+}26+27+type model struct {28+ input textinput.Model29+ err error30+}31+32+func (m model) Init() tea.Cmd {33+ return nil34+}35+36+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {37+ var cmds []tea.Cmd38+39+ switch msg := msg.(type) {40+ case tea.KeyPressMsg:41+ m.err = nil42+ switch msg.String() {43+ case "ctrl+c":44+ return m, tea.Quit45+ case "enter":46+ // Write the sequence to the terminal.47+ val := m.input.Value()48+ val = "\"" + val + "\""49+50+ // Unescape the sequence.51+ seq, err := strconv.Unquote(val)52+ if err != nil {53+ m.err = err54+ return m, nil55+ }56+57+ if !strings.HasPrefix(seq, "\x1b") {58+ m.err = fmt.Errorf("sequence is not an ANSI escape sequence")59+ return m, nil60+ }61+62+ m.input.SetValue("")63+64+ // Write the sequence to the terminal.65+ return m, func() tea.Msg {66+ io.WriteString(os.Stdout, seq)67+ return nil68+ }69+ }70+ default:71+ _, typ, ok := strings.Cut(fmt.Sprintf("%T", msg), ".")72+ if ok && unicode.IsUpper(rune(typ[0])) {73+ // Only log messages that are exported types.74+ cmds = append(cmds, tea.Printf("Received message: %T %+v", msg, msg))75+ }76+ }77+78+ var cmd tea.Cmd79+ m.input, cmd = m.input.Update(msg)80+ cmds = append(cmds, cmd)81+82+ return m, tea.Batch(cmds...)83+}84+85+func (m model) View() tea.View {86+ var s strings.Builder87+ s.WriteString(m.input.View())88+ if m.err != nil {89+ s.WriteString("\n\nError: " + m.err.Error())90+ }91+ s.WriteString("\n\nPress ctrl+c to quit, enter to write the sequence to terminal")92+ v := tea.NewView(s.String())93+ v.Cursor = m.input.Cursor()94+ return v95+}96+97+func main() {98+ p := tea.NewProgram(newModel())99+ if _, err := p.Run(); err != nil {100+ log.Fatal(err)101+ }102+}modified:examples/realtime/main.go+5 added-5 removed
7 unmodified lines8 "math/rand"9 "os"10 "time"11 12- "github.com/charmbracelet/bubbles/spinner"13- tea "github.com/charmbracelet/bubbletea"12+ "charm.land/bubbles/v2/spinner"13+ tea "charm.land/bubbletea/v2"14 )15 16 // A message used to indicate that activity has occurred. In the real world (for17 // example, chat) this would contain actual data.35 unmodified lines53 }54 55 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {56 switch msg.(type) {57- case tea.KeyMsg:57+ case tea.KeyPressMsg:58 m.quitting = true59 return m, tea.Quit60 case responseMsg:61 m.responses++ // record external activity6 unmodified lines68 return m, nil69 }70 }71 72-func (m model) View() string {72+func (m model) View() tea.View {73 s := fmt.Sprintf("\n %s Events received: %d\n\n Press any key to exit\n", m.spinner.View(), m.responses)74 if m.quitting {75 s += "\n"76 }77- return s77+ return tea.NewView(s)78 }79 80 func main() {81 p := tea.NewProgram(model{9 unmodified linesmodified:examples/result/main.go+5 added-5 removed
6 unmodified lines7 "fmt"8 "os"9 "strings"10 11- tea "github.com/charmbracelet/bubbletea"11+ tea "charm.land/bubbletea/v2"12 )13 14 var choices = []string{"Taro", "Coffee", "Lychee"}15 7 unmodified lines23 }24 25 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {26 switch msg := msg.(type) {27- case tea.KeyMsg:27+ case tea.KeyPressMsg:28 switch msg.String() {29 case "ctrl+c", "q", "esc":30 return m, tea.Quit31 18 unmodified lines50 51 return m, nil52 }53 54-func (m model) View() string {54+func (m model) View() tea.View {55 s := strings.Builder{}56 s.WriteString("What kind of Bubble Tea would you like to order?\n\n")57 58- for i := 0; i < len(choices); i++ {58+ for i := range choices {59 if m.cursor == i {60 s.WriteString("(•) ")61 } else {62 s.WriteString("( ) ")2 unmodified lines65 s.WriteString("\n")66 }67 s.WriteString("\n(press q to quit)\n")68 69- return s.String()69+ return tea.NewView(s.String())70 }71 72 func main() {73 p := tea.NewProgram(model{})13 unmodified linesmodified:examples/send-msg/main.go+15 added-13 removed
8 unmodified lines9 "os"10 "strings"11 "time"12 13- "github.com/charmbracelet/bubbles/spinner"14- tea "github.com/charmbracelet/bubbletea"15- "github.com/charmbracelet/lipgloss"13+ "charm.land/bubbles/v2/spinner"14+ tea "charm.land/bubbletea/v2"15+ "charm.land/lipgloss/v2"16 )17 18 var (19 spinnerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))37 unmodified lines57 }58 59 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {60 switch msg := msg.(type) {61- case tea.KeyMsg:61+ case tea.KeyPressMsg:62 m.quitting = true63 return m, tea.Quit64 case resultMsg:65 m.results = append(m.results[1:], msg)6 unmodified lines72 return m, nil73 }74 }75 76-func (m model) View() string {77- var s string76+func (m model) View() tea.View {77+ var b strings.Builder78 79 if m.quitting {80- s += "That’s all for today!"80+ b.WriteString("That's all for today!")81 } else {82- s += m.spinner.View() + " Eating food..."82+ b.WriteString(m.spinner.View())83+ b.WriteString(" Eating food...")84 }85 85- s += "\n\n"86+ b.WriteString("\n\n")87 88 for _, res := range m.results {88- s += res.String() + "\n"89+ b.WriteString(res.String())90+ b.WriteString("\n")91 }92 93 if !m.quitting {92- s += helpStyle.Render("Press any key to exit")94+ b.WriteString(helpStyle.Render("Press any key to exit"))95 }96 97 if m.quitting {96- s += "\n"98+ b.WriteString("\n")99 }100 99- return appStyle.Render(s)101+ return tea.NewView(appStyle.Render(b.String()))102 }103 104 func main() {105 p := tea.NewProgram(newModel())28 unmodified linesmodified:examples/sequence/main.go+7 added-4 removed
5 unmodified lines6 "fmt"7 "os"8 "time"9 10- tea "github.com/charmbracelet/bubbletea"10+ tea "charm.land/bubbletea/v2"11 )12 13 type model struct{}14 15 func (m model) Init() tea.Cmd {16+ // A tea.Sequence is a command that runs a series of commands in17+ // order. Contrast this with tea.Batch, which runs a series of commands18+ // concurrently, with no order guarantees.19 return tea.Sequence(20 tea.Batch(21 tea.Sequence(22 SleepPrintln("1-1-1", 1000),29 unmodified lines52 }53 54 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {55 switch msg.(type) {53- case tea.KeyMsg:56+ case tea.KeyPressMsg:57 return m, tea.Quit58 }59 return m, nil60 }61 59-func (m model) View() string {60- return ""62+func (m model) View() tea.View {63+ return tea.NewView("")64 }65 66 func main() {67 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesadded:examples/set-terminal-color/main.go+201 added
1+package main2+3+import (4+ "image/color"5+ "log"6+ "strings"7+8+ "charm.land/bubbles/v2/textinput"9+ tea "charm.land/bubbletea/v2"10+ "charm.land/lipgloss/v2"11+ "github.com/lucasb-eyer/go-colorful"12+)13+14+type colorType int15+16+const (17+ foreground colorType = iota + 118+ background19+ cursor20+)21+22+func (c colorType) String() string {23+ switch c {24+ case foreground:25+ return "Foreground"26+ case background:27+ return "Background"28+ case cursor:29+ return "Cursor"30+ default:31+ return "Unknown"32+ }33+}34+35+type state int36+37+const (38+ chooseState state = iota39+ inputState40+)41+42+type model struct {43+ ti textinput.Model44+ choice colorType45+ state state46+ choiceIndex int47+ err error48+ fg, bg, cc color.Color49+}50+51+func (m model) Init() tea.Cmd {52+ return textinput.Blink53+}54+55+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {56+ switch msg := msg.(type) {57+ case tea.KeyPressMsg:58+ switch msg.String() {59+ case "ctrl+c", "q":60+ return m, tea.Quit61+ }62+63+ switch m.state {64+ case chooseState:65+ m.ti.Blur()66+ switch msg.String() {67+ case "j", "down":68+ m.choiceIndex++69+ if m.choiceIndex > 2 {70+ m.choiceIndex = 071+ }72+ case "k", "up":73+ m.choiceIndex--74+ if m.choiceIndex < 0 {75+ m.choiceIndex = 276+ }77+ case "enter":78+ m.state = inputState79+ m.ti.Focus()80+ switch m.choiceIndex {81+ case 0:82+ m.choice = foreground83+ case 1:84+ m.choice = background85+ case 2:86+ m.choice = cursor87+ }88+ }89+90+ case inputState:91+ m.ti.Focus()92+ switch msg.String() {93+ case "esc":94+ m.choice = 095+ m.choiceIndex = 096+ m.state = chooseState97+ m.err = nil98+ m.ti.Blur()99+ case "enter":100+ val := m.ti.Value()101+ col, err := colorful.Hex(val)102+ if err != nil {103+ m.err = err104+ } else {105+ m.err = nil106+ choice := m.choice107+ m.choice = 0108+ m.choiceIndex = 0109+ m.state = chooseState110+111+ // Reset the text input112+ m.ti.Reset()113+114+ switch choice {115+ case foreground:116+ m.fg = col117+ case background:118+ m.bg = col119+ case cursor:120+ m.cc = col121+ }122+ }123+124+ m.ti.Blur()125+126+ default:127+ var cmd tea.Cmd128+ m.ti, cmd = m.ti.Update(msg)129+ return m, cmd130+ }131+ }132+ }133+134+ return m, nil135+}136+137+func (m model) View() tea.View {138+ var s strings.Builder139+ instructions := lipgloss.NewStyle().Width(40).Render("Choose a terminal-wide color to set. All settings will be cleared on exit.")140+141+ switch m.state {142+ case chooseState:143+ s.WriteString(instructions + "\n\n")144+ for i, c := range []colorType{foreground, background, cursor} {145+ if i == m.choiceIndex {146+ s.WriteString(" > ")147+ } else {148+ s.WriteString(" ")149+ }150+ s.WriteString(c.String())151+ s.WriteString("\n")152+ }153+ case inputState:154+ s.WriteString("Enter a color in hex format:\n\n")155+ s.WriteString(m.ti.View())156+ s.WriteString("\n")157+ }158+159+ if m.err != nil {160+ s.WriteString("\nError: ")161+ s.WriteString(m.err.Error())162+ }163+164+ s.WriteString("\nPress q to quit")165+166+ switch m.state {167+ case chooseState:168+ s.WriteString(", j/k to move, and enter to select")169+ case inputState:170+ s.WriteString(", and enter to submit, esc to go back")171+ }172+173+ s.WriteString("\n")174+175+ v := tea.NewView(s.String())176+ if m.ti.Focused() {177+ v.Cursor = m.ti.Cursor()178+ v.Cursor.Y += 2 // account for the prompt179+ v.Cursor.Color = m.cc180+ }181+ v.BackgroundColor = m.bg182+ v.ForegroundColor = m.fg183+184+ return v185+}186+187+func main() {188+ ti := textinput.New()189+ ti.Placeholder = "#ff00ff"190+ ti.CharLimit = 156191+ ti.SetWidth(20)192+ ti.SetVirtualCursor(false)193+ p := tea.NewProgram(model{194+ ti: ti,195+ })196+197+ _, err := p.Run()198+ if err != nil {199+ log.Fatalf("Error running program: %v", err)200+ }201+}modified:examples/set-window-title/main.go+12 added-5 removed
4 unmodified lines5 import (6 "fmt"7 "os"8 9- tea "github.com/charmbracelet/bubbletea"9+ tea "charm.land/bubbletea/v2"10+ "charm.land/lipgloss/v2"11 )12 13+const windowTitle = "Hello, Bubble Tea"14+15 type model struct{}16 17 func (m model) Init() tea.Cmd {15- return tea.SetWindowTitle("Bubble Tea Example")18+ return nil19 }20 21 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {22 switch msg.(type) {20- case tea.KeyMsg:23+ case tea.KeyPressMsg:24 return m, tea.Quit25 }26 return m, nil27 }28 26-func (m model) View() string {27- return "\nPress any key to quit."29+func (m model) View() tea.View {30+ wrap := lipgloss.NewStyle().Width(78).Render31+ v := tea.NewView(wrap("The window title has been set to '"+windowTitle+"'. It will be cleared on exit.") +32+ "\n\nPress any key to quit.")33+ v.WindowTitle = windowTitle34+ return v35 }36 37 func main() {38 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesmodified:examples/simple/testdata/TestApp.golden+5 added-5 removed
1-[?25l[?2004h
Hi. This program will exit in 10 seconds.[K2-[K3-To quit sooner press ctrl-c, or press ctrl-z to suspend...[K4-[K
[3AHi. This program will exit in 9 seconds.[K1+[?2004h[?25l[=1;1u[?u
Hi. This program will exit in 10 seconds.2 3+To quit sooner press ctrl-c, or press ctrl-z to suspend...4+[3A[30C9 [P[?25l5 7-
[2K
[?2004l[?25h[?1002l[?1003l[?1006l6+7+
[J[?25h[0 q[?25h[?2004lmodified:examples/simple/main_test.go+17 added-15 removed
1 package main2 3-import (4- "bytes"5- "io"6- "regexp"7- "testing"8- "time"9-10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/x/exp/teatest"12-)13-3+/*4 func TestApp(t *testing.T) {5+ // TODO: Enable this test again6+ // Since we added colorprofile.Writer to standard_renderer.go, this test7+ // keeps failing. This is because the output is colored and has escape8+ // sequences but the test runs against a buffer output and not a terminal,9+ // tty, or pty. One way to fix this is to pass a color profile to the test10+ // program using [tea.WithColorProfile(Ascii)].11+ t.Skip("this test is currently disabled")12+13 m := model(10)14 tm := teatest.NewTestModel(15 t, m,16 teatest.WithInitialTermSize(70, 30),6 unmodified lines23 24 time.Sleep(time.Second + time.Millisecond*200)25 tm.Type("I'm typing things, but it'll be ignored by my program")26 tm.Send("ignored msg")29- tm.Send(tea.KeyMsg{30- Type: tea.KeyEnter,27+ tm.Send(tea.KeyPressMsg{28+ Code: tea.KeyEnter,29 })30 31 if err := tm.Quit(); err != nil {32 t.Fatal(err)10 unmodified lines43 }44 }45 46 func TestAppInteractive(t *testing.T) {47+ t.Skip("This test is flaky and needs to be fixed.\n" +48+ "We need a more concrete way to set the initial terminal size")49+50 m := model(10)51 tm := teatest.NewTestModel(52 t, m,53 teatest.WithInitialTermSize(70, 30),9 unmodified lines63 teatest.WaitFor(t, tm.Output(), func(out []byte) bool {64 return bytes.Contains(out, []byte("This program will exit in 7 seconds"))65 }, teatest.WithDuration(5*time.Second))66 66- tm.Send(tea.KeyMsg{67- Type: tea.KeyEnter,67+ tm.Send(tea.KeyPressMsg{68+ Code: tea.KeyEnter,69 })70 71 if err := tm.Quit(); err != nil {72 t.Fatal(err)11 unmodified lines84 tb.Fatal(err)85 }86 return bts87 }88+*/modified:examples/simple/main.go+4 added-4 removed
6 unmodified lines7 "log"8 "os"9 "time"10 11- tea "github.com/charmbracelet/bubbletea"11+ tea "charm.land/bubbletea/v2"12 )13 14 func main() {15 // Log to a file. Useful in debugging since you can't really log to stdout.27 unmodified lines43 // message and send back an updated model accordingly. You can also return44 // a command, which is a function that performs I/O and returns a message.45 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {46 switch msg := msg.(type) {47- case tea.KeyMsg:47+ case tea.KeyPressMsg:48 switch msg.String() {49 case "ctrl+c", "q":50 return m, tea.Quit51 case "ctrl+z":11 unmodified lines63 }64 65 // View returns a string based on data in the model. That string which will be66 // rendered to the terminal.67-func (m model) View() string {68- return fmt.Sprintf("Hi. This program will exit in %d seconds.\n\nTo quit sooner press ctrl-c, or press ctrl-z to suspend...\n", m)67+func (m model) View() tea.View {68+ return tea.NewView(fmt.Sprintf("Hi. This program will exit in %d seconds.\n\nTo quit sooner press ctrl-c, or press ctrl-z to suspend...\n", m))69 }70 71 // Messages are events that we respond to in our Update function. This72 // particular one indicates that the timer has ticked.6 unmodified linesadded:examples/space/main.go+134 added
1+package main2+3+import (4+ "fmt"5+ "image/color"6+ "math/rand"7+ "os"8+ "strings"9+ "time"10+11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13+)14+15+// An example to show the FPS count of a moving space-like background.16+//17+// This was ported from the talented Orhun Parmaksız (@orhun)'s space example18+// from his blog post "Why stdout is faster than stderr?".19+20+type model struct {21+ colors [][]color.Color22+ lastWidth int23+ lastHeight int24+ frameCount int25+ width int26+ height int27+}28+29+func (m model) Init() tea.Cmd {30+ return tea.Batch(31+ tickCmd(),32+ )33+}34+35+func tickCmd() tea.Cmd {36+ return tea.Tick(time.Second/60, func(time.Time) tea.Msg {37+ return tickMsg{}38+ })39+}40+41+type tickMsg struct{}42+43+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {44+ switch msg := msg.(type) {45+ case tea.KeyPressMsg:46+ switch msg.String() {47+ case "q", "ctrl+c":48+ return m, tea.Quit49+ }50+51+ case tea.WindowSizeMsg:52+ m.width = msg.Width53+ m.height = msg.Height54+ if m.width != m.lastWidth || m.height != m.lastHeight {55+ m.setupColors()56+ m.lastWidth = m.width57+ m.lastHeight = m.height58+ }59+60+ case tickMsg:61+ m.frameCount++62+ return m, tickCmd()63+ }64+65+ return m, nil66+}67+68+func (m *model) setupColors() {69+ height := m.height * 2 // double height for half blocks70+ m.colors = make([][]color.Color, height)71+72+ for y := range height {73+ m.colors[y] = make([]color.Color, m.width)74+ randomnessFactor := float64(height-y) / float64(height)75+76+ for x := range m.width {77+ baseValue := randomnessFactor * (float64(height-y) / float64(height))78+ randomOffset := (rand.Float64() * 0.2) - 0.179+ value := clamp(baseValue+randomOffset, 0, 1)80+81+ // Convert value to grayscale color (0-255)82+ gray := uint8(value * 255)83+ m.colors[y][x] = lipgloss.Color(fmt.Sprintf("#%02x%02x%02x", gray, gray, gray))84+ }85+ }86+}87+88+func clamp(value, min, max float64) float64 {89+ if value < min {90+ return min91+ }92+ if value > max {93+ return max94+ }95+ return value96+}97+98+func (m model) View() tea.View {99+ // Title100+ title := lipgloss.NewStyle().Bold(true).Render("Space")101+102+ // Color display103+ var s strings.Builder104+ height := m.height - 1 // leave one line for title105+ for y := range height {106+ for x := range m.width {107+ xi := (x + m.frameCount) % m.width108+ fg := m.colors[y*2][xi]109+ bg := m.colors[y*2+1][xi]110+ st := lipgloss.NewStyle().Foreground(fg).Background(bg)111+ s.WriteString(st.Render("▀"))112+ }113+ if y < height-1 {114+ s.WriteString("\n")115+ }116+ }117+118+ v := tea.NewView(strings.Join([]string{119+ title,120+ s.String(),121+ }, "\n"))122+ v.AltScreen = true123+ return v124+}125+126+func main() {127+ p := tea.NewProgram(model{}, tea.WithFPS(120))128+129+ _, err := p.Run()130+ if err != nil {131+ fmt.Printf("Error running program: %v", err)132+ os.Exit(1)133+ }134+}modified:examples/spinner/main.go+8 added-8 removed
5 unmodified lines6 import (7 "fmt"8 "os"9 10- "github.com/charmbracelet/bubbles/spinner"11- tea "github.com/charmbracelet/bubbletea"12- "github.com/charmbracelet/lipgloss"10+ "charm.land/bubbles/v2/spinner"11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13 )14 15 type errMsg error16 15 unmodified lines32 }33 34 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {35 switch msg := msg.(type) {36- case tea.KeyMsg:36+ case tea.KeyPressMsg:37 switch msg.String() {38 case "q", "esc", "ctrl+c":39 m.quitting = true40 return m, tea.Quit11 unmodified lines52 return m, cmd53 }54 }55 56-func (m model) View() string {56+func (m model) View() tea.View {57 if m.err != nil {58- return m.err.Error()58+ return tea.NewView(m.err.Error())59 }60 str := fmt.Sprintf("\n\n %s Loading forever...press q to quit\n\n", m.spinner.View())61 if m.quitting {62- return str + "\n"62+ return tea.NewView(str + "\n")63 }64- return str64+ return tea.NewView(str)65 }66 67 func main() {68 p := tea.NewProgram(initialModel())5 unmodified linesmodified:examples/spinners/main.go+7 added-6 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/spinner"8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/spinner"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10 )11 12 var (13 // Available spinners34 unmodified lines48 }49 50 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {51 switch msg := msg.(type) {52- case tea.KeyMsg:52+ case tea.KeyPressMsg:53 switch msg.String() {54 case "ctrl+c", "q", "esc":55 return m, tea.Quit56 case "h", "left":27 unmodified lines84 m.spinner.Style = spinnerStyle85 m.spinner.Spinner = spinners[m.index]86 }87 88-func (m model) View() (s string) {88+func (m model) View() tea.View {89 var gap string90 switch m.index {91 case 1:92 gap = ""93 default:94 gap = " "95 }96 97+ var s string98 s += fmt.Sprintf("\n %s%s%s\n\n", m.spinner.View(), gap, textStyle("Spinning..."))99 s += helpStyle("h/l, ←/→: change spinner • q: exit\n")99- return100+ return tea.NewView(s)101 }added:examples/splash/main.go+178 added
1+package main2+3+import (4+ "fmt"5+ "image/color"6+ "math"7+ "strings"8+ "time"9+10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12+)13+14+// This example was ported from the awesome Textualize project by @willmcgugan.15+// Check it out here:16+// https://github.com/Textualize/textual/blob/main/examples/splash.py17+18+// Color gradient19+var colors = []color.Color{20+ lipgloss.Color("#881177"),21+ lipgloss.Color("#aa3355"),22+ lipgloss.Color("#cc6666"),23+ lipgloss.Color("#ee9944"),24+ lipgloss.Color("#eedd00"),25+ lipgloss.Color("#99dd55"),26+ lipgloss.Color("#44dd88"),27+ lipgloss.Color("#22ccbb"),28+ lipgloss.Color("#00bbcc"),29+ lipgloss.Color("#0099cc"),30+ lipgloss.Color("#3366bb"),31+ lipgloss.Color("#663399"),32+}33+34+type model struct {35+ width int36+ height int37+ rate int6438+}39+40+func (m model) Init() tea.Cmd {41+ return tick42+}43+44+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {45+ switch msg := msg.(type) {46+ case tea.KeyPressMsg:47+ return m, tea.Quit48+ case tea.WindowSizeMsg:49+ m.width = msg.Width50+ m.height = msg.Height51+ case tickMsg:52+ return m, tick53+ }54+ return m, nil55+}56+57+func (m model) View() tea.View {58+ var v tea.View59+ v.AltScreen = true60+ if m.width == 0 {61+ v.SetContent("Initializing...")62+ return v63+ }64+65+ v.SetContent(m.gradient())66+ return v67+}68+69+func (m model) gradient() string {70+ // Time-based angle for animation71+ t := float64(time.Now().UnixNano()*m.rate) / float64(time.Second)72+ angleRadians := -t * math.Pi / 180.073+ sinAngle := math.Sin(angleRadians)74+ cosAngle := math.Cos(angleRadians)75+76+ centerX := float64(m.width) / 277+ centerY := float64(m.height)78+79+ var output strings.Builder80+81+ for lineY := range m.height {82+ pointY := float64(lineY)*2 - centerY83+ pointX := 0.0 - centerX84+85+ x1 := (centerX + (pointX*cosAngle - pointY*sinAngle)) / float64(m.width)86+ x2 := (centerX + (pointX*cosAngle - (pointY+1.0)*sinAngle)) / float64(m.width)87+ pointX = float64(m.width) - centerX88+ endX1 := (centerX + (pointX*cosAngle - pointY*sinAngle)) / float64(m.width)89+ deltaX := (endX1 - x1) / float64(m.width)90+91+ if math.Abs(deltaX) < 0.0001 {92+ // Special case for verticals93+ color1 := getGradientColor(x1)94+ color2 := getGradientColor(x2)95+ style := lipgloss.NewStyle().96+ Foreground(color1).97+ Background(color2)98+ output.WriteString(style.Render(strings.Repeat("▀", m.width)))99+ } else {100+ // Render each column in the row101+ for x := range m.width {102+ pos1 := x1 + float64(x)*deltaX103+ pos2 := x2 + float64(x)*deltaX104+ color1 := getGradientColor(pos1)105+ color2 := getGradientColor(pos2)106+ style := lipgloss.NewStyle().107+ Foreground(color1).108+ Background(color2)109+ output.WriteString(style.Render("▀"))110+ }111+ }112+ if lineY < m.height-1 {113+ output.WriteString("\n")114+ }115+ }116+117+ return output.String()118+}119+120+func getGradientColor(position float64) color.Color {121+ // Normalize position to [0,1]122+ if position <= 0 {123+ position = 0124+ }125+ if position >= 1 {126+ position = 1127+ }128+129+ // Calculate the color index130+ idx := position * float64(len(colors)-1)131+ i1 := int(math.Floor(idx))132+ i2 := int(math.Ceil(idx))133+134+ // Ensure indices are within bounds135+ i1 = i1 % len(colors)136+ i2 = i2 % len(colors)137+ if i1 < 0 {138+ i1 += len(colors)139+ }140+ if i2 < 0 {141+ i2 += len(colors)142+ }143+144+ // Interpolate between colors145+ t := idx - float64(i1)146+ return interpolateColors(colors[i1], colors[i2], t)147+}148+149+func interpolateColors(color1, color2 color.Color, t float64) color.Color {150+ // Parse hex colors151+ r1, g1, b1, _ := color1.RGBA()152+ r1, g1, b1 = r1>>8, g1>>8, b1>>8153+ r2, g2, b2, _ := color2.RGBA()154+ r2, g2, b2 = r2>>8, g2>>8, b2>>8155+156+ // Interpolate157+ r := int(float64(r1)*(1-t) + float64(r2)*t)158+ g := int(float64(g1)*(1-t) + float64(g2)*t)159+ b := int(float64(b1)*(1-t) + float64(b2)*t)160+161+ return color.RGBA{uint8(r), uint8(g), uint8(b), 255}162+}163+164+type tickMsg time.Time165+166+func tick() tea.Msg {167+ return tickMsg(time.Now())168+}169+170+func main() {171+ p := tea.NewProgram(172+ model{rate: 90},173+ )174+175+ if _, err := p.Run(); err != nil {176+ fmt.Printf("Error running program: %v", err)177+ }178+}modified:examples/split-editors/main.go+56 added-25 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/help"8- "github.com/charmbracelet/bubbles/key"9- "github.com/charmbracelet/bubbles/textarea"10- tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/help"8+ "charm.land/bubbles/v2/key"9+ "charm.land/bubbles/v2/textarea"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12 )13 14 const (15 initialInputs = 22 unmodified lines18 helpHeight = 519 )20 21 var (22- cursorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212"))22+ cursorColor = lipgloss.Color("212")23 24 cursorLineStyle = lipgloss.NewStyle().25 Background(lipgloss.Color("57")).26 Foreground(lipgloss.Color("230"))27 28 placeholderStyle = lipgloss.NewStyle().29 Foreground(lipgloss.Color("238"))30 31- endOfBufferStyle = lipgloss.NewStyle().32- Foreground(lipgloss.Color("235"))33-31 focusedPlaceholderStyle = lipgloss.NewStyle().32 Foreground(lipgloss.Color("99"))33 34 focusedBorderStyle = lipgloss.NewStyle().1 unmodified line36 BorderForeground(lipgloss.Color("238"))37 38 blurredBorderStyle = lipgloss.NewStyle().39 Border(lipgloss.HiddenBorder())40+41+ endOfBufferStyle = lipgloss.NewStyle().42+ Foreground(lipgloss.Color("235"))43 )44 45 type keymap = struct {46 next, prev, add, remove, quit key.Binding3 unmodified lines50 t := textarea.New()51 t.Prompt = ""52 t.Placeholder = "Type something"53 t.ShowLineNumbers = true54- t.Cursor.Style = cursorStyle55- t.FocusedStyle.Placeholder = focusedPlaceholderStyle56- t.BlurredStyle.Placeholder = placeholderStyle57- t.FocusedStyle.CursorLine = cursorLineStyle58- t.FocusedStyle.Base = focusedBorderStyle59- t.BlurredStyle.Base = blurredBorderStyle60- t.FocusedStyle.EndOfBuffer = endOfBufferStyle61- t.BlurredStyle.EndOfBuffer = endOfBufferStyle54+ t.SetVirtualCursor(true)55+56+ s := t.Styles()57+ s.Cursor.Color = cursorColor58+ s.Focused.Placeholder = focusedPlaceholderStyle59+ s.Blurred.Placeholder = placeholderStyle60+ s.Focused.CursorLine = cursorLineStyle61+ s.Focused.CursorLineNumber = cursorLineStyle62+ s.Focused.Base = focusedBorderStyle63+ s.Blurred.Base = blurredBorderStyle64+ s.Focused.EndOfBuffer = endOfBufferStyle65+ s.Blurred.EndOfBuffer = endOfBufferStyle66+ t.SetStyles(s)67+68 t.KeyMap.DeleteWordBackward.SetEnabled(false)69 t.KeyMap.LineNext = key.NewBinding(key.WithKeys("down"))70 t.KeyMap.LinePrevious = key.NewBinding(key.WithKeys("up"))71 t.Blur()35 unmodified lines107 key.WithHelp("esc", "quit"),108 ),109 },110 }105- for i := 0; i < initialInputs; i++ {111+ for i := range initialInputs {112 m.inputs[i] = newTextarea()113 }114 m.inputs[m.focus].Focus()115 m.updateKeybindings()7 unmodified lines123 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {124 var cmds []tea.Cmd125 126 switch msg := msg.(type) {121- case tea.KeyMsg:127+ case tea.KeyPressMsg:128 switch {129 case key.Matches(msg, m.keymap.quit):130 for i := range m.inputs {131 m.inputs[i].Blur()52 unmodified lines184 m.keymap.add.SetEnabled(len(m.inputs) < maxInputs)185 m.keymap.remove.SetEnabled(len(m.inputs) > minInputs)186 }187 182-func (m model) View() string {188+func (m model) inputViews() []string {189+ var views []string190+ for i := range m.inputs {191+ views = append(views, m.inputs[i].View())192+ }193+ return views194+}195+196+func (m model) View() tea.View {197 help := m.help.ShortHelpView([]key.Binding{198 m.keymap.next,199 m.keymap.prev,200 m.keymap.add,201 m.keymap.remove,202 m.keymap.quit,203 })204 191- var views []string192- for i := range m.inputs {193- views = append(views, m.inputs[i].View())205+ v := tea.NewView(lipgloss.JoinHorizontal(lipgloss.Top, m.inputViews()...) + "\n\n" + help)206+ v.AltScreen = true207+ return v208+}209+210+func (m model) Cursor() *tea.Cursor {211+ focusedInput := m.inputs[m.focus]212+ if focusedInput.VirtualCursor() {213+ return nil214 }215 196- return lipgloss.JoinHorizontal(lipgloss.Top, views...) + "\n\n" + help216+ views := m.inputViews()217+ c := focusedInput.Cursor()218+219+ // Find textrea offset to position real cursor.220+ //221+ // To do this we calculate the width of all textareas to the left of222+ // the focused one.223+ for i := range m.focus {224+ c.X += lipgloss.Width(views[i])225+ }226+227+ return c228 }229 230 func main() {200- if _, err := tea.NewProgram(newModel(), tea.WithAltScreen()).Run(); err != nil {231+ if _, err := tea.NewProgram(newModel()).Run(); err != nil {232 fmt.Println("Error while running program:", err)233 os.Exit(1)234 }235 }modified:examples/stopwatch/main.go+8 added-8 removed
3 unmodified lines4 "fmt"5 "os"6 "time"7 8- "github.com/charmbracelet/bubbles/help"9- "github.com/charmbracelet/bubbles/key"10- "github.com/charmbracelet/bubbles/stopwatch"11- tea "github.com/charmbracelet/bubbletea"8+ "charm.land/bubbles/v2/help"9+ "charm.land/bubbles/v2/key"10+ "charm.land/bubbles/v2/stopwatch"11+ tea "charm.land/bubbletea/v2"12 )13 14 type model struct {15 stopwatch stopwatch.Model12 unmodified lines28 func (m model) Init() tea.Cmd {29 return m.stopwatch.Init()30 }31 32-func (m model) View() string {32+func (m model) View() tea.View {33 // Note: you could further customize the time output by getting the34 // duration from m.stopwatch.Elapsed(), which returns a time.Duration, and35 // skip m.stopwatch.View() altogether.36 s := m.stopwatch.View() + "\n"37 if !m.quitting {38 s = "Elapsed: " + s39 s += m.helpView()40 }41- return s41+ return tea.NewView(s)42 }43 44 func (m model) helpView() string {45 return "\n" + m.help.ShortHelpView([]key.Binding{5 unmodified lines51 }52 53 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {54 switch msg := msg.(type) {55- case tea.KeyMsg:55+ case tea.KeyPressMsg:56 switch {57 case key.Matches(msg, m.keymap.quit):58 m.quitting = true59 return m, tea.Quit11 unmodified lines71 }72 73 func main() {74 m := model{75- stopwatch: stopwatch.NewWithInterval(time.Millisecond),75+ stopwatch: stopwatch.New(stopwatch.WithInterval(time.Millisecond)),76 keymap: keymap{77 start: key.NewBinding(78 key.WithKeys("s"),79 key.WithHelp("s", "start"),24 unmodified linesmodified:examples/suspend/main.go+5 added-5 removed
3 unmodified lines4 "errors"5 "fmt"6 "os"7 8- tea "github.com/charmbracelet/bubbletea"8+ tea "charm.land/bubbletea/v2"9 )10 11 type model struct {12 quitting bool8 unmodified lines21 switch msg := msg.(type) {22 case tea.ResumeMsg:23 m.suspending = false24 return m, nil25- case tea.KeyMsg:25+ case tea.KeyPressMsg:26 switch msg.String() {27 case "q", "esc":28 m.quitting = true29 return m, tea.Quit7 unmodified lines37 }38 return m, nil39 }40 41-func (m model) View() string {41+func (m model) View() tea.View {42 if m.suspending || m.quitting {43- return ""43+ return tea.NewView("")44 }45 46- return "\nPress ctrl-z to suspend, ctrl+c to interrupt, q, or esc to exit\n"46+ return tea.NewView("\nPress ctrl-z to suspend, ctrl+c to interrupt, q, or esc to exit\n")47 }48 49 func main() {50 if _, err := tea.NewProgram(model{}).Run(); err != nil {7 unmodified linesmodified:examples/table/main.go+6 added-6 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/table"8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/lipgloss"7+ "charm.land/bubbles/v2/table"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10 )11 12 var baseStyle = lipgloss.NewStyle().13 BorderStyle(lipgloss.NormalBorder()).7 unmodified lines21 22 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {23 var cmd tea.Cmd24 switch msg := msg.(type) {25- case tea.KeyMsg:25+ case tea.KeyPressMsg:26 switch msg.String() {27 case "esc":28 if m.table.Focused() {29 m.table.Blur()11 unmodified lines41 m.table, cmd = m.table.Update(msg)42 return m, cmd43 }44 45-func (m model) View() string {46- return baseStyle.Render(m.table.View()) + "\n"45+func (m model) View() tea.View {46+ return tea.NewView(baseStyle.Render(m.table.View()) + "\n " + m.table.HelpView() + "\n")47 }48 49 func main() {50 columns := []table.Column{134 unmodified linesmodified:examples/table-resize/main.go+74 added-59 removed
1 package main2 3 import (4 "fmt"5+ "image/color"6 "os"7 7- tea "github.com/charmbracelet/bubbletea"8- "github.com/charmbracelet/lipgloss"9- "github.com/charmbracelet/lipgloss/table"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10+ "charm.land/lipgloss/v2/table"11 )12 13+// Pokemon types.14+const (15+ None = ""16+ Bug = "Bug"17+ Electric = "Electric"18+ Fire = "Fire"19+ Flying = "Flying"20+ Grass = "Grass"21+ Ground = "Ground"22+ Normal = "Normal"23+ Poison = "Poison"24+ Water = "Water"25+)26+27 type model struct {28 table *table.Table29 }30 4 unmodified lines35 switch msg := msg.(type) {36 case tea.WindowSizeMsg:37 m.table = m.table.Width(msg.Width)38 m.table = m.table.Height(msg.Height)24- case tea.KeyMsg:39+ case tea.KeyPressMsg:40 switch msg.String() {41 case "q", "ctrl+c":42 return m, tea.Quit43 case "enter":1 unmodified line45 }46 return m, cmd47 }48 34-func (m model) View() string {35- return "\n" + m.table.String() + "\n"49+func (m model) View() tea.View {50+ v := tea.NewView("\n" + m.table.String() + "\n")51+ v.AltScreen = true52+ return v53 }54 55 func main() {39- re := lipgloss.NewRenderer(os.Stdout)40- baseStyle := re.NewStyle().Padding(0, 1)56+ baseStyle := lipgloss.NewStyle().Padding(0, 1)57 headerStyle := baseStyle.Foreground(lipgloss.Color("252")).Bold(true)58 selectedStyle := baseStyle.Foreground(lipgloss.Color("#01BE85")).Background(lipgloss.Color("#00432F"))43- typeColors := map[string]lipgloss.Color{44- "Bug": lipgloss.Color("#D7FF87"),45- "Electric": lipgloss.Color("#FDFF90"),46- "Fire": lipgloss.Color("#FF7698"),47- "Flying": lipgloss.Color("#FF87D7"),48- "Grass": lipgloss.Color("#75FBAB"),49- "Ground": lipgloss.Color("#FF875F"),50- "Normal": lipgloss.Color("#929292"),51- "Poison": lipgloss.Color("#7D5AFC"),52- "Water": lipgloss.Color("#00E2C7"),59+ typeColors := map[string]color.Color{60+ Bug: lipgloss.Color("#D7FF87"),61+ Electric: lipgloss.Color("#FDFF90"),62+ Fire: lipgloss.Color("#FF7698"),63+ Flying: lipgloss.Color("#FF87D7"),64+ Grass: lipgloss.Color("#75FBAB"),65+ Ground: lipgloss.Color("#FF875F"),66+ Normal: lipgloss.Color("#929292"),67+ Poison: lipgloss.Color("#7D5AFC"),68+ Water: lipgloss.Color("#00E2C7"),69 }54- dimTypeColors := map[string]lipgloss.Color{55- "Bug": lipgloss.Color("#97AD64"),56- "Electric": lipgloss.Color("#FCFF5F"),57- "Fire": lipgloss.Color("#BA5F75"),58- "Flying": lipgloss.Color("#C97AB2"),59- "Grass": lipgloss.Color("#59B980"),60- "Ground": lipgloss.Color("#C77252"),61- "Normal": lipgloss.Color("#727272"),62- "Poison": lipgloss.Color("#634BD0"),63- "Water": lipgloss.Color("#439F8E"),70+ dimTypeColors := map[string]color.Color{71+ Bug: lipgloss.Color("#97AD64"),72+ Electric: lipgloss.Color("#FCFF5F"),73+ Fire: lipgloss.Color("#BA5F75"),74+ Flying: lipgloss.Color("#C97AB2"),75+ Grass: lipgloss.Color("#59B980"),76+ Ground: lipgloss.Color("#C77252"),77+ Normal: lipgloss.Color("#727272"),78+ Poison: lipgloss.Color("#634BD0"),79+ Water: lipgloss.Color("#439F8E"),80 }81 headers := []string{"#", "NAME", "TYPE 1", "TYPE 2", "JAPANESE", "OFFICIAL ROM."}82 rows := [][]string{67- {"1", "Bulbasaur", "Grass", "Poison", "フシギダネ", "Bulbasaur"},68- {"2", "Ivysaur", "Grass", "Poison", "フシギソウ", "Ivysaur"},69- {"3", "Venusaur", "Grass", "Poison", "フシギバナ", "Venusaur"},70- {"4", "Charmander", "Fire", "", "ヒトカゲ", "Hitokage"},71- {"5", "Charmeleon", "Fire", "", "リザード", "Lizardo"},72- {"6", "Charizard", "Fire", "Flying", "リザードン", "Lizardon"},73- {"7", "Squirtle", "Water", "", "ゼニガメ", "Zenigame"},74- {"8", "Wartortle", "Water", "", "カメール", "Kameil"},75- {"9", "Blastoise", "Water", "", "カメックス", "Kamex"},76- {"10", "Caterpie", "Bug", "", "キャタピー", "Caterpie"},77- {"11", "Metapod", "Bug", "", "トランセル", "Trancell"},78- {"12", "Butterfree", "Bug", "Flying", "バタフリー", "Butterfree"},79- {"13", "Weedle", "Bug", "Poison", "ビードル", "Beedle"},80- {"14", "Kakuna", "Bug", "Poison", "コクーン", "Cocoon"},81- {"15", "Beedrill", "Bug", "Poison", "スピアー", "Spear"},82- {"16", "Pidgey", "Normal", "Flying", "ポッポ", "Poppo"},83- {"17", "Pidgeotto", "Normal", "Flying", "ピジョン", "Pigeon"},84- {"18", "Pidgeot", "Normal", "Flying", "ピジョット", "Pigeot"},85- {"19", "Rattata", "Normal", "", "コラッタ", "Koratta"},86- {"20", "Raticate", "Normal", "", "ラッタ", "Ratta"},87- {"21", "Spearow", "Normal", "Flying", "オニスズメ", "Onisuzume"},88- {"22", "Fearow", "Normal", "Flying", "オニドリル", "Onidrill"},89- {"23", "Ekans", "Poison", "", "アーボ", "Arbo"},90- {"24", "Arbok", "Poison", "", "アーボック", "Arbok"},91- {"25", "Pikachu", "Electric", "", "ピカチュウ", "Pikachu"},92- {"26", "Raichu", "Electric", "", "ライチュウ", "Raichu"},93- {"27", "Sandshrew", "Ground", "", "サンド", "Sand"},94- {"28", "Sandslash", "Ground", "", "サンドパン", "Sandpan"},83+ {"1", "Bulbasaur", Grass, Poison, "フシギダネ", "Bulbasaur"},84+ {"2", "Ivysaur", Grass, Poison, "フシギソウ", "Ivysaur"},85+ {"3", "Venusaur", Grass, Poison, "フシギバナ", "Venusaur"},86+ {"4", "Charmander", Fire, None, "ヒトカゲ", "Hitokage"},87+ {"5", "Charmeleon", Fire, None, "リザード", "Lizardo"},88+ {"6", "Charizard", Fire, Flying, "リザードン", "Lizardon"},89+ {"7", "Squirtle", Water, None, "ゼニガメ", "Zenigame"},90+ {"8", "Wartortle", Water, None, "カメール", "Kameil"},91+ {"9", "Blastoise", Water, None, "カメックス", "Kamex"},92+ {"10", "Caterpie", Bug, None, "キャタピー", "Caterpie"},93+ {"11", "Metapod", Bug, None, "トランセル", "Trancell"},94+ {"12", "Butterfree", Bug, Flying, "バタフリー", "Butterfree"},95+ {"13", "Weedle", Bug, Poison, "ビードル", "Beedle"},96+ {"14", "Kakuna", Bug, Poison, "コクーン", "Cocoon"},97+ {"15", "Beedrill", Bug, Poison, "スピアー", "Spear"},98+ {"16", "Pidgey", Normal, Flying, "ポッポ", "Poppo"},99+ {"17", "Pidgeotto", Normal, Flying, "ピジョン", "Pigeon"},100+ {"18", "Pidgeot", Normal, Flying, "ピジョット", "Pigeot"},101+ {"19", "Rattata", Normal, None, "コラッタ", "Koratta"},102+ {"20", "Raticate", Normal, None, "ラッタ", "Ratta"},103+ {"21", "Spearow", Normal, Flying, "オニスズメ", "Onisuzume"},104+ {"22", "Fearow", Normal, Flying, "オニドリル", "Onidrill"},105+ {"23", "Ekans", Poison, None, "アーボ", "Arbo"},106+ {"24", "Arbok", Poison, None, "アーボック", "Arbok"},107+ {"25", "Pikachu", Electric, None, "ピカチュウ", "Pikachu"},108+ {"26", "Raichu", Electric, None, "ライチュウ", "Raichu"},109+ {"27", "Sandshrew", Ground, None, "サンド", "Sand"},110+ {"28", "Sandslash", Ground, None, "サンドパン", "Sandpan"},111 }112 113 t := table.New().114 Headers(headers...).115 Rows(rows...).116 Border(lipgloss.NormalBorder()).101- BorderStyle(re.NewStyle().Foreground(lipgloss.Color("238"))).117+ BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("238"))).118 StyleFunc(func(row, col int) lipgloss.Style {119 if row == 0 {120 return headerStyle121 }33 unmodified lines155 return baseStyle.Foreground(lipgloss.Color("252"))156 }).157 Border(lipgloss.ThickBorder())158 143- m := model{t}144- if _, err := tea.NewProgram(m, tea.WithAltScreen()).Run(); err != nil {159+ if _, err := tea.NewProgram(model{t}).Run(); err != nil {160 fmt.Println("Error running program:", err)161 os.Exit(1)162 }163 }modified:examples/tabs/main.go+47 added-18 removed
3 unmodified lines4 "fmt"5 "os"6 "strings"7 8- tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/lipgloss"8+ tea "charm.land/bubbletea/v2"9+ "charm.land/lipgloss/v2"10 )11 12+type styles struct {13+ doc lipgloss.Style14+ highlight lipgloss.Style15+ inactiveTab lipgloss.Style16+ activeTab lipgloss.Style17+ window lipgloss.Style18+}19+20+func newStyles(bgIsDark bool) *styles {21+ lightDark := lipgloss.LightDark(bgIsDark)22+23+ inactiveTabBorder := tabBorderWithBottom("┴", "─", "┴")24+ activeTabBorder := tabBorderWithBottom("┘", " ", "└")25+ highlightColor := lightDark(lipgloss.Color("#874BFD"), lipgloss.Color("#7D56F4"))26+27+ s := new(styles)28+ s.doc = lipgloss.NewStyle().29+ Padding(1, 2, 1, 2)30+ s.inactiveTab = lipgloss.NewStyle().31+ Border(inactiveTabBorder, true).32+ BorderForeground(highlightColor).33+ Padding(0, 1)34+ s.activeTab = s.inactiveTab.35+ Border(activeTabBorder, true)36+ s.window = lipgloss.NewStyle().37+ BorderForeground(highlightColor).38+ Padding(2, 0).39+ Align(lipgloss.Center).40+ Border(lipgloss.NormalBorder()).41+ UnsetBorderTop()42+ return s43+}44+45 type model struct {46 Tabs []string47 TabContent []string48+ styles *styles49 activeTab int50 }51 52 func (m model) Init() tea.Cmd {1 unmodified line54 }55 56 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {57 switch msg := msg.(type) {24- case tea.KeyMsg:58+ case tea.KeyPressMsg:59 switch keypress := msg.String(); keypress {60 case "ctrl+c", "q":61 return m, tea.Quit62 case "right", "l", "n", "tab":15 unmodified lines78 border.BottomRight = right79 return border80 }81 48-var (49- inactiveTabBorder = tabBorderWithBottom("┴", "─", "┴")50- activeTabBorder = tabBorderWithBottom("┘", " ", "└")51- docStyle = lipgloss.NewStyle().Padding(1, 2, 1, 2)52- highlightColor = lipgloss.AdaptiveColor{Light: "#874BFD", Dark: "#7D56F4"}53- inactiveTabStyle = lipgloss.NewStyle().Border(inactiveTabBorder, true).BorderForeground(highlightColor).Padding(0, 1)54- activeTabStyle = inactiveTabStyle.Border(activeTabBorder, true)55- windowStyle = lipgloss.NewStyle().BorderForeground(highlightColor).Padding(2, 0).Align(lipgloss.Center).Border(lipgloss.NormalBorder()).UnsetBorderTop()56-)82+func (m model) View() tea.View {83+ if m.styles == nil {84+ return tea.NewView("")85+ }86 58-func (m model) View() string {87 doc := strings.Builder{}88+ s := m.styles89 90 var renderedTabs []string91 92 for i, t := range m.Tabs {93 var style lipgloss.Style94 isFirst, isLast, isActive := i == 0, i == len(m.Tabs)-1, i == m.activeTab95 if isActive {67- style = activeTabStyle96+ style = s.activeTab97 } else {69- style = inactiveTabStyle98+ style = s.inactiveTab99 }100 border, _, _, _, _ := style.GetBorder()101 if isFirst && isActive {102 border.BottomLeft = "│"10 unmodified lines113 114 row := lipgloss.JoinHorizontal(lipgloss.Top, renderedTabs...)115 doc.WriteString(row)116 doc.WriteString("\n")88- doc.WriteString(windowStyle.Width((lipgloss.Width(row) - windowStyle.GetHorizontalFrameSize())).Render(m.TabContent[m.activeTab]))89- return docStyle.Render(doc.String())117+ doc.WriteString(s.window.Width((lipgloss.Width(row))).Render(m.TabContent[m.activeTab]))118+ return tea.NewView(s.doc.Render(doc.String()))119 }120 121 func main() {122 tabs := []string{"Lip Gloss", "Blush", "Eye Shadow", "Mascara", "Foundation"}123 tabContent := []string{"Lip Gloss Tab", "Blush Tab", "Eye Shadow Tab", "Mascara Tab", "Foundation Tab"}95- m := model{Tabs: tabs, TabContent: tabContent}124+ m := model{Tabs: tabs, TabContent: tabContent, styles: newStyles(true)} // default to dark styles.125 if _, err := tea.NewProgram(m).Run(); err != nil {126 fmt.Println("Error running program:", err)127 os.Exit(1)128 }1 unmodified linemodified:examples/textarea/main.go+43 added-14 removed
2 unmodified lines3 // A simple program demonstrating the textarea component from the Bubbles4 // component library.5 6 import (7- "fmt"7 "log"8+ "strings"9 10- "github.com/charmbracelet/bubbles/textarea"11- tea "github.com/charmbracelet/bubbletea"10+ "charm.land/bubbles/v2/textarea"11+ tea "charm.land/bubbletea/v2"12+ "charm.land/lipgloss/v2"13 )14 15 func main() {16 p := tea.NewProgram(initialModel())12 unmodified lines29 30 func initialModel() model {31 ti := textarea.New()32 ti.Placeholder = "Once upon a time..."33+ ti.SetVirtualCursor(false)34+ ti.SetStyles(textarea.DefaultStyles(true)) // default to dark styles.35 ti.Focus()36 37 return model{38 textarea: ti,1 unmodified line40 }41 }42 43 func (m model) Init() tea.Cmd {41- return textarea.Blink44+ return tea.Batch(textarea.Blink, tea.RequestBackgroundColor)45 }46 47 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {48 var cmds []tea.Cmd49 var cmd tea.Cmd50 51 switch msg := msg.(type) {49- case tea.KeyMsg:50- switch msg.Type {51- case tea.KeyEsc:52+ case tea.BackgroundColorMsg:53+ // Update styling now that we know the background color.54+ m.textarea.SetStyles(textarea.DefaultStyles(msg.IsDark()))55+56+ case tea.KeyPressMsg:57+ switch msg.String() {58+ case "esc":59 if m.textarea.Focused() {60 m.textarea.Blur()61 }55- case tea.KeyCtrlC:62+ case "ctrl+c":63 return m, tea.Quit64 default:65 if !m.textarea.Focused() {66 cmd = m.textarea.Focus()67 cmds = append(cmds, cmd)68 }69 }70 64- // We handle errors just like any other message71+ // We handle errors just like any other message72 case errMsg:73 m.err = msg74 return m, nil75 }2 unmodified lines78 cmds = append(cmds, cmd)79 return m, tea.Batch(cmds...)80 }81 75-func (m model) View() string {76- return fmt.Sprintf(77- "Tell me a story.\n\n%s\n\n%s",82+func (m model) headerView() string {83+ return "Tell me a story.\n"84+}85+86+func (m model) View() tea.View {87+ const (88+ footer = "\n(ctrl+c to quit)\n"89+ )90+91+ var c *tea.Cursor92+ if !m.textarea.VirtualCursor() {93+ c = m.textarea.Cursor()94+95+ // Set the y offset of the cursor based on the position of the textarea96+ // in the application.97+ offset := lipgloss.Height(m.headerView())98+ c.Y += offset99+ }100+101+ f := strings.Join([]string{102+ m.headerView(),103 m.textarea.View(),79- "(ctrl+c to quit)",80- ) + "\n\n"104+ footer,105+ }, "\n")106+107+ v := tea.NewView(f)108+ v.Cursor = c109+ return v110 }modified:examples/textinput/main.go+29 added-22 removed
2 unmodified lines3 // A simple program demonstrating the text input component from the Bubbles4 // component library.5 6 import (7- "fmt"7 "log"8 10- "github.com/charmbracelet/bubbles/textinput"11- tea "github.com/charmbracelet/bubbletea"9+ "charm.land/bubbles/v2/textinput"10+ tea "charm.land/bubbletea/v2"11+ "charm.land/lipgloss/v2"12 )13 14 func main() {15 p := tea.NewProgram(initialModel())8 unmodified lines24 25 type model struct {26 textInput textinput.Model27 err error28+ quitting bool29 }30 31 func initialModel() model {32 ti := textinput.New()33 ti.Placeholder = "Pikachu"34+ ti.SetVirtualCursor(false)35 ti.Focus()36 ti.CharLimit = 15635- ti.Width = 2037+ ti.SetWidth(20)38 37- return model{38- textInput: ti,39- err: nil,40- }39+ return model{textInput: ti}40 }41 42 func (m model) Init() tea.Cmd {43 return textinput.Blink2 unmodified lines46 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {47 var cmd tea.Cmd48 49 switch msg := msg.(type) {51- case tea.KeyMsg:52- switch msg.Type {53- case tea.KeyEnter, tea.KeyCtrlC, tea.KeyEsc:50+ case tea.KeyPressMsg:51+ switch msg.String() {52+ case "enter", "ctrl+c", "esc":53+ m.quitting = true54 return m, tea.Quit55 }56-57- // We handle errors just like any other message58- case errMsg:59- m.err = msg60- return m, nil56 }57 58 m.textInput, cmd = m.textInput.Update(msg)59 return m, cmd60 }61 67-func (m model) View() string {68- return fmt.Sprintf(69- "What’s your favorite Pokémon?\n\n%s\n\n%s",70- m.textInput.View(),71- "(esc to quit)",72- ) + "\n"62+func (m model) View() tea.View {63+ var c *tea.Cursor64+ if !m.textInput.VirtualCursor() {65+ c = m.textInput.Cursor()66+ c.Y += lipgloss.Height(m.headerView())67+ }68+69+ str := lipgloss.JoinVertical(lipgloss.Top, m.headerView(), m.textInput.View(), m.footerView())70+ if m.quitting {71+ str += "\n"72+ }73+74+ v := tea.NewView(str)75+ v.Cursor = c76+ return v77 }78+79+func (m model) headerView() string { return "What’s your favorite Pokémon?\n" }80+func (m model) footerView() string { return "\n(esc to quit)" }modified:examples/textinputs/main.go+34 added-16 removed
6 unmodified lines7 "fmt"8 "os"9 "strings"10 11- "github.com/charmbracelet/bubbles/cursor"12- "github.com/charmbracelet/bubbles/textinput"13- tea "github.com/charmbracelet/bubbletea"14- "github.com/charmbracelet/lipgloss"11+ "charm.land/bubbles/v2/cursor"12+ "charm.land/bubbles/v2/textinput"13+ tea "charm.land/bubbletea/v2"14+ "charm.land/lipgloss/v2"15 )16 17 var (18 focusedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))10 unmodified lines29 type model struct {30 focusIndex int31 inputs []textinput.Model32 cursorMode cursor.Mode33+ quitting bool34 }35 36 func initialModel() model {37 m := model{2 unmodified lines40 41 var t textinput.Model42 for i := range m.inputs {43 t = textinput.New()43- t.Cursor.Style = cursorStyle44 t.CharLimit = 3245 46+ s := t.Styles()47+ s.Cursor.Color = lipgloss.Color("205")48+ s.Focused.Prompt = focusedStyle49+ s.Focused.Text = focusedStyle50+ s.Blurred.Prompt = blurredStyle51+ s.Focused.Text = focusedStyle52+ t.SetStyles(s)53+54 switch i {55 case 0:56 t.Placeholder = "Nickname"57 t.Focus()50- t.PromptStyle = focusedStyle51- t.TextStyle = focusedStyle58 case 1:59 t.Placeholder = "Email"60 t.CharLimit = 6461 case 2:13 unmodified lines75 }76 77 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {78 switch msg := msg.(type) {73- case tea.KeyMsg:79+ case tea.KeyPressMsg:80 switch msg.String() {81 case "ctrl+c", "esc":82+ m.quitting = true83 return m, tea.Quit84 85 // Change cursor mode86 case "ctrl+r":2 unmodified lines89 m.cursorMode = cursor.CursorBlink90 }91 cmds := make([]tea.Cmd, len(m.inputs))92 for i := range m.inputs {86- cmds[i] = m.inputs[i].Cursor.SetMode(m.cursorMode)93+ s := m.inputs[i].Styles()94+ s.Cursor.Blink = m.cursorMode == cursor.CursorBlink95+ m.inputs[i].SetStyles(s)96 }97 return m, tea.Batch(cmds...)98 99 // Set focus to next input23 unmodified lines123 for i := 0; i <= len(m.inputs)-1; i++ {124 if i == m.focusIndex {125 // Set focused state126 cmds[i] = m.inputs[i].Focus()118- m.inputs[i].PromptStyle = focusedStyle119- m.inputs[i].TextStyle = focusedStyle127 continue128 }129 // Remove focused state130 m.inputs[i].Blur()124- m.inputs[i].PromptStyle = noStyle125- m.inputs[i].TextStyle = noStyle131 }132 133 return m, tea.Batch(cmds...)134 }16 unmodified lines151 152 return tea.Batch(cmds...)153 }154 150-func (m model) View() string {155+func (m model) View() tea.View {156 var b strings.Builder157+ var c *tea.Cursor158 153- for i := range m.inputs {159+ for i, in := range m.inputs {160 b.WriteString(m.inputs[i].View())161 if i < len(m.inputs)-1 {162 b.WriteRune('\n')163 }164+ if m.cursorMode != cursor.CursorHide && in.Focused() {165+ c = in.Cursor()166+ if c != nil {167+ c.Y += i168+ }169+ }170 }171 172 button := &blurredButton173 if m.focusIndex == len(m.inputs) {4 unmodified lines178 b.WriteString(helpStyle.Render("cursor mode is "))179 b.WriteString(cursorModeHelpStyle.Render(m.cursorMode.String()))180 b.WriteString(helpStyle.Render(" (ctrl+r to change style)"))181 170- return b.String()182+ if m.quitting {183+ b.WriteRune('\n')184+ }185+186+ v := tea.NewView(b.String())187+ v.Cursor = c188+ return v189 }190 191 func main() {192 if _, err := tea.NewProgram(initialModel()).Run(); err != nil {4 unmodified linesmodified:examples/timer/main.go+8 added-8 removed
3 unmodified lines4 "fmt"5 "os"6 "time"7 8- "github.com/charmbracelet/bubbles/help"9- "github.com/charmbracelet/bubbles/key"10- "github.com/charmbracelet/bubbles/timer"11- tea "github.com/charmbracelet/bubbletea"8+ "charm.land/bubbles/v2/help"9+ "charm.land/bubbles/v2/key"10+ "charm.land/bubbles/v2/timer"11+ tea "charm.land/bubbletea/v2"12 )13 14 const timeout = time.Second * 515 32 unmodified lines48 case timer.TimeoutMsg:49 m.quitting = true50 return m, tea.Quit51 52- case tea.KeyMsg:52+ case tea.KeyPressMsg:53 switch {54 case key.Matches(msg, m.keymap.quit):55 m.quitting = true56 return m, tea.Quit15 unmodified lines72 m.keymap.quit,73 })74 }75 76-func (m model) View() string {76+func (m model) View() tea.View {77 // For a more detailed timer view you could read m.timer.Timeout to get78 // the remaining time as a time.Duration and skip calling m.timer.View()79 // entirely.80 s := m.timer.View()5 unmodified lines86 if !m.quitting {87 s = "Exiting in " + s88 s += m.helpView()89 }90- return s90+ return tea.NewView(s)91 }92 93 func main() {94 m := model{95- timer: timer.NewWithInterval(timeout, time.Millisecond),95+ timer: timer.New(timeout, timer.WithInterval(time.Millisecond)),96 keymap: keymap{97 start: key.NewBinding(98 key.WithKeys("s"),99 key.WithHelp("s", "start"),23 unmodified linesmodified:examples/tui-daemon-combo/main.go+8 added-8 removed
7 unmodified lines8 "math/rand"9 "os"10 "time"11 12- "github.com/charmbracelet/bubbles/spinner"13- tea "github.com/charmbracelet/bubbletea"14- "github.com/charmbracelet/lipgloss"12+ "charm.land/bubbles/v2/spinner"13+ tea "charm.land/bubbletea/v2"14+ "charm.land/lipgloss/v2"15 "github.com/mattn/go-isatty"16 )17 18 var (4 unmodified lines23 func main() {24 var (25 daemonMode bool26 showHelp bool27- opts []tea.ProgramOption27 )28 29 flag.BoolVar(&daemonMode, "d", false, "run as a daemon")30 flag.BoolVar(&showHelp, "h", false, "show help")3 unmodified lines34 flag.Usage()35 os.Exit(0)36 }37 38+ opts := []tea.ProgramOption{}39 if daemonMode || !isatty.IsTerminal(os.Stdout.Fd()) {40 // If we're in daemon mode don't render the TUI41- opts = []tea.ProgramOption{tea.WithoutRenderer()}41+ opts = append(opts, tea.WithoutRenderer())42 } else {43 // If we're in TUI mode, discard log output44 log.SetOutput(io.Discard)45 }37 unmodified lines83 }84 85 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {86 switch msg := msg.(type) {87- case tea.KeyMsg:87+ case tea.KeyPressMsg:88 m.quitting = true89 return m, tea.Quit90 case spinner.TickMsg:91 var cmd tea.Cmd9 unmodified lines101 return m, nil102 }103 }104 105-func (m model) View() string {105+func (m model) View() tea.View {106 s := "\n" +107 m.spinner.View() + " Doing some work...\n\n"108 109 for _, res := range m.results {9 unmodified lines119 if m.quitting {120 s += "\n"121 }122 123- return mainStyle.Render(s)123+ return tea.NewView(mainStyle.Render(s))124 }125 126 // processFinishedMsg is sent when a pretend process completes.127 type processFinishedMsg time.Duration12 unmodified linesadded:examples/vanish/main.go+36 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "charm.land/bubbletea/v2"8+)9+10+type model bool11+12+func (m model) Init() tea.Cmd {13+ return nil14+}15+16+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {17+ if _, ok := msg.(tea.KeyPressMsg); ok {18+ m = true19+ return m, tea.Quit20+ }21+ return m, nil22+}23+24+func (m model) View() tea.View {25+ if m {26+ return tea.NewView("")27+ }28+ return tea.NewView("Press any key to quit.\n(When this program quits, it will vanish without a trace.)")29+}30+31+func main() {32+ p := tea.NewProgram(model(false))33+ if _, err := p.Run(); err != nil {34+ fmt.Fprintln(os.Stderr, "Oh no:", err)35+ }36+}modified:examples/views/main.go+9 added-9 removed
11 unmodified lines12 "strconv"13 "strings"14 "time"15 16- tea "github.com/charmbracelet/bubbletea"17- "github.com/charmbracelet/lipgloss"16+ tea "charm.land/bubbletea/v2"17+ "charm.land/lipgloss/v2"18 "github.com/fogleman/ease"19 "github.com/lucasb-eyer/go-colorful"20 )21 76 unmodified lines98 return updateChosen(msg, m)99 }100 101 // The main view, which just calls the appropriate sub-view102-func (m model) View() string {102+func (m model) View() tea.View {103 var s string104 if m.Quitting {105- return "\n See you later!\n\n"105+ return tea.NewView("\n See you later!\n\n")106 }107 if !m.Chosen {108 s = choicesView(m)109 } else {110 s = chosenView(m)111 }112- return mainStyle.Render("\n" + s + "\n\n")112+ return tea.NewView(mainStyle.Render("\n" + s + "\n"))113 }114 115 // Sub-update functions116 117 // Update loop for the first view where you're choosing a task.118 func updateChoices(msg tea.Msg, m model) (tea.Model, tea.Cmd) {119 switch msg := msg.(type) {120- case tea.KeyMsg:120+ case tea.KeyPressMsg:121 switch msg.String() {122 case "j", "down":123 m.Choice++124 if m.Choice > 3 {109 unmodified lines234 w := float64(progressBarWidth)235 236 fullSize := int(math.Round(w * percent))237 var fullCells string238- for i := 0; i < fullSize; i++ {238+ for i := range fullSize {239 fullCells += ramp[i].Render(progressFullChar)240 }241 242 emptySize := int(w) - fullSize12 unmodified lines255 for i := 0.0; i < steps; i++ {256 c := cA.BlendLuv(cB, i/steps)257 s = append(s, lipgloss.NewStyle().Foreground(lipgloss.Color(colorToHex(c))))258 }259- return259+ return s260 }261 262 // Convert a colorful.Color to a hexadecimal format.263 func colorToHex(c colorful.Color) string {6 unmodified lines270 s = strconv.FormatInt(int64(f*255), 16)271 if len(s) == 1 {272 s = "0" + s273 }274- return274+ return s275 }modified:examples/window-size/main.go+6 added-9 removed
3 unmodified lines4 5 import (6 "log"7 8- tea "github.com/charmbracelet/bubbletea"8+ tea "charm.land/bubbletea/v2"9 )10 11 func main() {12 p := tea.NewProgram(model{})9 unmodified lines22 }23 24 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {25 switch msg := msg.(type) {26- case tea.KeyMsg:26+ case tea.KeyPressMsg:27 if s := msg.String(); s == "ctrl+c" || s == "q" || s == "esc" {28 return m, tea.Quit29 }30+ return m, tea.RequestWindowSize31 31- return m, tea.WindowSize()32-32 case tea.WindowSizeMsg:34- return m, tea.Printf("%dx%d", msg.Width, msg.Height)33+ return m, tea.Printf("The window size is: %dx%d", msg.Width, msg.Height)34 }35 36 return m, nil37 }38 40-func (m model) View() string {41- s := "When you're done press q to quit. Press any other key to query the window-size.\n"42-43- return s39+func (m model) View() tea.View {40+ return tea.NewView("\nWhen you're done press q to quit.\nPress any other key to query the window-size.\n")41 }modified:examples/go.mod+16 added-23 removed
1 module examples2 3-go 1.24.23+go 1.25.24 5-toolchain go1.24.55+replace charm.land/bubbletea/v2 => ../6 7 require (8- github.com/charmbracelet/bubbles v1.0.09- github.com/charmbracelet/bubbletea v1.3.1010- github.com/charmbracelet/glamour v0.10.08+ charm.land/bubbles/v2 v2.0.0-beta.1.0.20251110211018-84a82dfeeed89+ charm.land/bubbletea/v2 v2.0.0-rc.1.0.20251106192006-06c0cda318b310+ charm.land/lipgloss/v2 v2.0.0-beta.3.0.20251205162909-7869489d897111+ github.com/charmbracelet/colorprofile v0.4.112+ github.com/charmbracelet/glamour/v2 v2.0.0-20251106195642-800eb817593013 github.com/charmbracelet/harmonica v0.2.012- github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c66083413- github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b2814+ github.com/charmbracelet/x/ansi v0.11.615+ github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb16 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf177617 github.com/lucasb-eyer/go-colorful v1.3.018 github.com/mattn/go-isatty v0.0.2019+ github.com/segmentio/ksuid v1.0.420 )21 22 require (23 github.com/alecthomas/chroma/v2 v2.14.0 // indirect24 github.com/atotto/clipboard v0.1.4 // indirect22- github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect23- github.com/aymanbagabas/go-udiff v0.3.1 // indirect25 github.com/aymerick/douceur v0.2.0 // indirect25- github.com/charmbracelet/colorprofile v0.4.1 // indirect26- github.com/charmbracelet/x/ansi v0.11.6 // indirect27- github.com/charmbracelet/x/cellbuf v0.0.15 // indirect28- github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 // indirect26+ github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 // indirect27 github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect28 github.com/charmbracelet/x/term v0.2.2 // indirect29+ github.com/charmbracelet/x/termios v0.1.1 // indirect30+ github.com/charmbracelet/x/windows v0.2.2 // indirect31 github.com/clipperhouse/displaywidth v0.9.0 // indirect32 github.com/clipperhouse/stringish v0.1.1 // indirect33 github.com/clipperhouse/uax29/v2 v2.5.0 // indirect34 github.com/dlclark/regexp2 v1.11.0 // indirect35 github.com/dustin/go-humanize v1.0.1 // indirect36- github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect36 github.com/gorilla/css v1.0.1 // indirect38- github.com/mattn/go-localereader v0.0.1 // indirect37 github.com/mattn/go-runewidth v0.0.19 // indirect38 github.com/microcosm-cc/bluemonday v1.0.27 // indirect41- github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect39 github.com/muesli/cancelreader v0.2.2 // indirect43- github.com/muesli/reflow v0.3.0 // indirect44- github.com/muesli/termenv v0.16.0 // indirect40 github.com/rivo/uniseg v0.4.7 // indirect41 github.com/sahilm/fuzzy v0.1.1 // indirect42 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect43 github.com/yuin/goldmark v1.7.8 // indirect44 github.com/yuin/goldmark-emoji v1.0.5 // indirect50- golang.org/x/net v0.38.0 // indirect51- golang.org/x/sys v0.38.0 // indirect52- golang.org/x/term v0.31.0 // indirect45+ golang.org/x/net v0.39.0 // indirect46+ golang.org/x/sync v0.19.0 // indirect47+ golang.org/x/sys v0.40.0 // indirect48 golang.org/x/text v0.24.0 // indirect49 )55-56-replace github.com/charmbracelet/bubbletea => ../modified:examples/go.sum+24 added-34 removed
1+charm.land/bubbles/v2 v2.0.0-beta.1.0.20251110211018-84a82dfeeed8 h1:2bzaNBvZHgpLjxlQTDjoeY0YGjQtMflWiDZMEbviiRE=2+charm.land/bubbles/v2 v2.0.0-beta.1.0.20251110211018-84a82dfeeed8/go.mod h1:5AbN6cEd/47gkEf8TgiQ2O3RZ5QxMS14l9W+7F9fPC4=3+charm.land/lipgloss/v2 v2.0.0-beta.3.0.20251205162909-7869489d8971 h1:xZFcNsJMiIDbFtWRyDmkKNk1sjojfaom4Zoe0cyH/8c=4+charm.land/lipgloss/v2 v2.0.0-beta.3.0.20251205162909-7869489d8971/go.mod h1:i61Y3FmdbcBNSKa+pKB3DaE4uVQmBLMs/xlvRyHcXAE=5 github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=6 github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=7 github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=8 github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=2 unmodified lines11 github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=12 github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=13 github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=14 github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=11-github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=12-github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=15 github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=16 github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=17 github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=18 github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=17-github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=18-github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=19 github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=20 github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=21-github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY=22-github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk=21+github.com/charmbracelet/glamour/v2 v2.0.0-20251106195642-800eb8175930 h1:+47Z2jVAWPSLGjPRbfZizW3OpcAYsu7EUk2DR+66FyM=22+github.com/charmbracelet/glamour/v2 v2.0.0-20251106195642-800eb8175930/go.mod h1:izs11tnkYaT3DTEH2E0V/lCb18VGZ7k9HLYEGuvgXGA=23 github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=24 github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=25-github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE=26-github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA=25+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA=26+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98=27 github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=28 github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=29-github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=30-github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=31-github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=32-github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=29+github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb h1:oTM8tZxV7FY0ehvYjFuICouuhzE08UZYNqUIp/lDQdY=30+github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0=31+github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=32+github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=33 github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=34 github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU=35-github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28 h1:sOWKNRjt8uOEVgPiJVIJCse1+mUDM2F/vYY6W0Go640=36-github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28/go.mod h1:l1w+LTJZCCozeGzMEWGxRw6Mo2DfcZUvupz8HGubdes=35 github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=36 github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=37+github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=38+github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=39+github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=40+github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=41 github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=42 github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=43 github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=44 github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=2 unmodified lines47 github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=48 github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=49 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=50 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=49-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=50-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=51 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=52 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=53 github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=54 github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=4 unmodified lines59 github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=60 github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=61 github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=62 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=63-github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=64-github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=65-github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=63 github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=64 github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=65 github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=66 github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=70-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=71-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=67 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=68 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=74-github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=75-github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=76-github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=77-github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=78-github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=79-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=69 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=70 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=71 github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=72 github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=73+github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=74+github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=75 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=76 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=77 github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=78 github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=1 unmodified line80 github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=81 github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=82 golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=83 golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=93-golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=94-golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=95-golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=84+golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=85+golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=86+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=87+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=88 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=97-golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=98-golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=99-golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=100-golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=89+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=90+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=91 golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=92 golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=modified:examples/README.md+5 added-5 removed
25 unmodified lines26 <a href="./composable-views/main.go">27 <img width="750" src="./composable-views/composable-views.gif" />28 </a>29 30-### Credit Card Form30+### ISBN Book Form31 32-The `credit-card-form` example demonstrates how to build a multi-step form with33-`textinputs` bubbles and validation on the inputs.32+The `isbn-form` example demonstrates how to build a multi-step form with33+`textinput` bubbles and validation on the inputs.34 35-<a href="./credit-card-form/main.go">36- <img width="750" src="./credit-card-form/credit-card-form.gif" />35+<a href="./isbn-form/main.go">36+ <img width="750" src="./isbn-form/isbn-form.gif" />37 </a>38 39 ### Debounce40 288 unmodified linesadded:testdata/TestClearMsg/bg_fg_cur_color.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$p]10;?]11;?]12;?added:testdata/TestClearMsg/clear_screen.golden+1 added
1+[?25l
[?2004h[>4;2m[=1;1u[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$padded:testdata/TestClearMsg/read_set_clipboard.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$p]52;c;?]52;c;c3VjY2Vzcw==added:testdata/TestViewModel/altscreen_autoexit.golden+1 added
1+[>4m[=0;1u[?1049h[?25l[?2004h[>4;2m[=1;1u[H[2Jsuccess[>4m[=0;1u
[24d[?1049l[?25h[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/altscreen.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/bg_set_color.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u]11;#ffffff
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l]111[?2026$p[?2027$padded:testdata/TestViewModel/bp_stop_start.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/cursor_hide.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/cursor_hideshow.golden+1 added
1+[?2004h[>4;2m[=1;1u[1 q
[Jsuccess
[?25h[>4m[=0;1u[J[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/kitty_stop_startreleases.golden+1 added
1+[?25l[?2004h[>4;2m[=3;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$padded:testdata/TestViewModel/mouse_allmotion.golden+1 added
1+[?25l[?2004h[?1003h[?1006h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$padded:testdata/TestViewModel/mouse_cellmotion.golden+1 added
1+[?25l[?2004h[?1002h[?1006h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$padded:testdata/TestViewModel/mouse_disable.golden+1 added
1+[?25l[?2004h[>4;2m[=1;1u
[Jsuccess[>4m[=0;1u
[J[?25h[?2004l[?2026$p[?2027$pmodified:tutorials/basics/main.go+11 added-7 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- tea "github.com/charmbracelet/bubbletea"7+ tea "charm.land/bubbletea/v2"8 )9 10 type model struct {11 cursor int2 unmodified lines14 }15 16 func initialModel() model {17 return model{18+ // Our to-do list is a grocery list19 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},20 21 // A map which indicates which choices are selected. We're using21- // the map like a mathematical set. The keys refer to the indexes22+ // the map like a mathematical set. The keys refer to the indexes23 // of the `choices` slice, above.24 selected: make(map[int]struct{}),25 }26 }27 28 func (m model) Init() tea.Cmd {28- return tea.SetWindowTitle("Grocery List")29+ return nil30 }31 32 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {33 switch msg := msg.(type) {33- case tea.KeyMsg:34+ case tea.KeyPressMsg:35 switch msg.String() {36 case "ctrl+c", "q":37 return m, tea.Quit38 case "up", "k":3 unmodified lines42 case "down", "j":43 if m.cursor < len(m.choices)-1 {44 m.cursor++45 }45- case "enter", " ":46+ case "enter", "space":47 _, ok := m.selected[m.cursor]48 if ok {49 delete(m.selected, m.cursor)50 } else {4 unmodified lines55 56 return m, nil57 }58 58-func (m model) View() string {59+func (m model) View() tea.View {60 s := "What should we buy at the market?\n\n"61 62 for i, choice := range m.choices {63 cursor := " "10 unmodified lines74 }75 76 s += "\nPress q to quit.\n"77 78+ v := tea.NewView(s)79+ v.WindowTitle = "Grocery List"80+77- return s81+ return v82 }83 84 func main() {85 p := tea.NewProgram(initialModel())5 unmodified linesmodified:tutorials/basics/README.md+38 added-38 removed
1-Bubble Tea Basics2-=================1+# Bubble Tea Basics2 3 Bubble Tea is based on the functional design paradigms of [The Elm5-Architecture][elm], which happens to work nicely with Go. It's a delightful way4+Architecture][elm], which happens to work nicely with Go. It’s a delightful way5 to build applications.6 7 This tutorial assumes you have a working knowledge of Go.8 9 By the way, the non-annotated source code for this program is available10 [on GitHub][tut-source].11 12 [elm]: https://guide.elm-lang.org/architecture/14-[tut-source]:https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics13+[tut-source]: https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics14 16-## Enough! Let's get to it.15+## Enough! Let’s get to it.16 18-For this tutorial, we're making a shopping list.17+For this tutorial, we’re making a shopping list.18 20-To start we'll define our package and import some libraries. Our only external21-import will be the Bubble Tea library, which we'll call `tea` for short.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 30- tea "github.com/charmbracelet/bubbletea"29+ tea "charm.land/bubbletea/v2"30 )31 ```32 33 Bubble Tea programs are comprised of a **model** that describes the application34 state and three simple methods on that model:35 37-* **Init**, a function that returns an initial command for the application to run.38-* **Update**, a function that handles incoming events and updates the model accordingly.39-* **View**, a function that renders the UI based on the data in the model.36+- **Init**, a function that returns an initial command for the application to run.37+- **Update**, a function that handles incoming events and updates the model accordingly.38+- **View**, a function that renders the UI based on the data in the model.39 40 ## The Model41 43-So let's start by defining our model which will store our application's state.42+So let’s start by defining our model which will store our application’s state.43 It can be any type, but a `struct` usually makes the most sense.44 45 ```go46 type model struct {22 unmodified lines69 }70 }71 ```72 74-Next, we define the `Init` method. `Init` can return a `Cmd` that could perform75-some initial I/O. For now, we don't need to do any I/O, so for the command,76-we'll just return `nil`, which translates to "no command."73+After that, we’ll define the `Init` method. `Init` can return a `Cmd` that74+could perform some initial I/O. For now, we don’t need to do any I/O, so for75+the command, we’ll just return `nil`, which translates to "no command."76 77 ```go78 func (m model) Init() tea.Cmd {80- // Just return `nil`, which means "no I/O right now, please."79 return nil80 }81 ```82 83 ## The Update Method84 87-Next up is the update method. The update function is called when ”things85+Next up is the update method. The update function is called when “things86 happen.” Its job is to look at what has happened and return an updated model in87 response. It can also return a `Cmd` to make more things happen, but for now90-don't worry about that part.88+don’t worry about that part.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 3 unmodified lines96 97 We usually figure out which type of `Msg` we received with a type switch, but98 you could also use a type assertion.99 102-For now, we'll just deal with `tea.KeyMsg` messages, which are automatically103-sent to the update function when keys are pressed.100+For now, we’ll just deal with `tea.KeyPressMsg` messages, which are101+automatically sent to the update function when keys are pressed.102 103 ```go104 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {105 switch msg := msg.(type) {106 107 // Is it a key press?110- case tea.KeyMsg:108+ case tea.KeyPressMsg:109 110 // Cool, what was the actual key pressed?111 switch msg.String() {112 12 unmodified lines125 if m.cursor < len(m.choices)-1 {126 m.cursor++127 }128 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", " ":129+ // The enter key and the space bar toggle the selected state for the130+ // item that the cursor is pointing at.131+ case "enter", "space":132 _, ok := m.selected[m.cursor]133 if ok {134 delete(m.selected, m.cursor)135 } else {15 unmodified lines151 ## The View Method152 153 At last, it’s time to render our UI. Of all the methods, the view is the154 simplest. We look at the model in its current state and use it to return157-a `string`. That string is our UI!155+a `tea.View`. The view declares our UI content and, optionally, terminal156+features like full-window mode (aka, altscreen mode), mouse tracking, cursor157+position, and more.158 159 Because the view describes the entire UI of your application, you don’t have to160 worry about redrawing logic and stuff like that. Bubble Tea takes care of it161 for you.162 163 ```go164-func (m model) View() string {164+func (m model) View() tea.View {165 // The header166 s := "What should we buy at the market?\n\n"167 168 // Iterate over our choices18 unmodified lines187 // The footer188 s += "\nPress q to quit.\n"189 190 // Send the UI for rendering191- return s191+ return tea.NewView(s)192 }193 ```194 195 ## All Together Now13 unmodified lines209 210 ## What’s Next?211 212 This tutorial covers the basics of building an interactive terminal UI, but213-in the real world you'll also need to perform I/O. To learn about that have a214-look at the [Command Tutorial][cmd]. It's pretty simple.213+in the real world you’ll also need to perform I/O. To learn about that have a214+look at the [Command Tutorial][cmd]. It’s pretty simple.215 216 There are also several [Bubble Tea examples][examples] available and, of course,217 there are [Go Docs][docs].218 219 [cmd]: http://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands/220 [examples]: http://github.com/charmbracelet/bubbletea/tree/master/examples221-[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc221+[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc222 223 ## Additional Resources224 225-* [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)226-* [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)225+- [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)226+- [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)227 228 ### Feedback229 230-We'd love to hear your thoughts on this tutorial. Feel free to drop us a note!230+We’d love to hear your thoughts on this tutorial. Feel free to drop us a note!231 232-* [Twitter](https://twitter.com/charmcli)233-* [The Fediverse](https://mastodon.social/@charmcli)234-* [Discord](https://charm.sh/chat)232+- [Twitter](https://twitter.com/charmcli)233+- [The Fediverse](https://mastodon.social/@charmcli)234+- [Discord](https://charm.sh/chat)235 236-***236+---237 238 Part of [Charm](https://charm.sh).239 240 <a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>2 unmodified linesmodified:tutorials/commands/main.go+6 added-6 removed
4 unmodified lines5 "net/http"6 "os"7 "time"8 9- tea "github.com/charmbracelet/bubbletea"9+ tea "charm.land/bubbletea/v2"10 )11 12 const url = "https://charm.sh/"13 34 unmodified lines48 case errMsg:49 m.err = msg50 return m, tea.Quit51 52- case tea.KeyMsg:53- if msg.Type == tea.KeyCtrlC {52+ case tea.KeyPressMsg:53+ if msg.Mod == tea.ModCtrl && msg.Code == 'c' {54 return m, tea.Quit55 }56 }57 58 return m, nil59 }60 61-func (m model) View() string {61+func (m model) View() tea.View {62 if m.err != nil {63- return fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err)63+ return tea.NewView(fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err))64 }65 66 s := fmt.Sprintf("Checking %s ... ", url)67 if m.status > 0 {68 s += fmt.Sprintf("%d %s!", m.status, http.StatusText(m.status))69 }70- return "\n" + s + "\n\n"70+ return tea.NewView("\n" + s + "\n\n")71 }72 73 func main() {74 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesmodified:tutorials/commands/README.md+34 added-35 removed
1-Commands in Bubble Tea2-======================1+# Commands in Bubble Tea2 3 This is the second tutorial for Bubble Tea covering commands, which deal with4 I/O. The tutorial assumes you have a working knowledge of Go and a decent5 understanding of [the first tutorial][basics].2 unmodified lines8 9 [basics]: https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics10 [source]: https://github.com/charmbracelet/bubbletea/blob/master/tutorials/commands/main.go11 13-## Let's Go!12+## Let’s Go!13 15-For this tutorial we're building a very simple program that makes an HTTP14+For this tutorial we’re building a very simple program that makes an HTTP15 request to a server and reports the status code of the response.16 18-We'll import a few necessary packages and put the URL we're going to check in17+We’ll import a few necessary packages and put the URL we’re going to check in18 a `const`.19 20 ```go21 package main3 unmodified lines25 "net/http"26 "os"27 "time"28 30- tea "github.com/charmbracelet/bubbletea"29+ tea "charm.land/bubbletea/v2"30 )31 32 const url = "https://charm.sh/"33 ```34 35 ## The Model36 38-Next we'll define our model. The only things we need to store are the status37+Next we’ll define our model. The only things we need to store are the status38 code of the HTTP response and a possible error.39 40 ```go41 type model struct {8 unmodified lines50 time, ticking a timer, reading from the disk, and network stuff are all I/O and51 should be run through commands. That might sound harsh, but it will keep your52 Bubble Tea program straightforward and simple.53 55-Anyway, let's write a `Cmd` that makes a request to a server and returns the54+Anyway, let’s write a `Cmd` that makes a request to a server and returns the55 result as a `Msg`.56 57 ```go58 func checkServer() tea.Msg {20 unmodified lines79 // error interface on the message.80 func (e errMsg) Error() string { return e.err.Error() }81 ```82 84-And notice that we've defined two new `Msg` types. They can be any type, even85-an empty struct. We'll come back to them later in our update function.86-First, let's write our initialization function.83+And notice that we’ve defined two new `Msg` types. They can be any type, even84+an empty struct. We’ll come back to them later in our update function.85+First, let’s write our initialization function.86 87 ## The Initialization Method88 89 The initialization method is very simple: we return the `Cmd` we made earlier.91-Note that we don't call the function; the Bubble Tea runtime will do that when90+Note that we don’t call the function; the Bubble Tea runtime will do that when91 the time is right.92 93 ```go95-func (m model) Init() (tea.Cmd) {94+func (m model) Init() tea.Cmd {95 return checkServer96 }97 ```98 21 unmodified lines120 // we're done and want to quit.121 m.err = msg122 return m, tea.Quit123 125- case tea.KeyMsg:124+ case tea.KeyPressMsg:125 // Ctrl+c exits. Even with short running programs it's good to have126 // a quit key, just in case your logic is off. Users will be very127 // annoyed if they can't exit.129- if msg.Type == tea.KeyCtrlC {130- return m, tea.Quit131- }128+ if msg.Mod == tea.ModCtrl && msg.Code == 'c' {129+ return m, tea.Quit130+ }131 }132 133 // If we happen to get any other messages, don't do anything.134 return m, nil2 unmodified lines137 138 ## The View Function139 140 Our view is very straightforward. We look at the current model and build a142-string accordingly:141+`tea.View` accordingly:142 143 ```go145-func (m model) View() string {144+func (m model) View() tea.View {145 // If there's an error, print it out and don't do anything else.146 if m.err != nil {148- return fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err)147+ return tea.NewView(fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err))148 }149 150 // Tell the user we're doing something.151 s := fmt.Sprintf("Checking %s ... ", url)3 unmodified lines155 s += fmt.Sprintf("%d %s!", m.status, http.StatusText(m.status))156 }157 158 // Send off whatever we came up with above for rendering.160- return "\n" + s + "\n\n"159+ return tea.NewView("\n" + s + "\n\n")160 }161 ```162 163 ## Run the program164 166-The only thing left to do is run the program, so let's do that! Our initial167-model doesn't need any data at all in this case, we just initialize it with165+The only thing left to do is run the program, so let’s do that! Our initial166+model doesn’t need any data at all in this case, we just initialize it with167 a `model` struct with default values.168 169 ```go170 func main() {3 unmodified lines174 }175 }176 ```177 179-And that's that. There's one more thing that is helpful to know about178+And that’s that. There’s one more thing that is helpful to know about179 `Cmd`s, though.180 181 ## One More Thing About Commands182 184-`Cmd`s are defined in Bubble Tea as `type Cmd func() Msg`. So they're just185-functions that don't take any arguments and return a `Msg`, which can be183+`Cmd`s are defined in Bubble Tea as `type Cmd func() Msg`. So they’re just184+functions that don’t take any arguments and return a `Msg`, which can be185 any type. If you need to pass arguments to a command, you just make a function186 that returns a command. For example:187 188 ```go19 unmodified lines208 }209 ```210 211 Anyway, just make sure you do as much stuff as you can in the innermost213-function, because that's the one that runs asynchronously.212+function, because that’s the one that runs asynchronously.213 214 ## Now What?215 216 After doing this tutorial and [the previous one][basics] you should be ready to3 unmodified lines220 221 And, of course, check out the [Go Docs][docs].222 223 [bubbles]: https://github.com/charmbracelet/bubbles225-[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc224+[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc225 [examples]: https://github.com/charmbracelet/bubbletea/tree/master/examples226 227 ## Additional Resources228 230-* [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)231-* [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)229+- [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)230+- [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)231 232 ### Feedback233 235-We'd love to hear your thoughts on this tutorial. Feel free to drop us a note!234+We’d love to hear your thoughts on this tutorial. Feel free to drop us a note!235 237-* [Twitter](https://twitter.com/charmcli)238-* [The Fediverse](https://mastodon.social/@charmcli)239-* [Discord](https://charm.sh/chat)236+- [Twitter](https://twitter.com/charmcli)237+- [The Fediverse](https://mastodon.social/@charmcli)238+- [Discord](https://charm.sh/chat)239 241-***240+---241 242 Part of [Charm](https://charm.sh).243 244 <a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>2 unmodified linesmodified:tutorials/go.mod+20 added-17 removed
1 module tutorial2 3-go 1.183+go 1.24.24 5-require github.com/charmbracelet/bubbletea v0.25.05+toolchain go1.24.106 7+require charm.land/bubbletea/v2 v2.0.0-00010101000000-0000000000008+9 require (8- github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect9- github.com/charmbracelet/lipgloss v0.13.1 // indirect10- github.com/charmbracelet/x/ansi v0.4.0 // indirect11- github.com/charmbracelet/x/term v0.2.0 // indirect12- github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect13- github.com/lucasb-eyer/go-colorful v1.2.0 // indirect14- github.com/mattn/go-isatty v0.0.20 // indirect15- github.com/mattn/go-localereader v0.0.1 // indirect16- github.com/mattn/go-runewidth v0.0.15 // indirect17- github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect10+ github.com/charmbracelet/colorprofile v0.4.1 // indirect11+ github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 // indirect12+ github.com/charmbracelet/x/ansi v0.11.6 // indirect13+ github.com/charmbracelet/x/term v0.2.2 // indirect14+ github.com/charmbracelet/x/termios v0.1.1 // indirect15+ github.com/charmbracelet/x/windows v0.2.2 // indirect16+ github.com/clipperhouse/displaywidth v0.9.0 // indirect17+ github.com/clipperhouse/stringish v0.1.1 // indirect18+ github.com/clipperhouse/uax29/v2 v2.5.0 // indirect19+ github.com/lucasb-eyer/go-colorful v1.3.0 // indirect20+ github.com/mattn/go-runewidth v0.0.19 // indirect21 github.com/muesli/cancelreader v0.2.2 // indirect19- github.com/muesli/termenv v0.15.2 // indirect22 github.com/rivo/uniseg v0.4.7 // indirect21- golang.org/x/sync v0.8.0 // indirect22- golang.org/x/sys v0.26.0 // indirect23- golang.org/x/text v0.13.0 // indirect23+ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect24+ golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect25+ golang.org/x/sync v0.19.0 // indirect26+ golang.org/x/sys v0.40.0 // indirect27 )28 26-replace github.com/charmbracelet/bubbletea => ../29+replace charm.land/bubbletea/v2 => ../modified:tutorials/go.sum+34 added-31 removed
1-github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2-github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3-github.com/charmbracelet/lipgloss v0.13.1 h1:Oik/oqDTMVA01GetT4JdEC033dNzWoQHdWnHnQmXE2A=4-github.com/charmbracelet/lipgloss v0.13.1/go.mod h1:zaYVJ2xKSKEnTEEbX6uAHabh2d975RJ+0yfkFpRBz5U=5-github.com/charmbracelet/x/ansi v0.4.0 h1:NqwHA4B23VwsDn4H3VcNX1W1tOmgnvY1NDx5tOXdnOU=6-github.com/charmbracelet/x/ansi v0.4.0/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=7-github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=8-github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=9-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=10-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=11-github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=12-github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=13-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=14-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=15-github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=16-github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=17-github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=18-github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=19-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=20-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=1+github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=2+github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=3+github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=4+github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=5+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA=6+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98=7+github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=8+github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=9+github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f h1:UytXHv0UxnsDFmL/7Z9Q5SBYPwSuRLXHbwx+6LycZ2w=10+github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=11+github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=12+github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=13+github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=14+github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=15+github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=16+github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=17+github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=18+github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=19+github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=20+github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=21+github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=22+github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=23+github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=24+github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=25+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=26+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=27 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=28 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=23-github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=24-github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=25-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=29 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=30 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=28-golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=29-golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=30-golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=31-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=32-golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=33-golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=34-golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=35-golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=31+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=32+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=33+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=34+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=35+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=36+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=37+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=38+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=added:clipboard.go+70 added
1+package tea2+3+// ClipboardMsg is a clipboard read message event. This message is emitted when4+// a terminal receives an OSC52 clipboard read message event.5+type ClipboardMsg struct {6+ Content string7+ Selection byte8+}9+10+// Clipboard returns the clipboard selection type. This will be one of the11+// following values:12+//13+// - c: System clipboard.14+// - p: Primary clipboard (X11/Wayland only).15+func (e ClipboardMsg) Clipboard() byte {16+ return e.Selection17+}18+19+// String returns the string representation of the clipboard message.20+func (e ClipboardMsg) String() string {21+ return e.Content22+}23+24+// setClipboardMsg is an internal message used to set the system clipboard25+// using OSC52.26+type setClipboardMsg string27+28+// SetClipboard produces a command that sets the system clipboard using OSC52.29+// Note that OSC52 is not supported in all terminals.30+func SetClipboard(s string) Cmd {31+ return func() Msg {32+ return setClipboardMsg(s)33+ }34+}35+36+// readClipboardMsg is an internal message used to read the system clipboard37+// using OSC52.38+type readClipboardMsg struct{}39+40+// ReadClipboard produces a command that reads the system clipboard using OSC52.41+// Note that OSC52 is not supported in all terminals.42+func ReadClipboard() Msg {43+ return readClipboardMsg{}44+}45+46+// setPrimaryClipboardMsg is an internal message used to set the primary47+// clipboard using OSC52.48+type setPrimaryClipboardMsg string49+50+// SetPrimaryClipboard produces a command that sets the primary clipboard using51+// OSC52. Primary clipboard selection is a feature present in X11 and Wayland52+// only.53+// Note that OSC52 is not supported in all terminals.54+func SetPrimaryClipboard(s string) Cmd {55+ return func() Msg {56+ return setPrimaryClipboardMsg(s)57+ }58+}59+60+// readPrimaryClipboardMsg is an internal message used to read the primary61+// clipboard using OSC52.62+type readPrimaryClipboardMsg struct{}63+64+// ReadPrimaryClipboard produces a command that reads the primary clipboard65+// using OSC52. Primary clipboard selection is a feature present in X11 and66+// Wayland only.67+// Note that OSC52 is not supported in all terminals.68+func ReadPrimaryClipboard() Msg {69+ return readPrimaryClipboardMsg{}70+}added:color.go+91 added
1+package tea2+3+import (4+ "image/color"5+6+ uv "github.com/charmbracelet/ultraviolet"7+)8+9+// backgroundColorMsg is a message that requests the terminal background color.10+type backgroundColorMsg struct{}11+12+// RequestBackgroundColor is a command that requests the terminal background color.13+func RequestBackgroundColor() Msg {14+ return backgroundColorMsg{}15+}16+17+// foregroundColorMsg is a message that requests the terminal foreground color.18+type foregroundColorMsg struct{}19+20+// RequestForegroundColor is a command that requests the terminal foreground color.21+func RequestForegroundColor() Msg {22+ return foregroundColorMsg{}23+}24+25+// cursorColorMsg is a message that requests the terminal cursor color.26+type cursorColorMsg struct{}27+28+// RequestCursorColor is a command that requests the terminal cursor color.29+func RequestCursorColor() Msg {30+ return cursorColorMsg{}31+}32+33+// ForegroundColorMsg represents a foreground color message. This message is34+// emitted when the program requests the terminal foreground color with the35+// [RequestForegroundColor] Cmd.36+type ForegroundColorMsg struct{ color.Color }37+38+// String returns the hex representation of the color.39+func (e ForegroundColorMsg) String() string {40+ return uv.ForegroundColorEvent(e).String()41+}42+43+// IsDark returns whether the color is dark.44+func (e ForegroundColorMsg) IsDark() bool {45+ return uv.ForegroundColorEvent(e).IsDark()46+}47+48+// BackgroundColorMsg represents a background color message. This message is49+// emitted when the program requests the terminal background color with the50+// [RequestBackgroundColor] Cmd.51+//52+// This is commonly used in [Update.Init] to get the terminal background color53+// for style definitions. For that you'll want to call54+// [BackgroundColorMsg.IsDark] to determine if the color is dark or light. For55+// example:56+//57+// func (m Model) Init() (Model, Cmd) {58+// return m, RequestBackgroundColor()59+// }60+//61+// func (m Model) Update(msg Msg) (Model, Cmd) {62+// switch msg := msg.(type) {63+// case BackgroundColorMsg:64+// m.styles = newStyles(msg.IsDark())65+// }66+// }67+type BackgroundColorMsg struct{ color.Color }68+69+// String returns the hex representation of the color.70+func (e BackgroundColorMsg) String() string {71+ return uv.BackgroundColorEvent(e).String()72+}73+74+// IsDark returns whether the color is dark.75+func (e BackgroundColorMsg) IsDark() bool {76+ return uv.BackgroundColorEvent(e).IsDark()77+}78+79+// CursorColorMsg represents a cursor color change message. This message is80+// emitted when the program requests the terminal cursor color.81+type CursorColorMsg struct{ color.Color }82+83+// String returns the hex representation of the color.84+func (e CursorColorMsg) String() string {85+ return uv.CursorColorEvent(e).String()86+}87+88+// IsDark returns whether the color is dark.89+func (e CursorColorMsg) IsDark() bool {90+ return uv.CursorColorEvent(e).IsDark()91+}modified:commands_test.go-56 removed
1 package tea2 3 import (4- "fmt"4 "testing"5 "time"6 )7 16 unmodified lines24 t.Fatalf("expected a msg %v but got %v", expected, msg)25 }26 }27 29-func TestSequentially(t *testing.T) {30- expectedErrMsg := fmt.Errorf("some err")31- expectedStrMsg := "some msg"32-33- nilReturnCmd := func() Msg {34- return nil35- }36-37- tests := []struct {38- name string39- cmds []Cmd40- expected Msg41- }{42- {43- name: "all nil",44- cmds: []Cmd{nilReturnCmd, nilReturnCmd},45- expected: nil,46- },47- {48- name: "null cmds",49- cmds: []Cmd{nil, nil},50- expected: nil,51- },52- {53- name: "one error",54- cmds: []Cmd{55- nilReturnCmd,56- func() Msg {57- return expectedErrMsg58- },59- nilReturnCmd,60- },61- expected: expectedErrMsg,62- },63- {64- name: "some msg",65- cmds: []Cmd{66- nilReturnCmd,67- func() Msg {68- return expectedStrMsg69- },70- nilReturnCmd,71- },72- expected: expectedStrMsg,73- },74- }75- for _, test := range tests {76- t.Run(test.name, func(t *testing.T) {77- if msg := Sequentially(test.cmds...)(); msg != test.expected {78- t.Fatalf("expected a msg %v but got %v", test.expected, msg)79- }80- })81- }82-}83-28 func TestBatch(t *testing.T) {29 testMultipleCommands[BatchMsg](t, Batch)30 }31 28 unmodified linesmodified:commands.go+14 added-61 removed
7 unmodified lines8 // about the results. Use a Batch to return several commands.9 //10 // Example:11 //12-// func (m model) Init() Cmd {13-// return tea.Batch(someCommand, someOtherCommand)12+// func (m model) Init() (Model, Cmd) {13+// return m, tea.Batch(someCommand, someOtherCommand)14 // }15 func Batch(cmds ...Cmd) Cmd {16 return compactCmds[BatchMsg](cmds)17 }15 unmodified lines33 // command possible. That is, considering the non-nil commands, if there are34 // none it returns nil, if there is exactly one it returns that command35 // directly, else it returns the non-nil commands as type T.36 func compactCmds[T ~[]Cmd](cmds []Cmd) Cmd {37- var validCmds []Cmd //nolint:prealloc37+ var validCmds []Cmd38 for _, c := range cmds {39 if c == nil {40 continue41 }41 unmodified lines83 // return TickMsg(t)84 // })85 // }86 //87-// func (m model) Init() Cmd {87+// func (m model) Init() (Model, Cmd) {88 // // Start ticking.89-// return tickEvery()89+// return m, tickEvery()90 // }91 //92 // func (m model) Update(msg Msg) (Model, Cmd) {93 // switch msg.(type) {43 unmodified lines137 // return TickMsg(t)138 // })139 // }140 //141-// func (m model) Init() Cmd {141+// func (m model) Init() (Model, Cmd) {142 // // Start ticking.143-// return doTick()143+// return m, doTick()144 // }145 //146 // func (m model) Update(msg Msg) (Model, Cmd) {147 // switch msg.(type) {14 unmodified lines162 return fn(ts)163 }164 }165 166-// Sequentially produces a command that sequentially executes the given167-// commands.168-// The Msg returned is the first non-nil message returned by a Cmd.169-//170-// func saveStateCmd() Msg {171-// if err := save(); err != nil {172-// return errMsg{err}173-// }174-// return nil175-// }176-//177-// cmd := Sequentially(saveStateCmd, Quit)178-//179-// Deprecated: use Sequence instead.180-func Sequentially(cmds ...Cmd) Cmd {181- return func() Msg {182- for _, cmd := range cmds {183- if cmd == nil {184- continue185- }186- if msg := cmd(); msg != nil {187- return msg188- }189- }190- return nil191- }192-}193-194-// setWindowTitleMsg is an internal message used to set the window title.195-type setWindowTitleMsg string196-197-// SetWindowTitle produces a command that sets the terminal title.198-//199-// For example:200-//201-// func (m model) Init() Cmd {202-// // Set title.203-// return tea.SetWindowTitle("My App")204-// }205-func SetWindowTitle(title string) Cmd {206- return func() Msg {207- return setWindowTitleMsg(title)208- }209-}210-166 type windowSizeMsg struct{}167 213-// WindowSize is a command that queries the terminal for its current size. It214-// delivers the results to Update via a [WindowSizeMsg]. Keep in mind that215-// WindowSizeMsgs will automatically be delivered to Update when the [Program]216-// starts and when the window dimensions change so in many cases you will not217-// need to explicitly invoke this command.218-func WindowSize() Cmd {219- return func() Msg {220- return windowSizeMsg{}221- }168+// RequestWindowSize is a command that queries the terminal for its current169+// size. It delivers the results to Update via a [WindowSizeMsg]. Keep in mind170+// that WindowSizeMsgs will automatically be delivered to Update when the171+// [Program] starts and when the window dimensions change so in many cases you172+// will not need to explicitly invoke this command.173+func RequestWindowSize() Msg {174+ return windowSizeMsg{}175 }added:cursed_renderer.go+830 added
1+package tea2+3+import (4+ "bytes"5+ "fmt"6+ "image/color"7+ "io"8+ "runtime"9+ "strings"10+ "sync"11+12+ "github.com/charmbracelet/colorprofile"13+ uv "github.com/charmbracelet/ultraviolet"14+ "github.com/charmbracelet/x/ansi"15+ "github.com/lucasb-eyer/go-colorful"16+)17+18+type cursedRenderer struct {19+ w io.Writer20+ buf bytes.Buffer // updates buffer to be flushed to [w]21+ scr *uv.TerminalRenderer22+ cellbuf uv.ScreenBuffer23+ lastView *View24+ env []string25+ term string // the terminal type $TERM26+ width, height int27+ mu sync.Mutex28+ profile colorprofile.Profile29+ logger uv.Logger30+ view View31+ hardTabs bool // whether to use hard tabs to optimize cursor movements32+ backspace bool // whether to use backspace to optimize cursor movements33+ mapnl bool34+ syncdUpdates bool // whether to use synchronized output mode for updates35+ starting bool // indicates whether the renderer is starting after being stopped36+}37+38+var _ renderer = &cursedRenderer{}39+40+func newCursedRenderer(w io.Writer, env []string, width, height int) (s *cursedRenderer) {41+ s = new(cursedRenderer)42+ s.w = w43+ s.env = env44+ s.term = uv.Environ(env).Getenv("TERM")45+ s.width, s.height = width, height // This needs to happen before [cursedRenderer.reset].46+ s.cellbuf = uv.NewScreenBuffer(s.width, s.height)47+ reset(s)48+ return49+}50+51+// setLogger sets the logger for the renderer.52+func (s *cursedRenderer) setLogger(logger uv.Logger) {53+ s.mu.Lock()54+ s.logger = logger55+ s.mu.Unlock()56+}57+58+// setOptimizations sets the cursor movement optimizations.59+func (s *cursedRenderer) setOptimizations(hardTabs, backspace, mapnl bool) {60+ s.mu.Lock()61+ s.hardTabs = hardTabs62+ s.backspace = backspace63+ s.mapnl = mapnl64+ s.scr.SetTabStops(s.width)65+ s.scr.SetBackspace(s.backspace)66+ s.scr.SetMapNewline(s.mapnl)67+ s.mu.Unlock()68+}69+70+// start implements renderer.71+func (s *cursedRenderer) start() {72+ s.mu.Lock()73+ defer s.mu.Unlock()74+75+ // Mark that we're starting. This is used to restore some state when76+ // starting the renderer again after it was stopped.77+ s.starting = true78+79+ if s.lastView == nil {80+ return81+ }82+83+ if s.lastView.AltScreen {84+ enableAltScreen(s, true, true)85+ }86+ enableTextCursor(s, s.lastView.Cursor != nil)87+ if s.lastView.Cursor != nil {88+ if s.lastView.Cursor.Color != nil {89+ col, ok := colorful.MakeColor(s.lastView.Cursor.Color)90+ if ok {91+ _, _ = s.scr.WriteString(ansi.SetCursorColor(col.Hex()))92+ }93+ }94+ curStyle := encodeCursorStyle(s.lastView.Cursor.Shape, s.lastView.Cursor.Blink)95+ if curStyle != 0 && curStyle != 1 {96+ _, _ = s.scr.WriteString(ansi.SetCursorStyle(curStyle))97+ }98+ }99+ if s.lastView.ForegroundColor != nil {100+ col, ok := colorful.MakeColor(s.lastView.ForegroundColor)101+ if ok {102+ _, _ = s.scr.WriteString(ansi.SetForegroundColor(col.Hex()))103+ }104+ }105+ if s.lastView.BackgroundColor != nil {106+ col, ok := colorful.MakeColor(s.lastView.BackgroundColor)107+ if ok {108+ _, _ = s.scr.WriteString(ansi.SetBackgroundColor(col.Hex()))109+ }110+ }111+ if !s.lastView.DisableBracketedPasteMode {112+ _, _ = s.scr.WriteString(ansi.SetModeBracketedPaste)113+ }114+ if s.lastView.ReportFocus {115+ _, _ = s.scr.WriteString(ansi.SetModeFocusEvent)116+ }117+ switch s.lastView.MouseMode {118+ case MouseModeNone:119+ case MouseModeCellMotion:120+ _, _ = s.scr.WriteString(ansi.SetModeMouseButtonEvent + ansi.SetModeMouseExtSgr)121+ case MouseModeAllMotion:122+ _, _ = s.scr.WriteString(ansi.SetModeMouseAnyEvent + ansi.SetModeMouseExtSgr)123+ }124+ if s.lastView.WindowTitle != "" {125+ _, _ = s.scr.WriteString(ansi.SetWindowTitle(s.lastView.WindowTitle))126+ }127+ if s.lastView.ProgressBar != nil {128+ setProgressBar(s, s.lastView.ProgressBar)129+ }130+ // Enable modifyOtherKeys and Kitty keyboard protocol.131+ // Both can coexist; terminals ignore what they don't support.132+ _, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)133+134+ kittyFlags := ansi.KittyDisambiguateEscapeCodes135+ if s.lastView.KeyboardEnhancements.ReportEventTypes {136+ kittyFlags |= ansi.KittyReportEventTypes137+ }138+ _, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))139+}140+141+// close implements renderer.142+func (s *cursedRenderer) close() (err error) {143+ s.mu.Lock()144+ defer s.mu.Unlock()145+146+ // Exit the altScreen and show cursor before closing. It's important that147+ // we don't change the [cursedRenderer] altScreen and cursorHidden states148+ // so that we can restore them when we start the renderer again. This is149+ // used when the user suspends the program and then resumes it.150+ if lv := s.lastView; lv != nil { //nolint:nestif151+ // NOTE: The Kitty keyboard specs specify that the terminal should have152+ // two registries for the main and alt screens. We disable keyboard153+ // enhancements whenever we enter/exit alt screen mode in154+ // [cursedRenderer.flush].155+ // Here, we reset the keyboard protocol of the last screen used156+ // assuming the other screen is already reset when we switched screens.157+ _, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)158+ _, _ = s.buf.WriteString(ansi.KittyKeyboard(0, 1))159+160+ // Go to the bottom of the screen.161+ // We need to go to the bottom of the screen regardless of whether162+ // we're in alt screen mode or not to avoid leaving the cursor in the163+ // middle in terminals that don't support alt screen mode.164+ s.scr.MoveTo(0, s.cellbuf.Height()-1)165+ _ = s.scr.Flush() // we need to flush to write the cursor movement166+ if lv.AltScreen {167+ enableAltScreen(s, false, true)168+ } else {169+ _, _ = s.scr.WriteString(ansi.EraseScreenBelow)170+ }171+ if lv.Cursor == nil {172+ enableTextCursor(s, true)173+ }174+ if !lv.DisableBracketedPasteMode {175+ _, _ = s.scr.WriteString(ansi.ResetModeBracketedPaste)176+ }177+ if lv.ReportFocus {178+ _, _ = s.scr.WriteString(ansi.ResetModeFocusEvent)179+ }180+ switch lv.MouseMode {181+ case MouseModeNone:182+ case MouseModeCellMotion, MouseModeAllMotion:183+ _, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent +184+ ansi.ResetModeMouseAnyEvent +185+ ansi.ResetModeMouseExtSgr)186+ }187+188+ if lv.WindowTitle != "" {189+ // Clear the window title if it was set.190+ _, _ = s.scr.WriteString(ansi.SetWindowTitle(""))191+ }192+ if lc := lv.Cursor; lc != nil {193+ curShape := encodeCursorStyle(lc.Shape, lc.Blink)194+ if curShape != 0 && curShape != 1 {195+ // Reset the cursor style to default if it was set to something other196+ // blinking block.197+ _, _ = s.scr.WriteString(ansi.SetCursorStyle(0))198+ }199+200+ if lc.Color != nil {201+ _, _ = s.scr.WriteString(ansi.ResetCursorColor)202+ }203+ }204+205+ if lv.BackgroundColor != nil {206+ _, _ = s.scr.WriteString(ansi.ResetBackgroundColor)207+ }208+ if lv.ForegroundColor != nil {209+ _, _ = s.scr.WriteString(ansi.ResetForegroundColor)210+ }211+ if lv.ProgressBar != nil && lv.ProgressBar.State != ProgressBarNone {212+ _, _ = s.scr.WriteString(ansi.ResetProgressBar)213+ }214+ }215+216+ if s.cellbuf.Method == ansi.GraphemeWidth {217+ // Make sure to turn off Unicode mode (2027)218+ _, _ = s.scr.WriteString(ansi.ResetModeUnicodeCore)219+ }220+221+ if err := s.scr.Flush(); err != nil {222+ return fmt.Errorf("bubbletea: error closing screen writer: %w", err)223+ }224+225+ if s.buf.Len() > 0 {226+ if s.logger != nil {227+ s.logger.Printf("output: %q", s.buf.String())228+ }229+ if _, err := io.Copy(s.w, &s.buf); err != nil {230+ return fmt.Errorf("bubbletea: error writing to screen: %w", err)231+ }232+ s.buf.Reset()233+ }234+235+ x, y := s.scr.Position()236+237+ // We want to clear the renderer state but not the cursor position. This is238+ // because we might be putting the tea process in the background, run some239+ // other process, and then return to the tea process. We want to keep the240+ // cursor position so that we can continue where we left off.241+ reset(s)242+ s.scr.SetPosition(x, y)243+244+ return nil245+}246+247+// writeString implements renderer.248+func (s *cursedRenderer) writeString(str string) (int, error) {249+ s.mu.Lock()250+ defer s.mu.Unlock()251+252+ return s.scr.WriteString(str) //nolint:wrapcheck253+}254+255+// flush implements renderer.256+func (s *cursedRenderer) flush(closing bool) error {257+ s.mu.Lock()258+ defer s.mu.Unlock()259+260+ view := s.view261+ frameArea := uv.Rect(0, 0, s.width, s.height)262+ if len(view.Content) == 0 {263+ // If the component is nil, we should clear the screen buffer.264+ frameArea.Max.Y = 0265+ }266+267+ content := uv.NewStyledString(view.Content)268+ if !view.AltScreen {269+ // We need to resizes the screen based on the frame height and270+ // terminal width. This is because the frame height can change based on271+ // the content of the frame. For example, if the frame contains a list272+ // of items, the height of the frame will be the number of items in the273+ // list. This is different from the alt screen buffer, which has a274+ // fixed height and width.275+ frameHeight := content.Height()276+ if frameHeight != frameArea.Dy() {277+ frameArea.Max.Y = frameHeight278+ }279+ }280+281+ if !s.starting && !closing && s.lastView != nil && viewEquals(s.lastView, &view) && frameArea == s.cellbuf.Bounds() {282+ // No changes, nothing to do.283+ return nil284+ }285+286+ // We're no longer starting.287+ s.starting = false288+289+ if frameArea != s.cellbuf.Bounds() {290+ s.scr.Erase() // Force a full redraw to avoid artifacts.291+292+ // We need to reset the touched lines buffer to match the new height.293+ s.cellbuf.Touched = nil294+295+ // Resize the screen buffer to match the frame area. This is necessary296+ // to ensure that the screen buffer is the same size as the frame area297+ // and to avoid rendering issues when the frame area is smaller than298+ // the screen buffer.299+ s.cellbuf.Resize(frameArea.Dx(), frameArea.Dy())300+ }301+302+ // Clear our screen buffer before copying the new frame into it to ensure303+ // we erase any old content.304+ s.cellbuf.Clear()305+ content.Draw(s.cellbuf, s.cellbuf.Bounds())306+307+ // If the frame height is greater than the screen height, we drop the308+ // lines from the top of the buffer.309+ if frameHeight := frameArea.Dy(); frameHeight > s.height {310+ s.cellbuf.Lines = s.cellbuf.Lines[frameHeight-s.height:]311+ }312+313+ // Alt screen mode.314+ shouldUpdateAltScreen := (s.lastView == nil && view.AltScreen) || (s.lastView != nil && s.lastView.AltScreen != view.AltScreen)315+ if shouldUpdateAltScreen {316+ // We want to enter/exit altscreen mode but defer writing the actual317+ // sequences until we flush the rest of the updates. This is because we318+ // control the cursor visibility and we need to ensure that happens319+ // after entering/exiting alt screen mode. Some terminals have320+ // different cursor visibility states for main and alt screen modes and321+ // this ensures we handle that correctly.322+ enableAltScreen(s, view.AltScreen, false)323+ }324+325+ // bracketed paste mode.326+ if s.lastView == nil || view.DisableBracketedPasteMode != s.lastView.DisableBracketedPasteMode {327+ if !view.DisableBracketedPasteMode {328+ _, _ = s.scr.WriteString(ansi.SetModeBracketedPaste)329+ } else if s.lastView != nil {330+ _, _ = s.scr.WriteString(ansi.ResetModeBracketedPaste)331+ }332+ }333+334+ // report focus events mode.335+ if s.lastView == nil || s.lastView.ReportFocus != view.ReportFocus {336+ if view.ReportFocus {337+ _, _ = s.scr.WriteString(ansi.SetModeFocusEvent)338+ } else if s.lastView != nil {339+ _, _ = s.scr.WriteString(ansi.ResetModeFocusEvent)340+ }341+ }342+343+ // mouse events mode.344+ if s.lastView == nil || view.MouseMode != s.lastView.MouseMode {345+ switch view.MouseMode {346+ case MouseModeNone:347+ if s.lastView != nil && s.lastView.MouseMode != MouseModeNone {348+ _, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent +349+ ansi.ResetModeMouseAnyEvent +350+ ansi.ResetModeMouseExtSgr)351+ }352+ case MouseModeCellMotion:353+ if s.lastView != nil && s.lastView.MouseMode == MouseModeAllMotion {354+ _, _ = s.scr.WriteString(ansi.ResetModeMouseAnyEvent)355+ }356+ _, _ = s.scr.WriteString(ansi.SetModeMouseButtonEvent + ansi.SetModeMouseExtSgr)357+ case MouseModeAllMotion:358+ if s.lastView != nil && s.lastView.MouseMode == MouseModeCellMotion {359+ _, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent)360+ }361+ _, _ = s.scr.WriteString(ansi.SetModeMouseAnyEvent + ansi.SetModeMouseExtSgr)362+ }363+ }364+365+ // Set window title.366+ if s.lastView == nil || view.WindowTitle != s.lastView.WindowTitle {367+ if s.lastView != nil || view.WindowTitle != "" {368+ _, _ = s.scr.WriteString(ansi.SetWindowTitle(view.WindowTitle))369+ }370+ }371+372+ // kitty keyboard protocol373+ if s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||374+ view.AltScreen != s.lastView.AltScreen {375+ // NOTE: We need to reset the keyboard protocol when switching376+ // between main and alt screen. This is because the specs specify377+ // two different states for the main and alt screen.378+379+ // Enable modifyOtherKeys and Kitty keyboard protocol.380+ _, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)381+382+ kittyFlags := ansi.KittyDisambiguateEscapeCodes // always enable basic key disambiguation383+ if view.KeyboardEnhancements.ReportEventTypes {384+ kittyFlags |= ansi.KittyReportEventTypes385+ }386+ _, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))387+ if !closing {388+ // Request keyboard enhancements when they change389+ _, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)390+ }391+ }392+393+ // Set terminal colors.394+ var (395+ cc, lcc color.Color396+ lfg, lbg color.Color397+ )398+ if view.Cursor != nil {399+ cc = view.Cursor.Color400+ }401+ if s.lastView != nil {402+ if s.lastView.Cursor != nil {403+ lcc = s.lastView.Cursor.Color404+ }405+ lfg = s.lastView.ForegroundColor406+ lbg = s.lastView.BackgroundColor407+ }408+ for _, c := range []struct {409+ newColor color.Color410+ oldColor color.Color411+ reset string412+ setter func(string) string413+ }{414+ {newColor: cc, oldColor: lcc, reset: ansi.ResetCursorColor, setter: ansi.SetCursorColor},415+ {newColor: view.ForegroundColor, oldColor: lfg, reset: ansi.ResetForegroundColor, setter: ansi.SetForegroundColor},416+ {newColor: view.BackgroundColor, oldColor: lbg, reset: ansi.ResetBackgroundColor, setter: ansi.SetBackgroundColor},417+ } {418+ if c.newColor != c.oldColor {419+ if c.newColor == nil {420+ // Reset the color if it was set to nil.421+ _, _ = s.scr.WriteString(c.reset)422+ } else {423+ // Set the color.424+ col, ok := colorful.MakeColor(c.newColor)425+ if ok {426+ _, _ = s.scr.WriteString(c.setter(col.Hex()))427+ }428+ }429+ }430+ }431+432+ // Set cursor shape and blink if set.433+ var ccStyle, lcStyle int434+ var lcur *Cursor435+ ccur := view.Cursor436+ if lv := s.lastView; lv != nil {437+ lcur = lv.Cursor438+ }439+ if ccur != nil {440+ ccStyle = encodeCursorStyle(ccur.Shape, ccur.Blink)441+ }442+ if lcur != nil {443+ lcStyle = encodeCursorStyle(lcur.Shape, lcur.Blink)444+ }445+ if ccStyle != lcStyle {446+ _, _ = s.scr.WriteString(ansi.SetCursorStyle(ccStyle))447+ }448+449+ // Render progress bar if it's changed.450+ if (s.lastView == nil && view.ProgressBar != nil && view.ProgressBar.State != ProgressBarNone) ||451+ (s.lastView != nil && (s.lastView.ProgressBar == nil) != (view.ProgressBar == nil)) ||452+ (s.lastView != nil && s.lastView.ProgressBar != nil && view.ProgressBar != nil && *s.lastView.ProgressBar != *view.ProgressBar) {453+ // Render or clear the progress bar if it was added or removed.454+ setProgressBar(s, view.ProgressBar)455+ }456+457+ // Render and queue changes to the screen buffer.458+ s.scr.Render(s.cellbuf.RenderBuffer)459+460+ if cur := view.Cursor; cur != nil {461+ // MoveTo must come after [uv.TerminalRenderer.Render] because the462+ // cursor position might get updated during rendering.463+ s.scr.MoveTo(view.Cursor.X, view.Cursor.Y)464+ } else if !view.AltScreen {465+ // We don't want the cursor to be dangling at the end of the line in466+ // inline mode because it can cause unwanted line wraps in some467+ // terminals. So we move it to the beginning of the next line if468+ // necessary.469+ // This is only needed when the cursor is hidden because when it's470+ // visible, we already set its position above.471+ x, y := s.scr.Position()472+ if x >= s.width-1 {473+ s.scr.MoveTo(0, y)474+ }475+ }476+477+ if err := s.scr.Flush(); err != nil {478+ return fmt.Errorf("bubbletea: error flushing screen writer: %w", err)479+ }480+481+ // Check if we have any render updates to flush.482+ hasUpdates := s.buf.Len() > 0483+484+ // Cursor visibility.485+ didShowCursor := s.lastView != nil && s.lastView.Cursor != nil486+ showCursor := view.Cursor != nil487+ hideCursor := !showCursor488+ shouldUpdateCursorVis := (s.lastView == nil || didShowCursor != showCursor) || shouldUpdateAltScreen489+490+ // Build final output buffer with synchronized output or hide/show cursor491+ // updates. But first, enter/exit alt screen mode if needed.492+ //493+ // Here, we have two scenarios:494+ // 1. Synchronized output updates are supported. In this case, we want to495+ // wrap all updates, unless it's just a cursor visibility change, in496+ // synchronized output mode. This is because synchronized output mode497+ // takes care of rendering the updates atomically. In the case of498+ // just a cursor visibility change, we don't need to enter499+ // synchronized output mode because it's just a single sequence to500+ // flush out to the terminal.501+ //502+ // 2. We don't have synchronized output updates support. In this case, and503+ // if the cursor is visible or should be visible, we wrap the updates504+ // with hide/show cursor sequences to try and mitigate cursor505+ // flickering. This is terminal dependent and may still result in506+ // flickering in some terminals. It's the best effort we can do instead507+ // of showing the cursor flying around the screen during updates.508+509+ var buf bytes.Buffer510+ if shouldUpdateAltScreen {511+ // We always disable keyboard enhancements when switching screens512+ // because the terminal is expected to have two different keyboard513+ // registries for main and alt screens.514+ _, _ = buf.WriteString(ansi.ResetModifyOtherKeys)515+ _, _ = buf.WriteString(ansi.KittyKeyboard(0, 1))516+ if view.AltScreen {517+ // Entering alt screen mode.518+ buf.WriteString(ansi.SetModeAltScreenSaveCursor)519+ } else {520+ // Exiting alt screen mode.521+ buf.WriteString(ansi.ResetModeAltScreenSaveCursor)522+ }523+ }524+525+ if s.syncdUpdates {526+ if hasUpdates {527+ // We have synchronized output updates enabled.528+ buf.WriteString(ansi.SetModeSynchronizedOutput)529+ }530+ if shouldUpdateCursorVis && hideCursor {531+ // Do we need to update the cursor visibility to hidden? If so, do532+ // it here before writing any updates to the buffer.533+ _, _ = buf.WriteString(ansi.ResetModeTextCursorEnable)534+ }535+ } else if (shouldUpdateCursorVis && hideCursor) || (hasUpdates && showCursor && didShowCursor) {536+ _, _ = buf.WriteString(ansi.ResetModeTextCursorEnable)537+ }538+539+ if hasUpdates {540+ buf.Write(s.buf.Bytes())541+ }542+543+ if s.syncdUpdates {544+ if shouldUpdateCursorVis && showCursor {545+ // Do we need to update the cursor visibility to visible? If so, do546+ // it here after writing any updates to the buffer.547+ _, _ = buf.WriteString(ansi.SetModeTextCursorEnable)548+ }549+ if hasUpdates {550+ // Close synchronized output mode.551+ buf.WriteString(ansi.ResetModeSynchronizedOutput)552+ }553+ } else if (shouldUpdateCursorVis && showCursor) || (hasUpdates && showCursor && didShowCursor) {554+ _, _ = buf.WriteString(ansi.SetModeTextCursorEnable)555+ }556+557+ // Reset internal screen renderer buffer.558+ s.buf.Reset()559+560+ // If our updates flush buffer has content, write it to the output writer.561+ if buf.Len() > 0 {562+ if s.logger != nil {563+ s.logger.Printf("output: %q", buf.String())564+ }565+ if _, err := io.Copy(s.w, &buf); err != nil {566+ return fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)567+ }568+ }569+570+ s.lastView = &view571+572+ return nil573+}574+575+// render implements renderer.576+func (s *cursedRenderer) render(v View) {577+ s.mu.Lock()578+ defer s.mu.Unlock()579+580+ s.view = v581+}582+583+// reset implements renderer.584+func (s *cursedRenderer) reset() {585+ s.mu.Lock()586+ reset(s)587+ s.mu.Unlock()588+}589+590+func reset(s *cursedRenderer) {591+ s.buf.Reset()592+ scr := uv.NewTerminalRenderer(&s.buf, s.env)593+ scr.SetColorProfile(s.profile)594+ scr.SetRelativeCursor(true) // Always start in inline mode595+ scr.SetFullscreen(false) // Always start in inline mode596+ scr.SetTabStops(s.width)597+ scr.SetBackspace(s.backspace)598+ scr.SetMapNewline(s.mapnl)599+ scr.SetScrollOptim(runtime.GOOS != "windows") // disable scroll optimization on Windows due to bugs in some terminals600+ s.scr = scr601+}602+603+// setColorProfile implements renderer.604+func (s *cursedRenderer) setColorProfile(p colorprofile.Profile) {605+ s.mu.Lock()606+ s.profile = p607+ s.scr.SetColorProfile(p)608+ s.mu.Unlock()609+}610+611+// resize implements renderer.612+func (s *cursedRenderer) resize(w, h int) {613+ s.mu.Lock()614+ // We need to mark the screen for clear to force a redraw. However, we615+ // only do so if we're using alt screen or the width has changed.616+ // That's because redrawing is expensive and we can avoid it if the617+ // width hasn't changed in inline mode. On the other hand, when using618+ // alt screen mode, we always want to redraw because some terminals619+ // would scroll the screen and our content would be lost.620+ s.scr.Erase()621+ s.width, s.height = w, h622+ s.scr.Resize(s.width, s.height)623+ s.mu.Unlock()624+}625+626+// clearScreen implements renderer.627+func (s *cursedRenderer) clearScreen() {628+ s.mu.Lock()629+ // Move the cursor to the top left corner of the screen and trigger a full630+ // screen redraw.631+ s.scr.MoveTo(0, 0)632+ s.scr.Erase()633+ s.mu.Unlock()634+}635+636+// enableAltScreen sets the alt screen mode.637+// Note that this writes to the buffer directly if write is true.638+func enableAltScreen(s *cursedRenderer, enable bool, write bool) {639+ if enable {640+ enterAltScreen(s, write)641+ } else {642+ exitAltScreen(s, write)643+ }644+}645+646+func enterAltScreen(s *cursedRenderer, write bool) {647+ s.scr.SaveCursor()648+ if write {649+ s.buf.WriteString(ansi.SetModeAltScreenSaveCursor)650+ }651+ s.scr.SetFullscreen(true)652+ s.scr.SetRelativeCursor(false)653+ s.scr.Erase()654+}655+656+func exitAltScreen(s *cursedRenderer, write bool) {657+ s.scr.Erase()658+ s.scr.SetRelativeCursor(true)659+ s.scr.SetFullscreen(false)660+ if write {661+ s.buf.WriteString(ansi.ResetModeAltScreenSaveCursor)662+ }663+ s.scr.RestoreCursor()664+}665+666+// enableTextCursor sets the text cursor mode.667+func enableTextCursor(s *cursedRenderer, enable bool) {668+ if enable {669+ _, _ = s.scr.WriteString(ansi.SetModeTextCursorEnable)670+ } else {671+ _, _ = s.scr.WriteString(ansi.ResetModeTextCursorEnable)672+ }673+}674+675+// setSyncdUpdates implements renderer.676+func (s *cursedRenderer) setSyncdUpdates(syncd bool) {677+ s.mu.Lock()678+ s.syncdUpdates = syncd679+ s.mu.Unlock()680+}681+682+// setWidthMethod implements renderer.683+func (s *cursedRenderer) setWidthMethod(method ansi.Method) {684+ s.mu.Lock()685+ if method == ansi.GraphemeWidth {686+ // Turn on Unicode mode (2027) for accurate grapheme width calculation.687+ // This is needed for proper rendering of wide characters and emojis.688+ _, _ = s.scr.WriteString(ansi.SetModeUnicodeCore)689+ } else if s.cellbuf.Method == ansi.GraphemeWidth {690+ // Turn off Unicode mode if we're switching away from grapheme width691+ // calculation to avoid issues with some terminals that might still be692+ // in Unicode mode and render characters incorrectly.693+ _, _ = s.scr.WriteString(ansi.ResetModeUnicodeCore)694+ }695+ s.cellbuf.Method = method696+ s.mu.Unlock()697+}698+699+// insertAbove implements renderer.700+func (s *cursedRenderer) insertAbove(str string) error {701+ s.mu.Lock()702+ defer s.mu.Unlock()703+704+ if len(str) == 0 {705+ return nil706+ }707+708+ var sb strings.Builder709+ w, h := s.cellbuf.Width(), s.cellbuf.Height()710+ _, y := s.scr.Position()711+712+ // We need to scroll the screen up by the number of lines in the queue.713+ sb.WriteByte('\r')714+ down := h - y - 1715+ if down > 0 {716+ sb.WriteString(ansi.CursorDown(down))717+ }718+719+ lines := strings.Split(str, "\n")720+ offset := len(lines)721+ for _, line := range lines {722+ lineWidth := ansi.StringWidth(line)723+ if w > 0 && lineWidth > w {724+ offset += (lineWidth / w)725+ }726+ }727+728+ // Scroll the screen up by the offset to make room for the new lines.729+ sb.WriteString(strings.Repeat("\n", offset))730+731+ // XXX: Now go to the top of the screen, insert new lines, and write732+ // the queued strings. It is important to use [Screen.moveCursor]733+ // instead of [Screen.move] because we don't want to perform any checks734+ // on the cursor position.735+ up := offset + h - 1736+ sb.WriteString(ansi.CursorUp(up))737+ sb.WriteString(ansi.InsertLine(offset))738+ for _, line := range lines {739+ sb.WriteString(line)740+ sb.WriteString(ansi.EraseLineRight)741+ sb.WriteString("\r\n")742+ }743+744+ s.scr.SetPosition(0, 0)745+746+ if s.logger != nil {747+ s.logger.Printf("insert above: %q", sb.String())748+ }749+750+ _, err := io.WriteString(s.w, sb.String())751+ if err != nil {752+ return fmt.Errorf("bubbletea: error writing insert above to the writer: %w", err)753+ }754+755+ return nil756+}757+758+// onMouse implements renderer.759+func (s *cursedRenderer) onMouse(m MouseMsg) Cmd {760+ if s.lastView != nil && s.lastView.OnMouse != nil {761+ return s.lastView.OnMouse(m)762+ }763+ return nil764+}765+766+func setProgressBar(s *cursedRenderer, pb *ProgressBar) {767+ if pb == nil {768+ _, _ = s.scr.WriteString(ansi.ResetProgressBar)769+ return770+ }771+772+ var seq string773+ switch pb.State {774+ case ProgressBarNone:775+ seq = ansi.ResetProgressBar776+ case ProgressBarDefault:777+ seq = ansi.SetProgressBar(pb.Value)778+ case ProgressBarError:779+ seq = ansi.SetErrorProgressBar(pb.Value)780+ case ProgressBarIndeterminate:781+ seq = ansi.SetIndeterminateProgressBar782+ case ProgressBarWarning:783+ seq = ansi.SetWarningProgressBar(pb.Value)784+ }785+ if seq != "" {786+ _, _ = s.scr.WriteString(seq)787+ }788+}789+790+func viewEquals(a, b *View) bool {791+ if a == nil || b == nil {792+ return false793+ }794+795+ if a.Content != b.Content ||796+ a.AltScreen != b.AltScreen ||797+ a.DisableBracketedPasteMode != b.DisableBracketedPasteMode ||798+ a.ReportFocus != b.ReportFocus ||799+ a.MouseMode != b.MouseMode ||800+ a.WindowTitle != b.WindowTitle ||801+ a.ForegroundColor != b.ForegroundColor ||802+ a.BackgroundColor != b.BackgroundColor ||803+ a.KeyboardEnhancements != b.KeyboardEnhancements {804+ return false805+ }806+807+ if (a.Cursor == nil) != (b.Cursor == nil) {808+ return false809+ }810+ if a.Cursor != nil && b.Cursor != nil {811+ if a.Cursor.X != b.Cursor.X ||812+ a.Cursor.Y != b.Cursor.Y ||813+ a.Cursor.Shape != b.Cursor.Shape ||814+ a.Cursor.Blink != b.Cursor.Blink ||815+ a.Cursor.Color != b.Cursor.Color {816+ return false817+ }818+ }819+820+ if (a.ProgressBar == nil) != (b.ProgressBar == nil) {821+ return false822+ }823+ if a.ProgressBar != nil && b.ProgressBar != nil {824+ if *a.ProgressBar != *b.ProgressBar {825+ return false826+ }827+ }828+829+ return true830+}added:cursor.go+28 added
1+package tea2+3+// Position represents a position in the terminal.4+type Position struct{ X, Y int }5+6+// CursorPositionMsg is a message that represents the terminal cursor position.7+type CursorPositionMsg struct {8+ X, Y int9+}10+11+// CursorShape represents a terminal cursor shape.12+type CursorShape int13+14+// Cursor shapes.15+const (16+ CursorBlock CursorShape = iota17+ CursorUnderline18+ CursorBar19+)20+21+// requestCursorPosMsg is a message that requests the cursor position.22+type requestCursorPosMsg struct{}23+24+// RequestCursorPosition is a command that requests the cursor position.25+// The cursor position will be sent as a [CursorPositionMsg] message.26+func RequestCursorPosition() Msg {27+ return requestCursorPosMsg{}28+}added:environ.go+34 added
1+package tea2+3+import uv "github.com/charmbracelet/ultraviolet"4+5+// EnvMsg is a message that represents the environment variables of the6+// program. This is useful for getting the environment variables of programs7+// running in a remote session like SSH. In that case, using [os.Getenv] would8+// return the server's environment variables, not the client's.9+//10+// This message is sent to the program when it starts.11+//12+// Example:13+//14+// switch msg := msg.(type) {15+// case EnvMsg:16+// // What terminal type is being used?17+// term := msg.Getenv("TERM")18+// }19+type EnvMsg uv.Environ20+21+// Getenv returns the value of the environment variable named by the key. If22+// the variable is not present in the environment, the value returned will be23+// the empty string.24+func (msg EnvMsg) Getenv(key string) (v string) {25+ return uv.Environ(msg).Getenv(key)26+}27+28+// LookupEnv retrieves the value of the environment variable named by the key.29+// If the variable is present in the environment the value (which may be empty)30+// is returned and the boolean is true. Otherwise the returned value will be31+// empty and the boolean will be false.32+func (msg EnvMsg) LookupEnv(key string) (s string, v bool) {33+ return uv.Environ(msg).LookupEnv(key)34+}modified:exec_test.go+9 added-9 removed
12 unmodified lines13 cmd string14 err error15 }16 17-func (m testExecModel) Init() Cmd {17+func (m *testExecModel) Init() Cmd {18 c := exec.Command(m.cmd) //nolint:gosec19 return ExecProcess(c, func(err error) Msg {20 return execFinishedMsg{err}21 })10 unmodified lines32 33 return m, nil34 }35 36-func (m *testExecModel) View() string {37- return "\n"36+func (m *testExecModel) View() View {37+ return NewView("\n")38 }39 40 type spyRenderer struct {41 renderer42 calledReset bool43 }44 45-func (r *spyRenderer) resetLinesRendered() {46- r.calledReset = true47- r.renderer.resetLinesRendered()48-}49-45 func TestTeaExec(t *testing.T) {46 type test struct {47 name string48 cmd string49 expectErr bool50 }51+52+ // TODO: add more tests for windows53 tests := []test{54 {55 name: "invalid command",56 cmd: "invalid",21 unmodified lines78 var buf bytes.Buffer79 var in bytes.Buffer80 81 m := &testExecModel{cmd: test.cmd}85- p := NewProgram(m, WithInput(&in), WithOutput(&buf))82+ p := NewProgram(m,83+ WithInput(&in),84+ WithOutput(&buf),85+ )86 if _, err := p.Run(); err != nil {87 t.Error(err)88 }89 p.renderer = &spyRenderer{renderer: p.renderer}14 unmodified linesmodified:exec.go+1 added-5 removed
98 unmodified lines99 }100 101 // exec runs an ExecCommand and delivers the results to the program as a Msg.102 func (p *Program) exec(c ExecCommand, fn ExecCallback) {103- if err := p.ReleaseTerminal(); err != nil {103+ if err := p.releaseTerminal(false); err != nil {104 // If we can't release input, abort.105 if fn != nil {106 go p.Send(fn(err))107 }5 unmodified lines113 c.SetStderr(os.Stderr)114 115 // Execute system command.116 if err := c.Run(); err != nil {117- p.renderer.resetLinesRendered()117 _ = p.RestoreTerminal() // also try to restore the terminal.118 if fn != nil {119 go p.Send(fn(err))120 }121 return122 }123 125- // Maintain the existing output from the command126- p.renderer.resetLinesRendered()127-124 // Have the program re-capture input.125 err := p.RestoreTerminal()126 if fn != nil {127 go p.Send(fn(err))2 unmodified linesmodified:go.mod+20 added-16 removed
1-module github.com/charmbracelet/bubbletea1+module charm.land/bubbletea/v22 3-go 1.24.03+retract v2.0.0-beta1 // We add a "." after the "beta" in the version number.4 5+go 1.24.26+7+toolchain go1.24.48+9 require (6- github.com/charmbracelet/lipgloss v1.1.07- github.com/charmbracelet/x/ansi v0.10.210+ github.com/charmbracelet/colorprofile v0.4.111+ github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb812+ github.com/charmbracelet/x/ansi v0.11.613+ github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f14 github.com/charmbracelet/x/term v0.2.29- github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f10- github.com/mattn/go-localereader v0.0.111- github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f615+ github.com/lucasb-eyer/go-colorful v1.3.016 github.com/muesli/cancelreader v0.2.213- golang.org/x/sys v0.37.017+ golang.org/x/sys v0.40.018 )19 20 require (17- github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect18- github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect19- github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect20- github.com/lucasb-eyer/go-colorful v1.3.0 // indirect21- github.com/mattn/go-isatty v0.0.20 // indirect22- github.com/mattn/go-runewidth v0.0.17 // indirect23- github.com/muesli/termenv v0.16.0 // indirect21+ github.com/aymanbagabas/go-udiff v0.2.0 // indirect22+ github.com/charmbracelet/x/termios v0.1.1 // indirect23+ github.com/charmbracelet/x/windows v0.2.2 // indirect24+ github.com/clipperhouse/displaywidth v0.9.0 // indirect25+ github.com/clipperhouse/stringish v0.1.1 // indirect26+ github.com/clipperhouse/uax29/v2 v2.5.0 // indirect27+ github.com/mattn/go-runewidth v0.0.19 // indirect28 github.com/rivo/uniseg v0.4.7 // indirect29 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect26- golang.org/x/text v0.3.8 // indirect30+ golang.org/x/sync v0.19.0 // indirect31 )modified:go.sum+26 added-29 removed
1-github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2-github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3-github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=4-github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=5-github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=6-github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=7-github.com/charmbracelet/x/ansi v0.10.2 h1:ith2ArZS0CJG30cIUfID1LXN7ZFXRCww6RUvAPA+Pzw=8-github.com/charmbracelet/x/ansi v0.10.2/go.mod h1:HbLdJjQH4UH4AqA2HpRWuWNluRE6zxJH/yteYEYCFa8=9-github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=10-github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=1+github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=2+github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=3+github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=4+github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=5+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA=6+github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98=7+github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=8+github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=9+github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f h1:UytXHv0UxnsDFmL/7Z9Q5SBYPwSuRLXHbwx+6LycZ2w=10+github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=11 github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=12 github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=13-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=14-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=13+github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=14+github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=15+github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=16+github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=17+github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=18+github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=19+github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=20+github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=21+github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=22+github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=23 github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=24 github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=17-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=18-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=19-github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=20-github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=21-github.com/mattn/go-runewidth v0.0.17 h1:78v8ZlW0bP43XfmAfPsdXcoNCelfMHsDmd/pkENfrjQ=22-github.com/mattn/go-runewidth v0.0.17/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=23-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=24-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=25+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=26+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=27 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=28 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=27-github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=28-github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=29-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=29 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=30 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=31 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=32 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=33 golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=34 golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=36-golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=37-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=38-golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=39-golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=40-golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=41-golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=35+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=36+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=37+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=38+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=added:input.go+54 added
1+package tea2+3+import (4+ uv "github.com/charmbracelet/ultraviolet"5+)6+7+// translateInputEvent translates an input event into a Bubble Tea Msg.8+func (p *Program) translateInputEvent(e uv.Event) Msg {9+ switch e := e.(type) {10+ case uv.ClipboardEvent:11+ return ClipboardMsg(e)12+ case uv.ForegroundColorEvent:13+ return ForegroundColorMsg(e)14+ case uv.BackgroundColorEvent:15+ return BackgroundColorMsg(e)16+ case uv.CursorColorEvent:17+ return CursorColorMsg(e)18+ case uv.CursorPositionEvent:19+ return CursorPositionMsg(e)20+ case uv.FocusEvent:21+ return FocusMsg(e)22+ case uv.BlurEvent:23+ return BlurMsg(e)24+ case uv.KeyPressEvent:25+ return KeyPressMsg(e)26+ case uv.KeyReleaseEvent:27+ return KeyReleaseMsg(e)28+ case uv.MouseClickEvent:29+ return MouseClickMsg(e)30+ case uv.MouseMotionEvent:31+ return MouseMotionMsg(e)32+ case uv.MouseReleaseEvent:33+ return MouseReleaseMsg(e)34+ case uv.MouseWheelEvent:35+ return MouseWheelMsg(e)36+ case uv.PasteEvent:37+ return PasteMsg(e)38+ case uv.PasteStartEvent:39+ return PasteStartMsg(e)40+ case uv.PasteEndEvent:41+ return PasteEndMsg(e)42+ case uv.WindowSizeEvent:43+ return WindowSizeMsg(e)44+ case uv.CapabilityEvent:45+ return CapabilityMsg(e)46+ case uv.TerminalVersionEvent:47+ return TerminalVersionMsg(e)48+ case uv.KeyboardEnhancementsEvent:49+ return KeyboardEnhancementsMsg(e)50+ case uv.ModeReportEvent:51+ return ModeReportMsg(e)52+ }53+ return e54+}deleted:inputreader_other.go-19 removed
1-//go:build !windows2-// +build !windows3-4-package tea5-6-import (7- "fmt"8- "io"9-10- "github.com/muesli/cancelreader"11-)12-13-func newInputReader(r io.Reader, _ bool) (cancelreader.CancelReader, error) {14- cr, err := cancelreader.NewReader(r)15- if err != nil {16- return nil, fmt.Errorf("bubbletea: error creating cancel reader: %w", err)17- }18- return cr, nil19-}deleted:inputreader_windows.go-129 removed
1-//go:build windows2-// +build windows3-4-package tea5-6-import (7- "fmt"8- "io"9- "os"10- "sync"11-12- "github.com/charmbracelet/x/term"13- "github.com/erikgeiser/coninput"14- "github.com/muesli/cancelreader"15- "golang.org/x/sys/windows"16-)17-18-type conInputReader struct {19- cancelMixin20-21- conin windows.Handle22-23- originalMode uint3224-}25-26-var _ cancelreader.CancelReader = &conInputReader{}27-28-func newInputReader(r io.Reader, enableMouse bool) (cancelreader.CancelReader, error) {29- fallback := func(io.Reader) (cancelreader.CancelReader, error) {30- return cancelreader.NewReader(r)31- }32- if f, ok := r.(term.File); !ok || f.Fd() != os.Stdin.Fd() {33- return fallback(r)34- }35-36- conin, err := coninput.NewStdinHandle()37- if err != nil {38- return fallback(r)39- }40-41- modes := []uint32{42- windows.ENABLE_WINDOW_INPUT,43- windows.ENABLE_EXTENDED_FLAGS,44- }45-46- // Since we have options to enable mouse events, [WithMouseCellMotion],47- // [WithMouseAllMotion], and [EnableMouseCellMotion],48- // [EnableMouseAllMotion], and [DisableMouse], we need to check if the user49- // has enabled mouse events and add the appropriate mode accordingly.50- // Otherwise, mouse events will be enabled all the time.51- if enableMouse {52- modes = append(modes, windows.ENABLE_MOUSE_INPUT)53- }54-55- originalMode, err := prepareConsole(conin, modes...)56- if err != nil {57- return nil, fmt.Errorf("failed to prepare console input: %w", err)58- }59-60- return &conInputReader{61- conin: conin,62- originalMode: originalMode,63- }, nil64-}65-66-// Cancel implements cancelreader.CancelReader.67-func (r *conInputReader) Cancel() bool {68- r.setCanceled()69-70- // Warning: These cancel methods do not reliably work on console input71- // and should not be counted on.72- return windows.CancelIoEx(r.conin, nil) == nil || windows.CancelIo(r.conin) == nil73-}74-75-// Close implements cancelreader.CancelReader.76-func (r *conInputReader) Close() error {77- if r.originalMode != 0 {78- err := windows.SetConsoleMode(r.conin, r.originalMode)79- if err != nil {80- return fmt.Errorf("reset console mode: %w", err)81- }82- }83-84- return nil85-}86-87-// Read implements cancelreader.CancelReader.88-func (r *conInputReader) Read(_ []byte) (n int, err error) {89- if r.isCanceled() {90- err = cancelreader.ErrCanceled91- }92- return93-}94-95-func prepareConsole(input windows.Handle, modes ...uint32) (originalMode uint32, err error) {96- err = windows.GetConsoleMode(input, &originalMode)97- if err != nil {98- return 0, fmt.Errorf("get console mode: %w", err)99- }100-101- newMode := coninput.AddInputModes(0, modes...)102-103- err = windows.SetConsoleMode(input, newMode)104- if err != nil {105- return 0, fmt.Errorf("set console mode: %w", err)106- }107-108- return originalMode, nil109-}110-111-// cancelMixin represents a goroutine-safe cancellation status.112-type cancelMixin struct {113- unsafeCanceled bool114- lock sync.Mutex115-}116-117-func (c *cancelMixin) setCanceled() {118- c.lock.Lock()119- defer c.lock.Unlock()120-121- c.unsafeCanceled = true122-}123-124-func (c *cancelMixin) isCanceled() bool {125- c.lock.Lock()126- defer c.lock.Unlock()127-128- return c.unsafeCanceled129-}deleted:key_other.go-13 removed
1-//go:build !windows2-// +build !windows3-4-package tea5-6-import (7- "context"8- "io"9-)10-11-func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {12- return readAnsiInputs(ctx, msgs, input)13-}deleted:key_sequences.go-129 removed
1-package tea2-3-import (4- "bytes"5- "sort"6- "unicode/utf8"7-)8-9-// extSequences is used by the map-based algorithm below. It contains10-// the sequences plus their alternatives with an escape character11-// prefixed, plus the control chars, plus the space.12-// It does not contain the NUL character, which is handled specially13-// by detectOneMsg.14-var extSequences = func() map[string]Key {15- s := map[string]Key{}16- for seq, key := range sequences {17- s[seq] = key18- if !key.Alt {19- key.Alt = true20- s["\x1b"+seq] = key21- }22- }23- for i := keyNUL + 1; i <= keyDEL; i++ {24- if i == keyESC {25- continue26- }27- s[string([]byte{byte(i)})] = Key{Type: i}28- s[string([]byte{'\x1b', byte(i)})] = Key{Type: i, Alt: true}29- if i == keyUS {30- i = keyDEL - 131- }32- }33- s[" "] = Key{Type: KeySpace, Runes: spaceRunes}34- s["\x1b "] = Key{Type: KeySpace, Alt: true, Runes: spaceRunes}35- s["\x1b\x1b"] = Key{Type: KeyEscape, Alt: true}36- return s37-}()38-39-// seqLengths is the sizes of valid sequences, starting with the40-// largest size.41-var seqLengths = func() []int {42- sizes := map[int]struct{}{}43- for seq := range extSequences {44- sizes[len(seq)] = struct{}{}45- }46- lsizes := make([]int, 0, len(sizes))47- for sz := range sizes {48- lsizes = append(lsizes, sz)49- }50- sort.Slice(lsizes, func(i, j int) bool { return lsizes[i] > lsizes[j] })51- return lsizes52-}()53-54-// detectSequence uses a longest prefix match over the input55-// sequence and a hash map.56-func detectSequence(input []byte) (hasSeq bool, width int, msg Msg) {57- seqs := extSequences58- for _, sz := range seqLengths {59- if sz > len(input) {60- continue61- }62- prefix := input[:sz]63- key, ok := seqs[string(prefix)]64- if ok {65- return true, sz, KeyMsg(key)66- }67- }68- // Is this an unknown CSI sequence?69- if loc := unknownCSIRe.FindIndex(input); loc != nil {70- return true, loc[1], unknownCSISequenceMsg(input[:loc[1]])71- }72-73- return false, 0, nil74-}75-76-// detectBracketedPaste detects an input pasted while bracketed77-// paste mode was enabled.78-//79-// Note: this function is a no-op if bracketed paste was not enabled80-// on the terminal, since in that case we'd never see this81-// particular escape sequence.82-func detectBracketedPaste(input []byte) (hasBp bool, width int, msg Msg) {83- // Detect the start sequence.84- const bpStart = "\x1b[200~"85- if len(input) < len(bpStart) || string(input[:len(bpStart)]) != bpStart {86- return false, 0, nil87- }88-89- // Skip over the start sequence.90- input = input[len(bpStart):]91-92- // If we saw the start sequence, then we must have an end sequence93- // as well. Find it.94- const bpEnd = "\x1b[201~"95- idx := bytes.Index(input, []byte(bpEnd))96- inputLen := len(bpStart) + idx + len(bpEnd)97- if idx == -1 {98- // We have encountered the end of the input buffer without seeing99- // the marker for the end of the bracketed paste.100- // Tell the outer loop we have done a short read and we want more.101- return true, 0, nil102- }103-104- // The paste is everything in-between.105- paste := input[:idx]106-107- // All there is in-between is runes, not to be interpreted further.108- k := Key{Type: KeyRunes, Paste: true}109- for len(paste) > 0 {110- r, w := utf8.DecodeRune(paste)111- if r != utf8.RuneError {112- k.Runes = append(k.Runes, r)113- }114- paste = paste[w:]115- }116-117- return true, inputLen, KeyMsg(k)118-}119-120-// detectReportFocus detects a focus report sequence.121-func detectReportFocus(input []byte) (hasRF bool, width int, msg Msg) {122- switch {123- case bytes.Equal(input, []byte("\x1b[I")):124- return true, 3, FocusMsg{} //nolint:mnd125- case bytes.Equal(input, []byte("\x1b[O")):126- return true, 3, BlurMsg{} //nolint:mnd127- }128- return false, 0, nil129-}deleted:key_test.go-734 removed
1-package tea2-3-import (4- "bytes"5- "context"6- "errors"7- "flag"8- "fmt"9- "io"10- "math/rand"11- "reflect"12- "runtime"13- "sort"14- "strings"15- "sync"16- "testing"17- "time"18-)19-20-func TestKeyString(t *testing.T) {21- t.Run("alt+space", func(t *testing.T) {22- if got := KeyMsg(Key{23- Type: KeySpace,24- Alt: true,25- }).String(); got != "alt+ " {26- t.Fatalf(`expected a "alt+ ", got %q`, got)27- }28- })29-30- t.Run("runes", func(t *testing.T) {31- if got := KeyMsg(Key{32- Type: KeyRunes,33- Runes: []rune{'a'},34- }).String(); got != "a" {35- t.Fatalf(`expected an "a", got %q`, got)36- }37- })38-39- t.Run("invalid", func(t *testing.T) {40- if got := KeyMsg(Key{41- Type: KeyType(99999),42- }).String(); got != "" {43- t.Fatalf(`expected a "", got %q`, got)44- }45- })46-}47-48-func TestKeyTypeString(t *testing.T) {49- t.Run("space", func(t *testing.T) {50- if got := KeySpace.String(); got != " " {51- t.Fatalf(`expected a " ", got %q`, got)52- }53- })54-55- t.Run("invalid", func(t *testing.T) {56- if got := KeyType(99999).String(); got != "" {57- t.Fatalf(`expected a "", got %q`, got)58- }59- })60-}61-62-type seqTest struct {63- seq []byte64- msg Msg65-}66-67-// buildBaseSeqTests returns sequence tests that are valid for the68-// detectSequence() function.69-func buildBaseSeqTests() []seqTest {70- td := []seqTest{}71- for seq, key := range sequences {72- td = append(td, seqTest{[]byte(seq), KeyMsg(key)})73- if !key.Alt {74- key.Alt = true75- td = append(td, seqTest{[]byte("\x1b" + seq), KeyMsg(key)})76- }77- }78- // Add all the control characters.79- for i := keyNUL + 1; i <= keyDEL; i++ {80- if i == keyESC {81- // Not handled in detectSequence(), so not part of the base test82- // suite.83- continue84- }85- td = append(td, seqTest{[]byte{byte(i)}, KeyMsg{Type: i}})86- td = append(td, seqTest{[]byte{'\x1b', byte(i)}, KeyMsg{Type: i, Alt: true}})87- if i == keyUS {88- i = keyDEL - 189- }90- }91-92- // Additional special cases.93- td = append(td,94- // Unrecognized CSI sequence.95- seqTest{96- []byte{'\x1b', '[', '-', '-', '-', '-', 'X'},97- unknownCSISequenceMsg([]byte{'\x1b', '[', '-', '-', '-', '-', 'X'}),98- },99- // A lone space character.100- seqTest{101- []byte{' '},102- KeyMsg{Type: KeySpace, Runes: []rune(" ")},103- },104- // An escape character with the alt modifier.105- seqTest{106- []byte{'\x1b', ' '},107- KeyMsg{Type: KeySpace, Runes: []rune(" "), Alt: true},108- },109- )110- return td111-}112-113-func TestDetectSequence(t *testing.T) {114- td := buildBaseSeqTests()115- for _, tc := range td {116- t.Run(fmt.Sprintf("%q", string(tc.seq)), func(t *testing.T) {117- hasSeq, width, msg := detectSequence(tc.seq)118- if !hasSeq {119- t.Fatalf("no sequence found")120- }121- if width != len(tc.seq) {122- t.Errorf("parser did not consume the entire input: got %d, expected %d", width, len(tc.seq))123- }124- if !reflect.DeepEqual(tc.msg, msg) {125- t.Errorf("expected event %#v (%T), got %#v (%T)", tc.msg, tc.msg, msg, msg)126- }127- })128- }129-}130-131-func TestDetectOneMsg(t *testing.T) {132- td := buildBaseSeqTests()133- // Add tests for the inputs that detectOneMsg() can parse, but134- // detectSequence() cannot.135- td = append(td,136- // focus/blur137- seqTest{138- []byte{'\x1b', '[', 'I'},139- FocusMsg{},140- },141- seqTest{142- []byte{'\x1b', '[', 'O'},143- BlurMsg{},144- },145- // Mouse event.146- seqTest{147- []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)},148- MouseMsg{X: 32, Y: 16, Type: MouseWheelUp, Button: MouseButtonWheelUp, Action: MouseActionPress},149- },150- // SGR Mouse event.151- seqTest{152- []byte("\x1b[<0;33;17M"),153- MouseMsg{X: 32, Y: 16, Type: MouseLeft, Button: MouseButtonLeft, Action: MouseActionPress},154- },155- // Runes.156- seqTest{157- []byte{'a'},158- KeyMsg{Type: KeyRunes, Runes: []rune("a")},159- },160- seqTest{161- []byte{'\x1b', 'a'},162- KeyMsg{Type: KeyRunes, Runes: []rune("a"), Alt: true},163- },164- seqTest{165- []byte{'a', 'a', 'a'},166- KeyMsg{Type: KeyRunes, Runes: []rune("aaa")},167- },168- // Multi-byte rune.169- seqTest{170- []byte("☃"),171- KeyMsg{Type: KeyRunes, Runes: []rune("☃")},172- },173- seqTest{174- []byte("\x1b☃"),175- KeyMsg{Type: KeyRunes, Runes: []rune("☃"), Alt: true},176- },177- // Standalone control chacters.178- seqTest{179- []byte{'\x1b'},180- KeyMsg{Type: KeyEscape},181- },182- seqTest{183- []byte{byte(keySOH)},184- KeyMsg{Type: KeyCtrlA},185- },186- seqTest{187- []byte{'\x1b', byte(keySOH)},188- KeyMsg{Type: KeyCtrlA, Alt: true},189- },190- seqTest{191- []byte{byte(keyNUL)},192- KeyMsg{Type: KeyCtrlAt},193- },194- seqTest{195- []byte{'\x1b', byte(keyNUL)},196- KeyMsg{Type: KeyCtrlAt, Alt: true},197- },198- // Invalid characters.199- seqTest{200- []byte{'\x80'},201- unknownInputByteMsg(0x80),202- },203- )204-205- if runtime.GOOS != "windows" {206- // Sadly, utf8.DecodeRune([]byte(0xfe)) returns a valid rune on windows.207- // This is incorrect, but it makes our test fail if we try it out.208- td = append(td, seqTest{209- []byte{'\xfe'},210- unknownInputByteMsg(0xfe),211- })212- }213-214- for _, tc := range td {215- t.Run(fmt.Sprintf("%q", string(tc.seq)), func(t *testing.T) {216- width, msg := detectOneMsg(tc.seq, false /* canHaveMoreData */)217- if width != len(tc.seq) {218- t.Errorf("parser did not consume the entire input: got %d, expected %d", width, len(tc.seq))219- }220- if !reflect.DeepEqual(tc.msg, msg) {221- t.Errorf("expected event %#v (%T), got %#v (%T)", tc.msg, tc.msg, msg, msg)222- }223- })224- }225-}226-227-func TestReadLongInput(t *testing.T) {228- input := strings.Repeat("a", 1000)229- msgs := testReadInputs(t, bytes.NewReader([]byte(input)))230- if len(msgs) != 1 {231- t.Errorf("expected 1 messages, got %d", len(msgs))232- }233- km := msgs[0]234- k := Key(km.(KeyMsg))235- if k.Type != KeyRunes {236- t.Errorf("expected key runes, got %d", k.Type)237- }238- if len(k.Runes) != 1000 || !reflect.DeepEqual(k.Runes, []rune(input)) {239- t.Errorf("unexpected runes: %+v", k)240- }241- if k.Alt {242- t.Errorf("unexpected alt")243- }244-}245-246-func TestReadInput(t *testing.T) {247- type test struct {248- keyname string249- in []byte250- out []Msg251- }252- testData := []test{253- {254- "a",255- []byte{'a'},256- []Msg{257- KeyMsg{258- Type: KeyRunes,259- Runes: []rune{'a'},260- },261- },262- },263- {264- " ",265- []byte{' '},266- []Msg{267- KeyMsg{268- Type: KeySpace,269- Runes: []rune{' '},270- },271- },272- },273- {274- "a alt+a",275- []byte{'a', '\x1b', 'a'},276- []Msg{277- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},278- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true},279- },280- },281- {282- "a alt+a a",283- []byte{'a', '\x1b', 'a', 'a'},284- []Msg{285- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},286- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true},287- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},288- },289- },290- {291- "ctrl+a",292- []byte{byte(keySOH)},293- []Msg{294- KeyMsg{295- Type: KeyCtrlA,296- },297- },298- },299- {300- "ctrl+a ctrl+b",301- []byte{byte(keySOH), byte(keySTX)},302- []Msg{303- KeyMsg{Type: KeyCtrlA},304- KeyMsg{Type: KeyCtrlB},305- },306- },307- {308- "alt+a",309- []byte{byte(0x1b), 'a'},310- []Msg{311- KeyMsg{312- Type: KeyRunes,313- Alt: true,314- Runes: []rune{'a'},315- },316- },317- },318- {319- "abcd",320- []byte{'a', 'b', 'c', 'd'},321- []Msg{322- KeyMsg{323- Type: KeyRunes,324- Runes: []rune{'a', 'b', 'c', 'd'},325- },326- },327- },328- {329- "up",330- []byte("\x1b[A"),331- []Msg{332- KeyMsg{333- Type: KeyUp,334- },335- },336- },337- {338- "wheel up",339- []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)},340- []Msg{341- MouseMsg{342- X: 32,343- Y: 16,344- Type: MouseWheelUp,345- Button: MouseButtonWheelUp,346- Action: MouseActionPress,347- },348- },349- },350- {351- "left motion release",352- []byte{353- '\x1b', '[', 'M', byte(32) + 0b0010_0000, byte(32 + 33), byte(16 + 33),354- '\x1b', '[', 'M', byte(32) + 0b0000_0011, byte(64 + 33), byte(32 + 33),355- },356- []Msg{357- MouseMsg(MouseEvent{358- X: 32,359- Y: 16,360- Type: MouseLeft,361- Button: MouseButtonLeft,362- Action: MouseActionMotion,363- }),364- MouseMsg(MouseEvent{365- X: 64,366- Y: 32,367- Type: MouseRelease,368- Button: MouseButtonNone,369- Action: MouseActionRelease,370- }),371- },372- },373- {374- "shift+tab",375- []byte{'\x1b', '[', 'Z'},376- []Msg{377- KeyMsg{378- Type: KeyShiftTab,379- },380- },381- },382- {383- "enter",384- []byte{'\r'},385- []Msg{KeyMsg{Type: KeyEnter}},386- },387- {388- "alt+enter",389- []byte{'\x1b', '\r'},390- []Msg{391- KeyMsg{392- Type: KeyEnter,393- Alt: true,394- },395- },396- },397- {398- "insert",399- []byte{'\x1b', '[', '2', '~'},400- []Msg{401- KeyMsg{402- Type: KeyInsert,403- },404- },405- },406- {407- "alt+ctrl+a",408- []byte{'\x1b', byte(keySOH)},409- []Msg{410- KeyMsg{411- Type: KeyCtrlA,412- Alt: true,413- },414- },415- },416- {417- "?CSI[45 45 45 45 88]?",418- []byte{'\x1b', '[', '-', '-', '-', '-', 'X'},419- []Msg{unknownCSISequenceMsg([]byte{'\x1b', '[', '-', '-', '-', '-', 'X'})},420- },421- // Powershell sequences.422- {423- "up",424- []byte{'\x1b', 'O', 'A'},425- []Msg{KeyMsg{Type: KeyUp}},426- },427- {428- "down",429- []byte{'\x1b', 'O', 'B'},430- []Msg{KeyMsg{Type: KeyDown}},431- },432- {433- "right",434- []byte{'\x1b', 'O', 'C'},435- []Msg{KeyMsg{Type: KeyRight}},436- },437- {438- "left",439- []byte{'\x1b', 'O', 'D'},440- []Msg{KeyMsg{Type: KeyLeft}},441- },442- {443- "alt+enter",444- []byte{'\x1b', '\x0d'},445- []Msg{KeyMsg{Type: KeyEnter, Alt: true}},446- },447- {448- "alt+backspace",449- []byte{'\x1b', '\x7f'},450- []Msg{KeyMsg{Type: KeyBackspace, Alt: true}},451- },452- {453- "ctrl+@",454- []byte{'\x00'},455- []Msg{KeyMsg{Type: KeyCtrlAt}},456- },457- {458- "alt+ctrl+@",459- []byte{'\x1b', '\x00'},460- []Msg{KeyMsg{Type: KeyCtrlAt, Alt: true}},461- },462- {463- "esc",464- []byte{'\x1b'},465- []Msg{KeyMsg{Type: KeyEsc}},466- },467- {468- "alt+esc",469- []byte{'\x1b', '\x1b'},470- []Msg{KeyMsg{Type: KeyEsc, Alt: true}},471- },472- {473- "[a b] o",474- []byte{475- '\x1b', '[', '2', '0', '0', '~',476- 'a', ' ', 'b',477- '\x1b', '[', '2', '0', '1', '~',478- 'o',479- },480- []Msg{481- KeyMsg{Type: KeyRunes, Runes: []rune("a b"), Paste: true},482- KeyMsg{Type: KeyRunes, Runes: []rune("o")},483- },484- },485- {486- "[a\x03\nb]",487- []byte{488- '\x1b', '[', '2', '0', '0', '~',489- 'a', '\x03', '\n', 'b',490- '\x1b', '[', '2', '0', '1', '~',491- },492- []Msg{493- KeyMsg{Type: KeyRunes, Runes: []rune("a\x03\nb"), Paste: true},494- },495- },496- }497- if runtime.GOOS != "windows" {498- // Sadly, utf8.DecodeRune([]byte(0xfe)) returns a valid rune on windows.499- // This is incorrect, but it makes our test fail if we try it out.500- testData = append(testData,501- test{502- "?0xfe?",503- []byte{'\xfe'},504- []Msg{unknownInputByteMsg(0xfe)},505- },506- test{507- "a ?0xfe? b",508- []byte{'a', '\xfe', ' ', 'b'},509- []Msg{510- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},511- unknownInputByteMsg(0xfe),512- KeyMsg{Type: KeySpace, Runes: []rune{' '}},513- KeyMsg{Type: KeyRunes, Runes: []rune{'b'}},514- },515- },516- )517- }518-519- for i, td := range testData {520- t.Run(fmt.Sprintf("%d: %s", i, td.keyname), func(t *testing.T) {521- msgs := testReadInputs(t, bytes.NewReader(td.in))522- var buf strings.Builder523- for i, msg := range msgs {524- if i > 0 {525- buf.WriteByte(' ')526- }527- if s, ok := msg.(fmt.Stringer); ok {528- buf.WriteString(s.String())529- } else {530- fmt.Fprintf(&buf, "%#v:%T", msg, msg)531- }532- }533-534- title := buf.String()535- if title != td.keyname {536- t.Errorf("expected message titles:\n %s\ngot:\n %s", td.keyname, title)537- }538-539- if len(msgs) != len(td.out) {540- t.Fatalf("unexpected message list length: got %d, expected %d\n%#v", len(msgs), len(td.out), msgs)541- }542-543- if !reflect.DeepEqual(td.out, msgs) {544- t.Fatalf("expected:\n%#v\ngot:\n%#v", td.out, msgs)545- }546- })547- }548-}549-550-func testReadInputs(t *testing.T, input io.Reader) []Msg {551- // We'll check that the input reader finishes at the end552- // without error.553- var wg sync.WaitGroup554- var inputErr error555- ctx, cancel := context.WithCancel(context.Background())556- defer func() {557- cancel()558- wg.Wait()559- if inputErr != nil && !errors.Is(inputErr, io.EOF) {560- t.Fatalf("unexpected input error: %v", inputErr)561- }562- }()563-564- // The messages we're consuming.565- msgsC := make(chan Msg)566-567- // Start the reader in the background.568- wg.Add(1)569- go func() {570- defer wg.Done()571- inputErr = readAnsiInputs(ctx, msgsC, input)572- msgsC <- nil573- }()574-575- var msgs []Msg576-loop:577- for {578- select {579- case msg := <-msgsC:580- if msg == nil {581- // end of input marker for the test.582- break loop583- }584- msgs = append(msgs, msg)585- case <-time.After(2 * time.Second):586- t.Errorf("timeout waiting for input event")587- break loop588- }589- }590- return msgs591-}592-593-// randTest defines the test input and expected output for a sequence594-// of interleaved control sequences and control characters.595-type randTest struct {596- data []byte597- lengths []int598- names []string599-}600-601-// seed is the random seed to randomize the input. This helps check602-// that all the sequences get ultimately exercised.603-var seed = flag.Int64("seed", 0, "random seed (0 to autoselect)")604-605-// genRandomData generates a randomized test, with a random seed unless606-// the seed flag was set.607-func genRandomData(logfn func(int64), length int) randTest {608- // We'll use a random source. However, we give the user the option609- // to override it to a specific value for reproduceability.610- s := *seed611- if s == 0 {612- s = time.Now().UnixNano()613- }614- // Inform the user so they know what to reuse to get the same data.615- logfn(s)616- return genRandomDataWithSeed(s, length)617-}618-619-// genRandomDataWithSeed generates a randomized test with a fixed seed.620-func genRandomDataWithSeed(s int64, length int) randTest {621- src := rand.NewSource(s)622- r := rand.New(src)623-624- // allseqs contains all the sequences, in sorted order. We sort625- // to make the test deterministic (when the seed is also fixed).626- type seqpair struct {627- seq string628- name string629- }630- var allseqs []seqpair631- for seq, key := range sequences {632- allseqs = append(allseqs, seqpair{seq, key.String()})633- }634- sort.Slice(allseqs, func(i, j int) bool { return allseqs[i].seq < allseqs[j].seq })635-636- // res contains the computed test.637- var res randTest638-639- for len(res.data) < length {640- alt := r.Intn(2)641- prefix := ""642- esclen := 0643- if alt == 1 {644- prefix = "alt+"645- esclen = 1646- }647- kind := r.Intn(3)648- switch kind {649- case 0:650- // A control character.651- if alt == 1 {652- res.data = append(res.data, '\x1b')653- }654- res.data = append(res.data, 1)655- res.names = append(res.names, prefix+"ctrl+a")656- res.lengths = append(res.lengths, 1+esclen)657-658- case 1, 2:659- // A sequence.660- seqi := r.Intn(len(allseqs))661- s := allseqs[seqi]662- if strings.HasPrefix(s.name, "alt+") {663- esclen = 0664- prefix = ""665- alt = 0666- }667- if alt == 1 {668- res.data = append(res.data, '\x1b')669- }670- res.data = append(res.data, s.seq...)671- res.names = append(res.names, prefix+s.name)672- res.lengths = append(res.lengths, len(s.seq)+esclen)673- }674- }675- return res676-}677-678-// TestDetectRandomSequencesLex checks that the lex-generated sequence679-// detector works over concatenations of random sequences.680-func TestDetectRandomSequencesLex(t *testing.T) {681- runTestDetectSequence(t, detectSequence)682-}683-684-func runTestDetectSequence(685- t *testing.T, detectSequence func(input []byte) (hasSeq bool, width int, msg Msg),686-) {687- for i := 0; i < 10; i++ {688- t.Run("", func(t *testing.T) {689- td := genRandomData(func(s int64) { t.Logf("using random seed: %d", s) }, 1000)690-691- t.Logf("%#v", td)692-693- // tn is the event number in td.694- // i is the cursor in the input data.695- // w is the length of the last sequence detected.696- for tn, i, w := 0, 0, 0; i < len(td.data); tn, i = tn+1, i+w {697- hasSequence, width, msg := detectSequence(td.data[i:])698- if !hasSequence {699- t.Fatalf("at %d (ev %d): failed to find sequence", i, tn)700- }701- if width != td.lengths[tn] {702- t.Errorf("at %d (ev %d): expected width %d, got %d", i, tn, td.lengths[tn], width)703- }704- w = width705-706- s, ok := msg.(fmt.Stringer)707- if !ok {708- t.Errorf("at %d (ev %d): expected stringer event, got %T", i, tn, msg)709- } else {710- if td.names[tn] != s.String() {711- t.Errorf("at %d (ev %d): expected event %q, got %q", i, tn, td.names[tn], s.String())712- }713- }714- }715- })716- }717-}718-719-// TestDetectRandomSequencesMap checks that the map-based sequence720-// detector works over concatenations of random sequences.721-func TestDetectRandomSequencesMap(t *testing.T) {722- runTestDetectSequence(t, detectSequence)723-}724-725-// BenchmarkDetectSequenceMap benchmarks the map-based sequence726-// detector.727-func BenchmarkDetectSequenceMap(b *testing.B) {728- td := genRandomDataWithSeed(123, 10000)729- for i := 0; i < b.N; i++ {730- for j, w := 0, 0; j < len(td.data); j += w {731- _, w, _ = detectSequence(td.data[j:])732- }733- }734-}deleted:key_windows.go-441 removed
1-//go:build windows2-// +build windows3-4-package tea5-6-import (7- "context"8- "fmt"9- "io"10- "time"11-12- "github.com/erikgeiser/coninput"13- localereader "github.com/mattn/go-localereader"14- "github.com/muesli/cancelreader"15-)16-17-func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {18- if coninReader, ok := input.(*conInputReader); ok {19- return readConInputs(ctx, msgs, coninReader)20- }21-22- return readAnsiInputs(ctx, msgs, localereader.NewReader(input))23-}24-25-func readConInputs(ctx context.Context, msgsch chan<- Msg, con *conInputReader) error {26- var ps coninput.ButtonState // keep track of previous mouse state27- var ws coninput.WindowBufferSizeEventRecord // keep track of the last window size event28- for {29- events, err := peekAndReadConsInput(con)30- if err != nil {31- return err32- }33- for _, event := range events {34- var msgs []Msg35- switch e := event.Unwrap().(type) {36- case coninput.KeyEventRecord:37- if !e.KeyDown || e.VirtualKeyCode == coninput.VK_SHIFT {38- continue39- }40-41- for i := 0; i < int(e.RepeatCount); i++ {42- eventKeyType := keyType(e)43- var runes []rune44-45- // Add the character only if the key type is an actual character and not a control sequence.46- // This mimics the behavior in readAnsiInputs where the character is also removed.47- // We don't need to handle KeySpace here. See the comment in keyType().48- if eventKeyType == KeyRunes {49- runes = []rune{e.Char}50- }51-52- msgs = append(msgs, KeyMsg{53- Type: eventKeyType,54- Runes: runes,55- Alt: e.ControlKeyState.Contains(coninput.LEFT_ALT_PRESSED | coninput.RIGHT_ALT_PRESSED),56- })57- }58- case coninput.WindowBufferSizeEventRecord:59- if e != ws {60- ws = e61- msgs = append(msgs, WindowSizeMsg{62- Width: int(e.Size.X),63- Height: int(e.Size.Y),64- })65- }66- case coninput.MouseEventRecord:67- event := mouseEvent(ps, e)68- if event.Type != MouseUnknown {69- msgs = append(msgs, event)70- }71- ps = e.ButtonState72- case coninput.FocusEventRecord, coninput.MenuEventRecord:73- // ignore74- default: // unknown event75- continue76- }77-78- // Send all messages to the channel79- for _, msg := range msgs {80- select {81- case msgsch <- msg:82- case <-ctx.Done():83- err := ctx.Err()84- if err != nil {85- return fmt.Errorf("coninput context error: %w", err)86- }87- return nil88- }89- }90- }91- }92-}93-94-// Peek for new input in a tight loop and then read the input.95-// windows.CancelIo* does not work reliably so peek first and only use the data if96-// the console input is not cancelled.97-func peekAndReadConsInput(con *conInputReader) ([]coninput.InputRecord, error) {98- events, err := peekConsInput(con)99- if err != nil {100- return events, err101- }102- events, err = coninput.ReadNConsoleInputs(con.conin, intToUint32OrDie(len(events)))103- if con.isCanceled() {104- return events, cancelreader.ErrCanceled105- }106- if err != nil {107- return events, fmt.Errorf("read coninput events: %w", err)108- }109- return events, nil110-}111-112-// Convert i to unit32 or panic if it cannot be converted. Check satisfies lint G115.113-func intToUint32OrDie(i int) uint32 {114- if i < 0 {115- panic("cannot convert numEvents " + fmt.Sprint(i) + " to uint32")116- }117- return uint32(i) //nolint:gosec118-}119-120-// Keeps peeking until there is data or the input is cancelled.121-func peekConsInput(con *conInputReader) ([]coninput.InputRecord, error) {122- for {123- events, err := coninput.PeekNConsoleInputs(con.conin, 16)124- if con.isCanceled() {125- return events, cancelreader.ErrCanceled126- }127- if err != nil {128- return events, fmt.Errorf("peek coninput events: %w", err)129- }130- if len(events) > 0 {131- return events, nil132- }133- // Sleep for a bit to avoid busy waiting.134- time.Sleep(16 * time.Millisecond)135- }136-}137-138-func mouseEventButton(p, s coninput.ButtonState) (button MouseButton, action MouseAction) {139- btn := p ^ s140- action = MouseActionPress141- if btn&s == 0 {142- action = MouseActionRelease143- }144-145- if btn == 0 {146- switch {147- case s&coninput.FROM_LEFT_1ST_BUTTON_PRESSED > 0:148- button = MouseButtonLeft149- case s&coninput.FROM_LEFT_2ND_BUTTON_PRESSED > 0:150- button = MouseButtonMiddle151- case s&coninput.RIGHTMOST_BUTTON_PRESSED > 0:152- button = MouseButtonRight153- case s&coninput.FROM_LEFT_3RD_BUTTON_PRESSED > 0:154- button = MouseButtonBackward155- case s&coninput.FROM_LEFT_4TH_BUTTON_PRESSED > 0:156- button = MouseButtonForward157- }158- return button, action159- }160-161- switch btn {162- case coninput.FROM_LEFT_1ST_BUTTON_PRESSED: // left button163- button = MouseButtonLeft164- case coninput.RIGHTMOST_BUTTON_PRESSED: // right button165- button = MouseButtonRight166- case coninput.FROM_LEFT_2ND_BUTTON_PRESSED: // middle button167- button = MouseButtonMiddle168- case coninput.FROM_LEFT_3RD_BUTTON_PRESSED: // unknown (possibly mouse backward)169- button = MouseButtonBackward170- case coninput.FROM_LEFT_4TH_BUTTON_PRESSED: // unknown (possibly mouse forward)171- button = MouseButtonForward172- }173-174- return button, action175-}176-177-func mouseEvent(p coninput.ButtonState, e coninput.MouseEventRecord) MouseMsg {178- ev := MouseMsg{179- X: int(e.MousePositon.X),180- Y: int(e.MousePositon.Y),181- Alt: e.ControlKeyState.Contains(coninput.LEFT_ALT_PRESSED | coninput.RIGHT_ALT_PRESSED),182- Ctrl: e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED | coninput.RIGHT_CTRL_PRESSED),183- Shift: e.ControlKeyState.Contains(coninput.SHIFT_PRESSED),184- }185- switch e.EventFlags {186- case coninput.CLICK, coninput.DOUBLE_CLICK:187- ev.Button, ev.Action = mouseEventButton(p, e.ButtonState)188- if ev.Action == MouseActionRelease {189- ev.Type = MouseRelease190- }191- switch ev.Button { //nolint:exhaustive192- case MouseButtonLeft:193- ev.Type = MouseLeft194- case MouseButtonMiddle:195- ev.Type = MouseMiddle196- case MouseButtonRight:197- ev.Type = MouseRight198- case MouseButtonBackward:199- ev.Type = MouseBackward200- case MouseButtonForward:201- ev.Type = MouseForward202- }203- case coninput.MOUSE_WHEELED:204- if e.WheelDirection > 0 {205- ev.Button = MouseButtonWheelUp206- ev.Type = MouseWheelUp207- } else {208- ev.Button = MouseButtonWheelDown209- ev.Type = MouseWheelDown210- }211- case coninput.MOUSE_HWHEELED:212- if e.WheelDirection > 0 {213- ev.Button = MouseButtonWheelRight214- ev.Type = MouseWheelRight215- } else {216- ev.Button = MouseButtonWheelLeft217- ev.Type = MouseWheelLeft218- }219- case coninput.MOUSE_MOVED:220- ev.Button, _ = mouseEventButton(p, e.ButtonState)221- ev.Action = MouseActionMotion222- ev.Type = MouseMotion223- }224-225- return ev226-}227-228-func keyType(e coninput.KeyEventRecord) KeyType {229- code := e.VirtualKeyCode230-231- shiftPressed := e.ControlKeyState.Contains(coninput.SHIFT_PRESSED)232- ctrlPressed := e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED | coninput.RIGHT_CTRL_PRESSED)233-234- switch code { //nolint:exhaustive235- case coninput.VK_RETURN:236- return KeyEnter237- case coninput.VK_BACK:238- return KeyBackspace239- case coninput.VK_TAB:240- if shiftPressed {241- return KeyShiftTab242- }243- return KeyTab244- case coninput.VK_SPACE:245- return KeyRunes // this could be KeySpace but on unix space also produces KeyRunes246- case coninput.VK_ESCAPE:247- return KeyEscape248- case coninput.VK_UP:249- switch {250- case shiftPressed && ctrlPressed:251- return KeyCtrlShiftUp252- case shiftPressed:253- return KeyShiftUp254- case ctrlPressed:255- return KeyCtrlUp256- default:257- return KeyUp258- }259- case coninput.VK_DOWN:260- switch {261- case shiftPressed && ctrlPressed:262- return KeyCtrlShiftDown263- case shiftPressed:264- return KeyShiftDown265- case ctrlPressed:266- return KeyCtrlDown267- default:268- return KeyDown269- }270- case coninput.VK_RIGHT:271- switch {272- case shiftPressed && ctrlPressed:273- return KeyCtrlShiftRight274- case shiftPressed:275- return KeyShiftRight276- case ctrlPressed:277- return KeyCtrlRight278- default:279- return KeyRight280- }281- case coninput.VK_LEFT:282- switch {283- case shiftPressed && ctrlPressed:284- return KeyCtrlShiftLeft285- case shiftPressed:286- return KeyShiftLeft287- case ctrlPressed:288- return KeyCtrlLeft289- default:290- return KeyLeft291- }292- case coninput.VK_HOME:293- switch {294- case shiftPressed && ctrlPressed:295- return KeyCtrlShiftHome296- case shiftPressed:297- return KeyShiftHome298- case ctrlPressed:299- return KeyCtrlHome300- default:301- return KeyHome302- }303- case coninput.VK_END:304- switch {305- case shiftPressed && ctrlPressed:306- return KeyCtrlShiftEnd307- case shiftPressed:308- return KeyShiftEnd309- case ctrlPressed:310- return KeyCtrlEnd311- default:312- return KeyEnd313- }314- case coninput.VK_PRIOR:315- return KeyPgUp316- case coninput.VK_NEXT:317- return KeyPgDown318- case coninput.VK_DELETE:319- return KeyDelete320- case coninput.VK_F1:321- return KeyF1322- case coninput.VK_F2:323- return KeyF2324- case coninput.VK_F3:325- return KeyF3326- case coninput.VK_F4:327- return KeyF4328- case coninput.VK_F5:329- return KeyF5330- case coninput.VK_F6:331- return KeyF6332- case coninput.VK_F7:333- return KeyF7334- case coninput.VK_F8:335- return KeyF8336- case coninput.VK_F9:337- return KeyF9338- case coninput.VK_F10:339- return KeyF10340- case coninput.VK_F11:341- return KeyF11342- case coninput.VK_F12:343- return KeyF12344- case coninput.VK_F13:345- return KeyF13346- case coninput.VK_F14:347- return KeyF14348- case coninput.VK_F15:349- return KeyF15350- case coninput.VK_F16:351- return KeyF16352- case coninput.VK_F17:353- return KeyF17354- case coninput.VK_F18:355- return KeyF18356- case coninput.VK_F19:357- return KeyF19358- case coninput.VK_F20:359- return KeyF20360- default:361- switch {362- case e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED) && e.ControlKeyState.Contains(coninput.RIGHT_ALT_PRESSED):363- // AltGr is pressed, then it's a rune.364- fallthrough365- case !e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED) && !e.ControlKeyState.Contains(coninput.RIGHT_CTRL_PRESSED):366- return KeyRunes367- }368-369- switch e.Char {370- case '@':371- return KeyCtrlAt372- case '\x01':373- return KeyCtrlA374- case '\x02':375- return KeyCtrlB376- case '\x03':377- return KeyCtrlC378- case '\x04':379- return KeyCtrlD380- case '\x05':381- return KeyCtrlE382- case '\x06':383- return KeyCtrlF384- case '\a':385- return KeyCtrlG386- case '\b':387- return KeyCtrlH388- case '\t':389- return KeyCtrlI390- case '\n':391- return KeyCtrlJ392- case '\v':393- return KeyCtrlK394- case '\f':395- return KeyCtrlL396- case '\r':397- return KeyCtrlM398- case '\x0e':399- return KeyCtrlN400- case '\x0f':401- return KeyCtrlO402- case '\x10':403- return KeyCtrlP404- case '\x11':405- return KeyCtrlQ406- case '\x12':407- return KeyCtrlR408- case '\x13':409- return KeyCtrlS410- case '\x14':411- return KeyCtrlT412- case '\x15':413- return KeyCtrlU414- case '\x16':415- return KeyCtrlV416- case '\x17':417- return KeyCtrlW418- case '\x18':419- return KeyCtrlX420- case '\x19':421- return KeyCtrlY422- case '\x1a':423- return KeyCtrlZ424- case '\x1b':425- return KeyCtrlOpenBracket // KeyEscape426- case '\x1c':427- return KeyCtrlBackslash428- case '\x1f':429- return KeyCtrlUnderscore430- }431-432- switch code { //nolint:exhaustive433- case coninput.VK_OEM_4:434- return KeyCtrlOpenBracket435- case coninput.VK_OEM_6:436- return KeyCtrlCloseBracket437- }438-439- return KeyRunes440- }441-}modified:key.go+321 added-665 removed
1 package tea2 3 import (4- "context"4 "fmt"6- "io"7- "regexp"8- "strings"9- "unicode/utf8"10-)5 12-// KeyMsg contains information about a keypress. KeyMsgs are always sent to13-// the program's update function. There are a couple general patterns you could14-// use to check for keypresses:15-//16-// // Switch on the string representation of the key (shorter)17-// switch msg := msg.(type) {18-// case KeyMsg:19-// switch msg.String() {20-// case "enter":21-// fmt.Println("you pressed enter!")22-// case "a":23-// fmt.Println("you pressed a!")24-// }25-// }26-//27-// // Switch on the key type (more foolproof)28-// switch msg := msg.(type) {29-// case KeyMsg:30-// switch msg.Type {31-// case KeyEnter:32-// fmt.Println("you pressed enter!")33-// case KeyRunes:34-// switch string(msg.Runes) {35-// case "a":36-// fmt.Println("you pressed a!")37-// }38-// }39-// }40-//41-// Note that Key.Runes will always contain at least one character, so you can42-// always safely call Key.Runes[0]. In most cases Key.Runes will only contain43-// one character, though certain input method editors (most notably Chinese44-// IMEs) can input multiple runes at once.45-type KeyMsg Key46-47-// String returns a string representation for a key message. It's safe (and48-// encouraged) for use in key comparison.49-func (k KeyMsg) String() (str string) {50- return Key(k).String()51-}52-53-// Key contains information about a keypress.54-type Key struct {55- Type KeyType56- Runes []rune57- Alt bool58- Paste bool59-}60-61-// String returns a friendly string representation for a key. It's safe (and62-// encouraged) for use in key comparison.63-//64-// k := Key{Type: KeyEnter}65-// fmt.Println(k)66-// // Output: enter67-func (k Key) String() (str string) {68- var buf strings.Builder69- if k.Alt {70- buf.WriteString("alt+")71- }72- if k.Type == KeyRunes {73- if k.Paste {74- // Note: bubbles/keys bindings currently do string compares to75- // recognize shortcuts. Since pasted text should never activate76- // shortcuts, we need to ensure that the binding code doesn't77- // match Key events that result from pastes. We achieve this78- // here by enclosing pastes in '[...]' so that the string79- // comparison in Matches() fails in that case.80- buf.WriteByte('[')81- }82- buf.WriteString(string(k.Runes))83- if k.Paste {84- buf.WriteByte(']')85- }86- return buf.String()87- } else if s, ok := keyNames[k.Type]; ok {88- buf.WriteString(s)89- return buf.String()90- }91- return ""92-}93-94-// KeyType indicates the key pressed, such as KeyEnter or KeyBreak or KeyCtrlC.95-// All other keys will be type KeyRunes. To get the rune value, check the Rune96-// method on a Key struct, or use the Key.String() method:97-//98-// k := Key{Type: KeyRunes, Runes: []rune{'a'}, Alt: true}99-// if k.Type == KeyRunes {100-//101-// fmt.Println(k.Runes)102-// // Output: a103-//104-// fmt.Println(k.String())105-// // Output: alt+a106-//107-// }108-type KeyType int109-110-func (k KeyType) String() (str string) {111- if s, ok := keyNames[k]; ok {112- return s113- }114- return ""115-}116-117-// Control keys. We could do this with an iota, but the values are very118-// specific, so we set the values explicitly to avoid any confusion.119-//120-// See also:121-// https://en.wikipedia.org/wiki/C0_and_C1_control_codes122-const (123- keyNUL KeyType = 0 // null, \0124- keySOH KeyType = 1 // start of heading125- keySTX KeyType = 2 // start of text126- keyETX KeyType = 3 // break, ctrl+c127- keyEOT KeyType = 4 // end of transmission128- keyENQ KeyType = 5 // enquiry129- keyACK KeyType = 6 // acknowledge130- keyBEL KeyType = 7 // bell, \a131- keyBS KeyType = 8 // backspace132- keyHT KeyType = 9 // horizontal tabulation, \t133- keyLF KeyType = 10 // line feed, \n134- keyVT KeyType = 11 // vertical tabulation \v135- keyFF KeyType = 12 // form feed \f136- keyCR KeyType = 13 // carriage return, \r137- keySO KeyType = 14 // shift out138- keySI KeyType = 15 // shift in139- keyDLE KeyType = 16 // data link escape140- keyDC1 KeyType = 17 // device control one141- keyDC2 KeyType = 18 // device control two142- keyDC3 KeyType = 19 // device control three143- keyDC4 KeyType = 20 // device control four144- keyNAK KeyType = 21 // negative acknowledge145- keySYN KeyType = 22 // synchronous idle146- keyETB KeyType = 23 // end of transmission block147- keyCAN KeyType = 24 // cancel148- keyEM KeyType = 25 // end of medium149- keySUB KeyType = 26 // substitution150- keyESC KeyType = 27 // escape, \e151- keyFS KeyType = 28 // file separator152- keyGS KeyType = 29 // group separator153- keyRS KeyType = 30 // record separator154- keyUS KeyType = 31 // unit separator155- keyDEL KeyType = 127 // delete. on most systems this is mapped to backspace, I hear6+ uv "github.com/charmbracelet/ultraviolet"7 )8 158-// Control key aliases.9 const (160- KeyNull KeyType = keyNUL161- KeyBreak KeyType = keyETX162- KeyEnter KeyType = keyCR163- KeyBackspace KeyType = keyDEL164- KeyTab KeyType = keyHT165- KeyEsc KeyType = keyESC166- KeyEscape KeyType = keyESC167-168- KeyCtrlAt KeyType = keyNUL // ctrl+@169- KeyCtrlA KeyType = keySOH170- KeyCtrlB KeyType = keySTX171- KeyCtrlC KeyType = keyETX172- KeyCtrlD KeyType = keyEOT173- KeyCtrlE KeyType = keyENQ174- KeyCtrlF KeyType = keyACK175- KeyCtrlG KeyType = keyBEL176- KeyCtrlH KeyType = keyBS177- KeyCtrlI KeyType = keyHT178- KeyCtrlJ KeyType = keyLF179- KeyCtrlK KeyType = keyVT180- KeyCtrlL KeyType = keyFF181- KeyCtrlM KeyType = keyCR182- KeyCtrlN KeyType = keySO183- KeyCtrlO KeyType = keySI184- KeyCtrlP KeyType = keyDLE185- KeyCtrlQ KeyType = keyDC1186- KeyCtrlR KeyType = keyDC2187- KeyCtrlS KeyType = keyDC3188- KeyCtrlT KeyType = keyDC4189- KeyCtrlU KeyType = keyNAK190- KeyCtrlV KeyType = keySYN191- KeyCtrlW KeyType = keyETB192- KeyCtrlX KeyType = keyCAN193- KeyCtrlY KeyType = keyEM194- KeyCtrlZ KeyType = keySUB195- KeyCtrlOpenBracket KeyType = keyESC // ctrl+[196- KeyCtrlBackslash KeyType = keyFS // ctrl+\197- KeyCtrlCloseBracket KeyType = keyGS // ctrl+]198- KeyCtrlCaret KeyType = keyRS // ctrl+^199- KeyCtrlUnderscore KeyType = keyUS // ctrl+_200- KeyCtrlQuestionMark KeyType = keyDEL // ctrl+?10+ // KeyExtended is a special key code used to signify that a key event11+ // contains multiple runes.12+ KeyExtended = uv.KeyExtended13 )14 203-// Other keys.15+// Special key symbols.16 const (205- KeyRunes KeyType = -(iota + 1)206- KeyUp207- KeyDown208- KeyRight209- KeyLeft210- KeyShiftTab211- KeyHome212- KeyEnd213- KeyPgUp214- KeyPgDown215- KeyCtrlPgUp216- KeyCtrlPgDown217- KeyDelete218- KeyInsert219- KeySpace220- KeyCtrlUp221- KeyCtrlDown222- KeyCtrlRight223- KeyCtrlLeft224- KeyCtrlHome225- KeyCtrlEnd226- KeyShiftUp227- KeyShiftDown228- KeyShiftRight229- KeyShiftLeft230- KeyShiftHome231- KeyShiftEnd232- KeyCtrlShiftUp233- KeyCtrlShiftDown234- KeyCtrlShiftLeft235- KeyCtrlShiftRight236- KeyCtrlShiftHome237- KeyCtrlShiftEnd238- KeyF1239- KeyF2240- KeyF3241- KeyF4242- KeyF5243- KeyF6244- KeyF7245- KeyF8246- KeyF9247- KeyF10248- KeyF11249- KeyF12250- KeyF13251- KeyF14252- KeyF15253- KeyF16254- KeyF17255- KeyF18256- KeyF19257- KeyF20258-)17 260-// Mappings for control keys and other special keys to friendly consts.261-var keyNames = map[KeyType]string{262- // Control keys.18+ // Special keys.263- keyNUL: "ctrl+@", // also ctrl+` (that's ctrl+backtick)264- keySOH: "ctrl+a",265- keySTX: "ctrl+b",266- keyETX: "ctrl+c",267- keyEOT: "ctrl+d",268- keyENQ: "ctrl+e",269- keyACK: "ctrl+f",270- keyBEL: "ctrl+g",271- keyBS: "ctrl+h",272- keyHT: "tab", // also ctrl+i273- keyLF: "ctrl+j",274- keyVT: "ctrl+k",275- keyFF: "ctrl+l",276- keyCR: "enter",277- keySO: "ctrl+n",278- keySI: "ctrl+o",279- keyDLE: "ctrl+p",280- keyDC1: "ctrl+q",281- keyDC2: "ctrl+r",282- keyDC3: "ctrl+s",283- keyDC4: "ctrl+t",284- keyNAK: "ctrl+u",285- keySYN: "ctrl+v",286- keyETB: "ctrl+w",287- keyCAN: "ctrl+x",288- keyEM: "ctrl+y",289- keySUB: "ctrl+z",290- keyESC: "esc",291- keyFS: "ctrl+\\",292- keyGS: "ctrl+]",293- keyRS: "ctrl+^",294- keyUS: "ctrl+_",295- keyDEL: "backspace",19 297- // Other keys.298- KeyRunes: "runes",299- KeyUp: "up",300- KeyDown: "down",301- KeyRight: "right",302- KeySpace: " ", // for backwards compatibility303- KeyLeft: "left",304- KeyShiftTab: "shift+tab",305- KeyHome: "home",306- KeyEnd: "end",307- KeyCtrlHome: "ctrl+home",308- KeyCtrlEnd: "ctrl+end",309- KeyShiftHome: "shift+home",310- KeyShiftEnd: "shift+end",311- KeyCtrlShiftHome: "ctrl+shift+home",312- KeyCtrlShiftEnd: "ctrl+shift+end",313- KeyPgUp: "pgup",314- KeyPgDown: "pgdown",315- KeyCtrlPgUp: "ctrl+pgup",316- KeyCtrlPgDown: "ctrl+pgdown",317- KeyDelete: "delete",318- KeyInsert: "insert",319- KeyCtrlUp: "ctrl+up",320- KeyCtrlDown: "ctrl+down",321- KeyCtrlRight: "ctrl+right",322- KeyCtrlLeft: "ctrl+left",323- KeyShiftUp: "shift+up",324- KeyShiftDown: "shift+down",325- KeyShiftRight: "shift+right",326- KeyShiftLeft: "shift+left",327- KeyCtrlShiftUp: "ctrl+shift+up",328- KeyCtrlShiftDown: "ctrl+shift+down",329- KeyCtrlShiftLeft: "ctrl+shift+left",330- KeyCtrlShiftRight: "ctrl+shift+right",331- KeyF1: "f1",332- KeyF2: "f2",333- KeyF3: "f3",334- KeyF4: "f4",335- KeyF5: "f5",336- KeyF6: "f6",337- KeyF7: "f7",338- KeyF8: "f8",339- KeyF9: "f9",340- KeyF10: "f10",341- KeyF11: "f11",342- KeyF12: "f12",343- KeyF13: "f13",344- KeyF14: "f14",345- KeyF15: "f15",346- KeyF16: "f16",347- KeyF17: "f17",348- KeyF18: "f18",349- KeyF19: "f19",350- KeyF20: "f20",351-}20+ KeyUp = uv.KeyUp21+ KeyDown = uv.KeyDown22+ KeyRight = uv.KeyRight23+ KeyLeft = uv.KeyLeft24+ KeyBegin = uv.KeyBegin25+ KeyFind = uv.KeyFind26+ KeyInsert = uv.KeyInsert27+ KeyDelete = uv.KeyDelete28+ KeySelect = uv.KeySelect29+ KeyPgUp = uv.KeyPgUp30+ KeyPgDown = uv.KeyPgDown31+ KeyHome = uv.KeyHome32+ KeyEnd = uv.KeyEnd33 353-// Sequence mappings.354-var sequences = map[string]Key{355- // Arrow keys356- "\x1b[A": {Type: KeyUp},357- "\x1b[B": {Type: KeyDown},358- "\x1b[C": {Type: KeyRight},359- "\x1b[D": {Type: KeyLeft},360- "\x1b[1;2A": {Type: KeyShiftUp},361- "\x1b[1;2B": {Type: KeyShiftDown},362- "\x1b[1;2C": {Type: KeyShiftRight},363- "\x1b[1;2D": {Type: KeyShiftLeft},364- "\x1b[OA": {Type: KeyShiftUp}, // DECCKM365- "\x1b[OB": {Type: KeyShiftDown}, // DECCKM366- "\x1b[OC": {Type: KeyShiftRight}, // DECCKM367- "\x1b[OD": {Type: KeyShiftLeft}, // DECCKM368- "\x1b[a": {Type: KeyShiftUp}, // urxvt369- "\x1b[b": {Type: KeyShiftDown}, // urxvt370- "\x1b[c": {Type: KeyShiftRight}, // urxvt371- "\x1b[d": {Type: KeyShiftLeft}, // urxvt372- "\x1b[1;3A": {Type: KeyUp, Alt: true},373- "\x1b[1;3B": {Type: KeyDown, Alt: true},374- "\x1b[1;3C": {Type: KeyRight, Alt: true},375- "\x1b[1;3D": {Type: KeyLeft, Alt: true},34+ // Keypad keys.35 377- "\x1b[1;4A": {Type: KeyShiftUp, Alt: true},378- "\x1b[1;4B": {Type: KeyShiftDown, Alt: true},379- "\x1b[1;4C": {Type: KeyShiftRight, Alt: true},380- "\x1b[1;4D": {Type: KeyShiftLeft, Alt: true},36+ KeyKpEnter = uv.KeyKpEnter37+ KeyKpEqual = uv.KeyKpEqual38+ KeyKpMultiply = uv.KeyKpMultiply39+ KeyKpPlus = uv.KeyKpPlus40+ KeyKpComma = uv.KeyKpComma41+ KeyKpMinus = uv.KeyKpMinus42+ KeyKpDecimal = uv.KeyKpDecimal43+ KeyKpDivide = uv.KeyKpDivide44+ KeyKp0 = uv.KeyKp045+ KeyKp1 = uv.KeyKp146+ KeyKp2 = uv.KeyKp247+ KeyKp3 = uv.KeyKp348+ KeyKp4 = uv.KeyKp449+ KeyKp5 = uv.KeyKp550+ KeyKp6 = uv.KeyKp651+ KeyKp7 = uv.KeyKp752+ KeyKp8 = uv.KeyKp853+ KeyKp9 = uv.KeyKp954 382- "\x1b[1;5A": {Type: KeyCtrlUp},383- "\x1b[1;5B": {Type: KeyCtrlDown},384- "\x1b[1;5C": {Type: KeyCtrlRight},385- "\x1b[1;5D": {Type: KeyCtrlLeft},386- "\x1b[Oa": {Type: KeyCtrlUp, Alt: true}, // urxvt387- "\x1b[Ob": {Type: KeyCtrlDown, Alt: true}, // urxvt388- "\x1b[Oc": {Type: KeyCtrlRight, Alt: true}, // urxvt389- "\x1b[Od": {Type: KeyCtrlLeft, Alt: true}, // urxvt390- "\x1b[1;6A": {Type: KeyCtrlShiftUp},391- "\x1b[1;6B": {Type: KeyCtrlShiftDown},392- "\x1b[1;6C": {Type: KeyCtrlShiftRight},393- "\x1b[1;6D": {Type: KeyCtrlShiftLeft},394- "\x1b[1;7A": {Type: KeyCtrlUp, Alt: true},395- "\x1b[1;7B": {Type: KeyCtrlDown, Alt: true},396- "\x1b[1;7C": {Type: KeyCtrlRight, Alt: true},397- "\x1b[1;7D": {Type: KeyCtrlLeft, Alt: true},398- "\x1b[1;8A": {Type: KeyCtrlShiftUp, Alt: true},399- "\x1b[1;8B": {Type: KeyCtrlShiftDown, Alt: true},400- "\x1b[1;8C": {Type: KeyCtrlShiftRight, Alt: true},401- "\x1b[1;8D": {Type: KeyCtrlShiftLeft, Alt: true},55+ // The following are keys defined in the Kitty keyboard protocol.56+ // XXX: Investigate the names of these keys.57+ KeyKpSep = uv.KeyKpSep58+ KeyKpUp = uv.KeyKpUp59+ KeyKpDown = uv.KeyKpDown60+ KeyKpLeft = uv.KeyKpLeft61+ KeyKpRight = uv.KeyKpRight62+ KeyKpPgUp = uv.KeyKpPgUp63+ KeyKpPgDown = uv.KeyKpPgDown64+ KeyKpHome = uv.KeyKpHome65+ KeyKpEnd = uv.KeyKpEnd66+ KeyKpInsert = uv.KeyKpInsert67+ KeyKpDelete = uv.KeyKpDelete68+ KeyKpBegin = uv.KeyKpBegin69 403- // Miscellaneous keys404- "\x1b[Z": {Type: KeyShiftTab},70+ // Function keys.71 406- "\x1b[2~": {Type: KeyInsert},407- "\x1b[3;2~": {Type: KeyInsert, Alt: true},72+ KeyF1 = uv.KeyF173+ KeyF2 = uv.KeyF274+ KeyF3 = uv.KeyF375+ KeyF4 = uv.KeyF476+ KeyF5 = uv.KeyF577+ KeyF6 = uv.KeyF678+ KeyF7 = uv.KeyF779+ KeyF8 = uv.KeyF880+ KeyF9 = uv.KeyF981+ KeyF10 = uv.KeyF1082+ KeyF11 = uv.KeyF1183+ KeyF12 = uv.KeyF1284+ KeyF13 = uv.KeyF1385+ KeyF14 = uv.KeyF1486+ KeyF15 = uv.KeyF1587+ KeyF16 = uv.KeyF1688+ KeyF17 = uv.KeyF1789+ KeyF18 = uv.KeyF1890+ KeyF19 = uv.KeyF1991+ KeyF20 = uv.KeyF2092+ KeyF21 = uv.KeyF2193+ KeyF22 = uv.KeyF2294+ KeyF23 = uv.KeyF2395+ KeyF24 = uv.KeyF2496+ KeyF25 = uv.KeyF2597+ KeyF26 = uv.KeyF2698+ KeyF27 = uv.KeyF2799+ KeyF28 = uv.KeyF28100+ KeyF29 = uv.KeyF29101+ KeyF30 = uv.KeyF30102+ KeyF31 = uv.KeyF31103+ KeyF32 = uv.KeyF32104+ KeyF33 = uv.KeyF33105+ KeyF34 = uv.KeyF34106+ KeyF35 = uv.KeyF35107+ KeyF36 = uv.KeyF36108+ KeyF37 = uv.KeyF37109+ KeyF38 = uv.KeyF38110+ KeyF39 = uv.KeyF39111+ KeyF40 = uv.KeyF40112+ KeyF41 = uv.KeyF41113+ KeyF42 = uv.KeyF42114+ KeyF43 = uv.KeyF43115+ KeyF44 = uv.KeyF44116+ KeyF45 = uv.KeyF45117+ KeyF46 = uv.KeyF46118+ KeyF47 = uv.KeyF47119+ KeyF48 = uv.KeyF48120+ KeyF49 = uv.KeyF49121+ KeyF50 = uv.KeyF50122+ KeyF51 = uv.KeyF51123+ KeyF52 = uv.KeyF52124+ KeyF53 = uv.KeyF53125+ KeyF54 = uv.KeyF54126+ KeyF55 = uv.KeyF55127+ KeyF56 = uv.KeyF56128+ KeyF57 = uv.KeyF57129+ KeyF58 = uv.KeyF58130+ KeyF59 = uv.KeyF59131+ KeyF60 = uv.KeyF60132+ KeyF61 = uv.KeyF61133+ KeyF62 = uv.KeyF62134+ KeyF63 = uv.KeyF63135 409- "\x1b[3~": {Type: KeyDelete},410- "\x1b[3;3~": {Type: KeyDelete, Alt: true},136+ // The following are keys defined in the Kitty keyboard protocol.137+ // XXX: Investigate the names of these keys.138 412- "\x1b[5~": {Type: KeyPgUp},413- "\x1b[5;3~": {Type: KeyPgUp, Alt: true},414- "\x1b[5;5~": {Type: KeyCtrlPgUp},415- "\x1b[5^": {Type: KeyCtrlPgUp}, // urxvt416- "\x1b[5;7~": {Type: KeyCtrlPgUp, Alt: true},139+ KeyCapsLock = uv.KeyCapsLock140+ KeyScrollLock = uv.KeyScrollLock141+ KeyNumLock = uv.KeyNumLock142+ KeyPrintScreen = uv.KeyPrintScreen143+ KeyPause = uv.KeyPause144+ KeyMenu = uv.KeyMenu145 418- "\x1b[6~": {Type: KeyPgDown},419- "\x1b[6;3~": {Type: KeyPgDown, Alt: true},420- "\x1b[6;5~": {Type: KeyCtrlPgDown},421- "\x1b[6^": {Type: KeyCtrlPgDown}, // urxvt422- "\x1b[6;7~": {Type: KeyCtrlPgDown, Alt: true},146+ KeyMediaPlay = uv.KeyMediaPlay147+ KeyMediaPause = uv.KeyMediaPause148+ KeyMediaPlayPause = uv.KeyMediaPlayPause149+ KeyMediaReverse = uv.KeyMediaReverse150+ KeyMediaStop = uv.KeyMediaStop151+ KeyMediaFastForward = uv.KeyMediaFastForward152+ KeyMediaRewind = uv.KeyMediaRewind153+ KeyMediaNext = uv.KeyMediaNext154+ KeyMediaPrev = uv.KeyMediaPrev155+ KeyMediaRecord156 424- "\x1b[1~": {Type: KeyHome},425- "\x1b[H": {Type: KeyHome}, // xterm, lxterm426- "\x1b[1;3H": {Type: KeyHome, Alt: true}, // xterm, lxterm427- "\x1b[1;5H": {Type: KeyCtrlHome}, // xterm, lxterm428- "\x1b[1;7H": {Type: KeyCtrlHome, Alt: true}, // xterm, lxterm429- "\x1b[1;2H": {Type: KeyShiftHome}, // xterm, lxterm430- "\x1b[1;4H": {Type: KeyShiftHome, Alt: true}, // xterm, lxterm431- "\x1b[1;6H": {Type: KeyCtrlShiftHome}, // xterm, lxterm432- "\x1b[1;8H": {Type: KeyCtrlShiftHome, Alt: true}, // xterm, lxterm157+ KeyLowerVol = uv.KeyLowerVol158+ KeyRaiseVol = uv.KeyRaiseVol159+ KeyMute = uv.KeyMute160 434- "\x1b[4~": {Type: KeyEnd},435- "\x1b[F": {Type: KeyEnd}, // xterm, lxterm436- "\x1b[1;3F": {Type: KeyEnd, Alt: true}, // xterm, lxterm437- "\x1b[1;5F": {Type: KeyCtrlEnd}, // xterm, lxterm438- "\x1b[1;7F": {Type: KeyCtrlEnd, Alt: true}, // xterm, lxterm439- "\x1b[1;2F": {Type: KeyShiftEnd}, // xterm, lxterm440- "\x1b[1;4F": {Type: KeyShiftEnd, Alt: true}, // xterm, lxterm441- "\x1b[1;6F": {Type: KeyCtrlShiftEnd}, // xterm, lxterm442- "\x1b[1;8F": {Type: KeyCtrlShiftEnd, Alt: true}, // xterm, lxterm161+ KeyLeftShift = uv.KeyLeftShift162+ KeyLeftAlt = uv.KeyLeftAlt163+ KeyLeftCtrl = uv.KeyLeftCtrl164+ KeyLeftSuper = uv.KeyLeftSuper165+ KeyLeftHyper = uv.KeyLeftHyper166+ KeyLeftMeta = uv.KeyLeftMeta167+ KeyRightShift = uv.KeyRightShift168+ KeyRightAlt = uv.KeyRightAlt169+ KeyRightCtrl = uv.KeyRightCtrl170+ KeyRightSuper = uv.KeyRightSuper171+ KeyRightHyper = uv.KeyRightHyper172+ KeyRightMeta = uv.KeyRightMeta173+ KeyIsoLevel3Shift = uv.KeyIsoLevel3Shift174+ KeyIsoLevel5Shift = uv.KeyIsoLevel5Shift175 444- "\x1b[7~": {Type: KeyHome}, // urxvt445- "\x1b[7^": {Type: KeyCtrlHome}, // urxvt446- "\x1b[7$": {Type: KeyShiftHome}, // urxvt447- "\x1b[7@": {Type: KeyCtrlShiftHome}, // urxvt176+ // Special names in C0.177 449- "\x1b[8~": {Type: KeyEnd}, // urxvt450- "\x1b[8^": {Type: KeyCtrlEnd}, // urxvt451- "\x1b[8$": {Type: KeyShiftEnd}, // urxvt452- "\x1b[8@": {Type: KeyCtrlShiftEnd}, // urxvt178+ KeyBackspace = uv.KeyBackspace179+ KeyTab = uv.KeyTab180+ KeyEnter = uv.KeyEnter181+ KeyReturn = uv.KeyReturn182+ KeyEscape = uv.KeyEscape183+ KeyEsc = uv.KeyEsc184 454- // Function keys, Linux console455- "\x1b[[A": {Type: KeyF1}, // linux console456- "\x1b[[B": {Type: KeyF2}, // linux console457- "\x1b[[C": {Type: KeyF3}, // linux console458- "\x1b[[D": {Type: KeyF4}, // linux console459- "\x1b[[E": {Type: KeyF5}, // linux console185+ // Special names in G0.186 461- // Function keys, X11462- "\x1bOP": {Type: KeyF1}, // vt100, xterm463- "\x1bOQ": {Type: KeyF2}, // vt100, xterm464- "\x1bOR": {Type: KeyF3}, // vt100, xterm465- "\x1bOS": {Type: KeyF4}, // vt100, xterm187+ KeySpace = uv.KeySpace188+)189 467- "\x1b[1;3P": {Type: KeyF1, Alt: true}, // vt100, xterm468- "\x1b[1;3Q": {Type: KeyF2, Alt: true}, // vt100, xterm469- "\x1b[1;3R": {Type: KeyF3, Alt: true}, // vt100, xterm470- "\x1b[1;3S": {Type: KeyF4, Alt: true}, // vt100, xterm190+// KeyPressMsg represents a key press message.191+type KeyPressMsg Key192 472- "\x1b[11~": {Type: KeyF1}, // urxvt473- "\x1b[12~": {Type: KeyF2}, // urxvt474- "\x1b[13~": {Type: KeyF3}, // urxvt475- "\x1b[14~": {Type: KeyF4}, // urxvt193+// String implements [fmt.Stringer] and is quite useful for matching key194+// events. For details, on what this returns see [Key.String].195+func (k KeyPressMsg) String() string {196+ return Key(k).String()197+}198 477- "\x1b[15~": {Type: KeyF5}, // vt100, xterm, also urxvt199+// Keystroke returns the keystroke representation of the [Key]. While less type200+// safe than looking at the individual fields, it will usually be more201+// convenient and readable to use this method when matching against keys.202+//203+// Note that modifier keys are always printed in the following order:204+// - ctrl205+// - alt206+// - shift207+// - meta208+// - hyper209+// - super210+//211+// For example, you'll always see "ctrl+shift+alt+a" and never212+// "shift+ctrl+alt+a".213+func (k KeyPressMsg) Keystroke() string {214+ return uv.Key(k).Keystroke()215+}216 479- "\x1b[15;3~": {Type: KeyF5, Alt: true}, // vt100, xterm, also urxvt217+// Key returns the underlying key event. This is a syntactic sugar for casting218+// the key event to a [Key].219+func (k KeyPressMsg) Key() Key {220+ return Key(k)221+}222 481- "\x1b[17~": {Type: KeyF6}, // vt100, xterm, also urxvt482- "\x1b[18~": {Type: KeyF7}, // vt100, xterm, also urxvt483- "\x1b[19~": {Type: KeyF8}, // vt100, xterm, also urxvt484- "\x1b[20~": {Type: KeyF9}, // vt100, xterm, also urxvt485- "\x1b[21~": {Type: KeyF10}, // vt100, xterm, also urxvt223+// KeyReleaseMsg represents a key release message.224+type KeyReleaseMsg Key225 487- "\x1b[17;3~": {Type: KeyF6, Alt: true}, // vt100, xterm488- "\x1b[18;3~": {Type: KeyF7, Alt: true}, // vt100, xterm489- "\x1b[19;3~": {Type: KeyF8, Alt: true}, // vt100, xterm490- "\x1b[20;3~": {Type: KeyF9, Alt: true}, // vt100, xterm491- "\x1b[21;3~": {Type: KeyF10, Alt: true}, // vt100, xterm226+// String implements [fmt.Stringer] and is quite useful for matching key227+// events. For details, on what this returns see [Key.String].228+func (k KeyReleaseMsg) String() string {229+ return Key(k).String()230+}231 493- "\x1b[23~": {Type: KeyF11}, // vt100, xterm, also urxvt494- "\x1b[24~": {Type: KeyF12}, // vt100, xterm, also urxvt495-496- "\x1b[23;3~": {Type: KeyF11, Alt: true}, // vt100, xterm497- "\x1b[24;3~": {Type: KeyF12, Alt: true}, // vt100, xterm498-499- "\x1b[1;2P": {Type: KeyF13},500- "\x1b[1;2Q": {Type: KeyF14},501-502- "\x1b[25~": {Type: KeyF13}, // vt100, xterm, also urxvt503- "\x1b[26~": {Type: KeyF14}, // vt100, xterm, also urxvt504-505- "\x1b[25;3~": {Type: KeyF13, Alt: true}, // vt100, xterm506- "\x1b[26;3~": {Type: KeyF14, Alt: true}, // vt100, xterm507-508- "\x1b[1;2R": {Type: KeyF15},509- "\x1b[1;2S": {Type: KeyF16},510-511- "\x1b[28~": {Type: KeyF15}, // vt100, xterm, also urxvt512- "\x1b[29~": {Type: KeyF16}, // vt100, xterm, also urxvt513-514- "\x1b[28;3~": {Type: KeyF15, Alt: true}, // vt100, xterm515- "\x1b[29;3~": {Type: KeyF16, Alt: true}, // vt100, xterm516-517- "\x1b[15;2~": {Type: KeyF17},518- "\x1b[17;2~": {Type: KeyF18},519- "\x1b[18;2~": {Type: KeyF19},520- "\x1b[19;2~": {Type: KeyF20},521-522- "\x1b[31~": {Type: KeyF17},523- "\x1b[32~": {Type: KeyF18},524- "\x1b[33~": {Type: KeyF19},525- "\x1b[34~": {Type: KeyF20},526-527- // Powershell sequences.528- "\x1bOA": {Type: KeyUp, Alt: false},529- "\x1bOB": {Type: KeyDown, Alt: false},530- "\x1bOC": {Type: KeyRight, Alt: false},531- "\x1bOD": {Type: KeyLeft, Alt: false},232+// Keystroke returns the keystroke representation of the [Key]. While less type233+// safe than looking at the individual fields, it will usually be more234+// convenient and readable to use this method when matching against keys.235+//236+// Note that modifier keys are always printed in the following order:237+// - ctrl238+// - alt239+// - shift240+// - meta241+// - hyper242+// - super243+//244+// For example, you'll always see "ctrl+shift+alt+a" and never245+// "shift+ctrl+alt+a".246+func (k KeyReleaseMsg) Keystroke() string {247+ return uv.Key(k).Keystroke()248 }249 534-// unknownInputByteMsg is reported by the input reader when an invalid535-// utf-8 byte is detected on the input. Currently, it is not handled536-// further by bubbletea. However, having this event makes it possible537-// to troubleshoot invalid inputs.538-type unknownInputByteMsg byte539-540-func (u unknownInputByteMsg) String() string {541- return fmt.Sprintf("?%#02x?", int(u))250+// Key returns the underlying key event. This is a convenience method and251+// syntactic sugar to satisfy the [KeyMsg] interface, and cast the key event to252+// [Key].253+func (k KeyReleaseMsg) Key() Key {254+ return Key(k)255 }256 544-// unknownCSISequenceMsg is reported by the input reader when an545-// unrecognized CSI sequence is detected on the input. Currently, it546-// is not handled further by bubbletea. However, having this event547-// makes it possible to troubleshoot invalid inputs.548-type unknownCSISequenceMsg []byte257+// KeyMsg represents a key event. This can be either a key press or a key258+// release event.259+type KeyMsg interface {260+ fmt.Stringer261 550-func (u unknownCSISequenceMsg) String() string {551- return fmt.Sprintf("?CSI%+v?", []byte(u)[2:])262+ // Key returns the underlying key event.263+ Key() Key264 }265 554-var spaceRunes = []rune{' '}266+// Key represents a Key press or release event. It contains information about267+// the Key pressed, like the runes, the type of Key, and the modifiers pressed.268+// There are a couple general patterns you could use to check for key presses269+// or releases:270+//271+// // Switch on the string representation of the key (shorter)272+// switch msg := msg.(type) {273+// case KeyPressMsg:274+// switch msg.String() {275+// case "enter":276+// fmt.Println("you pressed enter!")277+// case "a":278+// fmt.Println("you pressed a!")279+// }280+// }281+//282+// // Switch on the key type (more foolproof)283+// switch msg := msg.(type) {284+// case KeyMsg:285+// // catch both KeyPressMsg and KeyReleaseMsg286+// switch key := msg.Key(); key.Code {287+// case KeyEnter:288+// fmt.Println("you pressed enter!")289+// default:290+// switch key.Text {291+// case "a":292+// fmt.Println("you pressed a!")293+// }294+// }295+// }296+//297+// Note that [Key.Text] will be empty for special keys like [KeyEnter],298+// [KeyTab], and for keys that don't represent printable characters like key299+// combos with modifier keys. In other words, [Key.Text] is populated only for300+// keys that represent printable characters shifted or unshifted (like 'a',301+// 'A', '1', '!', etc.).302+type Key struct {303+ // Text contains the actual characters received. This usually the same as304+ // [Key.Code]. When [Key.Text] is non-empty, it indicates that the key305+ // pressed represents printable character(s).306+ Text string307 556-// readAnsiInputs reads keypress and mouse inputs from a TTY and produces messages557-// containing information about the key or mouse events accordingly.558-func readAnsiInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {559- var buf [256]byte308+ // Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on.309+ Mod KeyMod310 561- var leftOverFromPrevIteration []byte562-loop:563- for {564- // Read and block.565- numBytes, err := input.Read(buf[:])566- if err != nil {567- return fmt.Errorf("error reading input: %w", err)568- }569- b := buf[:numBytes]570- if leftOverFromPrevIteration != nil {571- b = append(leftOverFromPrevIteration, b...)572- }311+ // Code represents the key pressed. This is usually a special key like312+ // [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'.313+ Code rune314 574- // If we had a short read (numBytes < len(buf)), we're sure that575- // the end of this read is an event boundary, so there is no doubt576- // if we are encountering the end of the buffer while parsing a message.577- // However, if we've succeeded in filling up the buffer, there may578- // be more data in the OS buffer ready to be read in, to complete579- // the last message in the input. In that case, we will retry with580- // the left over data in the next iteration.581- canHaveMoreData := numBytes == len(buf)315+ // ShiftedCode is the actual, shifted key pressed by the user. For example,316+ // if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will317+ // be 'A' and [Key.Code] will be 'a'.318+ //319+ // In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the320+ // unshifted key on the keyboard.321+ //322+ // This is only available with the Kitty Keyboard Protocol or the Windows323+ // Console API.324+ ShiftedCode rune325 583- var i, w int584- for i, w = 0, 0; i < len(b); i += w {585- var msg Msg586- w, msg = detectOneMsg(b[i:], canHaveMoreData)587- if w == 0 {588- // Expecting more bytes beyond the current buffer. Try waiting589- // for more input.590- leftOverFromPrevIteration = make([]byte, 0, len(b[i:])+len(buf))591- leftOverFromPrevIteration = append(leftOverFromPrevIteration, b[i:]...)592- continue loop593- }326+ // BaseCode is the key pressed according to the standard PC-101 key layout.327+ // On international keyboards, this is the key that would be pressed if the328+ // keyboard was set to US PC-101 layout.329+ //330+ // For example, if the user presses 'q' on a French AZERTY keyboard,331+ // [Key.BaseCode] will be 'q'.332+ //333+ // This is only available with the Kitty Keyboard Protocol or the Windows334+ // Console API.335+ BaseCode rune336 595- select {596- case msgs <- msg:597- case <-ctx.Done():598- err := ctx.Err()599- if err != nil {600- err = fmt.Errorf("found context error while reading input: %w", err)601- }602- return err603- }604- }605- leftOverFromPrevIteration = nil606- }337+ // IsRepeat indicates whether the key is being held down and sending events338+ // repeatedly.339+ //340+ // This is only available with the Kitty Keyboard Protocol or the Windows341+ // Console API.342+ IsRepeat bool343 }344 609-var (610- unknownCSIRe = regexp.MustCompile(`^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]`)611- mouseSGRRegex = regexp.MustCompile(`(\d+);(\d+);(\d+)([Mm])`)612-)345+// String implements [fmt.Stringer] and is quite useful for matching key346+// events. It will return the textual representation of the [Key] if there is347+// one, otherwise, it will fallback to [Key.Keystroke].348+//349+// For example, you'll always get "?" and instead of "shift+/" on a US ANSI350+// keyboard.351+func (k Key) String() string {352+ return uv.Key(k).String()353+}354 614-func detectOneMsg(b []byte, canHaveMoreData bool) (w int, msg Msg) {615- // Detect mouse events.616- // X10 mouse events have a length of 6 bytes617- const mouseEventX10Len = 6618- if len(b) >= mouseEventX10Len && b[0] == '\x1b' && b[1] == '[' {619- switch b[2] {620- case 'M':621- return mouseEventX10Len, MouseMsg(parseX10MouseEvent(b))622- case '<':623- if matchIndices := mouseSGRRegex.FindSubmatchIndex(b[3:]); matchIndices != nil {624- // SGR mouse events length is the length of the match plus the length of the escape sequence625- mouseEventSGRLen := matchIndices[1] + 3 //nolint:mnd626- return mouseEventSGRLen, MouseMsg(parseSGRMouseEvent(b))627- }628- }629- }630-631- // Detect focus events.632- var foundRF bool633- foundRF, w, msg = detectReportFocus(b)634- if foundRF {635- return w, msg636- }637-638- // Detect bracketed paste.639- var foundbp bool640- foundbp, w, msg = detectBracketedPaste(b)641- if foundbp {642- return w, msg643- }644-645- // Detect escape sequence and control characters other than NUL,646- // possibly with an escape character in front to mark the Alt647- // modifier.648- var foundSeq bool649- foundSeq, w, msg = detectSequence(b)650- if foundSeq {651- return w, msg652- }653-654- // No non-NUL control character or escape sequence.655- // If we are seeing at least an escape character, remember it for later below.656- alt := false657- i := 0658- if b[0] == '\x1b' {659- alt = true660- i++661- }662-663- // Are we seeing a standalone NUL? This is not handled by detectSequence().664- if i < len(b) && b[i] == 0 {665- return i + 1, KeyMsg{Type: keyNUL, Alt: alt}666- }667-668- // Find the longest sequence of runes that are not control669- // characters from this point.670- var runes []rune671- for rw := 0; i < len(b); i += rw {672- var r rune673- r, rw = utf8.DecodeRune(b[i:])674- if r == utf8.RuneError || r <= rune(keyUS) || r == rune(keyDEL) || r == ' ' {675- // Rune errors are handled below; control characters and spaces will676- // be handled by detectSequence in the next call to detectOneMsg.677- break678- }679- runes = append(runes, r)680- if alt {681- // We only support a single rune after an escape alt modifier.682- i += rw683- break684- }685- }686- if i >= len(b) && canHaveMoreData {687- // We have encountered the end of the input buffer. Alas, we can't688- // be sure whether the data in the remainder of the buffer is689- // complete (maybe there was a short read). Instead of sending anything690- // dumb to the message channel, do a short read. The outer loop will691- // handle this case by extending the buffer as necessary.692- return 0, nil693- }694-695- // If we found at least one rune, we report the bunch of them as696- // a single KeyRunes or KeySpace event.697- if len(runes) > 0 {698- k := Key{Type: KeyRunes, Runes: runes, Alt: alt}699- if len(runes) == 1 && runes[0] == ' ' {700- k.Type = KeySpace701- }702- return i, KeyMsg(k)703- }704-705- // We didn't find an escape sequence, nor a valid rune. Was this a706- // lone escape character at the end of the input?707- if alt && len(b) == 1 {708- return 1, KeyMsg(Key{Type: KeyEscape})709- }710-711- // The character at the current position is neither an escape712- // sequence, a valid rune start or a sole escape character. Report713- // it as an invalid byte.714- return 1, unknownInputByteMsg(b[0])355+// Keystroke returns the keystroke representation of the [Key]. While less type356+// safe than looking at the individual fields, it will usually be more357+// convenient and readable to use this method when matching against keys.358+//359+// Note that modifier keys are always printed in the following order:360+// - ctrl361+// - alt362+// - shift363+// - meta364+// - hyper365+// - super366+//367+// For example, you'll always see "ctrl+shift+alt+a" and never368+// "shift+ctrl+alt+a".369+func (k Key) Keystroke() string {370+ return uv.Key(k).Keystroke()371 }added:keyboard.go+41 added
1+package tea2+3+import (4+ "github.com/charmbracelet/x/ansi"5+)6+7+// KeyboardEnhancementsMsg is a message that gets sent when the terminal8+// supports keyboard enhancements.9+type KeyboardEnhancementsMsg struct {10+ // Flags is a bitmask of enabled keyboard enhancement features. A non-zero11+ // value indicates that at least we have key disambiguation support.12+ //13+ // See [ansi.KittyReportEventTypes] and other constants for details.14+ //15+ // Example:16+ //17+ // ```go18+ // // The hard way19+ // if msg.Flags&ansi.KittyReportEventTypes != 0 {20+ // // Terminal supports reporting different key event types21+ // }22+ //23+ // // The easy way24+ // if msg.SupportsEventTypes() {25+ // // Terminal supports reporting different key event types26+ // }27+ // ```28+ Flags int29+}30+31+// SupportsKeyDisambiguation returns whether the terminal supports key32+// disambiguation (e.g., distinguishing between different modifier keys).33+func (k KeyboardEnhancementsMsg) SupportsKeyDisambiguation() bool {34+ return k.Flags > 035+}36+37+// SupportsEventTypes returns whether the terminal supports reporting38+// different types of key events (press, release, and repeat).39+func (k KeyboardEnhancementsMsg) SupportsEventTypes() bool {40+ return k.Flags&ansi.KittyReportEventTypes != 041+}modified:LICENSE+1 added-1 removed
1 MIT License2 3-Copyright (c) 2020-2025 Charmbracelet, Inc3+Copyright (c) 2020-2026 Charmbracelet, Inc.4 5 Permission is hereby granted, free of charge, to any person obtaining a copy6 of this software and associated documentation files (the "Software"), to deal7 in the Software without restriction, including without limitation the rights14 unmodified linesmodified:logging_test.go+2 added-2 removed
14 unmodified lines15 t.Error(err)16 }17 log.SetFlags(log.Lmsgprefix)18 log.Println("some test log")19- if err := f.Close(); err != nil {20- t.Error(err)19+ if closeErr := f.Close(); closeErr != nil {20+ t.Error(closeErr)21 }22 out, err := os.ReadFile(path)23 if err != nil {24 t.Error(err)5 unmodified linesadded:mod.go+27 added
1+package tea2+3+import uv "github.com/charmbracelet/ultraviolet"4+5+// KeyMod represents modifier keys.6+type KeyMod = uv.KeyMod7+8+// Modifier keys.9+const (10+ ModShift = uv.ModShift11+ ModAlt = uv.ModAlt12+ ModCtrl = uv.ModCtrl13+ ModMeta = uv.ModMeta14+15+ // These modifiers are used with the Kitty protocol.16+ // XXX: Meta and Super are swapped in the Kitty protocol,17+ // this is to preserve compatibility with XTerm modifiers.18+19+ ModHyper = uv.ModHyper20+ ModSuper = uv.ModSuper // Windows/Command keys21+22+ // These are key lock states.23+24+ ModCapsLock = uv.ModCapsLock25+ ModNumLock = uv.ModNumLock26+ ModScrollLock = uv.ModScrollLock // Defined in Windows API only27+)deleted:mouse_test.go-939 removed
1-package tea2-3-import (4- "fmt"5- "testing"6-)7-8-func TestMouseEvent_String(t *testing.T) {9- tt := []struct {10- name string11- event MouseEvent12- expected string13- }{14- {15- name: "unknown",16- event: MouseEvent{17- Action: MouseActionPress,18- Button: MouseButtonNone,19- Type: MouseUnknown,20- },21- expected: "unknown",22- },23- {24- name: "left",25- event: MouseEvent{26- Action: MouseActionPress,27- Button: MouseButtonLeft,28- Type: MouseLeft,29- },30- expected: "left press",31- },32- {33- name: "right",34- event: MouseEvent{35- Action: MouseActionPress,36- Button: MouseButtonRight,37- Type: MouseRight,38- },39- expected: "right press",40- },41- {42- name: "middle",43- event: MouseEvent{44- Action: MouseActionPress,45- Button: MouseButtonMiddle,46- Type: MouseMiddle,47- },48- expected: "middle press",49- },50- {51- name: "release",52- event: MouseEvent{53- Action: MouseActionRelease,54- Button: MouseButtonNone,55- Type: MouseRelease,56- },57- expected: "release",58- },59- {60- name: "wheel up",61- event: MouseEvent{62- Action: MouseActionPress,63- Button: MouseButtonWheelUp,64- Type: MouseWheelUp,65- },66- expected: "wheel up",67- },68- {69- name: "wheel down",70- event: MouseEvent{71- Action: MouseActionPress,72- Button: MouseButtonWheelDown,73- Type: MouseWheelDown,74- },75- expected: "wheel down",76- },77- {78- name: "wheel left",79- event: MouseEvent{80- Action: MouseActionPress,81- Button: MouseButtonWheelLeft,82- Type: MouseWheelLeft,83- },84- expected: "wheel left",85- },86- {87- name: "wheel right",88- event: MouseEvent{89- Action: MouseActionPress,90- Button: MouseButtonWheelRight,91- Type: MouseWheelRight,92- },93- expected: "wheel right",94- },95- {96- name: "motion",97- event: MouseEvent{98- Action: MouseActionMotion,99- Button: MouseButtonNone,100- Type: MouseMotion,101- },102- expected: "motion",103- },104- {105- name: "shift+left release",106- event: MouseEvent{107- Type: MouseLeft,108- Action: MouseActionRelease,109- Button: MouseButtonLeft,110- Shift: true,111- },112- expected: "shift+left release",113- },114- {115- name: "shift+left",116- event: MouseEvent{117- Type: MouseLeft,118- Action: MouseActionPress,119- Button: MouseButtonLeft,120- Shift: true,121- },122- expected: "shift+left press",123- },124- {125- name: "ctrl+shift+left",126- event: MouseEvent{127- Type: MouseLeft,128- Action: MouseActionPress,129- Button: MouseButtonLeft,130- Shift: true,131- Ctrl: true,132- },133- expected: "ctrl+shift+left press",134- },135- {136- name: "alt+left",137- event: MouseEvent{138- Type: MouseLeft,139- Action: MouseActionPress,140- Button: MouseButtonLeft,141- Alt: true,142- },143- expected: "alt+left press",144- },145- {146- name: "ctrl+left",147- event: MouseEvent{148- Type: MouseLeft,149- Action: MouseActionPress,150- Button: MouseButtonLeft,151- Ctrl: true,152- },153- expected: "ctrl+left press",154- },155- {156- name: "ctrl+alt+left",157- event: MouseEvent{158- Type: MouseLeft,159- Action: MouseActionPress,160- Button: MouseButtonLeft,161- Alt: true,162- Ctrl: true,163- },164- expected: "ctrl+alt+left press",165- },166- {167- name: "ctrl+alt+shift+left",168- event: MouseEvent{169- Type: MouseLeft,170- Action: MouseActionPress,171- Button: MouseButtonLeft,172- Alt: true,173- Ctrl: true,174- Shift: true,175- },176- expected: "ctrl+alt+shift+left press",177- },178- {179- name: "ignore coordinates",180- event: MouseEvent{181- X: 100,182- Y: 200,183- Type: MouseLeft,184- Action: MouseActionPress,185- Button: MouseButtonLeft,186- },187- expected: "left press",188- },189- {190- name: "broken type",191- event: MouseEvent{192- Type: MouseEventType(-100),193- Action: MouseAction(-110),194- Button: MouseButton(-120),195- },196- expected: "",197- },198- }199-200- for i := range tt {201- tc := tt[i]202-203- t.Run(tc.name, func(t *testing.T) {204- actual := tc.event.String()205-206- if tc.expected != actual {207- t.Fatalf("expected %q but got %q",208- tc.expected,209- actual,210- )211- }212- })213- }214-}215-216-func TestParseX10MouseEvent(t *testing.T) {217- encode := func(b byte, x, y int) []byte {218- return []byte{219- '\x1b',220- '[',221- 'M',222- byte(32) + b,223- byte(x + 32 + 1),224- byte(y + 32 + 1),225- }226- }227-228- tt := []struct {229- name string230- buf []byte231- expected MouseEvent232- }{233- // Position.234- {235- name: "zero position",236- buf: encode(0b0000_0000, 0, 0),237- expected: MouseEvent{238- X: 0,239- Y: 0,240- Type: MouseLeft,241- Action: MouseActionPress,242- Button: MouseButtonLeft,243- },244- },245- {246- name: "max position",247- buf: encode(0b0000_0000, 222, 222), // Because 255 (max int8) - 32 - 1.248- expected: MouseEvent{249- X: 222,250- Y: 222,251- Type: MouseLeft,252- Action: MouseActionPress,253- Button: MouseButtonLeft,254- },255- },256- // Simple.257- {258- name: "left",259- buf: encode(0b0000_0000, 32, 16),260- expected: MouseEvent{261- X: 32,262- Y: 16,263- Type: MouseLeft,264- Action: MouseActionPress,265- Button: MouseButtonLeft,266- },267- },268- {269- name: "left in motion",270- buf: encode(0b0010_0000, 32, 16),271- expected: MouseEvent{272- X: 32,273- Y: 16,274- Type: MouseLeft,275- Action: MouseActionMotion,276- Button: MouseButtonLeft,277- },278- },279- {280- name: "middle",281- buf: encode(0b0000_0001, 32, 16),282- expected: MouseEvent{283- X: 32,284- Y: 16,285- Type: MouseMiddle,286- Action: MouseActionPress,287- Button: MouseButtonMiddle,288- },289- },290- {291- name: "middle in motion",292- buf: encode(0b0010_0001, 32, 16),293- expected: MouseEvent{294- X: 32,295- Y: 16,296- Type: MouseMiddle,297- Action: MouseActionMotion,298- Button: MouseButtonMiddle,299- },300- },301- {302- name: "right",303- buf: encode(0b0000_0010, 32, 16),304- expected: MouseEvent{305- X: 32,306- Y: 16,307- Type: MouseRight,308- Action: MouseActionPress,309- Button: MouseButtonRight,310- },311- },312- {313- name: "right in motion",314- buf: encode(0b0010_0010, 32, 16),315- expected: MouseEvent{316- X: 32,317- Y: 16,318- Type: MouseRight,319- Action: MouseActionMotion,320- Button: MouseButtonRight,321- },322- },323- {324- name: "motion",325- buf: encode(0b0010_0011, 32, 16),326- expected: MouseEvent{327- X: 32,328- Y: 16,329- Type: MouseMotion,330- Action: MouseActionMotion,331- Button: MouseButtonNone,332- },333- },334- {335- name: "wheel up",336- buf: encode(0b0100_0000, 32, 16),337- expected: MouseEvent{338- X: 32,339- Y: 16,340- Type: MouseWheelUp,341- Action: MouseActionPress,342- Button: MouseButtonWheelUp,343- },344- },345- {346- name: "wheel down",347- buf: encode(0b0100_0001, 32, 16),348- expected: MouseEvent{349- X: 32,350- Y: 16,351- Type: MouseWheelDown,352- Action: MouseActionPress,353- Button: MouseButtonWheelDown,354- },355- },356- {357- name: "wheel left",358- buf: encode(0b0100_0010, 32, 16),359- expected: MouseEvent{360- X: 32,361- Y: 16,362- Type: MouseWheelLeft,363- Action: MouseActionPress,364- Button: MouseButtonWheelLeft,365- },366- },367- {368- name: "wheel right",369- buf: encode(0b0100_0011, 32, 16),370- expected: MouseEvent{371- X: 32,372- Y: 16,373- Type: MouseWheelRight,374- Action: MouseActionPress,375- Button: MouseButtonWheelRight,376- },377- },378- {379- name: "release",380- buf: encode(0b0000_0011, 32, 16),381- expected: MouseEvent{382- X: 32,383- Y: 16,384- Type: MouseRelease,385- Action: MouseActionRelease,386- Button: MouseButtonNone,387- },388- },389- {390- name: "backward",391- buf: encode(0b1000_0000, 32, 16),392- expected: MouseEvent{393- X: 32,394- Y: 16,395- Type: MouseBackward,396- Action: MouseActionPress,397- Button: MouseButtonBackward,398- },399- },400- {401- name: "forward",402- buf: encode(0b1000_0001, 32, 16),403- expected: MouseEvent{404- X: 32,405- Y: 16,406- Type: MouseForward,407- Action: MouseActionPress,408- Button: MouseButtonForward,409- },410- },411- {412- name: "button 10",413- buf: encode(0b1000_0010, 32, 16),414- expected: MouseEvent{415- X: 32,416- Y: 16,417- Type: MouseUnknown,418- Action: MouseActionPress,419- Button: MouseButton10,420- },421- },422- {423- name: "button 11",424- buf: encode(0b1000_0011, 32, 16),425- expected: MouseEvent{426- X: 32,427- Y: 16,428- Type: MouseUnknown,429- Action: MouseActionPress,430- Button: MouseButton11,431- },432- },433- // Combinations.434- {435- name: "alt+right",436- buf: encode(0b0000_1010, 32, 16),437- expected: MouseEvent{438- X: 32,439- Y: 16,440- Alt: true,441- Type: MouseRight,442- Action: MouseActionPress,443- Button: MouseButtonRight,444- },445- },446- {447- name: "ctrl+right",448- buf: encode(0b0001_0010, 32, 16),449- expected: MouseEvent{450- X: 32,451- Y: 16,452- Ctrl: true,453- Type: MouseRight,454- Action: MouseActionPress,455- Button: MouseButtonRight,456- },457- },458- {459- name: "left in motion",460- buf: encode(0b0010_0000, 32, 16),461- expected: MouseEvent{462- X: 32,463- Y: 16,464- Alt: false,465- Type: MouseLeft,466- Action: MouseActionMotion,467- Button: MouseButtonLeft,468- },469- },470- {471- name: "alt+right in motion",472- buf: encode(0b0010_1010, 32, 16),473- expected: MouseEvent{474- X: 32,475- Y: 16,476- Alt: true,477- Type: MouseRight,478- Action: MouseActionMotion,479- Button: MouseButtonRight,480- },481- },482- {483- name: "ctrl+right in motion",484- buf: encode(0b0011_0010, 32, 16),485- expected: MouseEvent{486- X: 32,487- Y: 16,488- Ctrl: true,489- Type: MouseRight,490- Action: MouseActionMotion,491- Button: MouseButtonRight,492- },493- },494- {495- name: "ctrl+alt+right",496- buf: encode(0b0001_1010, 32, 16),497- expected: MouseEvent{498- X: 32,499- Y: 16,500- Alt: true,501- Ctrl: true,502- Type: MouseRight,503- Action: MouseActionPress,504- Button: MouseButtonRight,505- },506- },507- {508- name: "ctrl+wheel up",509- buf: encode(0b0101_0000, 32, 16),510- expected: MouseEvent{511- X: 32,512- Y: 16,513- Ctrl: true,514- Type: MouseWheelUp,515- Action: MouseActionPress,516- Button: MouseButtonWheelUp,517- },518- },519- {520- name: "alt+wheel down",521- buf: encode(0b0100_1001, 32, 16),522- expected: MouseEvent{523- X: 32,524- Y: 16,525- Alt: true,526- Type: MouseWheelDown,527- Action: MouseActionPress,528- Button: MouseButtonWheelDown,529- },530- },531- {532- name: "ctrl+alt+wheel down",533- buf: encode(0b0101_1001, 32, 16),534- expected: MouseEvent{535- X: 32,536- Y: 16,537- Alt: true,538- Ctrl: true,539- Type: MouseWheelDown,540- Action: MouseActionPress,541- Button: MouseButtonWheelDown,542- },543- },544- // Overflow position.545- {546- name: "overflow position",547- buf: encode(0b0010_0000, 250, 223), // Because 255 (max int8) - 32 - 1.548- expected: MouseEvent{549- X: -6,550- Y: -33,551- Type: MouseLeft,552- Action: MouseActionMotion,553- Button: MouseButtonLeft,554- },555- },556- }557-558- for i := range tt {559- tc := tt[i]560-561- t.Run(tc.name, func(t *testing.T) {562- actual := parseX10MouseEvent(tc.buf)563-564- if tc.expected != actual {565- t.Fatalf("expected %#v but got %#v",566- tc.expected,567- actual,568- )569- }570- })571- }572-}573-574-// func TestParseX10MouseEvent_error(t *testing.T) {575-// tt := []struct {576-// name string577-// buf []byte578-// }{579-// {580-// name: "empty buf",581-// buf: nil,582-// },583-// {584-// name: "wrong high bit",585-// buf: []byte("\x1a[M@A1"),586-// },587-// {588-// name: "short buf",589-// buf: []byte("\x1b[M@A"),590-// },591-// {592-// name: "long buf",593-// buf: []byte("\x1b[M@A11"),594-// },595-// }596-//597-// for i := range tt {598-// tc := tt[i]599-//600-// t.Run(tc.name, func(t *testing.T) {601-// _, err := parseX10MouseEvent(tc.buf)602-//603-// if err == nil {604-// t.Fatalf("expected error but got nil")605-// }606-// })607-// }608-// }609-610-func TestParseSGRMouseEvent(t *testing.T) {611- encode := func(b, x, y int, r bool) []byte {612- re := 'M'613- if r {614- re = 'm'615- }616- return []byte(fmt.Sprintf("\x1b[<%d;%d;%d%c", b, x+1, y+1, re))617- }618-619- tt := []struct {620- name string621- buf []byte622- expected MouseEvent623- }{624- // Position.625- {626- name: "zero position",627- buf: encode(0, 0, 0, false),628- expected: MouseEvent{629- X: 0,630- Y: 0,631- Type: MouseLeft,632- Action: MouseActionPress,633- Button: MouseButtonLeft,634- },635- },636- {637- name: "225 position",638- buf: encode(0, 225, 225, false),639- expected: MouseEvent{640- X: 225,641- Y: 225,642- Type: MouseLeft,643- Action: MouseActionPress,644- Button: MouseButtonLeft,645- },646- },647- // Simple.648- {649- name: "left",650- buf: encode(0, 32, 16, false),651- expected: MouseEvent{652- X: 32,653- Y: 16,654- Type: MouseLeft,655- Action: MouseActionPress,656- Button: MouseButtonLeft,657- },658- },659- {660- name: "left in motion",661- buf: encode(32, 32, 16, false),662- expected: MouseEvent{663- X: 32,664- Y: 16,665- Type: MouseLeft,666- Action: MouseActionMotion,667- Button: MouseButtonLeft,668- },669- },670- {671- name: "left release",672- buf: encode(0, 32, 16, true),673- expected: MouseEvent{674- X: 32,675- Y: 16,676- Type: MouseRelease,677- Action: MouseActionRelease,678- Button: MouseButtonLeft,679- },680- },681- {682- name: "middle",683- buf: encode(1, 32, 16, false),684- expected: MouseEvent{685- X: 32,686- Y: 16,687- Type: MouseMiddle,688- Action: MouseActionPress,689- Button: MouseButtonMiddle,690- },691- },692- {693- name: "middle in motion",694- buf: encode(33, 32, 16, false),695- expected: MouseEvent{696- X: 32,697- Y: 16,698- Type: MouseMiddle,699- Action: MouseActionMotion,700- Button: MouseButtonMiddle,701- },702- },703- {704- name: "middle release",705- buf: encode(1, 32, 16, true),706- expected: MouseEvent{707- X: 32,708- Y: 16,709- Type: MouseRelease,710- Action: MouseActionRelease,711- Button: MouseButtonMiddle,712- },713- },714- {715- name: "right",716- buf: encode(2, 32, 16, false),717- expected: MouseEvent{718- X: 32,719- Y: 16,720- Type: MouseRight,721- Action: MouseActionPress,722- Button: MouseButtonRight,723- },724- },725- {726- name: "right release",727- buf: encode(2, 32, 16, true),728- expected: MouseEvent{729- X: 32,730- Y: 16,731- Type: MouseRelease,732- Action: MouseActionRelease,733- Button: MouseButtonRight,734- },735- },736- {737- name: "motion",738- buf: encode(35, 32, 16, false),739- expected: MouseEvent{740- X: 32,741- Y: 16,742- Type: MouseMotion,743- Action: MouseActionMotion,744- Button: MouseButtonNone,745- },746- },747- {748- name: "wheel up",749- buf: encode(64, 32, 16, false),750- expected: MouseEvent{751- X: 32,752- Y: 16,753- Type: MouseWheelUp,754- Action: MouseActionPress,755- Button: MouseButtonWheelUp,756- },757- },758- {759- name: "wheel down",760- buf: encode(65, 32, 16, false),761- expected: MouseEvent{762- X: 32,763- Y: 16,764- Type: MouseWheelDown,765- Action: MouseActionPress,766- Button: MouseButtonWheelDown,767- },768- },769- {770- name: "wheel left",771- buf: encode(66, 32, 16, false),772- expected: MouseEvent{773- X: 32,774- Y: 16,775- Type: MouseWheelLeft,776- Action: MouseActionPress,777- Button: MouseButtonWheelLeft,778- },779- },780- {781- name: "wheel right",782- buf: encode(67, 32, 16, false),783- expected: MouseEvent{784- X: 32,785- Y: 16,786- Type: MouseWheelRight,787- Action: MouseActionPress,788- Button: MouseButtonWheelRight,789- },790- },791- {792- name: "backward",793- buf: encode(128, 32, 16, false),794- expected: MouseEvent{795- X: 32,796- Y: 16,797- Type: MouseBackward,798- Action: MouseActionPress,799- Button: MouseButtonBackward,800- },801- },802- {803- name: "backward in motion",804- buf: encode(160, 32, 16, false),805- expected: MouseEvent{806- X: 32,807- Y: 16,808- Type: MouseBackward,809- Action: MouseActionMotion,810- Button: MouseButtonBackward,811- },812- },813- {814- name: "forward",815- buf: encode(129, 32, 16, false),816- expected: MouseEvent{817- X: 32,818- Y: 16,819- Type: MouseForward,820- Action: MouseActionPress,821- Button: MouseButtonForward,822- },823- },824- {825- name: "forward in motion",826- buf: encode(161, 32, 16, false),827- expected: MouseEvent{828- X: 32,829- Y: 16,830- Type: MouseForward,831- Action: MouseActionMotion,832- Button: MouseButtonForward,833- },834- },835- // Combinations.836- {837- name: "alt+right",838- buf: encode(10, 32, 16, false),839- expected: MouseEvent{840- X: 32,841- Y: 16,842- Alt: true,843- Type: MouseRight,844- Action: MouseActionPress,845- Button: MouseButtonRight,846- },847- },848- {849- name: "ctrl+right",850- buf: encode(18, 32, 16, false),851- expected: MouseEvent{852- X: 32,853- Y: 16,854- Ctrl: true,855- Type: MouseRight,856- Action: MouseActionPress,857- Button: MouseButtonRight,858- },859- },860- {861- name: "ctrl+alt+right",862- buf: encode(26, 32, 16, false),863- expected: MouseEvent{864- X: 32,865- Y: 16,866- Alt: true,867- Ctrl: true,868- Type: MouseRight,869- Action: MouseActionPress,870- Button: MouseButtonRight,871- },872- },873- {874- name: "alt+wheel press",875- buf: encode(73, 32, 16, false),876- expected: MouseEvent{877- X: 32,878- Y: 16,879- Alt: true,880- Type: MouseWheelDown,881- Action: MouseActionPress,882- Button: MouseButtonWheelDown,883- },884- },885- {886- name: "ctrl+wheel press",887- buf: encode(81, 32, 16, false),888- expected: MouseEvent{889- X: 32,890- Y: 16,891- Ctrl: true,892- Type: MouseWheelDown,893- Action: MouseActionPress,894- Button: MouseButtonWheelDown,895- },896- },897- {898- name: "ctrl+alt+wheel press",899- buf: encode(89, 32, 16, false),900- expected: MouseEvent{901- X: 32,902- Y: 16,903- Alt: true,904- Ctrl: true,905- Type: MouseWheelDown,906- Action: MouseActionPress,907- Button: MouseButtonWheelDown,908- },909- },910- {911- name: "ctrl+alt+shift+wheel press",912- buf: encode(93, 32, 16, false),913- expected: MouseEvent{914- X: 32,915- Y: 16,916- Shift: true,917- Alt: true,918- Ctrl: true,919- Type: MouseWheelDown,920- Action: MouseActionPress,921- Button: MouseButtonWheelDown,922- },923- },924- }925-926- for i := range tt {927- tc := tt[i]928-929- t.Run(tc.name, func(t *testing.T) {930- actual := parseSGRMouseEvent(tc.buf)931- if tc.expected != actual {932- t.Fatalf("expected %#v but got %#v",933- tc.expected,934- actual,935- )936- }937- })938- }939-}modified:mouse.go+95 added-259 removed
1 package tea2 3-import "strconv"3+import (4+ "fmt"5 5-// MouseMsg contains information about a mouse event and are sent to a programs6-// update function when mouse activity occurs. Note that the mouse must first7-// be enabled in order for the mouse events to be received.8-type MouseMsg MouseEvent9-10-// String returns a string representation of a mouse event.11-func (m MouseMsg) String() string {12- return MouseEvent(m).String()13-}14-15-// MouseEvent represents a mouse event, which could be a click, a scroll wheel16-// movement, a cursor movement, or a combination.17-type MouseEvent struct {18- X int19- Y int20- Shift bool21- Alt bool22- Ctrl bool23- Action MouseAction24- Button MouseButton25-26- // Deprecated: Use MouseAction & MouseButton instead.27- Type MouseEventType28-}29-30-// IsWheel returns true if the mouse event is a wheel event.31-func (m MouseEvent) IsWheel() bool {32- return m.Button == MouseButtonWheelUp || m.Button == MouseButtonWheelDown ||33- m.Button == MouseButtonWheelLeft || m.Button == MouseButtonWheelRight34-}35-36-// String returns a string representation of a mouse event.37-func (m MouseEvent) String() (s string) {38- if m.Ctrl {39- s += "ctrl+"40- }41- if m.Alt {42- s += "alt+"43- }44- if m.Shift {45- s += "shift+"46- }47-48- if m.Button == MouseButtonNone { //nolint:nestif49- if m.Action == MouseActionMotion || m.Action == MouseActionRelease {50- s += mouseActions[m.Action]51- } else {52- s += "unknown"53- }54- } else if m.IsWheel() {55- s += mouseButtons[m.Button]56- } else {57- btn := mouseButtons[m.Button]58- if btn != "" {59- s += btn60- }61- act := mouseActions[m.Action]62- if act != "" {63- s += " " + act64- }65- }66-67- return s68-}69-70-// MouseAction represents the action that occurred during a mouse event.71-type MouseAction int72-73-// Mouse event actions.74-const (75- MouseActionPress MouseAction = iota76- MouseActionRelease77- MouseActionMotion6+ uv "github.com/charmbracelet/ultraviolet"7 )8 80-var mouseActions = map[MouseAction]string{81- MouseActionPress: "press",82- MouseActionRelease: "release",83- MouseActionMotion: "motion",84-}9+// MouseButton represents the button that was pressed during a mouse message.10+type MouseButton = uv.MouseButton11 86-// MouseButton represents the button that was pressed during a mouse event.87-type MouseButton int88-12 // Mouse event buttons13 //14 // This is based on X11 mouse button codes.15 //10 unmodified lines26 // 1127 //28 // Other buttons are not supported.29 const (107- MouseButtonNone MouseButton = iota108- MouseButtonLeft109- MouseButtonMiddle110- MouseButtonRight111- MouseButtonWheelUp112- MouseButtonWheelDown113- MouseButtonWheelLeft114- MouseButtonWheelRight115- MouseButtonBackward116- MouseButtonForward117- MouseButton1030+ MouseNone = uv.MouseNone31+ MouseLeft = uv.MouseLeft32+ MouseMiddle = uv.MouseMiddle33+ MouseRight = uv.MouseRight34+ MouseWheelUp = uv.MouseWheelUp35+ MouseWheelDown = uv.MouseWheelDown36+ MouseWheelLeft = uv.MouseWheelLeft37+ MouseWheelRight = uv.MouseWheelRight38+ MouseBackward = uv.MouseBackward39+ MouseForward = uv.MouseForward40+ MouseButton10 = uv.MouseButton1041 MouseButton1142 )43 121-var mouseButtons = map[MouseButton]string{122- MouseButtonNone: "none",123- MouseButtonLeft: "left",124- MouseButtonMiddle: "middle",125- MouseButtonRight: "right",126- MouseButtonWheelUp: "wheel up",127- MouseButtonWheelDown: "wheel down",128- MouseButtonWheelLeft: "wheel left",129- MouseButtonWheelRight: "wheel right",130- MouseButtonBackward: "backward",131- MouseButtonForward: "forward",132- MouseButton10: "button 10",133- MouseButton11: "button 11",44+// MouseMsg represents a mouse message. This is a generic mouse message that45+// can represent any kind of mouse event.46+type MouseMsg interface {47+ fmt.Stringer48+49+ // Mouse returns the underlying mouse event.50+ Mouse() Mouse51 }52 136-// MouseEventType indicates the type of mouse event occurring.53+// Mouse represents a Mouse message. Use [MouseMsg] to represent all mouse54+// messages.55 //138-// Deprecated: Use MouseAction & MouseButton instead.139-type MouseEventType int140-141-// Mouse event types.56+// The X and Y coordinates are zero-based, with (0,0) being the upper left57+// corner of the terminal.58 //143-// Deprecated: Use MouseAction & MouseButton instead.144-const (145- MouseUnknown MouseEventType = iota146- MouseLeft147- MouseRight148- MouseMiddle149- MouseRelease // mouse button release (X10 only)150- MouseWheelUp151- MouseWheelDown152- MouseWheelLeft153- MouseWheelRight154- MouseBackward155- MouseForward156- MouseMotion157-)158-159-// Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events160-// look like:59+// // Catch all mouse events60+// switch msg := msg.(type) {61+// case MouseMsg:62+// m := msg.Mouse()63+// fmt.Println("Mouse event:", m.X, m.Y, m)64+// }65 //162-// ESC [ < Cb ; Cx ; Cy (M or m)163-//164-// where:165-//166-// Cb is the encoded button code167-// Cx is the x-coordinate of the mouse168-// Cy is the y-coordinate of the mouse169-// M is for button press, m is for button release170-//171-// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates172-func parseSGRMouseEvent(buf []byte) MouseEvent {173- str := string(buf[3:])174- matches := mouseSGRRegex.FindStringSubmatch(str)175- if len(matches) != 5 { //nolint:mnd176- // Unreachable, we already checked the regex in `detectOneMsg`.177- panic("invalid mouse event")178- }66+// // Only catch mouse click events67+// switch msg := msg.(type) {68+// case MouseClickMsg:69+// fmt.Println("Mouse click event:", msg.X, msg.Y, msg)70+// }71+type Mouse struct {72+ X, Y int73+ Button MouseButton74+ Mod KeyMod75+}76 180- b, _ := strconv.Atoi(matches[1])181- px := matches[2]182- py := matches[3]183- release := matches[4] == "m"184- m := parseMouseButton(b, true)77+// String returns a string representation of the mouse message.78+func (m Mouse) String() (s string) {79+ return uv.Mouse(m).String()80+}81 186- // Wheel buttons don't have release events187- // Motion can be reported as a release event in some terminals (Windows Terminal)188- if m.Action != MouseActionMotion && !m.IsWheel() && release {189- m.Action = MouseActionRelease190- m.Type = MouseRelease191- }82+// MouseClickMsg represents a mouse button click message.83+type MouseClickMsg Mouse84 193- x, _ := strconv.Atoi(px)194- y, _ := strconv.Atoi(py)85+// String returns a string representation of the mouse click message.86+func (e MouseClickMsg) String() string {87+ return Mouse(e).String()88+}89 196- // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).197- m.X = x - 1198- m.Y = y - 1199-200- return m90+// Mouse returns the underlying mouse event. This is a convenience method and91+// syntactic sugar to satisfy the [MouseMsg] interface, and cast the mouse92+// event to [Mouse].93+func (e MouseClickMsg) Mouse() Mouse {94+ return Mouse(e)95 }96 203-const x10MouseByteOffset = 3297+// MouseReleaseMsg represents a mouse button release message.98+type MouseReleaseMsg Mouse99 205-// Parse X10-encoded mouse events; the simplest kind. The last release of X10206-// was December 1986, by the way. The original X10 mouse protocol limits the Cx207-// and Cy coordinates to 223 (=255-032).208-//209-// X10 mouse events look like:210-//211-// ESC [M Cb Cx Cy212-//213-// See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking214-func parseX10MouseEvent(buf []byte) MouseEvent {215- v := buf[3:6]216- m := parseMouseButton(int(v[0]), false)100+// String returns a string representation of the mouse release message.101+func (e MouseReleaseMsg) String() string {102+ return Mouse(e).String()103+}104 218- // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).219- m.X = int(v[1]) - x10MouseByteOffset - 1220- m.Y = int(v[2]) - x10MouseByteOffset - 1221-222- return m105+// Mouse returns the underlying mouse event. This is a convenience method and106+// syntactic sugar to satisfy the [MouseMsg] interface, and cast the mouse107+// event to [Mouse].108+func (e MouseReleaseMsg) Mouse() Mouse {109+ return Mouse(e)110 }111 225-// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates226-func parseMouseButton(b int, isSGR bool) MouseEvent {227- var m MouseEvent228- e := b229- if !isSGR {230- e -= x10MouseByteOffset231- }112+// MouseWheelMsg represents a mouse wheel message event.113+type MouseWheelMsg Mouse114 233- const (234- bitShift = 0b0000_0100235- bitAlt = 0b0000_1000236- bitCtrl = 0b0001_0000237- bitMotion = 0b0010_0000238- bitWheel = 0b0100_0000239- bitAdd = 0b1000_0000 // additional buttons 8-11115+// String returns a string representation of the mouse wheel message.116+func (e MouseWheelMsg) String() string {117+ return Mouse(e).String()118+}119 241- bitsMask = 0b0000_0011242- )120+// Mouse returns the underlying mouse event. This is a convenience method and121+// syntactic sugar to satisfy the [MouseMsg] interface, and cast the mouse122+// event to [Mouse].123+func (e MouseWheelMsg) Mouse() Mouse {124+ return Mouse(e)125+}126 244- if e&bitAdd != 0 {245- m.Button = MouseButtonBackward + MouseButton(e&bitsMask)246- } else if e&bitWheel != 0 {247- m.Button = MouseButtonWheelUp + MouseButton(e&bitsMask)248- } else {249- m.Button = MouseButtonLeft + MouseButton(e&bitsMask)250- // X10 reports a button release as 0b0000_0011 (3)251- if e&bitsMask == bitsMask {252- m.Action = MouseActionRelease253- m.Button = MouseButtonNone254- }255- }127+// MouseMotionMsg represents a mouse motion message.128+type MouseMotionMsg Mouse129 257- // Motion bit doesn't get reported for wheel events.258- if e&bitMotion != 0 && !m.IsWheel() {259- m.Action = MouseActionMotion130+// String returns a string representation of the mouse motion message.131+func (e MouseMotionMsg) String() string {132+ m := Mouse(e)133+ if m.Button != 0 {134+ return m.String() + "+motion"135 }136+ return m.String() + "motion"137+}138 262- // Modifiers263- m.Alt = e&bitAlt != 0264- m.Ctrl = e&bitCtrl != 0265- m.Shift = e&bitShift != 0266-267- // backward compatibility268- switch {269- case m.Button == MouseButtonLeft && m.Action == MouseActionPress:270- m.Type = MouseLeft271- case m.Button == MouseButtonMiddle && m.Action == MouseActionPress:272- m.Type = MouseMiddle273- case m.Button == MouseButtonRight && m.Action == MouseActionPress:274- m.Type = MouseRight275- case m.Button == MouseButtonNone && m.Action == MouseActionRelease:276- m.Type = MouseRelease277- case m.Button == MouseButtonWheelUp && m.Action == MouseActionPress:278- m.Type = MouseWheelUp279- case m.Button == MouseButtonWheelDown && m.Action == MouseActionPress:280- m.Type = MouseWheelDown281- case m.Button == MouseButtonWheelLeft && m.Action == MouseActionPress:282- m.Type = MouseWheelLeft283- case m.Button == MouseButtonWheelRight && m.Action == MouseActionPress:284- m.Type = MouseWheelRight285- case m.Button == MouseButtonBackward && m.Action == MouseActionPress:286- m.Type = MouseBackward287- case m.Button == MouseButtonForward && m.Action == MouseActionPress:288- m.Type = MouseForward289- case m.Action == MouseActionMotion:290- m.Type = MouseMotion291- switch m.Button { //nolint:exhaustive292- case MouseButtonLeft:293- m.Type = MouseLeft294- case MouseButtonMiddle:295- m.Type = MouseMiddle296- case MouseButtonRight:297- m.Type = MouseRight298- case MouseButtonBackward:299- m.Type = MouseBackward300- case MouseButtonForward:301- m.Type = MouseForward302- }303- default:304- m.Type = MouseUnknown305- }306-307- return m139+// Mouse returns the underlying mouse event. This is a convenience method and140+// syntactic sugar to satisfy the [MouseMsg] interface, and cast the mouse141+// event to [Mouse].142+func (e MouseMotionMsg) Mouse() Mouse {143+ return Mouse(e)144 }deleted:nil_renderer_test.go-24 removed
1-package tea2-3-import "testing"4-5-func TestNilRenderer(t *testing.T) {6- r := nilRenderer{}7- r.start()8- r.stop()9- r.kill()10- r.write("a")11- r.repaint()12- r.enterAltScreen()13- if r.altScreen() {14- t.Errorf("altScreen should always return false")15- }16- r.exitAltScreen()17- r.clearScreen()18- r.showCursor()19- r.hideCursor()20- r.enableMouseCellMotion()21- r.disableMouseCellMotion()22- r.enableMouseAllMotion()23- r.disableMouseAllMotion()24-}modified:nil_renderer.go+49 added-25 removed
1 package tea2 3+import (4+ "github.com/charmbracelet/colorprofile"5+ "github.com/charmbracelet/x/ansi"6+)7+8+// nilRenderer is a no-op renderer. It implements the Renderer interface but9+// doesn't render anything to the terminal.10 type nilRenderer struct{}11 5-func (n nilRenderer) start() {}6-func (n nilRenderer) stop() {}7-func (n nilRenderer) kill() {}8-func (n nilRenderer) write(_ string) {}9-func (n nilRenderer) repaint() {}10-func (n nilRenderer) clearScreen() {}11-func (n nilRenderer) altScreen() bool { return false }12-func (n nilRenderer) enterAltScreen() {}13-func (n nilRenderer) exitAltScreen() {}14-func (n nilRenderer) showCursor() {}15-func (n nilRenderer) hideCursor() {}16-func (n nilRenderer) enableMouseCellMotion() {}17-func (n nilRenderer) disableMouseCellMotion() {}18-func (n nilRenderer) enableMouseAllMotion() {}19-func (n nilRenderer) disableMouseAllMotion() {}20-func (n nilRenderer) enableBracketedPaste() {}21-func (n nilRenderer) disableBracketedPaste() {}22-func (n nilRenderer) enableMouseSGRMode() {}23-func (n nilRenderer) disableMouseSGRMode() {}24-func (n nilRenderer) bracketedPasteActive() bool { return false }25-func (n nilRenderer) setWindowTitle(_ string) {}26-func (n nilRenderer) reportFocus() bool { return false }27-func (n nilRenderer) enableReportFocus() {}28-func (n nilRenderer) disableReportFocus() {}29-func (n nilRenderer) resetLinesRendered() {}12+var _ renderer = nilRenderer{}13+14+// start implements renderer.15+func (n nilRenderer) start() {}16+17+// clearScreen implements renderer.18+func (n nilRenderer) clearScreen() {}19+20+// insertAbove implements renderer.21+func (n nilRenderer) insertAbove(string) error { return nil }22+23+// resize implements renderer.24+func (n nilRenderer) resize(int, int) {}25+26+// setColorProfile implements renderer.27+func (n nilRenderer) setColorProfile(colorprofile.Profile) {}28+29+// flush implements the Renderer interface.30+func (nilRenderer) flush(bool) error { return nil }31+32+// close implements the Renderer interface.33+func (nilRenderer) close() error { return nil }34+35+// render implements the Renderer interface.36+func (nilRenderer) render(View) {}37+38+// reset implements the Renderer interface.39+func (nilRenderer) reset() {}40+41+// writeString implements the Renderer interface.42+func (nilRenderer) writeString(string) (int, error) { return 0, nil }43+44+// setSyncdUpdates implements the Renderer interface.45+func (n nilRenderer) setSyncdUpdates(bool) {}46+47+// setWidthMethod implements the Renderer interface.48+func (n nilRenderer) setWidthMethod(ansi.Method) {}49+50+// onMouse implements the Renderer interface.51+func (n nilRenderer) onMouse(MouseMsg) Cmd {52+ return nil53+}modified:options_test.go+27 added-73 removed
15 unmodified lines16 t.Errorf("expected output to custom, got %v", f.Fd())17 }18 })19 20- t.Run("custom input", func(t *testing.T) {21- var b bytes.Buffer22- p := NewProgram(nil, WithInput(&b))23- if p.input != &b {24- t.Errorf("expected input to custom, got %v", p.input)25- }26- if p.inputType != customInput {27- t.Errorf("expected startup options to have custom input set, got %v", p.input)28- }29- })30-20 t.Run("renderer", func(t *testing.T) {21 p := NewProgram(nil, WithoutRenderer())33- switch p.renderer.(type) {34- case *nilRenderer:35- return36- default:22+ if !p.disableRenderer {23 t.Errorf("expected renderer to be a nilRenderer, got %v", p.renderer)24 }25 })26 16 unmodified lines43 defer extCancel()44 45 p := NewProgram(nil, WithContext(extCtx))46 if p.externalCtx != extCtx || p.externalCtx == context.Background() {61- t.Errorf("expected passed in external context, got default (nil)")47+ t.Errorf("expected passed in external context, got default")48 }49 })50 51 t.Run("input options", func(t *testing.T) {66- exercise := func(t *testing.T, opt ProgramOption, expect inputType) {52+ exercise := func(t *testing.T, opt ProgramOption, fn func(*Program)) {53 p := NewProgram(nil, opt)68- if p.inputType != expect {69- t.Errorf("expected input type %s, got %s", expect, p.inputType)70- }54+ fn(p)55 }56 73- t.Run("tty input", func(t *testing.T) {74- exercise(t, WithInputTTY(), ttyInput)57+ t.Run("nil input", func(t *testing.T) {58+ exercise(t, WithInput(nil), func(p *Program) {59+ if !p.disableInput || p.input != nil {60+ t.Errorf("expected input to be disabled, got %v", p.input)61+ }62+ })63 })64 65 t.Run("custom input", func(t *testing.T) {66 var b bytes.Buffer79- exercise(t, WithInput(&b), customInput)67+ exercise(t, WithInput(&b), func(p *Program) {68+ if p.input != &b {69+ t.Errorf("expected input to be custom, got %v", p.input)70+ }71+ })72 })73 })74 75 t.Run("startup options", func(t *testing.T) {84- exercise := func(t *testing.T, opt ProgramOption, expect startupOptions) {76+ exercise := func(t *testing.T, opt ProgramOption, fn func(*Program)) {77 p := NewProgram(nil, opt)86- if !p.startupOptions.has(expect) {87- t.Errorf("expected startup options have %v, got %v", expect, p.startupOptions)88- }78+ fn(p)79 }80 91- t.Run("alt screen", func(t *testing.T) {92- exercise(t, WithAltScreen(), withAltScreen)93- })94-95- t.Run("bracketed paste disabled", func(t *testing.T) {96- exercise(t, WithoutBracketedPaste(), withoutBracketedPaste)97- })98-99- t.Run("ansi compression", func(t *testing.T) {100- exercise(t, WithANSICompressor(), withANSICompressor)101- })102-81 t.Run("without catch panics", func(t *testing.T) {104- exercise(t, WithoutCatchPanics(), withoutCatchPanics)82+ exercise(t, WithoutCatchPanics(), func(p *Program) {83+ if !p.disableCatchPanics {84+ t.Errorf("expected catch panics to be disabled")85+ }86+ })87 })88 89 t.Run("without signal handler", func(t *testing.T) {108- exercise(t, WithoutSignalHandler(), withoutSignalHandler)90+ exercise(t, WithoutSignalHandler(), func(p *Program) {91+ if !p.disableSignalHandler {92+ t.Errorf("expected signal handler to be disabled")93+ }94+ })95 })110-111- t.Run("mouse cell motion", func(t *testing.T) {112- p := NewProgram(nil, WithMouseAllMotion(), WithMouseCellMotion())113- if !p.startupOptions.has(withMouseCellMotion) {114- t.Errorf("expected startup options have %v, got %v", withMouseCellMotion, p.startupOptions)115- }116- if p.startupOptions.has(withMouseAllMotion) {117- t.Errorf("expected startup options not have %v, got %v", withMouseAllMotion, p.startupOptions)118- }119- })120-121- t.Run("mouse all motion", func(t *testing.T) {122- p := NewProgram(nil, WithMouseCellMotion(), WithMouseAllMotion())123- if !p.startupOptions.has(withMouseAllMotion) {124- t.Errorf("expected startup options have %v, got %v", withMouseAllMotion, p.startupOptions)125- }126- if p.startupOptions.has(withMouseCellMotion) {127- t.Errorf("expected startup options not have %v, got %v", withMouseCellMotion, p.startupOptions)128- }129- })96 })131-132- t.Run("multiple", func(t *testing.T) {133- p := NewProgram(nil, WithMouseAllMotion(), WithoutBracketedPaste(), WithAltScreen(), WithInputTTY())134- for _, opt := range []startupOptions{withMouseAllMotion, withoutBracketedPaste, withAltScreen} {135- if !p.startupOptions.has(opt) {136- t.Errorf("expected startup options have %v, got %v", opt, p.startupOptions)137- }138- if p.inputType != ttyInput {139- t.Errorf("expected input to be %v, got %v", opt, p.startupOptions)140- }141- }142- })97 }modified:options.go+24 added-108 removed
2 unmodified lines3 import (4 "context"5 "io"6 "sync/atomic"7+8+ "github.com/charmbracelet/colorprofile"9 )10 11 // ProgramOption is used to set options when initializing a Program. Program can12 // accept a variable number of options.26 unmodified lines39 // p := NewProgram(model, WithInput(nil))40 func WithInput(input io.Reader) ProgramOption {41 return func(p *Program) {42 p.input = input41- p.inputType = customInput43+ p.disableInput = input == nil44 }45 }46 45-// WithInputTTY opens a new TTY for input (or console input device on Windows).46-func WithInputTTY() ProgramOption {47- return func(p *Program) {48- p.inputType = ttyInput49- }50-}51-47 // WithEnvironment sets the environment variables that the program will use.48 // This useful when the program is running in a remote session (e.g. SSH) and49 // you want to pass the environment variables from the remote session to the50 // program.13 unmodified lines64 // WithoutSignalHandler disables the signal handler that Bubble Tea sets up for65 // Programs. This is useful if you want to handle signals yourself.66 func WithoutSignalHandler() ProgramOption {67 return func(p *Program) {73- p.startupOptions |= withoutSignalHandler68+ p.disableSignalHandler = true69 }70 }71 72 // WithoutCatchPanics disables the panic catching that Bubble Tea does by1 unmodified line74 // unusable state after a panic because Bubble Tea will not perform its usual75 // cleanup on exit.76 func WithoutCatchPanics() ProgramOption {77 return func(p *Program) {83- p.startupOptions |= withoutCatchPanics78+ p.disableCatchPanics = true79 }80 }81 82 // WithoutSignals will ignore OS signals.3 unmodified lines86 atomic.StoreUint32(&p.ignoreSignals, 1)87 }88 }89 95-// WithAltScreen starts the program with the alternate screen buffer enabled96-// (i.e. the program starts in full window mode). Note that the altscreen will97-// be automatically exited when the program quits.98-//99-// Example:100-//101-// p := tea.NewProgram(Model{}, tea.WithAltScreen())102-// if _, err := p.Run(); err != nil {103-// fmt.Println("Error running program:", err)104-// os.Exit(1)105-// }106-//107-// To enter the altscreen once the program has already started running use the108-// EnterAltScreen command.109-func WithAltScreen() ProgramOption {110- return func(p *Program) {111- p.startupOptions |= withAltScreen112- }113-}114-115-// WithoutBracketedPaste starts the program with bracketed paste disabled.116-func WithoutBracketedPaste() ProgramOption {117- return func(p *Program) {118- p.startupOptions |= withoutBracketedPaste119- }120-}121-122-// WithMouseCellMotion starts the program with the mouse enabled in "cell123-// motion" mode.124-//125-// Cell motion mode enables mouse click, release, and wheel events. Mouse126-// movement events are also captured if a mouse button is pressed (i.e., drag127-// events). Cell motion mode is better supported than all motion mode.128-//129-// This will try to enable the mouse in extended mode (SGR), if that is not130-// supported by the terminal it will fall back to normal mode (X10).131-//132-// To enable mouse cell motion once the program has already started running use133-// the EnableMouseCellMotion command. To disable the mouse when the program is134-// running use the DisableMouse command.135-//136-// The mouse will be automatically disabled when the program exits.137-func WithMouseCellMotion() ProgramOption {138- return func(p *Program) {139- p.startupOptions |= withMouseCellMotion // set140- p.startupOptions &^= withMouseAllMotion // clear141- }142-}143-144-// WithMouseAllMotion starts the program with the mouse enabled in "all motion"145-// mode.146-//147-// EnableMouseAllMotion is a special command that enables mouse click, release,148-// wheel, and motion events, which are delivered regardless of whether a mouse149-// button is pressed, effectively enabling support for hover interactions.150-//151-// This will try to enable the mouse in extended mode (SGR), if that is not152-// supported by the terminal it will fall back to normal mode (X10).153-//154-// Many modern terminals support this, but not all. If in doubt, use155-// EnableMouseCellMotion instead.156-//157-// To enable the mouse once the program has already started running use the158-// EnableMouseAllMotion command. To disable the mouse when the program is159-// running use the DisableMouse command.160-//161-// The mouse will be automatically disabled when the program exits.162-func WithMouseAllMotion() ProgramOption {163- return func(p *Program) {164- p.startupOptions |= withMouseAllMotion // set165- p.startupOptions &^= withMouseCellMotion // clear166- }167-}168-90 // WithoutRenderer disables the renderer. When this is set output and log91 // statements will be plainly sent to stdout (or another output if one is set)92 // without any rendering and redrawing logic. In other words, printing and93 // logging will behave the same way it would in a non-TUI commandline tool.2 unmodified lines96 // programs. For example, your program could behave like a daemon if output is97 // not a TTY.98 func WithoutRenderer() ProgramOption {99 return func(p *Program) {179- p.renderer = &nilRenderer{}100+ p.disableRenderer = true101 }102 }103 183-// WithANSICompressor removes redundant ANSI sequences to produce potentially184-// smaller output, at the cost of some processing overhead.185-//186-// This feature is provisional, and may be changed or removed in a future version187-// of this package.188-//189-// Deprecated: this incurs a noticeable performance hit. A future release will190-// optimize ANSI automatically without the performance penalty.191-func WithANSICompressor() ProgramOption {192- return func(p *Program) {193- p.startupOptions |= withANSICompressor194- }195-}196-104 // WithFilter supplies an event filter that will be invoked before Bubble Tea105 // processes a tea.Msg. The event filter can return any tea.Msg which will then106 // get handled by Bubble Tea instead of the original event. If the event filter107 // returns nil, the event will be ignored and Bubble Tea will not process it.36 unmodified lines144 p.fps = fps145 }146 }147 241-// WithReportFocus enables reporting when the terminal gains and loses242-// focus. When this is enabled [FocusMsg] and [BlurMsg] messages will be sent243-// to your Update method.244-//245-// Note that while most terminals and multiplexers support focus reporting,246-// some do not. Also note that tmux needs to be configured to report focus247-// events.248-func WithReportFocus() ProgramOption {148+// WithColorProfile sets the color profile that the program will use. This is149+// useful when you want to force a specific color profile. By default, Bubble150+// Tea will try to detect the terminal's color profile from environment151+// variables and terminfo capabilities. Use [tea.WithEnvironment] to set custom152+// environment variables.153+func WithColorProfile(profile colorprofile.Profile) ProgramOption {154 return func(p *Program) {250- p.startupOptions |= withReportFocus155+ p.profile = &profile156 }157 }158+159+// WithWindowSize sets the initial size of the terminal window. This is useful160+// when you need to set the initial size of the terminal window, for example161+// during testing or when you want to run your program in a non-interactive162+// environment.163+func WithWindowSize(width, height int) ProgramOption {164+ return func(p *Program) {165+ p.width = width166+ p.height = height167+ }168+}added:paste.go+20 added
1+package tea2+3+// PasteMsg is an message that is emitted when a terminal receives pasted text4+// using bracketed-paste.5+type PasteMsg struct {6+ Content string7+}8+9+// String returns the pasted content as a string.10+func (p PasteMsg) String() string {11+ return p.Content12+}13+14+// PasteStartMsg is an message that is emitted when the terminal starts the15+// bracketed-paste text.16+type PasteStartMsg struct{}17+18+// PasteEndMsg is an message that is emitted when the terminal ends the19+// bracketed-paste text.20+type PasteEndMsg struct{}added:profile.go+15 added
1+package tea2+3+import "github.com/charmbracelet/colorprofile"4+5+// ColorProfileMsg is a message that describes the terminal's color profile.6+// This message is send to the program's update function when the program is7+// started.8+//9+// To upgrade the terminal color profile, use the `tea.RequestCapability`10+// command to request the `RGB` and `Tc` terminfo capabilities. Bubble Tea will11+// then cache the terminal's color profile and send a `ColorProfileMsg` to the12+// program's update function.13+type ColorProfileMsg struct {14+ colorprofile.Profile15+}added:raw.go+37 added
1+package tea2+3+// RawMsg is a message that contains a string to be printed to the terminal4+// without any intermediate processing.5+type RawMsg struct {6+ Msg any7+}8+9+// Raw is a command that prints the given string to the terminal without any10+// formatting.11+//12+// This is intended for advanced use cases where you need to query the terminal13+// or send escape sequences directly. Don't use this unless you know what14+// you're doing :)15+//16+// Example:17+//18+// func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {19+// switch msg := msg.(type) {20+// case input.PrimaryDeviceAttributesEvent:21+// for _, attr := range msg {22+// if attr == 4 {23+// // We have Sixel graphics support!24+// break25+// }26+// }27+// }28+//29+// // Request the terminal primary device attributes to detect Sixel graphics30+// // support.31+// return m, tea.Raw(ansi.RequestPrimaryDeviceAttributes)32+// }33+func Raw(r any) Cmd {34+ return func() Msg {35+ return RawMsg{r}36+ }37+}modified:README.md+40 added-38 removed
1 # Bubble Tea2 3 <p>4- <picture>5- <source media="(prefers-color-scheme: light)" srcset="https://stuff.charm.sh/bubbletea/bubble-tea-v2-light.png" width="308">6- <source media="(prefers-color-scheme: dark)" srcset="https://stuff.charm.sh/bubbletea/bubble-tea-v2-dark.png" width="312">7- <img src="https://stuff.charm.sh/bubbletea/bubble-tea-v2-light.png" width="308" />8- </picture>9- <br>4+ <img src="https://github.com/user-attachments/assets/8d7f2c5a-6e0e-405c-9b3c-1269015bb2da" 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>11- <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>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>9 10 The fun, functional and stateful way to build terminal apps. A Go framework5 unmodified lines16 </p>17 18 Bubble Tea is in use in production and includes a number of features and19 performance optimizations we’ve added along the way. Among those is25-a framerate-based renderer, mouse support, focus reporting and more.20+a high-performance cell-based renderer, built-in color downsampling,21+declarative views, high-fidelity keyboard and mouse handling, native clipboard22+support, and more.23 24 To get started, see the tutorial below, the [examples][examples], the28-[docs][docs], the [video tutorials][youtube] and some common [resources](#libraries-we-use-with-bubble-tea).25+[docs][docs], and some common [resources](#libraries-we-use-with-bubble-tea).26 30-[youtube]: https://charm.sh/yt27+> [!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.31 32 ## By the way33 34 Be sure to check out [Bubbles][bubbles], a library of common UI components for Bubble Tea.36 unmodified lines71 import (72 "fmt"73 "os"74 75- tea "github.com/charmbracelet/bubbletea"75+ tea "charm.land/bubbletea/v2"76 )77 ```78 79 Bubble Tea programs are comprised of a **model** that describes the application15 unmodified lines95 selected map[int]struct{} // which to-do items are selected96 }97 ```98 99-### Initialization99+## Initialization100 101-Next, we’ll define our application’s initial state. In this case, we’re defining102-a function to return our initial model, however, we could just as easily define103-the initial model as a variable elsewhere, too.101+Next, we’ll define our application’s initial state. `Init` can return a `Cmd`102+that could perform some initial I/O. For now, we don’t need to do any I/O, so103+for the command, we’ll just return `nil`, which translates to “no command.”104 105 ```go106 func initialModel() model {107 return model{7 unmodified lines115 }116 }117 ```118 119-Next, we define the `Init` method. `Init` can return a `Cmd` that could perform120-some initial I/O. For now, we don't need to do any I/O, so for the command,121-we'll just return `nil`, which translates to "no command."119+After that, we’ll define our application’s initial state in the `Init` method. `Init`120+can return a `Cmd` that could perform some initial I/O. For now, we don't need121+to do any I/O, so for the command, we'll just return `nil`, which translates to122+"no command."123 124 ```go125 func (m model) Init() tea.Cmd {126 // Just return `nil`, which means "no I/O right now, please."2 unmodified lines129 ```130 131 ### The Update Method132 132-Next up is the update method. The update function is called when ”things133+Next up is the update method. The update function is called when “things134 happen.” Its job is to look at what has happened and return an updated model in135 response. It can also return a `Cmd` to make more things happen, but for now136 don't worry about that part.137 6 unmodified lines144 145 We usually figure out which type of `Msg` we received with a type switch, but146 you could also use a type assertion.147 147-For now, we'll just deal with `tea.KeyMsg` messages, which are automatically148-sent to the update function when keys are pressed.148+For now, we'll just deal with `tea.KeyPressMsg` messages, which are149+automatically sent to the update function when keys are pressed.150 151 ```go152 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {153 switch msg := msg.(type) {154 155 // Is it a key press?155- case tea.KeyMsg:156+ case tea.KeyPressMsg:157 158 // Cool, what was the actual key pressed?159 switch msg.String() {160 12 unmodified lines173 if m.cursor < len(m.choices)-1 {174 m.cursor++175 }176 176- // The "enter" key and the spacebar (a literal space) toggle177- // the selected state for the item that the cursor is pointing at.178- case "enter", " ":177+ // 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 {14 unmodified lines198 199 ### The View Method200 201 At last, it’s time to render our UI. Of all the methods, the view is the201-simplest. We look at the model in its current state and use it to return202-a `string`. That string is our UI!202+simplest. 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 features204+like alt screen mode, mouse tracking, cursor position, and more.205 206 Because the view describes the entire UI of your application, you don’t have to207 worry about redrawing logic and stuff like that. Bubble Tea takes care of it208 for you.209 210 ```go209-func (m model) View() string {211+func (m model) View() tea.View {212 // The header213 s := "What should we buy at the market?\n\n"214 215 // Iterate over our choices18 unmodified lines234 // The footer235 s += "\nPress q to quit.\n"236 237 // Send the UI for rendering236- return s238+ return tea.NewView(s)239 }240 ```241 242 ### All Together Now21 unmodified lines264 there are [Go Docs][docs].265 266 [cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/267 [examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples266-[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc268+[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc269 270 ## Debugging271 272 ### Debugging with Delve54 unmodified lines327 [ntcharts]: https://github.com/NimbleMarkets/ntcharts328 329 ## Bubble Tea in the Wild330 329-There are over [10,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.331+There are over [18,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.332 333 ### Staff favourites334 335 - [chezmoi](https://github.com/twpayne/chezmoi): securely manage your dotfiles across multiple machines4 unmodified lines340 - [Superfile](https://github.com/yorukot/superfile): a super file manager341 342 ### In Industry343 342-- Microsoft Azure – [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform343-- Daytona – [Daytona](https://github.com/daytonaio/daytona): open source dev environment manager344+- 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 database345-- Truffle Security Co. – [Trufflehog](https://github.com/trufflesecurity/trufflehog): find leaked credentials346-- NVIDIA – [container-canary](https://github.com/NVIDIA/container-canary): a container validator347-- AWS – [eks-node-viewer](https://github.com/awslabs/eks-node-viewer): a tool for visualizing dynamic node usage within an EKS cluster348-- MinIO – [mc](https://github.com/minio/mc): the official [MinIO](https://min.io) client349-- Ubuntu – [Authd](https://github.com/ubuntu/authd): an authentication daemon for cloud-based identity providers347+- 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 providers352 353 ### Charm stuff354 355 - [Glow](https://github.com/charmbracelet/glow): a markdown reader, browser, and online markdown stash47 unmodified linesmodified:renderer.go+82 added-66 removed
1 package tea2 3+import (4+ "fmt"5+6+ "github.com/charmbracelet/colorprofile"7+ "github.com/charmbracelet/x/ansi"8+)9+10+const (11+ // defaultFramerate specifies the maximum interval at which we should12+ // update the view.13+ defaultFPS = 6014+ maxFPS = 12015+)16+17 // renderer is the interface for Bubble Tea renderers.18 type renderer interface {5- // Start the renderer.19+ // start starts the renderer.20 start()21 8- // Stop the renderer, but render the final frame in the buffer, if any.9- stop()22+ // close closes the renderer and flushes any remaining data.23+ close() error24 11- // Stop the renderer without doing any final rendering.12- kill()25+ // render renders a frame to the output.26+ render(View)27 14- // Write a frame to the renderer. The renderer can write this data to15- // output at its discretion.16- write(string)28+ // flush flushes the renderer's buffer to the output.29+ flush(closing bool) error30 18- // Request a full re-render. Note that this will not trigger a render19- // immediately. Rather, this method causes the next render to be a full20- // repaint. Because of this, it's safe to call this method multiple times21- // in succession.22- repaint()31+ // reset resets the renderer's state to its initial state.32+ reset()33 24- // Clears the terminal.25- clearScreen()34+ // insertAbove inserts unmanaged lines above the renderer.35+ insertAbove(string) error36 27- // Whether or not the alternate screen buffer is enabled.28- altScreen() bool29- // Enable the alternate screen buffer.30- enterAltScreen()31- // Disable the alternate screen buffer.32- exitAltScreen()37+ // setSyncdUpdates sets whether to use synchronized updates.38+ setSyncdUpdates(bool)39 34- // Show the cursor.35- showCursor()36- // Hide the cursor.37- hideCursor()40+ // setWidthMethod sets the method for calculating the width of the terminal.41+ setWidthMethod(ansi.Method)42 39- // enableMouseCellMotion enables mouse click, release, wheel and motion40- // events if a mouse button is pressed (i.e., drag events).41- enableMouseCellMotion()43+ // resize notify the renderer of a terminal resize.44+ resize(int, int)45 43- // disableMouseCellMotion disables Mouse Cell Motion tracking.44- disableMouseCellMotion()46+ // setColorProfile sets the color profile.47+ setColorProfile(colorprofile.Profile)48 46- // enableMouseAllMotion enables mouse click, release, wheel and motion47- // events, regardless of whether a mouse button is pressed. Many modern48- // terminals support this, but not all.49- enableMouseAllMotion()49+ // clearScreen clears the screen.50+ clearScreen()51 51- // disableMouseAllMotion disables All Motion mouse tracking.52- disableMouseAllMotion()52+ // writeString writes a string to the renderer's output.53+ writeString(string) (int, error)54 54- // enableMouseSGRMode enables mouse extended mode (SGR).55- enableMouseSGRMode()55+ // onMouse handles a mouse event.56+ onMouse(MouseMsg) Cmd57+}58 57- // disableMouseSGRMode disables mouse extended mode (SGR).58- disableMouseSGRMode()59+type printLineMessage struct {60+ messageBody string61+}62 60- // enableBracketedPaste enables bracketed paste, where characters61- // inside the input are not interpreted when pasted as a whole.62- enableBracketedPaste()63+// Println prints above the Program. This output is unmanaged by the program and64+// will persist across renders by the Program.65+//66+// Unlike fmt.Println (but similar to log.Println) the message will be print on67+// its own line.68+//69+// If the altscreen is active no output will be printed.70+func Println(args ...any) Cmd {71+ return func() Msg {72+ return printLineMessage{73+ messageBody: fmt.Sprint(args...),74+ }75+ }76+}77 64- // disableBracketedPaste disables bracketed paste.65- disableBracketedPaste()66-67- // bracketedPasteActive reports whether bracketed paste mode is68- // currently enabled.69- bracketedPasteActive() bool70-71- // setWindowTitle sets the terminal window title.72- setWindowTitle(string)73-74- // reportFocus returns whether reporting focus events is enabled.75- reportFocus() bool76-77- // enableReportFocus reports focus events to the program.78- enableReportFocus()79-80- // disableReportFocus stops reporting focus events to the program.81- disableReportFocus()82-83- // resetLinesRendered ensures exec output remains on screen on exit84- resetLinesRendered()78+// Printf prints above the Program. It takes a format template followed by79+// values similar to fmt.Printf. This output is unmanaged by the program and80+// will persist across renders by the Program.81+//82+// Unlike fmt.Printf (but similar to log.Printf) the message will be print on83+// its own line.84+//85+// If the altscreen is active no output will be printed.86+func Printf(template string, args ...any) Cmd {87+ return func() Msg {88+ return printLineMessage{89+ messageBody: fmt.Sprintf(template, args...),90+ }91+ }92 }93 87-// repaintMsg forces a full repaint.88-type repaintMsg struct{}94+// encodeCursorStyle returns the integer value for the given cursor style and95+// blink state.96+func encodeCursorStyle(style CursorShape, blink bool) int {97+ // We're using the ANSI escape sequence values for cursor styles.98+ // We need to map both [style] and [steady] to the correct value.99+ style = (style * 2) + 1 //nolint:mnd100+ if !blink {101+ style++102+ }103+ return int(style)104+}modified:screen_test.go+161 added-38 removed
1 package tea2 3 import (4 "bytes"5+ "image/color"6 "testing"7+8+ "github.com/charmbracelet/colorprofile"9+ "github.com/charmbracelet/x/exp/golden"10 )11 12+type testViewOpts struct {13+ altScreen bool14+ mouseMode MouseMode15+ showCursor bool16+ disableBp bool17+ keyReleases bool18+ bgColor color.Color19+}20+21+func testViewOptsCmds(opts ...testViewOpts) []Cmd {22+ cmds := make([]Cmd, len(opts))23+ for i, o := range opts {24+ o := o25+ cmds[i] = func() Msg {26+ return o27+ }28+ }29+ return cmds30+}31+32+type testViewModel struct {33+ *testModel34+ opts testViewOpts35+}36+37+func (m *testViewModel) Update(msg Msg) (Model, Cmd) {38+ switch msg := msg.(type) {39+ case testViewOpts:40+ m.opts = msg41+ return m, nil42+ }43+ tm, cmd := m.testModel.Update(msg)44+ m.testModel = tm.(*testModel)45+ return m, cmd46+}47+48+func (m *testViewModel) View() View {49+ v := m.testModel.View()50+ v.AltScreen = m.opts.altScreen51+ v.MouseMode = m.opts.mouseMode52+ v.DisableBracketedPasteMode = m.opts.disableBp53+ v.KeyboardEnhancements.ReportEventTypes = m.opts.keyReleases54+ v.BackgroundColor = m.opts.bgColor55+ if m.opts.showCursor {56+ v.Cursor = NewCursor(0, 0)57+ }58+ return v59+}60+8-func TestClearMsg(t *testing.T) {61+func TestViewModel(t *testing.T) {62 tests := []struct {10- name string11- cmds sequenceMsg12- expected string63+ name string64+ opts []testViewOpts65 }{66 {15- name: "clear_screen",16- cmds: []Cmd{ClearScreen},17- expected: "\x1b[?25l\x1b[?2004h\x1b[2J\x1b[H\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",67+ name: "altscreen",68+ opts: []testViewOpts{69+ {altScreen: true},70+ {altScreen: false},71+ },72 },73 {20- name: "altscreen",21- cmds: []Cmd{EnterAltScreen, ExitAltScreen},22- expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[?1049l\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",74+ name: "altscreen_autoexit",75+ opts: []testViewOpts{76+ {altScreen: true},77+ },78 },79 {25- name: "altscreen_autoexit",26- cmds: []Cmd{EnterAltScreen},27- expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[H\rsuccess\x1b[K\r\n\x1b[K\x1b[2;H\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h",80+ name: "mouse_cellmotion",81+ opts: []testViewOpts{82+ {mouseMode: MouseModeCellMotion},83+ },84 },85 {30- name: "mouse_cellmotion",31- cmds: []Cmd{EnableMouseCellMotion},32- expected: "\x1b[?25l\x1b[?2004h\x1b[?1002h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",86+ name: "mouse_allmotion",87+ opts: []testViewOpts{88+ {mouseMode: MouseModeAllMotion},89+ },90 },91 {35- name: "mouse_allmotion",36- cmds: []Cmd{EnableMouseAllMotion},37- expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",92+ name: "mouse_disable",93+ opts: []testViewOpts{94+ {mouseMode: MouseModeAllMotion},95+ {mouseMode: MouseModeNone},96+ },97 },98 {40- name: "mouse_disable",41- cmds: []Cmd{EnableMouseAllMotion, DisableMouse},42- expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\x1b[?1002l\x1b[?1003l\x1b[?1006l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",99+ name: "cursor_hide",100+ opts: []testViewOpts{101+ {},102+ },103 },104 {45- name: "cursor_hide",46- cmds: []Cmd{HideCursor},47- expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",105+ name: "cursor_hideshow",106+ opts: []testViewOpts{107+ {showCursor: false},108+ {showCursor: true},109+ },110 },111 {50- name: "cursor_hideshow",51- cmds: []Cmd{HideCursor, ShowCursor},52- expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\x1b[?25h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",112+ name: "bp_stop_start",113+ opts: []testViewOpts{114+ {disableBp: true},115+ {disableBp: false},116+ },117 },118 {55- name: "bp_stop_start",56- cmds: []Cmd{DisableBracketedPaste, EnableBracketedPaste},57- expected: "\x1b[?25l\x1b[?2004h\x1b[?2004l\x1b[?2004h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",119+ name: "kitty_stop_startreleases",120+ opts: []testViewOpts{121+ {},122+ {keyReleases: true},123+ },124 },125+ {126+ name: "bg_set_color",127+ opts: []testViewOpts{128+ {bgColor: color.RGBA{255, 255, 255, 255}},129+ },130+ },131 }132 133 for _, test := range tests {134 t.Run(test.name, func(t *testing.T) {135 var buf bytes.Buffer136 var in bytes.Buffer137 66- m := &testModel{}67- p := NewProgram(m, WithInput(&in), WithOutput(&buf))138+ m := &testViewModel{testModel: &testModel{}}139+ p := NewProgram(m,140+ // Set the initial window size for the program.141+ WithWindowSize(80, 24),142+ // Use ANSI256 to increase test coverage.143+ WithColorProfile(colorprofile.ANSI256),144+ // always use xterm and 256 colors for tests145+ WithEnvironment([]string{"TERM=xterm-256color"}),146+ WithInput(&in),147+ WithOutput(&buf),148+ )149 69- test.cmds = append([]Cmd{func() Msg { return WindowSizeMsg{80, 24} }}, test.cmds...)70- test.cmds = append(test.cmds, Quit)71- go p.Send(test.cmds)150+ go p.Send(append(sequenceMsg(testViewOptsCmds(test.opts...)), Quit))151 152 if _, err := p.Run(); err != nil {153 t.Fatal(err)154 }155+ golden.RequireEqual(t, buf.Bytes())156+ })157+ }158+}159 77- if buf.String() != test.expected {78- t.Errorf("expected embedded sequence:\n%q\ngot:\n%q", test.expected, buf.String())160+func TestClearMsg(t *testing.T) {161+ type test struct {162+ name string163+ cmds sequenceMsg164+ }165+ tests := []test{166+ {167+ name: "clear_screen",168+ cmds: []Cmd{ClearScreen},169+ },170+ {171+ name: "read_set_clipboard",172+ cmds: []Cmd{ReadClipboard, SetClipboard("success")},173+ },174+ {175+ name: "bg_fg_cur_color",176+ cmds: []Cmd{RequestForegroundColor, RequestBackgroundColor, RequestCursorColor},177+ },178+ }179+180+ for _, test := range tests {181+ t.Run(test.name, func(t *testing.T) {182+ var buf bytes.Buffer183+ var in bytes.Buffer184+185+ m := &testModel{}186+ p := NewProgram(m,187+ // Set the initial window size for the program.188+ WithWindowSize(80, 24),189+ // Use ANSI256 to increase test coverage.190+ WithColorProfile(colorprofile.ANSI256),191+ // always use xterm and 256 colors for tests192+ WithEnvironment([]string{"TERM=xterm-256color"}),193+ WithInput(&in),194+ WithOutput(&buf),195+ )196+197+ go p.Send(append(test.cmds, Quit))198+199+ if _, err := p.Run(); err != nil {200+ t.Fatal(err)201 }202+ golden.RequireEqual(t, buf.Bytes())203 })204 }205 }modified:screen.go+35 added-215 removed
1 package tea2 3+import "github.com/charmbracelet/x/ansi"4+5 // WindowSizeMsg is used to report the terminal size. It's sent to Update once6 // initially and then on every terminal resize. Note that Windows does not7 // have support for reporting when resizes occur as it does not support the8 // SIGWINCH signal.15 unmodified lines24 // clearScreenMsg is an internal message that signals to clear the screen.25 // You can send a clearScreenMsg with ClearScreen.26 type clearScreenMsg struct{}27 26-// EnterAltScreen is a special command that tells the Bubble Tea program to27-// enter the alternate screen buffer.28+// ModeReportMsg is a message that represents a mode report event (DECRPM).29 //29-// Because commands run asynchronously, this command should not be used in your30-// model's Init function. To initialize your program with the altscreen enabled31-// use the WithAltScreen ProgramOption instead.32-func EnterAltScreen() Msg {33- return enterAltScreenMsg{}34-}35-36-// enterAltScreenMsg in an internal message signals that the program should37-// enter alternate screen buffer. You can send a enterAltScreenMsg with38-// EnterAltScreen.39-type enterAltScreenMsg struct{}40-41-// ExitAltScreen is a special command that tells the Bubble Tea program to exit42-// the alternate screen buffer. This command should be used to exit the43-// alternate screen buffer while the program is running.30+// This is sent by the terminal in response to a request for a terminal mode31+// report (DECRQM). It indicates the current setting of a specific terminal32+// mode like cursor visibility, mouse tracking, etc.33 //45-// Note that the alternate screen buffer will be automatically exited when the46-// program quits.47-func ExitAltScreen() Msg {48- return exitAltScreenMsg{}49-}50-51-// exitAltScreenMsg in an internal message signals that the program should exit52-// alternate screen buffer. You can send a exitAltScreenMsg with ExitAltScreen.53-type exitAltScreenMsg struct{}54-55-// EnableMouseCellMotion is a special command that enables mouse click,56-// release, and wheel events. Mouse movement events are also captured if57-// a mouse button is pressed (i.e., drag events).34+// Example:35 //59-// Because commands run asynchronously, this command should not be used in your60-// model's Init function. Use the WithMouseCellMotion ProgramOption instead.61-func EnableMouseCellMotion() Msg {62- return enableMouseCellMotionMsg{}63-}64-65-// enableMouseCellMotionMsg is a special command that signals to start66-// listening for "cell motion" type mouse events (ESC[?1002l). To send an67-// enableMouseCellMotionMsg, use the EnableMouseCellMotion command.68-type enableMouseCellMotionMsg struct{}69-70-// EnableMouseAllMotion is a special command that enables mouse click, release,71-// wheel, and motion events, which are delivered regardless of whether a mouse72-// button is pressed, effectively enabling support for hover interactions.36+// ```go37+// func (m model) Init() tea.Cmd {38+// // Does my terminal support reporting focus events?39+// return tea.Raw(ansi.RequestModeFocusEvent)40+// }41 //74-// Many modern terminals support this, but not all. If in doubt, use75-// EnableMouseCellMotion instead.42+// func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {43+// switch msg := msg.(type) {44+// case tea.ModeReportMsg:45+// if msg.Mode == ansi.ModeFocusEvent && !msg.Value.IsNotRecognized() {46+// // Terminal supports focus events47+// m.supportsFocus = true48+// }49+// }50+// return m, nil51+// }52 //77-// Because commands run asynchronously, this command should not be used in your78-// model's Init function. Use the WithMouseAllMotion ProgramOption instead.79-func EnableMouseAllMotion() Msg {80- return enableMouseAllMotionMsg{}81-}82-83-// enableMouseAllMotionMsg is a special command that signals to start listening84-// for "all motion" type mouse events (ESC[?1003l). To send an85-// enableMouseAllMotionMsg, use the EnableMouseAllMotion command.86-type enableMouseAllMotionMsg struct{}87-88-// DisableMouse is a special command that stops listening for mouse events.89-func DisableMouse() Msg {90- return disableMouseMsg{}91-}92-93-// disableMouseMsg is an internal message that signals to stop listening94-// for mouse events. To send a disableMouseMsg, use the DisableMouse command.95-type disableMouseMsg struct{}96-97-// HideCursor is a special command for manually instructing Bubble Tea to hide98-// the cursor. In some rare cases, certain operations will cause the terminal99-// to show the cursor, which is normally hidden for the duration of a Bubble100-// Tea program's lifetime. You will most likely not need to use this command.101-func HideCursor() Msg {102- return hideCursorMsg{}103-}104-105-// hideCursorMsg is an internal command used to hide the cursor. You can send106-// this message with HideCursor.107-type hideCursorMsg struct{}108-109-// ShowCursor is a special command for manually instructing Bubble Tea to show110-// the cursor.111-func ShowCursor() Msg {112- return showCursorMsg{}113-}114-115-// showCursorMsg is an internal command used to show the cursor. You can send116-// this message with ShowCursor.117-type showCursorMsg struct{}118-119-// EnableBracketedPaste is a special command that tells the Bubble Tea program120-// to accept bracketed paste input.53+// func (m model) View() tea.View {54+// var view tea.View55+// view.ReportFocus = m.supportsFocus56+// view.SetContent(fmt.Sprintf("Terminal supports focus events: %v", m.supportsFocus))57+// return view58+// }59+// ```60 //122-// Note that bracketed paste will be automatically disabled when the123-// program quits.124-func EnableBracketedPaste() Msg {125- return enableBracketedPasteMsg{}126-}61+// See: https://vt100.net/docs/vt510-rm/DECRPM.html62+type ModeReportMsg struct {63+ // Mode is the mode number.64+ Mode ansi.Mode65 128-// enableBracketedPasteMsg in an internal message signals that129-// bracketed paste should be enabled. You can send an130-// enableBracketedPasteMsg with EnableBracketedPaste.131-type enableBracketedPasteMsg struct{}132-133-// DisableBracketedPaste is a special command that tells the Bubble Tea program134-// to stop processing bracketed paste input.135-//136-// Note that bracketed paste will be automatically disabled when the137-// program quits.138-func DisableBracketedPaste() Msg {139- return disableBracketedPasteMsg{}66+ // Value is the mode value.67+ Value ansi.ModeSetting68 }141-142-// disableBracketedPasteMsg in an internal message signals that143-// bracketed paste should be disabled. You can send an144-// disableBracketedPasteMsg with DisableBracketedPaste.145-type disableBracketedPasteMsg struct{}146-147-// enableReportFocusMsg is an internal message that signals to enable focus148-// reporting. You can send an enableReportFocusMsg with EnableReportFocus.149-type enableReportFocusMsg struct{}150-151-// EnableReportFocus is a special command that tells the Bubble Tea program to152-// report focus events to the program.153-func EnableReportFocus() Msg {154- return enableReportFocusMsg{}155-}156-157-// disableReportFocusMsg is an internal message that signals to disable focus158-// reporting. You can send an disableReportFocusMsg with DisableReportFocus.159-type disableReportFocusMsg struct{}160-161-// DisableReportFocus is a special command that tells the Bubble Tea program to162-// stop reporting focus events to the program.163-func DisableReportFocus() Msg {164- return disableReportFocusMsg{}165-}166-167-// EnterAltScreen enters the alternate screen buffer, which consumes the entire168-// terminal window. ExitAltScreen will return the terminal to its former state.169-//170-// Deprecated: Use the WithAltScreen ProgramOption instead.171-func (p *Program) EnterAltScreen() {172- if p.renderer != nil {173- p.renderer.enterAltScreen()174- } else {175- p.startupOptions |= withAltScreen176- }177-}178-179-// ExitAltScreen exits the alternate screen buffer.180-//181-// Deprecated: The altscreen will exited automatically when the program exits.182-func (p *Program) ExitAltScreen() {183- if p.renderer != nil {184- p.renderer.exitAltScreen()185- } else {186- p.startupOptions &^= withAltScreen187- }188-}189-190-// EnableMouseCellMotion enables mouse click, release, wheel and motion events191-// if a mouse button is pressed (i.e., drag events).192-//193-// Deprecated: Use the WithMouseCellMotion ProgramOption instead.194-func (p *Program) EnableMouseCellMotion() {195- if p.renderer != nil {196- p.renderer.enableMouseCellMotion()197- } else {198- p.startupOptions |= withMouseCellMotion199- }200-}201-202-// DisableMouseCellMotion disables Mouse Cell Motion tracking. This will be203-// called automatically when exiting a Bubble Tea program.204-//205-// Deprecated: The mouse will automatically be disabled when the program exits.206-func (p *Program) DisableMouseCellMotion() {207- if p.renderer != nil {208- p.renderer.disableMouseCellMotion()209- } else {210- p.startupOptions &^= withMouseCellMotion211- }212-}213-214-// EnableMouseAllMotion enables mouse click, release, wheel and motion events,215-// regardless of whether a mouse button is pressed. Many modern terminals216-// support this, but not all.217-//218-// Deprecated: Use the WithMouseAllMotion ProgramOption instead.219-func (p *Program) EnableMouseAllMotion() {220- if p.renderer != nil {221- p.renderer.enableMouseAllMotion()222- } else {223- p.startupOptions |= withMouseAllMotion224- }225-}226-227-// DisableMouseAllMotion disables All Motion mouse tracking. This will be228-// called automatically when exiting a Bubble Tea program.229-//230-// Deprecated: The mouse will automatically be disabled when the program exits.231-func (p *Program) DisableMouseAllMotion() {232- if p.renderer != nil {233- p.renderer.disableMouseAllMotion()234- } else {235- p.startupOptions &^= withMouseAllMotion236- }237-}238-239-// SetWindowTitle sets the terminal window title.240-//241-// Deprecated: Use the SetWindowTitle command instead.242-func (p *Program) SetWindowTitle(title string) {243- if p.renderer != nil {244- p.renderer.setWindowTitle(title)245- } else {246- p.startupTitle = title247- }248-}deleted:standard_renderer.go-790 removed
1-package tea2-3-import (4- "bytes"5- "fmt"6- "io"7- "strings"8- "sync"9- "time"10-11- "github.com/charmbracelet/x/ansi"12- "github.com/muesli/ansi/compressor"13-)14-15-const (16- // defaultFramerate specifies the maximum interval at which we should17- // update the view.18- defaultFPS = 6019- maxFPS = 12020-)21-22-// standardRenderer is a framerate-based terminal renderer, updating the view23-// at a given framerate to avoid overloading the terminal emulator.24-//25-// In cases where very high performance is needed the renderer can be told26-// to exclude ranges of lines, allowing them to be written to directly.27-type standardRenderer struct {28- mtx *sync.Mutex29- out io.Writer30-31- buf bytes.Buffer32- queuedMessageLines []string33- framerate time.Duration34- ticker *time.Ticker35- done chan struct{}36- lastRender string37- lastRenderedLines []string38- linesRendered int39- altLinesRendered int40- useANSICompressor bool41- once sync.Once42-43- // cursor visibility state44- cursorHidden bool45-46- // essentially whether or not we're using the full size of the terminal47- altScreenActive bool48-49- // whether or not we're currently using bracketed paste50- bpActive bool51-52- // reportingFocus whether reporting focus events is enabled53- reportingFocus bool54-55- // renderer dimensions; usually the size of the window56- width int57- height int58-59- // lines explicitly set not to render60- ignoreLines map[int]struct{}61-}62-63-// newRenderer creates a new renderer. Normally you'll want to initialize it64-// with os.Stdout as the first argument.65-func newRenderer(out io.Writer, useANSICompressor bool, fps int) renderer {66- if fps < 1 {67- fps = defaultFPS68- } else if fps > maxFPS {69- fps = maxFPS70- }71- r := &standardRenderer{72- out: out,73- mtx: &sync.Mutex{},74- done: make(chan struct{}),75- framerate: time.Second / time.Duration(fps),76- useANSICompressor: useANSICompressor,77- queuedMessageLines: []string{},78- }79- if r.useANSICompressor {80- r.out = &compressor.Writer{Forward: out}81- }82- return r83-}84-85-// start starts the renderer.86-func (r *standardRenderer) start() {87- if r.ticker == nil {88- r.ticker = time.NewTicker(r.framerate)89- } else {90- // If the ticker already exists, it has been stopped and we need to91- // reset it.92- r.ticker.Reset(r.framerate)93- }94-95- // Since the renderer can be restarted after a stop, we need to reset96- // the done channel and its corresponding sync.Once.97- r.once = sync.Once{}98-99- go r.listen()100-}101-102-// stop permanently halts the renderer, rendering the final frame.103-func (r *standardRenderer) stop() {104- // Stop the renderer before acquiring the mutex to avoid a deadlock.105- r.once.Do(func() {106- r.done <- struct{}{}107- })108-109- // flush locks the mutex110- r.flush()111-112- r.mtx.Lock()113- defer r.mtx.Unlock()114-115- r.execute(ansi.EraseEntireLine)116- // Move the cursor back to the beginning of the line117- r.execute("\r")118-119- if r.useANSICompressor {120- if w, ok := r.out.(io.WriteCloser); ok {121- _ = w.Close()122- }123- }124-}125-126-// execute writes a sequence to the terminal.127-func (r *standardRenderer) execute(seq string) {128- _, _ = io.WriteString(r.out, seq)129-}130-131-// kill halts the renderer. The final frame will not be rendered.132-func (r *standardRenderer) kill() {133- // Stop the renderer before acquiring the mutex to avoid a deadlock.134- r.once.Do(func() {135- r.done <- struct{}{}136- })137-138- r.mtx.Lock()139- defer r.mtx.Unlock()140-141- r.execute(ansi.EraseEntireLine)142- // Move the cursor back to the beginning of the line143- r.execute("\r")144-}145-146-// listen waits for ticks on the ticker, or a signal to stop the renderer.147-func (r *standardRenderer) listen() {148- for {149- select {150- case <-r.done:151- r.ticker.Stop()152- return153-154- case <-r.ticker.C:155- r.flush()156- }157- }158-}159-160-// flush renders the buffer.161-func (r *standardRenderer) flush() {162- r.mtx.Lock()163- defer r.mtx.Unlock()164-165- if r.buf.Len() == 0 || r.buf.String() == r.lastRender {166- // Nothing to do.167- return168- }169-170- // Output buffer.171- buf := &bytes.Buffer{}172-173- // Moving to the beginning of the section, that we rendered.174- if r.altScreenActive {175- buf.WriteString(ansi.CursorHomePosition)176- } else if r.linesRendered > 1 {177- buf.WriteString(ansi.CursorUp(r.linesRendered - 1))178- }179-180- newLines := strings.Split(r.buf.String(), "\n")181-182- // If we know the output's height, we can use it to determine how many183- // lines we can render. We drop lines from the top of the render buffer if184- // necessary, as we can't navigate the cursor into the terminal's scrollback185- // buffer.186- if r.height > 0 && len(newLines) > r.height {187- newLines = newLines[len(newLines)-r.height:]188- }189-190- flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive191-192- if flushQueuedMessages {193- // Dump the lines we've queued up for printing.194- for _, line := range r.queuedMessageLines {195- if ansi.StringWidth(line) < r.width {196- // We only erase the rest of the line when the line is shorter than197- // the width of the terminal. When the cursor reaches the end of198- // the line, any escape sequences that follow will only affect the199- // last cell of the line.200-201- // Removing previously rendered content at the end of line.202- line = line + ansi.EraseLineRight203- }204-205- _, _ = buf.WriteString(line)206- _, _ = buf.WriteString("\r\n")207- }208- // Clear the queued message lines.209- r.queuedMessageLines = []string{}210- }211-212- // Paint new lines.213- for i := 0; i < len(newLines); i++ {214- canSkip := !flushQueuedMessages && // Queuing messages triggers repaint -> we don't have access to previous frame content.215- len(r.lastRenderedLines) > i && r.lastRenderedLines[i] == newLines[i] // Previously rendered line is the same.216-217- if _, ignore := r.ignoreLines[i]; ignore || canSkip {218- // Unless this is the last line, move the cursor down.219- if i < len(newLines)-1 {220- buf.WriteByte('\n')221- }222- continue223- }224-225- if i == 0 && r.lastRender == "" {226- // On first render, reset the cursor to the start of the line227- // before writing anything.228- buf.WriteByte('\r')229- }230-231- line := newLines[i]232-233- // Truncate lines wider than the width of the window to avoid234- // wrapping, which will mess up rendering. If we don't have the235- // width of the window this will be ignored.236- //237- // Note that on Windows we only get the width of the window on238- // program initialization, so after a resize this won't perform239- // correctly (signal SIGWINCH is not supported on Windows).240- if r.width > 0 {241- line = ansi.Truncate(line, r.width, "")242- }243-244- if ansi.StringWidth(line) < r.width {245- // We only erase the rest of the line when the line is shorter than246- // the width of the terminal. When the cursor reaches the end of247- // the line, any escape sequences that follow will only affect the248- // last cell of the line.249-250- // Removing previously rendered content at the end of line.251- line = line + ansi.EraseLineRight252- }253-254- _, _ = buf.WriteString(line)255-256- if i < len(newLines)-1 {257- _, _ = buf.WriteString("\r\n")258- }259- }260-261- // Clearing left over content from last render.262- if r.lastLinesRendered() > len(newLines) {263- buf.WriteString(ansi.EraseScreenBelow)264- }265-266- if r.altScreenActive {267- r.altLinesRendered = len(newLines)268- } else {269- r.linesRendered = len(newLines)270- }271-272- // Make sure the cursor is at the start of the last line to keep rendering273- // behavior consistent.274- if r.altScreenActive {275- // This case fixes a bug in macOS terminal. In other terminals the276- // other case seems to do the job regardless of whether or not we're277- // using the full terminal window.278- buf.WriteString(ansi.CursorPosition(0, len(newLines)))279- } else {280- buf.WriteByte('\r')281- }282-283- _, _ = r.out.Write(buf.Bytes())284- r.lastRender = r.buf.String()285-286- // Save previously rendered lines for comparison in the next render. If we287- // don't do this, we can't skip rendering lines that haven't changed.288- // See https://github.com/charmbracelet/bubbletea/pull/1233289- r.lastRenderedLines = newLines290- r.buf.Reset()291-}292-293-// lastLinesRendered returns the number of lines rendered lastly.294-func (r *standardRenderer) lastLinesRendered() int {295- if r.altScreenActive {296- return r.altLinesRendered297- }298- return r.linesRendered299-}300-301-// write writes to the internal buffer. The buffer will be outputted via the302-// ticker which calls flush().303-func (r *standardRenderer) write(s string) {304- r.mtx.Lock()305- defer r.mtx.Unlock()306- r.buf.Reset()307-308- // If an empty string was passed we should clear existing output and309- // rendering nothing. Rather than introduce additional state to manage310- // this, we render a single space as a simple (albeit less correct)311- // solution.312- if s == "" {313- s = " "314- }315-316- _, _ = r.buf.WriteString(s)317-}318-319-func (r *standardRenderer) repaint() {320- r.lastRender = ""321- r.lastRenderedLines = nil322-}323-324-func (r *standardRenderer) clearScreen() {325- r.mtx.Lock()326- defer r.mtx.Unlock()327-328- r.execute(ansi.EraseEntireScreen)329- r.execute(ansi.CursorHomePosition)330-331- r.repaint()332-}333-334-func (r *standardRenderer) altScreen() bool {335- r.mtx.Lock()336- defer r.mtx.Unlock()337-338- return r.altScreenActive339-}340-341-func (r *standardRenderer) enterAltScreen() {342- r.mtx.Lock()343- defer r.mtx.Unlock()344-345- if r.altScreenActive {346- return347- }348-349- r.altScreenActive = true350- r.execute(ansi.SetAltScreenSaveCursorMode)351-352- // Ensure that the terminal is cleared, even when it doesn't support353- // alt screen (or alt screen support is disabled, like GNU screen by354- // default).355- //356- // Note: we can't use r.clearScreen() here because the mutex is already357- // locked.358- r.execute(ansi.EraseEntireScreen)359- r.execute(ansi.CursorHomePosition)360-361- // cmd.exe and other terminals keep separate cursor states for the AltScreen362- // and the main buffer. We have to explicitly reset the cursor visibility363- // whenever we enter AltScreen.364- if r.cursorHidden {365- r.execute(ansi.HideCursor)366- } else {367- r.execute(ansi.ShowCursor)368- }369-370- // Entering the alt screen resets the lines rendered count.371- r.altLinesRendered = 0372-373- r.repaint()374-}375-376-func (r *standardRenderer) exitAltScreen() {377- r.mtx.Lock()378- defer r.mtx.Unlock()379-380- if !r.altScreenActive {381- return382- }383-384- r.altScreenActive = false385- r.execute(ansi.ResetAltScreenSaveCursorMode)386-387- // cmd.exe and other terminals keep separate cursor states for the AltScreen388- // and the main buffer. We have to explicitly reset the cursor visibility389- // whenever we exit AltScreen.390- if r.cursorHidden {391- r.execute(ansi.HideCursor)392- } else {393- r.execute(ansi.ShowCursor)394- }395-396- r.repaint()397-}398-399-func (r *standardRenderer) showCursor() {400- r.mtx.Lock()401- defer r.mtx.Unlock()402-403- r.cursorHidden = false404- r.execute(ansi.ShowCursor)405-}406-407-func (r *standardRenderer) hideCursor() {408- r.mtx.Lock()409- defer r.mtx.Unlock()410-411- r.cursorHidden = true412- r.execute(ansi.HideCursor)413-}414-415-func (r *standardRenderer) enableMouseCellMotion() {416- r.mtx.Lock()417- defer r.mtx.Unlock()418-419- r.execute(ansi.SetButtonEventMouseMode)420-}421-422-func (r *standardRenderer) disableMouseCellMotion() {423- r.mtx.Lock()424- defer r.mtx.Unlock()425-426- r.execute(ansi.ResetButtonEventMouseMode)427-}428-429-func (r *standardRenderer) enableMouseAllMotion() {430- r.mtx.Lock()431- defer r.mtx.Unlock()432-433- r.execute(ansi.SetAnyEventMouseMode)434-}435-436-func (r *standardRenderer) disableMouseAllMotion() {437- r.mtx.Lock()438- defer r.mtx.Unlock()439-440- r.execute(ansi.ResetAnyEventMouseMode)441-}442-443-func (r *standardRenderer) enableMouseSGRMode() {444- r.mtx.Lock()445- defer r.mtx.Unlock()446-447- r.execute(ansi.SetSgrExtMouseMode)448-}449-450-func (r *standardRenderer) disableMouseSGRMode() {451- r.mtx.Lock()452- defer r.mtx.Unlock()453-454- r.execute(ansi.ResetSgrExtMouseMode)455-}456-457-func (r *standardRenderer) enableBracketedPaste() {458- r.mtx.Lock()459- defer r.mtx.Unlock()460-461- r.execute(ansi.SetBracketedPasteMode)462- r.bpActive = true463-}464-465-func (r *standardRenderer) disableBracketedPaste() {466- r.mtx.Lock()467- defer r.mtx.Unlock()468-469- r.execute(ansi.ResetBracketedPasteMode)470- r.bpActive = false471-}472-473-func (r *standardRenderer) bracketedPasteActive() bool {474- r.mtx.Lock()475- defer r.mtx.Unlock()476-477- return r.bpActive478-}479-480-func (r *standardRenderer) enableReportFocus() {481- r.mtx.Lock()482- defer r.mtx.Unlock()483-484- r.execute(ansi.SetFocusEventMode)485- r.reportingFocus = true486-}487-488-func (r *standardRenderer) disableReportFocus() {489- r.mtx.Lock()490- defer r.mtx.Unlock()491-492- r.execute(ansi.ResetFocusEventMode)493- r.reportingFocus = false494-}495-496-func (r *standardRenderer) reportFocus() bool {497- r.mtx.Lock()498- defer r.mtx.Unlock()499-500- return r.reportingFocus501-}502-503-// setWindowTitle sets the terminal window title.504-func (r *standardRenderer) setWindowTitle(title string) {505- r.execute(ansi.SetWindowTitle(title))506-}507-508-// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea509-// renderer.510-func (r *standardRenderer) setIgnoredLines(from int, to int) {511- // Lock if we're going to be clearing some lines since we don't want512- // anything jacking our cursor.513- if r.lastLinesRendered() > 0 {514- r.mtx.Lock()515- defer r.mtx.Unlock()516- }517-518- if r.ignoreLines == nil {519- r.ignoreLines = make(map[int]struct{})520- }521- for i := from; i < to; i++ {522- r.ignoreLines[i] = struct{}{}523- }524-525- // Erase ignored lines526- lastLinesRendered := r.lastLinesRendered()527- if lastLinesRendered > 0 {528- buf := &bytes.Buffer{}529-530- for i := lastLinesRendered - 1; i >= 0; i-- {531- if _, exists := r.ignoreLines[i]; exists {532- buf.WriteString(ansi.EraseEntireLine)533- }534- buf.WriteString(ansi.CUU1)535- }536- buf.WriteString(ansi.CursorPosition(0, lastLinesRendered)) // put cursor back537- _, _ = r.out.Write(buf.Bytes())538- }539-}540-541-// clearIgnoredLines returns control of any ignored lines to the standard542-// Bubble Tea renderer. That is, any lines previously set to be ignored can be543-// rendered to again.544-func (r *standardRenderer) clearIgnoredLines() {545- r.ignoreLines = nil546-}547-548-func (r *standardRenderer) resetLinesRendered() {549- r.linesRendered = 0550-}551-552-// insertTop effectively scrolls up. It inserts lines at the top of a given553-// area designated to be a scrollable region, pushing everything else down.554-// This is roughly how ncurses does it.555-//556-// To call this function use command ScrollUp().557-//558-// For this to work renderer.ignoreLines must be set to ignore the scrollable559-// region since we are bypassing the normal Bubble Tea renderer here.560-//561-// Because this method relies on the terminal dimensions, it's only valid for562-// full-window applications (generally those that use the alternate screen563-// buffer).564-//565-// This method bypasses the normal rendering buffer and is philosophically566-// different than the normal way we approach rendering in Bubble Tea. It's for567-// use in high-performance rendering, such as a pager that could potentially568-// be rendering very complicated ansi. In cases where the content is simpler569-// standard Bubble Tea rendering should suffice.570-//571-// Deprecated: This option is deprecated and will be removed in a future572-// version of this package.573-func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {574- r.mtx.Lock()575- defer r.mtx.Unlock()576-577- buf := &bytes.Buffer{}578-579- buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary))580- buf.WriteString(ansi.CursorPosition(0, topBoundary))581- buf.WriteString(ansi.InsertLine(len(lines)))582- _, _ = buf.WriteString(strings.Join(lines, "\r\n"))583- buf.WriteString(ansi.SetTopBottomMargins(0, r.height))584-585- // Move cursor back to where the main rendering routine expects it to be586- buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered()))587-588- _, _ = r.out.Write(buf.Bytes())589-}590-591-// insertBottom effectively scrolls down. It inserts lines at the bottom of592-// a given area designated to be a scrollable region, pushing everything else593-// up. This is roughly how ncurses does it.594-//595-// To call this function use the command ScrollDown().596-//597-// See note in insertTop() for caveats, how this function only makes sense for598-// full-window applications, and how it differs from the normal way we do599-// rendering in Bubble Tea.600-//601-// Deprecated: This option is deprecated and will be removed in a future602-// version of this package.603-func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {604- r.mtx.Lock()605- defer r.mtx.Unlock()606-607- buf := &bytes.Buffer{}608-609- buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary))610- buf.WriteString(ansi.CursorPosition(0, bottomBoundary))611- _, _ = buf.WriteString("\r\n" + strings.Join(lines, "\r\n"))612- buf.WriteString(ansi.SetTopBottomMargins(0, r.height))613-614- // Move cursor back to where the main rendering routine expects it to be615- buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered()))616-617- _, _ = r.out.Write(buf.Bytes())618-}619-620-// handleMessages handles internal messages for the renderer.621-func (r *standardRenderer) handleMessages(msg Msg) {622- switch msg := msg.(type) {623- case repaintMsg:624- // Force a repaint by clearing the render cache as we slide into a625- // render.626- r.mtx.Lock()627- r.repaint()628- r.mtx.Unlock()629-630- case WindowSizeMsg:631- r.mtx.Lock()632- r.width = msg.Width633- r.height = msg.Height634- r.repaint()635- r.mtx.Unlock()636-637- case clearScrollAreaMsg:638- r.clearIgnoredLines()639-640- // Force a repaint on the area where the scrollable stuff was in this641- // update cycle642- r.mtx.Lock()643- r.repaint()644- r.mtx.Unlock()645-646- case syncScrollAreaMsg:647- // Re-render scrolling area648- r.clearIgnoredLines()649- r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary)650- r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)651-652- // Force non-scrolling stuff to repaint in this update cycle653- r.mtx.Lock()654- r.repaint()655- r.mtx.Unlock()656-657- case scrollUpMsg:658- r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)659-660- case scrollDownMsg:661- r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)662-663- case printLineMessage:664- if !r.altScreenActive {665- lines := strings.Split(msg.messageBody, "\n")666- r.mtx.Lock()667- r.queuedMessageLines = append(r.queuedMessageLines, lines...)668- r.repaint()669- r.mtx.Unlock()670- }671- }672-}673-674-// HIGH-PERFORMANCE RENDERING STUFF675-676-type syncScrollAreaMsg struct {677- lines []string678- topBoundary int679- bottomBoundary int680-}681-682-// SyncScrollArea performs a paint of the entire region designated to be the683-// scrollable area. This is required to initialize the scrollable region and684-// should also be called on resize (WindowSizeMsg).685-//686-// For high-performance, scroll-based rendering only.687-//688-// Deprecated: This option will be removed in a future version of this package.689-func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {690- return func() Msg {691- return syncScrollAreaMsg{692- lines: lines,693- topBoundary: topBoundary,694- bottomBoundary: bottomBoundary,695- }696- }697-}698-699-type clearScrollAreaMsg struct{}700-701-// ClearScrollArea deallocates the scrollable region and returns the control of702-// those lines to the main rendering routine.703-//704-// For high-performance, scroll-based rendering only.705-//706-// Deprecated: This option will be removed in a future version of this package.707-func ClearScrollArea() Msg {708- return clearScrollAreaMsg{}709-}710-711-type scrollUpMsg struct {712- lines []string713- topBoundary int714- bottomBoundary int715-}716-717-// ScrollUp adds lines to the top of the scrollable region, pushing existing718-// lines below down. Lines that are pushed out the scrollable region disappear719-// from view.720-//721-// For high-performance, scroll-based rendering only.722-//723-// Deprecated: This option will be removed in a future version of this package.724-func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {725- return func() Msg {726- return scrollUpMsg{727- lines: newLines,728- topBoundary: topBoundary,729- bottomBoundary: bottomBoundary,730- }731- }732-}733-734-type scrollDownMsg struct {735- lines []string736- topBoundary int737- bottomBoundary int738-}739-740-// ScrollDown adds lines to the bottom of the scrollable region, pushing741-// existing lines above up. Lines that are pushed out of the scrollable region742-// disappear from view.743-//744-// For high-performance, scroll-based rendering only.745-//746-// Deprecated: This option will be removed in a future version of this package.747-func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {748- return func() Msg {749- return scrollDownMsg{750- lines: newLines,751- topBoundary: topBoundary,752- bottomBoundary: bottomBoundary,753- }754- }755-}756-757-type printLineMessage struct {758- messageBody string759-}760-761-// Println prints above the Program. This output is unmanaged by the program and762-// will persist across renders by the Program.763-//764-// Unlike fmt.Println (but similar to log.Println) the message will be print on765-// its own line.766-//767-// If the altscreen is active no output will be printed.768-func Println(args ...interface{}) Cmd {769- return func() Msg {770- return printLineMessage{771- messageBody: fmt.Sprint(args...),772- }773- }774-}775-776-// Printf prints above the Program. It takes a format template followed by777-// values similar to fmt.Printf. This output is unmanaged by the program and778-// will persist across renders by the Program.779-//780-// Unlike fmt.Printf (but similar to log.Printf) the message will be print on781-// its own line.782-//783-// If the altscreen is active no output will be printed.784-func Printf(template string, args ...interface{}) Cmd {785- return func() Msg {786- return printLineMessage{787- messageBody: fmt.Sprintf(template, args...),788- }789- }790-}deleted:tea_init.go-22 removed
1-package tea2-3-import (4- "github.com/charmbracelet/lipgloss"5-)6-7-func init() {8- // XXX: This is a workaround to make assure that Lip Gloss and Termenv9- // query the terminal before any Bubble Tea Program runs and acquires the10- // terminal. Without this, Programs that use Lip Gloss/Termenv might hang11- // while waiting for a a [termenv.OSCTimeout] while querying the terminal12- // for its background/foreground colors.13- //14- // This happens because Bubble Tea acquires the terminal before termenv15- // reads any responses.16- //17- // Note that this will only affect programs running on the default IO i.e.18- // [os.Stdout] and [os.Stdin].19- //20- // This workaround will be removed in v2.21- _ = lipgloss.HasDarkBackground()22-}modified:tea_test.go+153 added-37 removed
2 unmodified lines3 import (4 "bytes"5 "context"6 "errors"7+ "io"8+ "strings"9 "sync"10 "sync/atomic"11 "testing"12 "time"15 unmodified lines28 executed atomic.Value29 counter atomic.Value30 }31 30-func (m testModel) Init() Cmd {32+func (m *testModel) Init() Cmd {33 return nil34 }35 36 func (m *testModel) Update(msg Msg) (Model, Cmd) {9 unmodified lines46 } else {47 m.counter.Store(i.(int) + 1)48 }49 48- case KeyMsg:49- return m, Quit50+ case KeyPressMsg:51+ switch msg.String() {52+ case "q", "ctrl+c":53+ return m, Quit54+ }55 56 case panicMsg:57 panic("testing panic behavior")58 }59 60 return m, nil61 }62 58-func (m *testModel) View() string {63+func (m *testModel) View() View {64 m.executed.Store(true)60- return "success\n"65+ return NewView("success")66 }67 68 func TestTeaModel(t *testing.T) {69 var buf bytes.Buffer70 var in bytes.Buffer71 in.Write([]byte("q"))72 68- ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second)73+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)74 defer cancel()75 71- p := NewProgram(&testModel{}, WithInput(&in), WithOutput(&buf), WithContext(ctx))76+ p := NewProgram(&testModel{},77+ WithContext(ctx),78+ WithInput(&in),79+ WithOutput(&buf),80+ )81 if _, err := p.Run(); err != nil {82 t.Fatal(err)83 }84 6 unmodified lines91 var buf bytes.Buffer92 var in bytes.Buffer93 94 m := &testModel{}86- p := NewProgram(m, WithInput(&in), WithOutput(&buf))95+ p := NewProgram(m,96+ WithInput(&in),97+ WithOutput(&buf),98+ )99 go func() {100 for {101 time.Sleep(time.Millisecond)102 if m.executed.Load() != nil {16 unmodified lines119 waitStarted := make(chan struct{})120 errChan := make(chan error, 1)121 122 m := &testModel{}111- p := NewProgram(m, WithInput(&in), WithOutput(&buf))123+ p := NewProgram(m,124+ WithInput(&in),125+ WithOutput(&buf),126+ )127 128 go func() {129 _, err := p.Run()130 errChan <- err16 unmodified lines147 148 <-progStarted149 150 var wg sync.WaitGroup136- for i := 0; i < 5; i++ {151+ for range 5 {152 wg.Add(1)153 go func() {154 p.Wait()155 wg.Done()16 unmodified lines172 waitStarted := make(chan struct{})173 errChan := make(chan error, 1)174 175 m := &testModel{}161- p := NewProgram(m, WithInput(&in), WithOutput(&buf))176+ p := NewProgram(m,177+ WithInput(&in),178+ WithOutput(&buf),179+ )180 181 go func() {182 _, err := p.Run()183 errChan <- err16 unmodified lines200 201 <-progStarted202 203 var wg sync.WaitGroup186- for i := 0; i < 5; i++ {204+ for range 5 {205 wg.Add(1)206 go func() {207 p.Wait()208 wg.Done()22 unmodified lines231 shutdowns := uint32(0)232 p := NewProgram(m,233 WithInput(&in),234 WithOutput(&buf),217- WithFilter(func(_ Model, msg Msg) Msg {218- if _, ok := msg.(QuitMsg); !ok {219- return msg220- }221- if shutdowns < preventCount {222- atomic.AddUint32(&shutdowns, 1)223- return nil224- }235+ )236+ p.filter = func(_ Model, msg Msg) Msg {237+ if _, ok := msg.(QuitMsg); !ok {238 return msg226- }))239+ }240+ if shutdowns < preventCount {241+ atomic.AddUint32(&shutdowns, 1)242+ return nil243+ }244+ return msg245+ }246 247 go func() {248 for atomic.LoadUint32(&shutdowns) <= preventCount {249 time.Sleep(time.Millisecond)250 p.Quit()251 }252 }()253 235- if err := p.Start(); err != nil {254+ if _, err := p.Run(); err != nil {255 t.Fatal(err)256 }257 if shutdowns != preventCount {258 t.Errorf("Expected %d prevented shutdowns, got %d", preventCount, shutdowns)4 unmodified lines263 var buf bytes.Buffer264 var in bytes.Buffer265 266 m := &testModel{}248- p := NewProgram(m, WithInput(&in), WithOutput(&buf))267+ p := NewProgram(m,268+ WithInput(&in),269+ WithOutput(&buf),270+ )271 go func() {272 for {273 time.Sleep(time.Millisecond)274 if m.executed.Load() != nil {16 unmodified lines291 }292 }293 294 func TestTeaContext(t *testing.T) {273- ctx, cancel := context.WithCancel(context.Background())295+ ctx, cancel := context.WithCancel(t.Context())296 var buf bytes.Buffer297 var in bytes.Buffer298 299 m := &testModel{}278- p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))300+ p := NewProgram(m,301+ WithContext(ctx),302+ WithInput(&in),303+ WithOutput(&buf),304+ )305 go func() {306 for {307 time.Sleep(time.Millisecond)308 if m.executed.Load() != nil {15 unmodified lines324 }325 }326 327 func TestTeaContextImplodeDeadlock(t *testing.T) {302- ctx, cancel := context.WithCancel(context.Background())328+ ctx, cancel := context.WithCancel(t.Context())329 var buf bytes.Buffer330 var in bytes.Buffer331 332 m := &testModel{}307- p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))333+ p := NewProgram(m,334+ WithContext(ctx),335+ WithInput(&in),336+ WithOutput(&buf),337+ )338 go func() {339 for {340 time.Sleep(time.Millisecond)341 if m.executed.Load() != nil {8 unmodified lines350 }351 }352 353 func TestTeaContextBatchDeadlock(t *testing.T) {324- ctx, cancel := context.WithCancel(context.Background())354+ ctx, cancel := context.WithCancel(t.Context())355 var buf bytes.Buffer356 var in bytes.Buffer357 358 inc := func() Msg {1 unmodified line360 return incrementMsg{}361 }362 363 m := &testModel{}334- p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))364+ p := NewProgram(m,365+ WithContext(ctx),366+ WithInput(&in),367+ WithOutput(&buf),368+ )369 go func() {370 for {371 time.Sleep(time.Millisecond)372 if m.executed.Load() != nil {20 unmodified lines393 return incrementMsg{}394 }395 396 m := &testModel{}363- p := NewProgram(m, WithInput(&in), WithOutput(&buf))397+ p := NewProgram(m,398+ WithInput(&in),399+ WithOutput(&buf),400+ )401 go func() {402 p.Send(BatchMsg{inc, inc})403 404 for {23 unmodified lines428 return incrementMsg{}429 }430 431 m := &testModel{}395- p := NewProgram(m, WithInput(&in), WithOutput(&buf))432+ p := NewProgram(m,433+ WithInput(&in),434+ WithOutput(&buf),435+ )436 go p.Send(sequenceMsg{inc, inc, Quit})437 438 if _, err := p.Run(); err != nil {439 t.Fatal(err)15 unmodified lines455 return BatchMsg{inc, inc}456 }457 458 m := &testModel{}419- p := NewProgram(m, WithInput(&in), WithOutput(&buf))459+ p := NewProgram(m,460+ WithInput(&in),461+ WithOutput(&buf),462+ )463 go p.Send(sequenceMsg{batch, inc, Quit})464 465 if _, err := p.Run(); err != nil {466 t.Fatal(err)12 unmodified lines479 return incrementMsg{}480 }481 482 m := &testModel{}440- p := NewProgram(m, WithInput(&in), WithOutput(&buf))483+ p := NewProgram(m,484+ WithInput(&in),485+ WithOutput(&buf),486+ )487 go p.Send(sequenceMsg{inc, Sequence(inc, inc, Batch(inc, inc)), Quit})488 489 if _, err := p.Run(); err != nil {490 t.Fatal(err)8 unmodified lines499 var buf bytes.Buffer500 var in bytes.Buffer501 502 m := &testModel{}457- p := NewProgram(m, WithInput(&in), WithOutput(&buf))503+ p := NewProgram(m,504+ WithInput(&in),505+ WithOutput(&buf),506+ )507 508 // sending before the program is started is a blocking operation509 go p.Send(Quit())510 9 unmodified lines520 var buf bytes.Buffer521 var in bytes.Buffer522 523 m := &testModel{}475- NewProgram(m, WithInput(&in), WithOutput(&buf))524+ NewProgram(m,525+ WithInput(&in),526+ WithOutput(&buf),527+ )528 }529 530 func TestTeaPanic(t *testing.T) {531 var buf bytes.Buffer532 var in bytes.Buffer533 534 m := &testModel{}483- p := NewProgram(m, WithInput(&in), WithOutput(&buf))535+ p := NewProgram(m,536+ WithInput(&in),537+ WithOutput(&buf),538+ )539 go func() {540 for {541 time.Sleep(time.Millisecond)542 if m.executed.Load() != nil {18 unmodified lines561 var buf bytes.Buffer562 var in bytes.Buffer563 564 m := &testModel{}510- p := NewProgram(m, WithInput(&in), WithOutput(&buf))565+ p := NewProgram(m,566+ WithInput(&in),567+ WithOutput(&buf),568+ )569 go func() {570 for {571 time.Sleep(time.Millisecond)572 if m.executed.Load() != nil {17 unmodified lines590 if !errors.Is(err, ErrProgramKilled) {591 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)592 }593 }594+595+type benchModel struct {596+ t testing.TB597+}598+599+func (m benchModel) Init() Cmd {600+ return nil601+}602+603+func (m benchModel) Update(msg Msg) (Model, Cmd) {604+ switch msg := msg.(type) {605+ case KeyPressMsg:606+ switch msg.String() {607+ case "q", "ctrl+c":608+ return m, Quit609+ }610+ }611+612+ return m, nil613+}614+615+func (m benchModel) View() View {616+ view := strings.Join([]string{617+ " \x1b[38;5;63m╭─────────────────────────╮\x1b[m",618+ " \x1b[38;5;63m│\x1b[m\x1b[25X\x1b[28G\x1b[38;5;63m│\x1b[m",619+ " \x1b[38;5;63m│\x1b[m \x1b[38;5;231mHello There!\x1b[m \x1b[38;5;63m│\x1b[m",620+ " \x1b[38;5;63m│\x1b[m\x1b[25X\x1b[28G\x1b[38;5;63m│\x1b[m",621+ " \x1b[38;5;63m╰─────────────────────────╯\x1b[m",622+ }, "\n")623+624+ return NewView(view)625+}626+627+func BenchmarkTeaRun(b *testing.B) {628+ for i := 0; i < b.N; i++ {629+ var buf bytes.Buffer630+631+ m := benchModel{b}632+ r, w := io.Pipe()633+ p := NewProgram(m,634+ WithInput(r),635+ WithOutput(&buf),636+ )637+638+ go func() {639+ for _, input := range "abcdefghijklmnopq" {640+ time.Sleep(10 * time.Millisecond)641+ w.Write([]byte(string(input)))642+ }643+ }()644+645+ if _, err := p.Run(); err != nil {646+ b.Fatalf("Run failed: %v", err)647+ }648+649+ _ = r.CloseWithError(io.EOF)650+ }651+}modified:tea.go+762 added-288 removed
8 unmodified lines9 // Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples10 package tea11 12 import (13+ "bytes"14 "context"15 "errors"16 "fmt"17+ "image/color"18 "io"19+ "log"20 "os"21 "os/signal"19- "runtime"22 "runtime/debug"23+ "strconv"24+ "strings"25 "sync"26 "sync/atomic"27 "syscall"28+ "time"29 30+ "github.com/charmbracelet/colorprofile"31+ uv "github.com/charmbracelet/ultraviolet"32+ "github.com/charmbracelet/x/ansi"33 "github.com/charmbracelet/x/term"34 "github.com/muesli/cancelreader"35 )36 8 unmodified lines45 var ErrInterrupted = errors.New("program was interrupted")46 47 // Msg contain data from the result of a IO operation. Msgs trigger the update48 // function and, henceforth, the UI.41-type Msg interface{}49+type Msg = uv.Event50 51 // Model contains the program's state as well as its core functions.52 type Model interface {53 // Init is the first function that will be called. It returns an optional3 unmodified lines57 // Update is called when a message is received. Use it to inspect messages58 // and, in response, update the model and/or send a command.59 Update(Msg) (Model, Cmd)60 53- // View renders the program's UI, which is just a string. The view is54- // rendered after every Update.55- View() string61+ // View renders the program's UI, which can be a string or a [Layer]. The62+ // view is rendered after every Update.63+ View() View64 }65 58-// Cmd is an IO operation that returns a message when it's complete. If it's59-// nil it's considered a no-op. Use it for things like HTTP requests, timers,60-// saving and loading from disk, and so on.66+// NewView is a helper function to create a new [View] with the given styled67+// string. A styled string represents text with styles and hyperlinks encoded68+// as ANSI escape codes.69 //62-// Note that there's almost never a reason to use a command to send a message63-// to another part of your program. That can almost always be done in the64-// update function.65-type Cmd func() Msg70+// Example:71+//72+// ```go73+// v := tea.NewView("Hello, World!")74+// ```75+func NewView(s string) View {76+ var view View77+ view.SetContent(s)78+ return view79+}80 67-type inputType int81+// View represents a terminal view that can be composed of multiple layers.82+// It can also contain a cursor that will be rendered on top of the layers.83+type View struct {84+ // Content is the screen content of the view. It holds styled strings that85+ // will be rendered to the terminal when the view is rendered.86+ //87+ // A styled string represents text with styles and hyperlinks encoded as88+ // ANSI escape codes.89+ //90+ // Example:91+ //92+ // ```go93+ // v := tea.NewView("Hello, World!")94+ // ```95+ Content string96 97+ // OnMouse is an optional mouse message handler that can be used to98+ // intercept mouse messages that depends on view content from last render.99+ // It can be useful for implementing view-specific behavior without100+ // breaking the unidirectional data flow of Bubble Tea.101+ //102+ // Example:103+ //104+ // ```go105+ // content := "Hello, World!"106+ // v := tea.NewView(content)107+ // v.OnMouse = func(msg tea.MouseMsg) tea.Cmd {108+ // return func() tea.Msg {109+ // m := msg.Mouse()110+ // // Check if the mouse is within the bounds of "World!"111+ // start := strings.Index(content, "World!")112+ // end := start + len("World!")113+ // if m.Y == 0 && m.X >= start && m.X < end {114+ // // Mouse is over "World!"115+ // return MyCustomMsg{116+ // MouseMsg: msg,117+ // }118+ // }119+ // }120+ // }121+ // return nil122+ // }123+ // return v124+ // ```125+ OnMouse func(msg MouseMsg) Cmd126+127+ // Cursor represents the cursor position, style, and visibility on the128+ // screen. When not nil, the cursor will be shown at the specified129+ // position.130+ Cursor *Cursor131+132+ // BackgroundColor when not nil, sets the terminal background color. Use133+ // nil to reset to the terminal's default background color.134+ BackgroundColor color.Color135+136+ // ForegroundColor when not nil, sets the terminal foreground color. Use137+ // nil to reset to the terminal's default foreground color.138+ ForegroundColor color.Color139+140+ // WindowTitle sets the terminal window title. Support depends on the141+ // terminal.142+ WindowTitle string143+144+ // ProgressBar when not nil, shows a progress bar in the terminal's145+ // progress bar section. Support depends on the terminal.146+ ProgressBar *ProgressBar147+148+ // AltScreen puts the program in the alternate screen buffer149+ // (i.e. the program goes into full window mode). Note that the altscreen will150+ // be automatically exited when the program quits.151+ //152+ // Example:153+ //154+ // func (m model) View() tea.View {155+ // v := tea.NewView("Hello, World!")156+ // v.AltScreen = true157+ // return v158+ // }159+ //160+ AltScreen bool161+162+ // ReportFocus enables reporting when the terminal gains and loses focus.163+ // When this is enabled [FocusMsg] and [BlurMsg] messages will be sent to164+ // your Update method.165+ //166+ // Note that while most terminals and multiplexers support focus reporting,167+ // some do not. Also note that tmux needs to be configured to report focus168+ // events.169+ ReportFocus bool170+171+ // DisableBracketedPasteMode disables bracketed paste mode for this view.172+ DisableBracketedPasteMode bool173+174+ // MouseMode sets the mouse mode for this view. It can be one of175+ // [MouseModeNone], [MouseModeCellMotion], or [MouseModeAllMotion].176+ MouseMode MouseMode177+178+ // KeyboardEnhancements describes what keyboard enhancement features Bubble179+ // Tea should request from the terminal.180+ //181+ // Bubble Tea supports requesting the following keyboard enhancement features:182+ // - ReportEventTypes: requests the terminal to report key repeat and183+ // release events.184+ //185+ // If the terminal supports any of these features, your program will186+ // receive a [KeyboardEnhancementsMsg] that indicates which features are187+ // available.188+ KeyboardEnhancements KeyboardEnhancements189+}190+191+// KeyboardEnhancements describes the requested keyboard enhancement features.192+// If the terminal supports any of them, it will respond with a193+// [KeyboardEnhancementsMsg] that indicates which features are supported.194+195+// KeyboardEnhancements defines different keyboard enhancement features that196+// can be requested from the terminal.197+198+// KeyboardEnhancements defines different keyboard enhancement features that199+// can be requested from the terminal.200+//201+// By default, Bubble Tea requests basic key disambiguation features from the202+// terminal. If the terminal supports keyboard enhancements, or any of its203+// additional features, it will respond with a [KeyboardEnhancementsMsg] that204+// indicates which features are supported.205+//206+// Example:207+//208+// ```go209+// func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {210+// switch msg := msg.(type) {211+// case tea.KeyboardEnhancementsMsg:212+// // We have basic key disambiguation support.213+// // We can handle "shift+enter", "ctrl+i", etc.214+// m.keyboardEnhancements = msg215+// if msg.ReportEventTypes {216+// // Even better! We can now handle key repeat and release events.217+// }218+// case tea.KeyPressMsg:219+// switch msg.String() {220+// case "shift+enter":221+// // Handle shift+enter222+// // This would not be possible without keyboard enhancements.223+// case "ctrl+j":224+// // Handle ctrl+j225+// }226+// case tea.KeyReleaseMsg:227+// // Whoa! A key was released!228+// }229+//230+// return m, nil231+// }232+//233+// func (m model) View() tea.View {234+// v := tea.NewView("Press some keys!")235+// // Request reporting key repeat and release events.236+// v.KeyboardEnhancements.ReportEventTypes = true237+// return v238+// }239+// ```240+type KeyboardEnhancements struct {241+ // ReportEventTypes requests the terminal to report key repeat and release242+ // events.243+ // If supported, your program will receive [KeyReleaseMsg]s and244+ // [KeyPressMsg] with the [Key.IsRepeat] field set indicating that this is245+ // a it's part of a key repeat sequence.246+ ReportEventTypes bool247+}248+249+// SetContent is a helper method to set the content of a [View] with a styled250+// string. A styled string represents text with styles and hyperlinks encoded251+// as ANSI escape codes.252+//253+// Example:254+//255+// ```go256+// var v tea.View257+// v.SetContent("Hello, World!")258+// ```259+func (v *View) SetContent(s string) {260+ v.Content = s261+}262+263+// MouseMode represents the mouse mode of a view.264+type MouseMode int265+266 const (70- defaultInput inputType = iota71- ttyInput72- customInput267+ // MouseModeNone disables mouse events.268+ MouseModeNone MouseMode = iota269+270+ // MouseModeCellMotion enables mouse click, release, and wheel events.271+ // Mouse movement events are also captured if a mouse button is pressed272+ // (i.e., drag events). Cell motion mode is better supported than all273+ // motion mode.274+ //275+ // This will try to enable the mouse in extended mode (SGR), if that is not276+ // supported by the terminal it will fall back to normal mode (X10).277+ MouseModeCellMotion278+279+ // MouseModeAllMotion enables all mouse events, including click, release,280+ // wheel, and movement events. You will receive mouse movement events even281+ // when no buttons are pressed.282+ //283+ // This will try to enable the mouse in extended mode (SGR), if that is not284+ // supported by the terminal it will fall back to normal mode (X10).285+ MouseModeAllMotion286 )287 75-// String implements the stringer interface for [inputType]. It is intended to76-// be used in testing.77-func (i inputType) String() string {288+// ProgressBarState represents the state of the progress bar.289+type ProgressBarState int290+291+// Progress bar states.292+const (293+ ProgressBarNone ProgressBarState = iota294+ ProgressBarDefault295+ ProgressBarError296+ ProgressBarIndeterminate297+ ProgressBarWarning298+)299+300+// String return a human-readable value for the given [ProgressBarState].301+func (s ProgressBarState) String() string {302 return [...]string{79- "default input",80- "tty input",81- "custom input",82- }[i]303+ "None",304+ "Default",305+ "Error",306+ "Indeterminate",307+ "Warning",308+ }[s]309 }310 85-// Options to customize the program during its initialization. These are86-// generally set with ProgramOptions.311+// ProgressBar represents the terminal progress bar.312 //88-// The options here are treated as bits.89-type startupOptions int16313+// Support depends on the terminal.314+//315+// See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences316+type ProgressBar struct {317+ // State is the current state of the progress bar. It can be one of318+ // [ProgressBarNone], [ProgressBarDefault], [ProgressBarError],319+ // [ProgressBarIndeterminate], and [ProgressBarWarn].320+ State ProgressBarState321+ // Value is the current value of the progress bar. It should be between322+ // 0 and 100.323+ Value int324+}325 91-func (s startupOptions) has(option startupOptions) bool {92- return s&option != 0326+// NewProgressBar returns a new progress bar with the given state and value.327+// The value is ignored if the state is [ProgressBarNone] or328+// [ProgressBarIndeterminate].329+func NewProgressBar(state ProgressBarState, value int) *ProgressBar {330+ return &ProgressBar{331+ State: state,332+ Value: min(max(value, 0), 100),333+ }334 }335 95-const (96- withAltScreen startupOptions = 1 << iota97- withMouseCellMotion98- withMouseAllMotion99- withANSICompressor100- withoutSignalHandler101- // Catching panics is incredibly useful for restoring the terminal to a102- // usable state after a panic occurs. When this is set, Bubble Tea will103- // recover from panics, print the stack trace, and disable raw mode. This104- // feature is on by default.105- withoutCatchPanics106- withoutBracketedPaste107- withReportFocus108-)336+// Cursor represents a cursor on the terminal screen.337+type Cursor struct {338+ // Position is a [Position] that determines the cursor's position on the339+ // screen relative to the top left corner of the frame.340+ Position341 342+ // Color is a [color.Color] that determines the cursor's color.343+ Color color.Color344+345+ // Shape is a [CursorShape] that determines the cursor's shape.346+ Shape CursorShape347+348+ // Blink is a boolean that determines whether the cursor should blink.349+ Blink bool350+}351+352+// NewCursor returns a new cursor with the default settings and the given353+// position.354+func NewCursor(x, y int) *Cursor {355+ return &Cursor{356+ Position: Position{X: x, Y: y},357+ Color: nil,358+ Shape: CursorBlock,359+ Blink: true,360+ }361+}362+363+// Cmd is an IO operation that returns a message when it's complete. If it's364+// nil it's considered a no-op. Use it for things like HTTP requests, timers,365+// saving and loading from disk, and so on.366+//367+// Note that there's almost never a reason to use a command to send a message368+// to another part of your program. That can almost always be done in the369+// update function.370+type Cmd func() Msg371+372 // channelHandlers manages the series of channels returned by various processes.373 // It allows us to wait for those processes to terminate before exiting the374 // program.113-type channelHandlers []chan struct{}375+type channelHandlers struct {376+ handlers []chan struct{}377+ mu sync.RWMutex378+}379 380 // Adds a channel to the list of handlers. We wait for all handlers to terminate381 // gracefully on shutdown.382 func (h *channelHandlers) add(ch chan struct{}) {118- *h = append(*h, ch)383+ h.mu.Lock()384+ h.handlers = append(h.handlers, ch)385+ h.mu.Unlock()386 }387 388 // shutdown waits for all handlers to terminate.122-func (h channelHandlers) shutdown() {389+func (h *channelHandlers) shutdown() {390 var wg sync.WaitGroup391+392+ h.mu.RLock()393+ defer h.mu.RUnlock()394+124- for _, ch := range h {395+ for _, ch := range h.handlers {396 wg.Add(1)397 go func(ch chan struct{}) {398 <-ch399 wg.Done()3 unmodified lines403 }404 405 // Program is a terminal user interface.406 type Program struct {407+ // disableInput disables all input. This is useful for programs that408+ // don't need input, like a progress bar or a spinner.409+ disableInput bool410+411+ // disableSignalHandler disables the signal handler that Bubble Tea sets up412+ // for Programs. This is useful if you want to handle signals yourself.413+ disableSignalHandler bool414+415+ // disableCatchPanics disables the panic catching that Bubble Tea does by416+ // default. If panic catching is disabled the terminal will be in a fairly417+ // unusable state after a panic because Bubble Tea will not perform its usual418+ // cleanup on exit.419+ disableCatchPanics bool420+421+ // filter supplies an event filter that will be invoked before Bubble Tea422+ // processes a tea.Msg. The event filter can return any tea.Msg which will423+ // then get handled by Bubble Tea instead of the original event. If the424+ // event filter returns nil, the event will be ignored and Bubble Tea will425+ // not process it.426+ //427+ // As an example, this could be used to prevent a program from shutting428+ // down if there are unsaved changes.429+ //430+ // Example:431+ //432+ // func filter(m tea.Model, msg tea.Msg) tea.Msg {433+ // if _, ok := msg.(tea.QuitMsg); !ok {434+ // return msg435+ // }436+ //437+ // model := m.(myModel)438+ // if model.hasChanges {439+ // return nil440+ // }441+ //442+ // return msg443+ // }444+ //445+ // p := tea.NewProgram(Model{});446+ // p.filter = filter447+ //448+ // if _,err := p.Run(context.Background()); err != nil {449+ // fmt.Println("Error running program:", err)450+ // os.Exit(1)451+ // }452+ filter func(Model, Msg) Msg453+454+ // fps sets a custom maximum fps at which the renderer should run. If less455+ // than 1, the default value of 60 will be used. If over 120, the fps will456+ // be capped at 120.457+ fps int458+459+ // initialModel is the initial model for the program and is the only460+ // required field when creating a new program.461 initialModel Model462 463+ // disableRenderer prevents the program from rendering to the terminal.464+ // This can be useful for running daemon-like programs that don't require a465+ // UI but still want to take advantage of Bubble Tea's architecture.466+ disableRenderer bool467+468 // handlers is a list of channels that need to be waited on before the469 // program can exit.470 handlers channelHandlers471 142- // Configuration options that will set as the program is initializing,143- // treated as bits. These options can be set via various ProgramOptions.144- startupOptions startupOptions472+ // ctx is the programs's internal context for signalling internal teardown.473+ // It is built and derived from the externalCtx in NewProgram().474+ ctx context.Context475+ cancel context.CancelFunc476 146- // startupTitle is the title that will be set on the terminal when the147- // program starts.148- startupTitle string149-150- inputType inputType151-477 // externalCtx is a context that was passed in via WithContext, otherwise defaulting478 // to ctx.Background() (in case it was not), the internal context is derived from it.479 externalCtx context.Context480 156- // ctx is the programs's internal context for signalling internal teardown.157- // It is built and derived from the externalCtx in NewProgram().158- ctx context.Context159- cancel context.CancelFunc481+ msgs chan Msg482+ errs chan error483+ finished chan struct{}484+ shutdownOnce sync.Once485 161- msgs chan Msg162- errs chan error163- finished chan struct{}486+ profile *colorprofile.Profile // the terminal color profile487 488 // where to send output, this will usually be os.Stdout.166- output io.Writer489+ output io.Writer490+ outputBuf bytes.Buffer // buffer used to queue commands to be sent to the output491+492 // ttyOutput is null if output is not a TTY.493 ttyOutput term.File494 previousOutputState *term.State495 renderer renderer496 497 // the environment variables for the program, defaults to os.Environ().173- environ []string498+ environ uv.Environ499+ // the program's logger for debugging.500+ logger uv.Logger501 502 // where to read inputs from, this will usually be os.Stdin.503 input io.Reader504 // ttyInput is null if input is not a TTY.505 ttyInput term.File506 previousTtyInputState *term.State507 cancelReader cancelreader.CancelReader508+ inputScanner *uv.TerminalReader509 readLoopDone chan struct{}510 183- // was the altscreen active before releasing the terminal?184- altScreenWasActive bool185- ignoreSignals uint32511+ // modes keeps track of terminal modes that have been enabled or disabled.512+ ignoreSignals uint32513 187- bpWasActive bool // was the bracketed paste mode active before releasing the terminal?188- reportFocus bool // was focus reporting active before releasing the terminal?514+ // ticker is the ticker that will be used to write to the renderer.515+ ticker *time.Ticker516 190- filter func(Model, Msg) Msg517+ // once is used to stop the renderer.518+ once sync.Once519 192- // fps is the frames per second we should set on the renderer, if193- // applicable,194- fps int520+ // rendererDone is used to stop the renderer.521+ rendererDone chan struct{}522 196- // mouseMode is true if the program should enable mouse mode on Windows.197- mouseMode bool523+ // Initial window size. Mainly used for testing.524+ width, height int525+526+ // whether to use hard tabs to optimize cursor movements527+ useHardTabs bool528+ // whether to use backspace to optimize cursor movements529+ useBackspace bool530+531+ mu sync.Mutex532 }533 534 // Quit is a special command that tells the Bubble Tea program to exit.535 func Quit() Msg {34 unmodified lines570 func Interrupt() Msg {571 return InterruptMsg{}572 }573 240-// NewProgram creates a new Program.574+// NewProgram creates a new [Program].575 func NewProgram(model Model, opts ...ProgramOption) *Program {576 p := &Program{577 initialModel: model,578 msgs: make(chan Msg),579+ errs: make(chan error, 1),580+ rendererDone: make(chan struct{}),581 }582 583 // Apply all options to the program.584 for _, opt := range opts {17 unmodified lines602 if p.environ == nil {603 p.environ = os.Environ()604 }605 606+ if p.fps < 1 {607+ p.fps = defaultFPS608+ } else if p.fps > maxFPS {609+ p.fps = maxFPS610+ }611+612+ tracePath, traceOk := os.LookupEnv("TEA_TRACE")613+ if traceOk && len(tracePath) > 0 {614+ // We have a trace filepath.615+ if f, err := os.OpenFile(tracePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600); err == nil {616+ p.logger = log.New(f, "bubbletea: ", log.LstdFlags|log.Lshortfile)617+ }618+ }619+620 return p621 }622 623 func (p *Program) handleSignals() chan struct{} {41 unmodified lines665 func (p *Program) handleResize() chan struct{} {666 ch := make(chan struct{})667 668 if p.ttyOutput != nil {319- // Get the initial terminal size and send it to the program.320- go p.checkResize()321-669 // Listen for window resizes.670 go p.listenForResize(ch)671 } else {672 close(ch)26 unmodified lines699 // possible to cancel them so we'll have to leak the goroutine700 // until Cmd returns.701 go func() {702 // Recover from panics.356- if !p.startupOptions.has(withoutCatchPanics) {703+ if !p.disableCatchPanics {704 defer func() {705 if r := recover(); r != nil {359- p.recoverFromGoPanic(r)706+ p.recoverFromPanic(r)707 }708 }()709 }710 6 unmodified lines717 718 return ch719 }720 374-func (p *Program) disableMouse() {375- p.renderer.disableMouseCellMotion()376- p.renderer.disableMouseAllMotion()377- p.renderer.disableMouseSGRMode()378-}379-721 // eventLoop is the central message loop. It receives and handles the default722 // Bubble Tea messages, update the model and triggers redraws.723 func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {724 for {4 unmodified lines729 case err := <-p.errs:730 return model, err731 732 case msg := <-p.msgs:733+ msg = p.translateInputEvent(msg)734+735 // Filter messages.736 if p.filter != nil {737 msg = p.filter(model, msg)738 }13 unmodified lines752 if suspendSupported {753 p.suspend()754 }755 413- case clearScreenMsg:414- p.renderer.clearScreen()415-416- case enterAltScreenMsg:417- p.renderer.enterAltScreen()418-419- case exitAltScreenMsg:420- p.renderer.exitAltScreen()421-422- case enableMouseCellMotionMsg, enableMouseAllMotionMsg:423- switch msg.(type) {424- case enableMouseCellMotionMsg:425- p.renderer.enableMouseCellMotion()426- case enableMouseAllMotionMsg:427- p.renderer.enableMouseAllMotion()756+ case CapabilityMsg:757+ switch msg.Content {758+ case "RGB", "Tc":759+ if *p.profile != colorprofile.TrueColor {760+ tc := colorprofile.TrueColor761+ p.profile = &tc762+ go p.Send(ColorProfileMsg{*p.profile})763+ }764 }429- // mouse mode (1006) is a no-op if the terminal doesn't support it.430- p.renderer.enableMouseSGRMode()765 432- // XXX: This is used to enable mouse mode on Windows. We need433- // to reinitialize the cancel reader to get the mouse events to434- // work.435- if runtime.GOOS == "windows" && !p.mouseMode {436- p.mouseMode = true437- p.initCancelReader(true) //nolint:errcheck,gosec766+ case ModeReportMsg:767+ switch msg.Mode {768+ case ansi.ModeSynchronizedOutput:769+ if msg.Value == ansi.ModeReset {770+ // The terminal supports synchronized output and it's771+ // currently disabled, so we can enable it on the renderer.772+ p.renderer.setSyncdUpdates(true)773+ }774+ case ansi.ModeUnicodeCore:775+ if msg.Value == ansi.ModeReset || msg.Value == ansi.ModeSet || msg.Value == ansi.ModePermanentlySet {776+ p.renderer.setWidthMethod(ansi.GraphemeWidth)777+ }778 }779 440- case disableMouseMsg:441- p.disableMouse()442-443- // XXX: On Windows, mouse mode is enabled on the input reader444- // level. We need to instruct the input reader to stop reading445- // mouse events.446- if runtime.GOOS == "windows" && p.mouseMode {447- p.mouseMode = false448- p.initCancelReader(true) //nolint:errcheck,gosec780+ case MouseMsg:781+ switch msg.(type) {782+ case MouseClickMsg, MouseReleaseMsg, MouseWheelMsg, MouseMotionMsg:783+ // Only send mouse messages to the renderer if they are an784+ // actual mouse event.785+ if cmd := p.renderer.onMouse(msg); cmd != nil {786+ go p.Send(cmd())787+ }788 }789 451- case showCursorMsg:452- p.renderer.showCursor()790+ case readClipboardMsg:791+ p.execute(ansi.RequestSystemClipboard)792 454- case hideCursorMsg:455- p.renderer.hideCursor()793+ case setClipboardMsg:794+ p.execute(ansi.SetSystemClipboard(string(msg)))795 457- case enableBracketedPasteMsg:458- p.renderer.enableBracketedPaste()796+ case readPrimaryClipboardMsg:797+ p.execute(ansi.RequestPrimaryClipboard)798 460- case disableBracketedPasteMsg:461- p.renderer.disableBracketedPaste()799+ case setPrimaryClipboardMsg:800+ p.execute(ansi.SetPrimaryClipboard(string(msg)))801 463- case enableReportFocusMsg:464- p.renderer.enableReportFocus()802+ case backgroundColorMsg:803+ p.execute(ansi.RequestBackgroundColor)804 466- case disableReportFocusMsg:467- p.renderer.disableReportFocus()805+ case foregroundColorMsg:806+ p.execute(ansi.RequestForegroundColor)807 808+ case cursorColorMsg:809+ p.execute(ansi.RequestCursorColor)810+811 case execMsg:812 // NB: this blocks.813 p.exec(msg.cmd, msg.fn)814 815+ case terminalVersion:816+ p.execute(ansi.RequestNameVersion)817+818+ case requestCapabilityMsg:819+ p.execute(ansi.RequestTermcap(string(msg)))820+821 case BatchMsg:822 go p.execBatchMsg(msg)823 continue824 825 case sequenceMsg:826 go p.execSequenceMsg(msg)827 continue828 481- case setWindowTitleMsg:482- p.SetWindowTitle(string(msg))829+ case WindowSizeMsg:830+ p.renderer.resize(msg.Width, msg.Height)831 832 case windowSizeMsg:833 go p.checkResize()486- }834 488- // Process internal messages for the renderer.489- if r, ok := p.renderer.(*standardRenderer); ok {490- r.handleMessages(msg)835+ case requestCursorPosMsg:836+ p.execute(ansi.RequestCursorPositionReport)837+838+ case RawMsg:839+ p.execute(fmt.Sprint(msg.Msg))840+841+ case printLineMessage:842+ p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec843+844+ case clearScreenMsg:845+ p.renderer.clearScreen()846+847+ case ColorProfileMsg:848+ p.renderer.setColorProfile(msg.Profile)849 }850 851 var cmd Cmd852 model, cmd = model.Update(msg) // run update3 unmodified lines856 return model, nil857 case cmds <- cmd: // process command (if any)858 }859 502- p.renderer.write(model.View()) // send view to renderer860+ p.render(model) // render view861 }862 }863 }864 865+// render renders the given view to the renderer.866+func (p *Program) render(model Model) {867+ if p.renderer != nil {868+ p.renderer.render(model.View()) // send view to renderer869+ }870+}871+872 func (p *Program) execSequenceMsg(msg sequenceMsg) {508- if !p.startupOptions.has(withoutCatchPanics) {873+ if !p.disableCatchPanics {874 defer func() {875 if r := recover(); r != nil {876 p.recoverFromGoPanic(r)877 }17 unmodified lines895 }896 }897 898 func (p *Program) execBatchMsg(msg BatchMsg) {534- if !p.startupOptions.has(withoutCatchPanics) {899+ if !p.disableCatchPanics {900 defer func() {901 if r := recover(); r != nil {902 p.recoverFromGoPanic(r)903 }9 unmodified lines913 wg.Add(1)914 go func() {915 defer wg.Done()916 552- if !p.startupOptions.has(withoutCatchPanics) {917+ if !p.disableCatchPanics {918 defer func() {919 if r := recover(); r != nil {920 p.recoverFromGoPanic(r)921 }14 unmodified lines936 937 wg.Wait() // wait for all commands from batch msg to finish938 }939 940+// shouldQuerySynchronizedOutput determines whether the terminal should be941+// queried for various capabilities.942+//943+// This function checks for terminals that are known to support mode 2026,944+// while excluding SSH sessions which may be unreliable, unless it's a945+// known-good terminal like Windows Terminal.946+//947+// The function returns true for:948+// - Terminals without TERM_PROGRAM set and not in SSH sessions949+// - Windows Terminal (WT_SESSION is set)950+// - Terminals with TERM_PROGRAM set (except Apple Terminal) and not in SSH sessions951+// - Specific terminal types: ghostty, wezterm, alacritty, kitty, rio952+func shouldQuerySynchronizedOutput(environ uv.Environ) bool {953+ termType := environ.Getenv("TERM")954+ termProg, okTermProg := environ.LookupEnv("TERM_PROGRAM")955+ _, okSSHTTY := environ.LookupEnv("SSH_TTY")956+ _, okWTSession := environ.LookupEnv("WT_SESSION")957+958+ return (!okTermProg && !okSSHTTY) ||959+ okWTSession ||960+ (okTermProg && !strings.Contains(termProg, "Apple") && !okSSHTTY) ||961+ strings.Contains(termType, "ghostty") ||962+ strings.Contains(termType, "wezterm") ||963+ strings.Contains(termType, "alacritty") ||964+ strings.Contains(termType, "kitty") ||965+ strings.Contains(termType, "rio")966+}967+968 // Run initializes the program and runs its event loops, blocking until it gets969 // terminated by either [Program.Quit], [Program.Kill], or its signal handler.970 // Returns the final model.971 func (p *Program) Run() (returnModel Model, returnErr error) {972+ if p.initialModel == nil {973+ return nil, errors.New("bubbletea: InitialModel cannot be nil")974+ }975+976+ // Initialize context and teardown channel.977 p.handlers = channelHandlers{}978 cmds := make(chan Cmd)581- p.errs = make(chan error, 1)979 980 p.finished = make(chan struct{})981 defer func() {982 close(p.finished)983 }()984 985 defer p.cancel()986 590- switch p.inputType {591- case defaultInput:592- p.input = os.Stdin593-594- // The user has not set a custom input, so we need to check whether or595- // not standard input is a terminal. If it's not, we open a new TTY for596- // input. This will allow things to "just work" in cases where data was597- // piped in or redirected to the application.598- //599- // To disable input entirely pass nil to the [WithInput] program option.600- f, isFile := p.input.(term.File)601- if !isFile {602- break603- }604- if term.IsTerminal(f.Fd()) {605- break606- }607-608- f, err := openInputTTY()987+ if p.disableInput {988+ p.input = nil989+ } else if p.input == nil {990+ // Always open the TTY for input.991+ ttyIn, _, err := OpenTTY()992 if err != nil {610- return p.initialModel, err993+ return p.initialModel, fmt.Errorf("bubbletea: error opening TTY: %w", err)994 }612- defer f.Close() //nolint:errcheck613- p.input = f995+ p.input = ttyIn614-615- case ttyInput:616- // Open a new TTY, by request617- f, err := openInputTTY()618- if err != nil {619- return p.initialModel, err620- }621- defer f.Close() //nolint:errcheck622- p.input = f623-624- case customInput:625- // (There is nothing extra to do.)996 }997 998 // Handle signals.629- if !p.startupOptions.has(withoutSignalHandler) {999+ if !p.disableSignalHandler {1000 p.handlers.add(p.handleSignals())1001 }1002 1003 // Recover from panics.634- if !p.startupOptions.has(withoutCatchPanics) {1004+ if !p.disableCatchPanics {1005 defer func() {1006 if r := recover(); r != nil {1007 returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)1008 p.recoverFromPanic(r)1009 }1010 }()1011 }1012 643- // If no renderer is set use the standard one.644- if p.renderer == nil {645- p.renderer = newRenderer(p.output, p.startupOptions.has(withANSICompressor), p.fps)646- }647-1013 // Check if output is a TTY before entering raw mode, hiding the cursor and1014 // so on.1015 if err := p.initTerminal(); err != nil {1016 return p.initialModel, err1017 }1018 654- // Honor program startup options.655- if p.startupTitle != "" {656- p.renderer.setWindowTitle(p.startupTitle)1019+ // Get the initial window size.1020+ width, height := p.width, p.height1021+ if p.ttyOutput != nil {1022+ // Set the initial size of the terminal.1023+ w, h, err := term.GetSize(p.ttyOutput.Fd())1024+ if err != nil {1025+ return p.initialModel, fmt.Errorf("bubbletea: error getting terminal size: %w", err)1026+ }1027+1028+ width, height = w, h1029 }658- if p.startupOptions&withAltScreen != 0 {659- p.renderer.enterAltScreen()1030+1031+ p.width, p.height = width, height1032+ resizeMsg := WindowSizeMsg{Width: p.width, Height: p.height}1033+1034+ if p.renderer == nil {1035+ if p.disableRenderer {1036+ p.renderer = &nilRenderer{}1037+ } else {1038+ // If no renderer is set use the cursed one.1039+ r := newCursedRenderer(1040+ p.output,1041+ p.environ,1042+ p.width,1043+ p.height,1044+ )1045+ r.setLogger(p.logger)1046+ // XXX: This breaks many things especially when we want the output1047+ // to be compatible with terminals that are not necessary a TTY.1048+ // This was originally done to work around a Wish emulated-pty1049+ // issue where when a PTY session is detected, and we don't1050+ // allocate a real PTY, the terminal settings (Termios and WinCon)1051+ // don't change and the we end up working in cooked mode instead of1052+ // raw mode.1053+ mapNl := false // p.ttyInput == nil1054+ r.setOptimizations(p.useHardTabs, p.useBackspace, mapNl)1055+ p.renderer = r1056+ }1057 }661- if p.startupOptions&withoutBracketedPaste == 0 {662- p.renderer.enableBracketedPaste()1058+1059+ // Get the color profile and send it to the program.1060+ if p.profile == nil {1061+ cp := colorprofile.Detect(p.output, p.environ)1062+ p.profile = &cp1063 }664- if p.startupOptions&withMouseCellMotion != 0 {665- p.renderer.enableMouseCellMotion()666- p.renderer.enableMouseSGRMode()667- } else if p.startupOptions&withMouseAllMotion != 0 {668- p.renderer.enableMouseAllMotion()669- p.renderer.enableMouseSGRMode()670- }1064 672- // XXX: Should we enable mouse mode on Windows?673- // This needs to happen before initializing the cancel and input reader.674- p.mouseMode = p.startupOptions&withMouseCellMotion != 0 || p.startupOptions&withMouseAllMotion != 01065+ // Set the color profile on the renderer and send it to the program.1066+ p.renderer.setColorProfile(*p.profile)1067+ go p.Send(ColorProfileMsg{*p.profile})1068 676- if p.startupOptions&withReportFocus != 0 {677- p.renderer.enableReportFocus()1069+ // Send the initial size to the program.1070+ go p.Send(resizeMsg)1071+ p.renderer.resize(resizeMsg.Width, resizeMsg.Height)1072+1073+ // Send the environment variables used by the program.1074+ go p.Send(EnvMsg(p.environ))1075+1076+ // Init the input reader and initial model.1077+ model := p.initialModel1078+ if p.input != nil {1079+ if err := p.initInputReader(false); err != nil {1080+ return model, err1081+ }1082 }1083 1084 // Start the renderer.681- p.renderer.start()1085+ p.startRenderer()1086 1087+ if shouldQuerySynchronizedOutput(p.environ) {1088+ // Query for synchronized updates support (mode 2026) and unicode core1089+ // (mode 2027). If the terminal supports it, the renderer will enable1090+ // it once we get the response.1091+ p.execute(ansi.RequestModeSynchronizedOutput +1092+ ansi.RequestModeUnicodeCore)1093+ }1094+1095 // Initialize the program.684- model := p.initialModel685- if initCmd := model.Init(); initCmd != nil {1096+ initCmd := model.Init()1097+ if initCmd != nil {1098 ch := make(chan struct{})1099 p.handlers.add(ch)1100 1101 go func() {6 unmodified lines1108 }()1109 }1110 1111 // Render the initial view.700- p.renderer.write(model.View())1112+ p.render(model)1113 702- // Subscribe to user input.703- if p.input != nil {704- if err := p.initCancelReader(false); err != nil {705- return model, err706- }707- }708-1114 // Handle resize events.1115 p.handlers.add(p.handleResize())1116 1117 // Process commands.1118 p.handlers.add(p.handleCommands(cmds))1119 1120 // Run event loop, handle updates and draw.1121+ var err error716- model, err := p.eventLoop(model, cmds)1122+ model, err = p.eventLoop(model, cmds)1123 1124 if err == nil && len(p.errs) > 0 {719- err = <-p.errs // Drain a leftover error in case eventLoop crashed1125+ err = <-p.errs // Drain a leftover error in case eventLoop crashed.1126 }1127 1128 killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil1129 if killed {11 unmodified lines1141 }1142 } else {1143 // Graceful shutdown of the program (not killed):1144 // Ensure we rendered the final state of the model.739- p.renderer.write(model.View())1145+ p.render(model)1146 }1147 1148 // Restore terminal state.1149 p.shutdown(killed)1150 1151 return model, err1152 }1153 748-// StartReturningModel initializes the program and runs its event loops,749-// blocking until it gets terminated by either [Program.Quit], [Program.Kill],750-// or its signal handler. Returns the final model.751-//752-// Deprecated: please use [Program.Run] instead.753-func (p *Program) StartReturningModel() (Model, error) {754- return p.Run()755-}756-757-// Start initializes the program and runs its event loops, blocking until it758-// gets terminated by either [Program.Quit], [Program.Kill], or its signal759-// handler.760-//761-// Deprecated: please use [Program.Run] instead.762-func (p *Program) Start() error {763- _, err := p.Run()764- return err765-}766-1154 // Send sends a message to the main update function, effectively allowing1155 // messages to be injected from outside the program for interoperability1156 // purposes.1157 //17 unmodified lines1175 func (p *Program) Quit() {1176 p.Send(Quit())1177 }1178 792-// Kill signals the program to stop immediately and restore the former terminal state.1179+// Kill stops the program immediately and restores the former terminal state.1180 // The final render that you would normally see when quitting will be skipped.1181 // [program.Run] returns a [ErrProgramKilled] error.1182 func (p *Program) Kill() {796- p.cancel()1183+ p.shutdown(true)1184 }1185 1186 // Wait waits/blocks until the underlying Program finished shutting down.1187 func (p *Program) Wait() {1188 <-p.finished1189 }1190 1191+// execute writes the given sequence to the program output.1192+func (p *Program) execute(seq string) {1193+ p.mu.Lock()1194+ _, _ = p.outputBuf.WriteString(seq)1195+ p.mu.Unlock()1196+}1197+1198+// flush flushes the output buffer to the program output.1199+func (p *Program) flush() error {1200+ p.mu.Lock()1201+ defer p.mu.Unlock()1202+1203+ if p.outputBuf.Len() == 0 {1204+ return nil1205+ }1206+ if p.logger != nil {1207+ p.logger.Printf("output: %q", p.outputBuf.String())1208+ }1209+ _, err := p.output.Write(p.outputBuf.Bytes())1210+ p.outputBuf.Reset()1211+ if err != nil {1212+ return fmt.Errorf("error writing to output: %w", err)1213+ }1214+ return nil1215+}1216+1217 // shutdown performs operations to free up resources and restore the terminal805-// to its original state. It is called once at the end of the program's lifetime.806-//807-// This method should not be called to signal the program to be killed/shutdown.808-// Doing so can lead to race conditions with the eventual call at the program's end.809-// As alternatives, the [Quit] or [Kill] convenience methods should be used instead.1218+// to its original state.1219 func (p *Program) shutdown(kill bool) {1220+ p.shutdownOnce.Do(func() {811- p.cancel()1221+ p.cancel()1222 813- // Wait for all handlers to finish.814- p.handlers.shutdown()1223+ // Wait for all handlers to finish.1224+ p.handlers.shutdown()1225 816- // Check if the cancel reader has been setup before waiting and closing.817- if p.cancelReader != nil {818- // Wait for input loop to finish.819- if p.cancelReader.Cancel() {820- if !kill {821- p.waitForReadLoop()1226+ // Check if the cancel reader has been setup before waiting and closing.1227+ if p.cancelReader != nil {1228+ // Wait for input loop to finish.1229+ if p.cancelReader.Cancel() {1230+ if !kill {1231+ p.waitForReadLoop()1232+ }1233 }1234+ _ = p.cancelReader.Close()1235 }824- _ = p.cancelReader.Close()825- }1236 827- if p.renderer != nil {828- if kill {829- p.renderer.kill()830- } else {831- p.renderer.stop()1237+ if p.renderer != nil {1238+ p.stopRenderer(kill)1239 }833- }1240 835- _ = p.restoreTerminalState()1241+ _ = p.restoreTerminalState()1242+ })1243 }1244 1245 // recoverFromPanic recovers from a panic, prints the stack trace, and restores1246 // the terminal to a usable state.2 unmodified lines1249 case p.errs <- ErrProgramPanic:1250 default:1251 }1252 p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore.846- fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)847- debug.PrintStack()1253+ // We use "\r\n" to ensure the output is formatted even when restoring the1254+ // terminal does not work or when raw mode is still active.1255+ rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")1256+ fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)1257+ stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")1258+ fmt.Fprint(os.Stderr, stack)1259+ if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {1260+ f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))1261+ if err == nil {1262+ defer f.Close() //nolint:errcheck1263+ fmt.Fprintln(f, rec) //nolint:errcheck1264+ fmt.Fprintln(f) //nolint:errcheck1265+ fmt.Fprintln(f, stack) //nolint:errcheck1266+ }1267+ }1268 }1269 1270 // recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and1271 // signals for the program to be killed and terminal restored to a usable state.2 unmodified lines1274 case p.errs <- ErrProgramPanic:1275 default:1276 }1277 p.cancel()858- fmt.Printf("Caught goroutine panic:\n\n%s\n\nRestoring terminal...\n\n", r)859- debug.PrintStack()1278+ // We use "\r\n" to ensure the output is formatted even when restoring the1279+ // terminal does not work or when raw mode is still active.1280+ rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")1281+ fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)1282+ stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")1283+ fmt.Fprint(os.Stderr, stack)1284+ if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {1285+ f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))1286+ if err == nil {1287+ defer f.Close() //nolint:errcheck1288+ fmt.Fprintln(f, rec) //nolint:errcheck1289+ fmt.Fprintln(f) //nolint:errcheck1290+ fmt.Fprintln(f, stack) //nolint:errcheck1291+ }1292+ }1293 }1294 1295 // ReleaseTerminal restores the original terminal state and cancels the input1296 // reader. You can return control to the Program with RestoreTerminal.1297 func (p *Program) ReleaseTerminal() error {1298+ return p.releaseTerminal(false)1299+}1300+1301+func (p *Program) releaseTerminal(reset bool) error {1302 atomic.StoreUint32(&p.ignoreSignals, 1)1303 if p.cancelReader != nil {1304 p.cancelReader.Cancel()1305 }1306 1307 p.waitForReadLoop()1308 1309 if p.renderer != nil {873- p.renderer.stop()874- p.altScreenWasActive = p.renderer.altScreen()875- p.bpWasActive = p.renderer.bracketedPasteActive()876- p.reportFocus = p.renderer.reportFocus()1310+ p.stopRenderer(false)1311+ if reset {1312+ p.renderer.reset()1313+ }1314 }1315 1316 return p.restoreTerminalState()1317 }6 unmodified lines1324 1325 if err := p.initTerminal(); err != nil {1326 return err1327 }891- if err := p.initCancelReader(false); err != nil {1328+ if err := p.initInputReader(false); err != nil {1329 return err1330 }894- if p.altScreenWasActive {895- p.renderer.enterAltScreen()896- } else {897- // entering alt screen already causes a repaint.898- go p.Send(repaintMsg{})899- }900- if p.renderer != nil {901- p.renderer.start()902- }903- if p.bpWasActive {904- p.renderer.enableBracketedPaste()905- }906- if p.reportFocus {907- p.renderer.enableReportFocus()908- }1331 1332+ p.startRenderer()1333+1334 // If the output is a terminal, it may have been resized while another1335 // process was at the foreground, in which case we may not have received1336 // SIGWINCH. Detect any size change now and propagate the new size as1337 // needed.1338 go p.checkResize()1339 916- return nil1340+ // Flush queued commands.1341+ return p.flush()1342 }1343 1344 // Println prints above the Program. This output is unmanaged by the program1345 // and will persist across renders by the Program.1346 //1347 // If the altscreen is active no output will be printed.923-func (p *Program) Println(args ...interface{}) {1348+func (p *Program) Println(args ...any) {1349 p.msgs <- printLineMessage{1350 messageBody: fmt.Sprint(args...),1351 }1352 }5 unmodified lines1358 // Unlike fmt.Printf (but similar to log.Printf) the message will be print on1359 // its own line.1360 //1361 // If the altscreen is active no output will be printed.937-func (p *Program) Printf(template string, args ...interface{}) {1362+func (p *Program) Printf(template string, args ...any) {1363 p.msgs <- printLineMessage{1364 messageBody: fmt.Sprintf(template, args...),1365 }1366 }1367+1368+// startRenderer starts the renderer.1369+func (p *Program) startRenderer() {1370+ framerate := time.Second / time.Duration(p.fps)1371+ if p.ticker == nil {1372+ p.ticker = time.NewTicker(framerate)1373+ } else {1374+ // If the ticker already exists, it has been stopped and we need to1375+ // reset it.1376+ p.ticker.Reset(framerate)1377+ }1378+1379+ // Since the renderer can be restarted after a stop, we need to reset1380+ // the done channel and its corresponding sync.Once.1381+ p.once = sync.Once{}1382+1383+ // Start the renderer.1384+ p.renderer.start()1385+ go func() {1386+ for {1387+ select {1388+ case <-p.rendererDone:1389+ p.ticker.Stop()1390+ return1391+1392+ case <-p.ticker.C:1393+ _ = p.flush()1394+ _ = p.renderer.flush(false)1395+ }1396+ }1397+ }()1398+}1399+1400+// stopRenderer stops the renderer.1401+// If kill is true, the renderer will be stopped immediately without flushing1402+// the last frame.1403+func (p *Program) stopRenderer(kill bool) {1404+ // Stop the renderer before acquiring the mutex to avoid a deadlock.1405+ p.once.Do(func() {1406+ p.rendererDone <- struct{}{}1407+ })1408+1409+ if !kill {1410+ // flush locks the mutex1411+ _ = p.renderer.flush(true)1412+ }1413+1414+ _ = p.renderer.close()1415+}added:termcap.go+48 added
1+package tea2+3+// requestCapabilityMsg is an internal message that requests the terminal to4+// send its Termcap/Terminfo response.5+type requestCapabilityMsg string6+7+// RequestCapability is a command that requests the terminal to send its8+// Termcap/Terminfo response for the given capability.9+//10+// Bubble Tea recognizes the following capabilities and will use them to11+// upgrade the program's color profile:12+// - "RGB" Xterm direct color13+// - "Tc" True color support14+//15+// Note: that some terminal's like Apple's Terminal.app do not support this and16+// will send the wrong response to the terminal breaking the program's output.17+//18+// When the Bubble Tea advertises a non-TrueColor profile, you can use this19+// command to query the terminal for its color capabilities. Example:20+//21+// switch msg := msg.(type) {22+// case tea.ColorProfileMsg:23+// if msg.Profile != colorprofile.TrueColor {24+// return m, tea.Batch(25+// tea.RequestCapability("RGB"),26+// tea.RequestCapability("Tc"),27+// )28+// }29+// }30+func RequestCapability(s string) Cmd {31+ return func() Msg {32+ return requestCapabilityMsg(s)33+ }34+}35+36+// CapabilityMsg represents a Termcap/Terminfo response event. Termcap37+// responses are generated by the terminal in response to RequestTermcap38+// (XTGETTCAP) requests.39+//40+// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands41+type CapabilityMsg struct {42+ Content string43+}44+45+// String returns the capability content as a string.46+func (c CapabilityMsg) String() string {47+ return c.Content48+}added:termios_bsd.go+13 added
1+//go:build dragonfly || freebsd2+// +build dragonfly freebsd3+4+package tea5+6+import (7+ "github.com/charmbracelet/x/term"8+ "golang.org/x/sys/unix"9+)10+11+func (p *Program) checkOptimizedMovements(s *term.State) {12+ p.useHardTabs = s.Oflag&unix.TABDLY == unix.TAB013+}added:termios_other.go+8 added
1+//go:build !windows && !darwin && !dragonfly && !freebsd && !linux && !solaris && !aix2+// +build !windows,!darwin,!dragonfly,!freebsd,!linux,!solaris,!aix3+4+package tea5+6+import "github.com/charmbracelet/x/term"7+8+func (*Program) checkOptimizedMovements(*term.State) {}added:termios_unix.go+14 added
1+//go:build darwin || linux || solaris || aix2+// +build darwin linux solaris aix3+4+package tea5+6+import (7+ "github.com/charmbracelet/x/term"8+ "golang.org/x/sys/unix"9+)10+11+func (p *Program) checkOptimizedMovements(s *term.State) {12+ p.useHardTabs = s.Oflag&unix.TABDLY == unix.TAB013+ p.useBackspace = s.Lflag&unix.BSDLY == unix.BS014+}added:termios_windows.go+11 added
1+//go:build windows2+// +build windows3+4+package tea5+6+import "github.com/charmbracelet/x/term"7+8+func (p *Program) checkOptimizedMovements(*term.State) {9+ p.useHardTabs = true10+ p.useBackspace = true11+}modified:tty_unix.go+5 added-8 removed
18 unmodified lines19 p.previousTtyInputState, err = term.MakeRaw(p.ttyInput.Fd())20 if err != nil {21 return fmt.Errorf("error entering raw mode: %w", err)22 }23+24+ // OPTIM: We can use hard tabs and backspaces to optimize cursor25+ // movements. This is based on termios settings support and whether26+ // they exist and enabled.27+ p.checkOptimizedMovements(p.previousTtyInputState)28 }29 30 if f, ok := p.output.(term.File); ok && term.IsTerminal(f.Fd()) {31 p.ttyOutput = f1 unmodified line33 34 return nil35 }36 32-func openInputTTY() (*os.File, error) {33- f, err := os.Open("/dev/tty")34- if err != nil {35- return nil, fmt.Errorf("could not open a new TTY: %w", err)36- }37- return f, nil38-}39-37 const suspendSupported = true38 39 // Send SIGTSTP to the entire process group.40 func suspendProcess() {6 unmodified linesmodified:tty_windows.go+10 added-14 removed
3 unmodified lines4 package tea5 6 import (7 "fmt"8- "os"8 9 "github.com/charmbracelet/x/term"10 "golang.org/x/sys/windows"11 )5 unmodified lines17 if f, ok := p.input.(term.File); ok && term.IsTerminal(f.Fd()) {18 p.ttyInput = f19 p.previousTtyInputState, err = term.MakeRaw(p.ttyInput.Fd())20 if err != nil {22- return fmt.Errorf("error making raw: %w", err)21+ return fmt.Errorf("error making terminal raw: %w", err)22 }23 24 // Enable VT input25 var mode uint3210 unmodified lines36 if f, ok := p.output.(term.File); ok && term.IsTerminal(f.Fd()) {37 p.ttyOutput = f38 p.previousOutputState, err = term.GetState(f.Fd())39 if err != nil {41- return fmt.Errorf("error getting state: %w", err)40+ return fmt.Errorf("error getting terminal state: %w", err)41 }42 43 var mode uint3244 if err := windows.GetConsoleMode(windows.Handle(p.ttyOutput.Fd()), &mode); err != nil {45 return fmt.Errorf("error getting console mode: %w", err)46 }47 49- if err := windows.SetConsoleMode(windows.Handle(p.ttyOutput.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil {48+ if err := windows.SetConsoleMode(windows.Handle(p.ttyOutput.Fd()),49+ mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|50+ windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil {51 return fmt.Errorf("error setting console mode: %w", err)52 }53+54+ //nolint:godox55+ // TODO: check if we can optimize cursor movements on Windows.56+ p.checkOptimizedMovements(p.previousOutputState)57 }58 54- return nil59+ return //nolint:nakedret60 }61 57-// Open the Windows equivalent of a TTY.58-func openInputTTY() (*os.File, error) {59- f, err := os.OpenFile("CONIN$", os.O_RDWR, 0o644) //nolint:gosec60- if err != nil {61- return nil, fmt.Errorf("error opening file: %w", err)62- }63- return f, nil64-}65-62 const suspendSupported = false63 64 func suspendProcess() {}modified:tty.go+36 added-41 removed
1 package tea2 3 import (4- "errors"4 "fmt"6- "io"5+ "os"6 "time"7 8+ uv "github.com/charmbracelet/ultraviolet"9 "github.com/charmbracelet/x/term"10- "github.com/muesli/cancelreader"10 )11 12 func (p *Program) suspend() {14- if err := p.ReleaseTerminal(); err != nil {13+ if err := p.releaseTerminal(true); err != nil {14 // If we can't release input, abort.15 return16 }17 3 unmodified lines21 go p.Send(ResumeMsg{})22 }23 24 func (p *Program) initTerminal() error {26- if _, ok := p.renderer.(*nilRenderer); ok {27- // No need to initialize the terminal if we're not rendering25+ if p.disableRenderer {26 return nil27 }30-31- if err := p.initInput(); err != nil {32- return err33- }34-35- p.renderer.hideCursor()36- return nil28+ return p.initInput()29 }30 31 // restoreTerminalState restores the terminal to the state prior to running the32 // Bubble Tea program.33 func (p *Program) restoreTerminalState() error {42- if p.renderer != nil {43- p.renderer.disableBracketedPaste()44- p.renderer.showCursor()45- p.disableMouse()34+ // Flush queued commands.35+ _ = p.flush()36 47- if p.renderer.reportFocus() {48- p.renderer.disableReportFocus()49- }50-51- if p.renderer.altScreen() {52- p.renderer.exitAltScreen()53-54- // give the terminal a moment to catch up55- time.Sleep(time.Millisecond * 10) //nolint:mnd56- }57- }58-37 return p.restoreInput()38 }39 40 // restoreInput restores the tty input to its original state.41 func (p *Program) restoreInput() error {42 if p.ttyInput != nil && p.previousTtyInputState != nil {43 if err := term.Restore(p.ttyInput.Fd(), p.previousTtyInputState); err != nil {66- return fmt.Errorf("error restoring console: %w", err)44+ return fmt.Errorf("bubbletea: error restoring console: %w", err)45 }46 }47 if p.ttyOutput != nil && p.previousOutputState != nil {48 if err := term.Restore(p.ttyOutput.Fd(), p.previousOutputState); err != nil {71- return fmt.Errorf("error restoring console: %w", err)49+ return fmt.Errorf("bubbletea: error restoring console: %w", err)50 }51 }52 return nil53 }54 77-// initCancelReader (re)commences reading inputs.78-func (p *Program) initCancelReader(cancel bool) error {55+// initInputReader (re)commences reading inputs.56+func (p *Program) initInputReader(cancel bool) error {57 if cancel && p.cancelReader != nil {58 p.cancelReader.Cancel()59 p.waitForReadLoop()60 }61 62+ term := p.environ.Getenv("TERM")63+64+ // Initialize the input reader.65+ // This need to be done after the terminal has been initialized and set to66+ // raw mode.67+68 var err error85- p.cancelReader, err = newInputReader(p.input, p.mouseMode)69+ p.cancelReader, err = uv.NewCancelReader(p.input)70 if err != nil {87- return fmt.Errorf("error creating cancelreader: %w", err)71+ return fmt.Errorf("bubbletea: could not create cancelable reader: %w", err)72 }73 74+ drv := uv.NewTerminalReader(p.cancelReader, term)75+ drv.SetLogger(p.logger)76+ p.inputScanner = drv77 p.readLoopDone = make(chan struct{})78+79 go p.readLoop()80 81 return nil82 }83 84 func (p *Program) readLoop() {85 defer close(p.readLoopDone)86 99- err := readInputs(p.ctx, p.msgs, p.cancelReader)100- if !errors.Is(err, io.EOF) && !errors.Is(err, cancelreader.ErrCanceled) {87+ if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {88 select {89 case <-p.ctx.Done():90+ return91 case p.errs <- err:92 }93 }94 }26 unmodified lines121 122 return123 }124 137- p.Send(WindowSizeMsg{138- Width: w,139- Height: h,140- })125+ p.width, p.height = w, h126+ p.Send(WindowSizeMsg{Width: w, Height: h})127 }128+129+// OpenTTY opens the running terminal's TTY for reading and writing.130+func OpenTTY() (*os.File, *os.File, error) {131+ in, out, err := uv.OpenTTY()132+ if err != nil {133+ return nil, nil, fmt.Errorf("bubbletea: could not open TTY: %w", err)134+ }135+ return in, out, nil136+}added:UPGRADE_GUIDE_V2.md+573 added
1+# Bubble Tea v2 Upgrade Guide2+3+This 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](WHATS_NEW_V2.md) doc.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.7+8+## Migration Checklist9+10+Here's the short version — a checklist you can follow top to bottom. Each item links to the relevant section below.11+12+- [ ] [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)24+25+## Import Paths26+27+The module path changed to a vanity domain. Lip Gloss moved too.28+29+```go30+// Before31+import tea "github.com/charmbracelet/bubbletea"32+import "github.com/charmbracelet/lipgloss"33+34+// After35+import tea "charm.land/bubbletea/v2"36+import "charm.land/lipgloss/v2"37+```38+39+## The Big Idea: Declarative Views40+41+The 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.42+43+This 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.44+45+```go46+// v1: imperative — scattered across NewProgram, Init, and Update47+p := tea.NewProgram(model{}, tea.WithAltScreen(), tea.WithMouseCellMotion())48+49+// v2: declarative — everything lives in View()50+func (m model) View() tea.View {51+ v := tea.NewView("Hello!")52+ v.AltScreen = true53+ v.MouseMode = tea.MouseModeCellMotion54+ return v55+}56+```57+58+Keep this in mind as you go through the rest of the guide — most of the "removed" things simply moved into View fields.59+60+## View Returns a `tea.View` Now61+62+The `View()` method no longer returns a `string`. It returns a `tea.View` struct.63+64+```go65+// Before:66+func (m model) View() string {67+ return "Hello, world!"68+}69+70+// After:71+func (m model) View() tea.View {72+ return tea.NewView("Hello, world!")73+}74+```75+76+You can also use the longer form if you need to set additional fields:77+78+```go79+func (m model) View() tea.View {80+ var v tea.View81+ v.SetContent("Hello, world!")82+ v.AltScreen = true83+ return v84+}85+```86+87+The `tea.View` struct has fields for everything that used to be controlled by options and commands:88+89+| 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 |101+| `KeyboardEnhancements` | Request keyboard enhancement features |102+| `OnMouse` | Intercept mouse messages based on view content |103+104+## Key Messages105+106+Key messages got a major overhaul. Here's the quick rundown:107+108+### `tea.KeyMsg` is now an interface109+110+In 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`:111+112+```go113+// Before:114+case tea.KeyMsg:115+ switch msg.String() {116+ case "q":117+ return m, tea.Quit118+ }119+120+// After:121+case tea.KeyPressMsg:122+ switch msg.String() {123+ case "q":124+ return m, tea.Quit125+ }126+```127+128+If you want to handle both presses and releases, use `tea.KeyMsg` and type-switch inside:129+130+```go131+case tea.KeyMsg:132+ switch key := msg.(type) {133+ case tea.KeyPressMsg:134+ // key press135+ case tea.KeyReleaseMsg:136+ // key release137+ }138+```139+140+### Key fields changed141+142+| v1 | v2 | Notes |143+|---|---|---|144+| `msg.Type` | `msg.Code` | A `rune` — can be `tea.KeyEnter`, `'a'`, etc. |145+| `msg.Runes` | `msg.Text` | Now a `string`, not `[]rune` |146+| `msg.Alt` | `msg.Mod` | `msg.Mod.Contains(tea.ModAlt)` for alt, etc. |147+| `tea.KeyRune` | — | Check `len(msg.Text) > 0` instead |148+| `tea.KeyCtrlC` | — | Use `msg.String() == "ctrl+c"` or check `msg.Code` + `msg.Mod` |149+150+### Space bar changed151+152+Space bar now returns `"space"` instead of `" "` when using `msg.String()`:153+154+```go155+// Before:156+case " ":157+158+// After:159+case "space":160+```161+162+`key.Code` is still `' '` and `key.Text` is still `" "`, but `String()` returns `"space"`.163+164+### Ctrl+key matching165+166+```go167+// Before:168+case tea.KeyCtrlC:169+ // ctrl+c170+171+// After (option A — string matching):172+case tea.KeyPressMsg:173+ switch msg.String() {174+ case "ctrl+c":175+ // ctrl+c176+ }177+178+// After (option B — field matching):179+case tea.KeyPressMsg:180+ if msg.Code == 'c' && msg.Mod == tea.ModCtrl {181+ // ctrl+c182+ }183+```184+185+### New Key fields186+187+These are new in v2 and don't have v1 equivalents:188+189+- **`key.ShiftedCode`** — the shifted key code (e.g., `'B'` when pressing shift+b)190+- **`key.BaseCode`** — the key on a US PC-101 layout (handy for international keyboards)191+- **`key.IsRepeat`** — whether the key is auto-repeating (Kitty protocol / Windows Console only)192+- **`key.Keystroke()`** — like `String()` but always includes modifier info193+194+## Paste Messages195+196+Paste events no longer come in as `tea.KeyMsg` with a `Paste` flag. They're now their own message types:197+198+```go199+// Before:200+case tea.KeyMsg:201+ if msg.Paste {202+ m.text += string(msg.Runes)203+ }204+205+// After:206+case tea.PasteMsg:207+ m.text += msg.Content208+case tea.PasteStartMsg:209+ // paste started210+case tea.PasteEndMsg:211+ // paste ended212+```213+214+## Mouse Messages215+216+### `tea.MouseMsg` is now an interface217+218+In 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()`:219+220+```go221+// Before:222+case tea.MouseMsg:223+ x, y := msg.X, msg.Y224+225+// After:226+case tea.MouseMsg:227+ mouse := msg.Mouse()228+ x, y := mouse.X, mouse.Y229+```230+231+### Mouse events are split by type232+233+Instead of checking `msg.Action`, match on specific message types:234+235+```go236+// Before:237+case tea.MouseMsg:238+ if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft {239+ // left click240+ }241+242+// After:243+case tea.MouseClickMsg:244+ if msg.Button == tea.MouseLeft {245+ // left click246+ }247+case tea.MouseReleaseMsg:248+ // release249+case tea.MouseWheelMsg:250+ // scroll251+case tea.MouseMotionMsg:252+ // movement253+```254+255+### Button constants renamed256+257+| v1 | v2 |258+|---|---|259+| `tea.MouseButtonLeft` | `tea.MouseLeft` |260+| `tea.MouseButtonRight` | `tea.MouseRight` |261+| `tea.MouseButtonMiddle` | `tea.MouseMiddle` |262+| `tea.MouseButtonWheelUp` | `tea.MouseWheelUp` |263+| `tea.MouseButtonWheelDown` | `tea.MouseWheelDown` |264+| `tea.MouseButtonWheelLeft` | `tea.MouseWheelLeft` |265+| `tea.MouseButtonWheelRight` | `tea.MouseWheelRight` |266+267+### `tea.MouseEvent` → `tea.Mouse`268+269+The `MouseEvent` struct is gone. The new `Mouse` struct has `X`, `Y`, `Button`, and `Mod` fields.270+271+### Mouse mode is now a View field272+273+```go274+// Before:275+p := tea.NewProgram(model{}, tea.WithMouseCellMotion())276+277+// After:278+func (m model) View() tea.View {279+ v := tea.NewView("...")280+ v.MouseMode = tea.MouseModeCellMotion281+ return v282+}283+```284+285+## Removed Program Options286+287+These options no longer exist. They all moved to View fields.288+289+| Removed Option | Do This Instead |290+|---|---|291+| `tea.WithAltScreen()` | `view.AltScreen = true` |292+| `tea.WithMouseCellMotion()` | `view.MouseMode = tea.MouseModeCellMotion` |293+| `tea.WithMouseAllMotion()` | `view.MouseMode = tea.MouseModeAllMotion` |294+| `tea.WithReportFocus()` | `view.ReportFocus = true` |295+| `tea.WithoutBracketedPaste()` | `view.DisableBracketedPasteMode = true` |296+| `tea.WithInputTTY()` | Just remove it — v2 always opens the TTY for input automatically |297+| `tea.WithANSICompressor()` | Just remove it — the new renderer handles optimization automatically |298+299+## Removed Commands300+301+These commands no longer exist. Set the corresponding View field instead.302+303+| Removed Command | Do This Instead |304+|---|---|305+| `tea.EnterAltScreen` | `view.AltScreen = true` |306+| `tea.ExitAltScreen` | `view.AltScreen = false` |307+| `tea.EnableMouseCellMotion` | `view.MouseMode = tea.MouseModeCellMotion` |308+| `tea.EnableMouseAllMotion` | `view.MouseMode = tea.MouseModeAllMotion` |309+| `tea.DisableMouse` | `view.MouseMode = tea.MouseModeNone` |310+| `tea.HideCursor` | `view.Cursor = nil` |311+| `tea.ShowCursor` | `view.Cursor = &tea.Cursor{...}` or `tea.NewCursor(x, y)` |312+| `tea.EnableBracketedPaste` | `view.DisableBracketedPasteMode = false` |313+| `tea.DisableBracketedPaste` | `view.DisableBracketedPasteMode = true` |314+| `tea.EnableReportFocus` | `view.ReportFocus = true` |315+| `tea.DisableReportFocus` | `view.ReportFocus = false` |316+| `tea.SetWindowTitle("...")` | `view.WindowTitle = "..."` |317+318+## Removed Program Methods319+320+These methods on `*Program` are gone.321+322+| Removed Method | Do This Instead |323+|---|---|324+| `p.Start()` | `p.Run()` |325+| `p.StartReturningModel()` | `p.Run()` |326+| `p.EnterAltScreen()` | `view.AltScreen = true` in `View()` |327+| `p.ExitAltScreen()` | `view.AltScreen = false` in `View()` |328+| `p.EnableMouseCellMotion()` | `view.MouseMode` in `View()` |329+| `p.DisableMouseCellMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |330+| `p.EnableMouseAllMotion()` | `view.MouseMode` in `View()` |331+| `p.DisableMouseAllMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |332+| `p.SetWindowTitle(...)` | `view.WindowTitle` in `View()` |333+334+## Renamed APIs335+336+| v1 | v2 | Notes |337+|---|---|---|338+| `tea.Sequentially(...)` | `tea.Sequence(...)` | `Sequentially` was already deprecated in v1 |339+| `tea.WindowSize()` | `tea.RequestWindowSize` | Now returns `Msg` directly, not a `Cmd` |340+341+## New Program Options342+343+These are new in v2:344+345+| Option | What It Does |346+|---|---|347+| `tea.WithColorProfile(p)` | Force a specific color profile (great for testing) |348+| `tea.WithWindowSize(w, h)` | Set initial terminal size (great for testing) |349+350+## Complete Before & After351+352+Here's a minimal but complete program showing the most common migration patterns side by side.353+354+**v1:**355+356+```go357+package main358+359+import (360+ "fmt"361+ "os"362+363+ tea "github.com/charmbracelet/bubbletea"364+)365+366+type model struct {367+ count int368+}369+370+func (m model) Init() tea.Cmd {371+ return nil372+}373+374+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {375+ switch msg := msg.(type) {376+ case tea.KeyMsg:377+ switch msg.String() {378+ case "q", "ctrl+c":379+ return m, tea.Quit380+ case " ":381+ m.count++382+ }383+ case tea.MouseMsg:384+ if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft {385+ m.count++386+ }387+ }388+ return m, nil389+}390+391+func (m model) View() string {392+ return fmt.Sprintf("Count: %d\n\nSpace or click to increment. q to quit.\n", m.count)393+}394+395+func main() {396+ p := tea.NewProgram(model{}, tea.WithAltScreen(), tea.WithMouseCellMotion())397+ if _, err := p.Run(); err != nil {398+ fmt.Fprintln(os.Stderr, err)399+ os.Exit(1)400+ }401+}402+```403+404+**v2:**405+406+```go407+package main408+409+import (410+ "fmt"411+ "os"412+413+ tea "charm.land/bubbletea/v2"414+)415+416+type model struct {417+ count int418+}419+420+func (m model) Init() tea.Cmd {421+ return nil422+}423+424+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {425+ switch msg := msg.(type) {426+ case tea.KeyPressMsg:427+ switch msg.String() {428+ case "q", "ctrl+c":429+ return m, tea.Quit430+ case "space":431+ m.count++432+ }433+ case tea.MouseClickMsg:434+ if msg.Button == tea.MouseLeft {435+ m.count++436+ }437+ }438+ return m, nil439+}440+441+func (m model) View() tea.View {442+ v := tea.NewView(fmt.Sprintf("Count: %d\n\nSpace or click to increment. q to quit.\n", m.count))443+ v.AltScreen = true444+ v.MouseMode = tea.MouseModeCellMotion445+ return v446+}447+448+func main() {449+ p := tea.NewProgram(model{})450+ if _, err := p.Run(); err != nil {451+ fmt.Fprintln(os.Stderr, err)452+ os.Exit(1)453+ }454+}455+```456+457+Notice how the `NewProgram` call got simpler? All the terminal feature flags moved into `View()` where they belong.458+459+## Quick Reference460+461+A flat old → new lookup table. Handy for search-and-replace and LLM-assisted migration.462+463+### Import Paths464+465+| v1 | v2 |466+|---|---|467+| `github.com/charmbracelet/bubbletea` | `charm.land/bubbletea/v2` |468+| `github.com/charmbracelet/lipgloss` | `charm.land/lipgloss/v2` |469+470+### Model Interface471+472+| v1 | v2 |473+|---|---|474+| `View() string` | `View() tea.View` |475+476+### Key Events477+478+| v1 | v2 |479+|---|---|480+| `tea.KeyMsg` (struct) | `tea.KeyPressMsg` for presses, `tea.KeyMsg` (interface) for both |481+| `msg.Type` | `msg.Code` |482+| `msg.Runes` | `msg.Text` (string, not `[]rune`) |483+| `msg.Alt` | `msg.Mod.Contains(tea.ModAlt)` |484+| `tea.KeyRune` | check `len(msg.Text) > 0` |485+| `tea.KeyCtrlC` | `msg.Code == 'c' && msg.Mod == tea.ModCtrl` or `msg.String() == "ctrl+c"` |486+| `case " ":` (space) | `case "space":` |487+488+### Mouse Events489+490+| v1 | v2 |491+|---|---|492+| `tea.MouseMsg` (struct) | `tea.MouseMsg` (interface) — call `.Mouse()` for the data |493+| `tea.MouseEvent` | `tea.Mouse` |494+| `tea.MouseButtonLeft` | `tea.MouseLeft` |495+| `tea.MouseButtonRight` | `tea.MouseRight` |496+| `tea.MouseButtonMiddle` | `tea.MouseMiddle` |497+| `tea.MouseButtonWheelUp` | `tea.MouseWheelUp` |498+| `tea.MouseButtonWheelDown` | `tea.MouseWheelDown` |499+| `msg.X`, `msg.Y` (direct) | `msg.Mouse().X`, `msg.Mouse().Y` |500+501+### Options → View Fields502+503+| v1 Option | v2 View Field |504+|---|---|505+| `tea.WithAltScreen()` | `view.AltScreen = true` |506+| `tea.WithMouseCellMotion()` | `view.MouseMode = tea.MouseModeCellMotion` |507+| `tea.WithMouseAllMotion()` | `view.MouseMode = tea.MouseModeAllMotion` |508+| `tea.WithReportFocus()` | `view.ReportFocus = true` |509+| `tea.WithoutBracketedPaste()` | `view.DisableBracketedPasteMode = true` |510+511+### Commands → View Fields512+513+| v1 Command | v2 View Field |514+|---|---|515+| `tea.EnterAltScreen` / `tea.ExitAltScreen` | `view.AltScreen = true/false` |516+| `tea.EnableMouseCellMotion` | `view.MouseMode = tea.MouseModeCellMotion` |517+| `tea.EnableMouseAllMotion` | `view.MouseMode = tea.MouseModeAllMotion` |518+| `tea.DisableMouse` | `view.MouseMode = tea.MouseModeNone` |519+| `tea.HideCursor` / `tea.ShowCursor` | `view.Cursor = nil` / `view.Cursor = &tea.Cursor{...}` |520+| `tea.EnableBracketedPaste` / `tea.DisableBracketedPaste` | `view.DisableBracketedPasteMode = false/true` |521+| `tea.EnableReportFocus` / `tea.DisableReportFocus` | `view.ReportFocus = true/false` |522+| `tea.SetWindowTitle("...")` | `view.WindowTitle = "..."` |523+524+### Removed Options (No Replacement Needed)525+526+| v1 Option | What Happened |527+|---|---|528+| `tea.WithInputTTY()` | v2 always opens the TTY for input automatically |529+| `tea.WithANSICompressor()` | The new renderer handles optimization automatically |530+531+### Removed Program Methods532+533+| v1 Method | v2 Replacement |534+|---|---|535+| `p.Start()` | `p.Run()` |536+| `p.StartReturningModel()` | `p.Run()` |537+| `p.EnterAltScreen()` | `view.AltScreen = true` in `View()` |538+| `p.ExitAltScreen()` | `view.AltScreen = false` in `View()` |539+| `p.EnableMouseCellMotion()` | `view.MouseMode` in `View()` |540+| `p.DisableMouseCellMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |541+| `p.EnableMouseAllMotion()` | `view.MouseMode` in `View()` |542+| `p.DisableMouseAllMotion()` | `view.MouseMode = tea.MouseModeNone` in `View()` |543+| `p.SetWindowTitle(...)` | `view.WindowTitle` in `View()` |544+545+### Other Renames546+547+| v1 | v2 |548+|---|---|549+| `tea.Sequentially(...)` | `tea.Sequence(...)` |550+| `tea.WindowSize()` | `tea.RequestWindowSize` (now returns `Msg`, not `Cmd`) |551+552+### New Program Options553+554+| Option | Description |555+|---|---|556+| `tea.WithColorProfile(p)` | Force a specific color profile |557+| `tea.WithWindowSize(w, h)` | Set initial window size (great for testing) |558+559+## Feedback560+561+Have thoughts on the v2 upgrade? We'd _love_ to hear about it. Let us know on…562+563+- [Discord](https://charm.land/chat)564+- [Matrix](https://charm.land/matrix)565+- [Email](mailto:vt100@charm.land)566+567+---568+569+Part of [Charm](https://charm.land).570+571+<a href="https://charm.land/"><img alt="The Charm logo" src="https://stuff.charm.land/charm-badge.jpg" width="400"></a>572+573+Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحةadded:xterm.go+22 added
1+package tea2+3+// TerminalVersionMsg is a message that represents the terminal version.4+type TerminalVersionMsg struct {5+ Name string6+}7+8+// String returns the terminal name as a string.9+func (t TerminalVersionMsg) String() string {10+ return t.Name11+}12+13+// terminalVersion is an internal message that queries the terminal for its14+// version using XTVERSION.15+type terminalVersion struct{}16+17+// RequestTerminalVersion is a command that queries the terminal for its18+// version using XTVERSION. Note that some terminals may not support this19+// command.20+func RequestTerminalVersion() Msg {21+ return terminalVersion{}22+}