-
Notifications
You must be signed in to change notification settings - Fork 17
/
nodes.go
85 lines (75 loc) · 1.68 KB
/
nodes.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package spot
type Node struct {
Content Control
Children []Node
}
func (n Node) Mount() {
n.mount(nil)
}
func (n Node) mount(parent Control) {
if n.Content != nil {
n.Content.Mount(parent)
}
for _, child := range n.Children {
child.mount(n.Content)
}
}
func (n *Node) updateChild(idx int, new Control) {
old := n.Children[idx].Content
if old == nil && new == nil {
return
}
if old != nil && new == nil {
if unmountable, ok := old.(Unmountable); ok {
unmountable.Unmount()
}
n.Children[idx].Content = nil
return
}
if old == nil && new != nil {
n.Children[idx].Content = new
new.Mount(n.Content)
return
}
ok := old.Update(new)
if !ok {
if unmountable, ok := old.(Unmountable); ok {
unmountable.Unmount()
}
n.Children[idx].Content = new
new.Mount(n.Content)
}
}
func (n *Node) Update(other Node, parent Control) {
if n.Content != nil && other.Content == nil {
if unmountable, ok := n.Content.(Unmountable); ok {
unmountable.Unmount()
}
n.Content = nil
} else if n.Content == nil && other.Content != nil {
n.Content = other.Content
n.Content.Mount(parent)
} else if n.Content != nil && other.Content != nil {
ok := n.Content.Update(other.Content)
if !ok {
if unmountable, ok := n.Content.(Unmountable); ok {
unmountable.Unmount()
}
n.Content = other.Content
n.Content.Mount(parent)
}
}
if len(n.Children) != len(other.Children) {
for idx := range n.Children {
n.updateChild(idx, nil)
}
n.Children = make([]Node, len(other.Children))
for idx := range n.Children {
n.updateChild(idx, other.Children[idx].Content)
}
return
}
for idx := range n.Children {
n.updateChild(idx, other.Children[idx].Content)
}
}