-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.go
118 lines (95 loc) · 2 KB
/
app.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
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
package domui
import (
"reflect"
"sync"
"syscall/js"
"time"
"github.com/reusee/dscope"
)
type RootElement Spec
type App struct {
wrapElement js.Value
element js.Value
dirty chan struct{}
rootNode *Node
scope dscope.Scope
scopeLock sync.Mutex
}
func NewApp(
renderElement js.Value,
defs ...any,
) *App {
app := &App{
dirty: make(chan struct{}, 1),
}
defs = append(
defs,
func() Update {
return app.Update
},
func() *App {
return app
},
)
app.scope = dscope.New(defs...)
app.scope = app.scope.Fork(
dscope.Methods(new(Def))...,
)
parentElement := js.Value(renderElement)
parentElement.Set("innerHTML", "")
wrap := document.Call("createElement", "div")
parentElement.Call("appendChild", wrap)
element := document.Call("createElement", "div")
wrap.Call("appendChild", element)
app.wrapElement = wrap
app.element = element
go func() {
for {
select {
case <-app.dirty:
app.Render()
}
}
}()
app.Render()
return app
}
func (a *App) Update(defs ...any) {
a.scopeLock.Lock()
defer a.scopeLock.Unlock()
a.scope = a.scope.Fork(defs...)
select {
case a.dirty <- struct{}{}:
default:
}
}
var rootElementType = reflect.TypeOf((*RootElement)(nil)).Elem()
type SlowRenderThreshold time.Duration
func (_ Def) SlowRenderThreshold() SlowRenderThreshold {
return SlowRenderThreshold(time.Millisecond) * 50
}
func (a *App) Render() {
t0 := time.Now()
var slowThreshold SlowRenderThreshold
defer func() {
e := time.Since(t0)
if e > time.Duration(slowThreshold) {
log("slow render in %v", time.Since(t0))
}
}()
a.scopeLock.Lock()
defer a.scopeLock.Unlock()
var rootElement RootElement
a.scope.Assign(&slowThreshold, &rootElement)
newNode := rootElement.(*Node)
var err error
a.element, err = patch(a.scope, newNode, a.element, a.rootNode)
ce(err)
a.rootNode = newNode
}
func (a *App) HTML() string {
if a.element.InstanceOf(htmlElement) {
return a.element.Get("outerHTML").String()
}
return a.element.Get("nodeValue").String()
}