Skip to content
Myr

feat: add generic event filter (#536)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

`WithFilter` lets you supply an event filter that will be invoked before Bubble Tea processes a `tea.Msg`. The event filter can return any `tea.Msg` which will then get handled by Bubble Tea instead of the original event. If the event filter returns nil, the event will be ignored and Bubble Tea will not process it. As an example, this could be used to prevent a program from shutting down if there are unsaved changes. Based on the fantastic work by @aschey and supersedes #521. Resolves #472.

authored by Christian Muehlhaeuser · committed by GitHub · parent 8514d90 · Browse files · 5 files+253 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+253 added−6 removed

  • other:+253 added−6 removed

5 files+253 added−6 removed

added:examples/prevent-quit/main.go+154 added
1package main23// A program demonstrating how to use the WithFilter option to intercept events.45import (6 "fmt"7 "log"89 "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"14)1516var (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"))20)2122func main() {23 p := tea.NewProgram(initialModel(), tea.WithFilter(filter))2425 if _, err := p.Run(); err != nil {26 log.Fatal(err)27 }28}2930func filter(teaModel tea.Model, msg tea.Msg) tea.Msg {31 if _, ok := msg.(tea.QuitMsg); !ok {32 return msg33 }3435 m := teaModel.(model)36 if m.hasChanges {37 return nil38 }3940 return msg41}4243type model struct {44 textarea textarea.Model45 help help.Model46 keymap keymap47 saveText string48 hasChanges bool49 quitting bool50}5152type keymap struct {53 save key.Binding54 quit key.Binding55}5657func initialModel() model {58 ti := textarea.New()59 ti.Placeholder = "Only the best words"60 ti.Focus()6162 return model{63 textarea: ti,64 help: help.NewModel(),65 keymap: keymap{66 save: key.NewBinding(67 key.WithKeys("ctrl+s"),68 key.WithHelp("ctrl+s", "save"),69 ),70 quit: key.NewBinding(71 key.WithKeys("esc", "ctrl+c"),72 key.WithHelp("esc", "quit"),73 ),74 },75 }76}7778func (m model) Init() tea.Cmd {79 return textarea.Blink80}8182func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {83 if m.quitting {84 return m.updatePromptView(msg)85 }8687 return m.updateTextView(msg)88}8990func (m model) updateTextView(msg tea.Msg) (tea.Model, tea.Cmd) {91 var cmds []tea.Cmd92 var cmd tea.Cmd9394 switch msg := msg.(type) {95 case tea.KeyMsg: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:105 m.saveText = ""106 m.hasChanges = true107 fallthrough108 default:109 if !m.textarea.Focused() {110 cmd = m.textarea.Focus()111 cmds = append(cmds, cmd)112 }113 }114 }115 m.textarea, cmd = m.textarea.Update(msg)116 cmds = append(cmds, cmd)117 return m, tea.Batch(cmds...)118}119120func (m model) updatePromptView(msg tea.Msg) (tea.Model, tea.Cmd) {121 switch msg := msg.(type) {122 case tea.KeyMsg: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.Quit127 }128 m.quitting = false129 }130131 return m, nil132}133134func (m model) View() string {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)139 }140 return "Very important, thank you\n"141 }142143 helpView := m.help.ShortHelpView([]key.Binding{144 m.keymap.save,145 m.keymap.quit,146 })147148 return fmt.Sprintf(149 "\nType some important things.\n\n%s\n\n %s\n %s",150 m.textarea.View(),151 saveTextStyle.Render(m.saveText),152 helpView,153 ) + "\n\n"154}
modified:options_test.go+7 added
33 unmodified lines
34 t.Errorf("expected renderer to be a nilRenderer, got %v", p.renderer)35 }36 })3738 t.Run("filter", func(t *testing.T) {39 p := NewProgram(nil, WithFilter(func(_ Model, msg Msg) Msg { return msg }))40 if p.filter == nil {41 t.Errorf("expected filter to be set")42 }43 })4445 t.Run("startup options", func(t *testing.T) {46 exercise := func(t *testing.T, opt ProgramOption, expect startupOptions) {47 p := NewProgram(nil, opt)48 if !p.startupOptions.has(expect) {
54 unmodified lines
modified:options.go+35 added
149 unmodified lines
150 return func(p *Program) {151 p.startupOptions |= withANSICompressor152 }153}154155// WithFilter supplies an event filter that will be invoked before Bubble Tea156// processes a tea.Msg. The event filter can return any tea.Msg which will then157// get handled by Bubble Tea instead of the original event. If the event filter158// returns nil, the event will be ignored and Bubble Tea will not process it.159//160// As an example, this could be used to prevent a program from shutting down if161// there are unsaved changes.162//163// Example:164//165// func filter(m tea.Model, msg tea.Msg) tea.Msg {166// if _, ok := msg.(tea.QuitMsg); !ok {167// return msg168// }169//170// model := m.(myModel)171// if model.hasChanges {172// return nil173// }174//175// return msg176// }177//178// p := tea.NewProgram(Model{}, tea.WithFilter(filter));179//180// if _,err := p.Run(); err != nil {181// fmt.Println("Error running program:", err)182// os.Exit(1)183// }184func WithFilter(filter func(Model, Msg) Msg) ProgramOption {185 return func(p *Program) {186 p.filter = filter187 }188}
modified:tea_test.go+41 added
75 unmodified lines
76 t.Fatal(err)77 }78}7980func TestTeaWithFilter(t *testing.T) {81 testTeaWithFilter(t, 0)82 testTeaWithFilter(t, 1)83 testTeaWithFilter(t, 2)84}8586func testTeaWithFilter(t *testing.T, preventCount uint32) {87 var buf bytes.Buffer88 var in bytes.Buffer8990 m := &testModel{}91 shutdowns := uint32(0)92 p := NewProgram(m,93 WithInput(&in),94 WithOutput(&buf),95 WithFilter(func(_ Model, msg Msg) Msg {96 if _, ok := msg.(QuitMsg); !ok {97 return msg98 }99 if shutdowns < preventCount {100 atomic.AddUint32(&shutdowns, 1)101 return nil102 }103 return msg104 }))105106 go func() {107 for atomic.LoadUint32(&shutdowns) <= preventCount {108 time.Sleep(time.Millisecond)109 p.Quit()110 }111 }()112113 if err := p.Start(); err != nil {114 t.Fatal(err)115 }116 if shutdowns != preventCount {117 t.Errorf("Expected %d prevented shutdowns, got %d", preventCount, shutdowns)118 }119}120121func TestTeaKill(t *testing.T) {122 var buf bytes.Buffer123 var in bytes.Buffer124
141 unmodified lines
modified:tea.go+16 added-6 removed
121 unmodified lines
122 // Lint ignore note: the linter will find false positive on unix systems123 // as this value only comes into play on Windows, hence the ignore comment124 // below.125 windowsStdin *os.File //nolint:golint,structcheck,unused126127 filter func(Model, Msg) Msg128}129130// Quit is a special command that tells the Bubble Tea program to exit.131func Quit() Msg {130 return quitMsg{}132 return QuitMsg{}133}134133// quitMsg in an internal message signals that the program should quit. You can134// send a quitMsg with Quit.135type quitMsg struct{}135// QuitMsg signals that the program should quit. You can send a QuitMsg with136// Quit.137type QuitMsg struct{}138139// NewProgram creates a new Program.140func NewProgram(model Model, opts ...ProgramOption) *Program {141 p := &Program{
53 unmodified lines
195 return196197 case <-sig:198 if !p.ignoreSignals {197 p.msgs <- quitMsg{}199 p.msgs <- QuitMsg{}200 return201 }202 }203 }
64 unmodified lines
268 case err := <-p.errs:269 return model, err270271 case msg := <-p.msgs:272 // Filter messages.273 if p.filter != nil {274 msg = p.filter(model, msg)275 }276 if msg == nil {277 continue278 }279280 // Handle special internal messages.281 switch msg := msg.(type) {272 case quitMsg:282 case QuitMsg:283 return model, nil284285 case clearScreenMsg:286 p.renderer.clearScreen()
377 unmodified lines