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.
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
Provenance
- Commit
c56884c- Tree
22b1986- Author
Christian Muehlhaeuser <muesli@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8514d90
5 files changed+253 added−6 removed
added:examples/prevent-quit/main.go+154 added
1+package main2+3+// A program demonstrating how to use the WithFilter option to intercept events.4+5+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"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"))20+)21+22+func main() {23+ p := tea.NewProgram(initialModel(), tea.WithFilter(filter))24+25+ if _, err := p.Run(); err != nil {26+ log.Fatal(err)27+ }28+}29+30+func filter(teaModel tea.Model, msg tea.Msg) tea.Msg {31+ if _, ok := msg.(tea.QuitMsg); !ok {32+ return msg33+ }34+35+ m := teaModel.(model)36+ if m.hasChanges {37+ return nil38+ }39+40+ return msg41+}42+43+type model struct {44+ textarea textarea.Model45+ help help.Model46+ keymap keymap47+ saveText string48+ hasChanges bool49+ quitting bool50+}51+52+type keymap struct {53+ save key.Binding54+ quit key.Binding55+}56+57+func initialModel() model {58+ ti := textarea.New()59+ ti.Placeholder = "Only the best words"60+ ti.Focus()61+62+ 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+}77+78+func (m model) Init() tea.Cmd {79+ return textarea.Blink80+}81+82+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {83+ if m.quitting {84+ return m.updatePromptView(msg)85+ }86+87+ return m.updateTextView(msg)88+}89+90+func (m model) updateTextView(msg tea.Msg) (tea.Model, tea.Cmd) {91+ var cmds []tea.Cmd92+ var cmd tea.Cmd93+94+ 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+}119+120+func (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+ }130+131+ return m, nil132+}133+134+func (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+ }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",150+ m.textarea.View(),151+ saveTextStyle.Render(m.saveText),152+ helpView,153+ ) + "\n\n"154+}modified:options_test.go+7 added
33 unmodified lines34 t.Errorf("expected renderer to be a nilRenderer, got %v", p.renderer)35 }36 })37 38+ 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+ })44+45 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 linesmodified:options.go+35 added
149 unmodified lines150 return func(p *Program) {151 p.startupOptions |= withANSICompressor152 }153 }154+155+// 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+// }184+func 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 lines76 t.Fatal(err)77 }78 }79 80+func TestTeaWithFilter(t *testing.T) {81+ testTeaWithFilter(t, 0)82+ testTeaWithFilter(t, 1)83+ testTeaWithFilter(t, 2)84+}85+86+func testTeaWithFilter(t *testing.T, preventCount uint32) {87+ var buf bytes.Buffer88+ var in bytes.Buffer89+90+ 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+ }))105+106+ go func() {107+ for atomic.LoadUint32(&shutdowns) <= preventCount {108+ time.Sleep(time.Millisecond)109+ p.Quit()110+ }111+ }()112+113+ 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+}120+121 func TestTeaKill(t *testing.T) {122 var buf bytes.Buffer123 var in bytes.Buffer124 141 unmodified linesmodified:tea.go+16 added-6 removed
121 unmodified lines122 // 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,unused126+127+ filter func(Model, Msg) Msg128 }129 130 // Quit is a special command that tells the Bubble Tea program to exit.131 func Quit() Msg {130- return quitMsg{}132+ return QuitMsg{}133 }134 133-// quitMsg in an internal message signals that the program should quit. You can134-// send a quitMsg with Quit.135-type quitMsg struct{}135+// QuitMsg signals that the program should quit. You can send a QuitMsg with136+// Quit.137+type QuitMsg struct{}138 139 // NewProgram creates a new Program.140 func NewProgram(model Model, opts ...ProgramOption) *Program {141 p := &Program{53 unmodified lines195 return196 197 case <-sig:198 if !p.ignoreSignals {197- p.msgs <- quitMsg{}199+ p.msgs <- QuitMsg{}200 return201 }202 }203 }64 unmodified lines268 case err := <-p.errs:269 return model, err270 271 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+ }279+280 // Handle special internal messages.281 switch msg := msg.(type) {272- case quitMsg:282+ case QuitMsg:283 return model, nil284 285 case clearScreenMsg:286 p.renderer.clearScreen()377 unmodified lines