mirror of
https://github.com/taigrr/bubbletea.git
synced 2026-04-02 02:59:09 -07:00
feat: add generic event filter (#536)
`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 is contained in:
committed by
GitHub
parent
8514d90b9e
commit
c56884c0e2
41
tea_test.go
41
tea_test.go
@@ -77,6 +77,47 @@ func TestTeaQuit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeaWithFilter(t *testing.T) {
|
||||
testTeaWithFilter(t, 0)
|
||||
testTeaWithFilter(t, 1)
|
||||
testTeaWithFilter(t, 2)
|
||||
}
|
||||
|
||||
func testTeaWithFilter(t *testing.T, preventCount uint32) {
|
||||
var buf bytes.Buffer
|
||||
var in bytes.Buffer
|
||||
|
||||
m := &testModel{}
|
||||
shutdowns := uint32(0)
|
||||
p := NewProgram(m,
|
||||
WithInput(&in),
|
||||
WithOutput(&buf),
|
||||
WithFilter(func(_ Model, msg Msg) Msg {
|
||||
if _, ok := msg.(QuitMsg); !ok {
|
||||
return msg
|
||||
}
|
||||
if shutdowns < preventCount {
|
||||
atomic.AddUint32(&shutdowns, 1)
|
||||
return nil
|
||||
}
|
||||
return msg
|
||||
}))
|
||||
|
||||
go func() {
|
||||
for atomic.LoadUint32(&shutdowns) <= preventCount {
|
||||
time.Sleep(time.Millisecond)
|
||||
p.Quit()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := p.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if shutdowns != preventCount {
|
||||
t.Errorf("Expected %d prevented shutdowns, got %d", preventCount, shutdowns)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeaKill(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
var in bytes.Buffer
|
||||
|
||||
Reference in New Issue
Block a user