@@ -140,4 +140,76 @@ func TestOptions(t *testing.T) {
140140 }
141141 }
142142 })
143+
144+ t .Run ("multiple filters" , func (t * testing.T ) {
145+ type multiIncrement struct {
146+ num int
147+ }
148+ type eventuallyIncrementMsg incrementMsg
149+
150+ // This filter converts multiIncrement to a sequence of eventuallyIncrementMsg.
151+ a := func (m Model , msg Msg ) Msg {
152+ if mul , ok := msg .(multiIncrement ); ok {
153+ var cmds []Cmd
154+ for range mul .num {
155+ cmds = append (cmds , func () Msg {
156+ return eventuallyIncrementMsg {}
157+ })
158+ }
159+ return sequenceMsg (cmds )
160+ }
161+ return msg
162+ }
163+
164+ // This filter converts eventuallyIncrementMsg into incrementMsg.
165+ // If loaded out of order, the c filter breaks.
166+ b := func (_ Model , msg Msg ) Msg {
167+ if msg , ok := msg .(eventuallyIncrementMsg ); ok {
168+ return incrementMsg (msg )
169+ }
170+ return msg
171+ }
172+
173+ // This filter quits after 10 incrementMsg.
174+ // Requires the b filter to work.
175+ c := func (m Model , msg Msg ) Msg {
176+ p := m .(* testModel )
177+ // Stop after 10 increments.
178+ if _ , ok := msg .(incrementMsg ); ok {
179+ if v := p .counter .Load (); v != nil && v .(int ) >= 10 {
180+ return QuitMsg {}
181+ }
182+ }
183+
184+ return msg
185+ }
186+
187+ var (
188+ buf bytes.Buffer
189+ in bytes.Buffer
190+ m = & testModel {}
191+ )
192+ p := NewProgram (m ,
193+ // The combination of filters a, b, and c in this test causes the test
194+ // to correctly quit at 10 increments.
195+
196+ // Convert into multiple eventuallyIncrementMsg.
197+ WithAddedFilter (a ),
198+ // Convert into incrementMsg.
199+ WithAddedFilter (b ),
200+ // Quit when the number of messages reaches 10.
201+ WithAddedFilter (c ),
202+
203+ WithInput (& in ),
204+ WithOutput (& buf ))
205+ go p .Send (multiIncrement {num : 20 })
206+
207+ if _ , err := p .Run (); err != nil {
208+ t .Fatal (err )
209+ }
210+
211+ if m .counter .Load ().(int ) != 10 {
212+ t .Fatalf ("counter should be 10, got %d" , m .counter .Load ())
213+ }
214+ })
143215}
0 commit comments