-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_model.go
65 lines (57 loc) · 1.42 KB
/
run_model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package testutil
import (
"fmt"
"reflect"
"testing"
"unsafe"
tea "github.com/charmbracelet/bubbletea"
)
func RunModel(_ testing.TB, m tea.Model, iterations int, message tea.Msg) string {
if iterations == 0 {
iterations = 1
}
m.Init()
var cmd tea.Cmd = func() tea.Msg {
return message
}
for i := 0; cmd != nil && i < iterations; i++ {
msgs := flatten(cmd())
var nextCmds []tea.Cmd
var next tea.Cmd
for _, msg := range msgs {
fmt.Printf("Message: %+v %+v\n", reflect.TypeOf(msg), msg)
m, next = m.Update(msg)
nextCmds = append(nextCmds, next)
}
cmd = tea.Batch(nextCmds...)
}
return m.View()
}
func flatten(p tea.Msg) (msgs []tea.Msg) {
if p == nil {
return nil
}
if reflect.TypeOf(p).Name() == "batchMsg" {
partials := extractBatchMessages(p)
for _, m := range partials {
msgs = append(msgs, flatten(m)...)
}
} else {
msgs = []tea.Msg{p}
}
return msgs
}
func extractBatchMessages(m tea.Msg) (ret []tea.Msg) {
sliceMsgType := reflect.SliceOf(reflect.TypeOf(tea.Cmd(nil)))
value := reflect.ValueOf(m) // note: this is technically unaddressable
// make our own instance that is addressable
valueCopy := reflect.New(value.Type()).Elem()
valueCopy.Set(value)
cmds := reflect.NewAt(sliceMsgType, unsafe.Pointer(valueCopy.UnsafeAddr())).Elem()
for i := 0; i < cmds.Len(); i++ {
item := cmds.Index(i)
r := item.Call(nil)
ret = append(ret, r[0].Interface().(tea.Msg))
}
return ret
}