Tutorials

Mouse Support

Add mouse interaction to your Bubble Tea applications.

Make your TUI clickable with mouse support!

The Code

package main

import (
    "fmt"
    tea "github.com/charmbracelet/bubbletea/v2"
)

type model struct {
    lastClick string
}

func (m model) Init() tea.Cmd {
    return nil
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.KeyPressMsg:
        if msg.String() == "q" {
            return m, tea.Quit
        }
    case tea.MouseMsg:
        m.lastClick = fmt.Sprintf("Mouse %s at (%d, %d)", 
            msg.Action, msg.X, msg.Y)
    }
    return m, nil
}

func (m model) View() string {
    s := "Mouse events are enabled!\n\n"
    if m.lastClick != "" {
        s += m.lastClick
    }
    s += "\n\nPress q to quit"
    return s
}

func main() {
    p := tea.NewProgram(model{}, tea.WithMouseAllMotion())
    p.Run()
}

Mouse Options

tea.WithMouseCellMotion() // Mouse events only when buttons are pressed
tea.WithMouseAllMotion()  // All mouse movement

Mouse Actions

  • tea.MouseActionPress
  • tea.MouseActionRelease
  • tea.MouseActionMotion
  • tea.MouseActionWheel