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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
package tui
import "github.com/grindlemire/go-tui/internal/debug"
type mountKey struct {
parent Component
index int
}
type mountState struct {
cache map[mountKey]Component
cleanups map[mountKey]func()
activeKeys map[mountKey]bool
persistKeys map[mountKey]bool
}
func newMountState() *mountState {
return &mountState{
cache: make(map[mountKey]Component),
cleanups: make(map[mountKey]func()),
activeKeys: make(map[mountKey]bool),
persistKeys: make(map[mountKey]bool),
}
}
type PropsUpdater interface {
UpdateProps(fresh Component)
}
func (a *App) mount(parent Component, index int, factory func() Component) *Element {
app := a
ms := app.mounts
key := mountKey{parent: parent, index: index}
ms.activeKeys[key] = true
instance, cached := ms.cache[key]
if !cached {
instance = factory()
ms.cache[key] = instance
debug.Log("Mount: NEW component at index %d, type %T", index, instance)
if binder, ok := instance.(AppBinder); ok {
binder.BindApp(app)
}
if init, ok := instance.(Initializer); ok {
cleanup := init.Init()
if cleanup != nil {
ms.cleanups[key] = cleanup
}
}
} else {
if updater, ok := instance.(PropsUpdater); ok {
fresh := factory()
debug.Log("Mount: CACHED component at index %d, calling UpdateProps, type %T", index, instance)
updater.UpdateProps(fresh)
} else {
debug.Log("Mount: CACHED component at index %d, NO UpdateProps, type %T", index, instance)
}
if binder, ok := instance.(AppBinder); ok {
binder.BindApp(app)
}
}
el := instance.Render(a)
el.component = instance
return el
}
func (a *App) Mount(parent Component, index int, factory func() Component) *Element {
return a.mount(parent, index, factory)
}
func (a *App) MountPersistent(parent Component, index int, factory func() Component) *Element {
key := mountKey{parent: parent, index: index}
a.mounts.persistKeys[key] = true
return a.mount(parent, index, factory)
}
func (ms *mountState) sweep() {
for key := range ms.cache {
if !ms.activeKeys[key] && !ms.persistKeys[key] {
if unbinder, ok := ms.cache[key].(AppUnbinder); ok {
unbinder.UnbindApp()
}
if cleanup, ok := ms.cleanups[key]; ok {
cleanup()
delete(ms.cleanups, key)
}
delete(ms.cache, key)
}
}
ms.activeKeys = make(map[mountKey]bool)
}
|