-
Notifications
You must be signed in to change notification settings - Fork 0
/
vgnode.go
336 lines (283 loc) · 9.58 KB
/
vgnode.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package vugu
import (
"bytes"
"encoding/binary"
"fmt"
"sort"
"github.com/cespare/xxhash"
// FIXME: see if we can clean it up programs which only use VGNode at run time (i.e in wasm)
// will not end up bundling this library for no reason - means the init() below needs to be cleaned up
// and probably have cruftBody be a function using once.Do - only needed if something calls it.
"golang.org/x/net/html"
)
// Things to sort out:
// * vg-if, vg-range, etc (JUST COPIED FROM ATTRS, EVALUATED LATER)
// * :whatever syntax (ALSO JUST COPIED FROM ATTRS, EVALUATED LATER)
// * vg-model (IGNORE FOR NOW, WILL BE COMPOSED FROM OTHER FEATURES)
// * @click and other events (JUST A METHOD NAME TO INVOKE ON THE COMPONENT TYPE)
// * components and their properties (TAG NAME IS JUST CHECKED LATER, AND IF MATCH CAUSES THE EVAL STEPS ABOVE TO USE A DIFFERENT PATH, ATTRS GET REFS INSTEAD OF TEXT RENDER ETC)
// actually, we should rework this so they are function pointers... and the
// template compilation can support actual Go code
// VDom states: Just one, after being converted from html.Node
// VGNodeType is one of the valid node types (error, text, docuemnt, element, comment, doctype).
// Note that only text, element and comment are currently used.
type VGNodeType uint32
// Available VGNodeTypes.
const (
ErrorNode = VGNodeType(html.ErrorNode)
TextNode = VGNodeType(html.TextNode)
DocumentNode = VGNodeType(html.DocumentNode)
ElementNode = VGNodeType(html.ElementNode)
CommentNode = VGNodeType(html.CommentNode)
DoctypeNode = VGNodeType(html.DoctypeNode)
)
// VGAtom is an integer corresponding to golang.org/x/net/html/atom.Atom.
// Note that this may be removed for simplicity and to remove the dependency
// on the package above. Suggest you don't use it.
type VGAtom uint32
// VGAttribute is the attribute on an HTML tag.
type VGAttribute struct {
Namespace, Key, Val string
}
func attrFromHtml(attr html.Attribute) VGAttribute {
return VGAttribute{
Namespace: attr.Namespace,
Key: attr.Key,
Val: attr.Val,
}
}
// VGNode represents a node from our virtual DOM with the dynamic parts wired up into functions.
type VGNode struct {
Parent, FirstChild, LastChild, PrevSibling, NextSibling *VGNode
Type VGNodeType
DataAtom VGAtom
Data string
Namespace string
Attr []VGAttribute
Props Props // dynamic attributes, used as input for components or converted to attributes for regular HTML elements
InnerHTML string // indicates that children should be ignored and this raw HTML is the children of this tag
DOMEventHandlers map[string]DOMEventHandler // describes invocations when DOM events happen
// default of 0 means it will be calculated when positionHash() is called
positionHashVal uint64
}
// SetDOMEventHandler will assign a named event to DOMEventHandlers (will allocate the map if nil).
// Used during VDOM construction and during render to determine browser events to hook up.
func (n *VGNode) SetDOMEventHandler(name string, h DOMEventHandler) {
if n.DOMEventHandlers == nil {
n.DOMEventHandlers = map[string]DOMEventHandler{name: h}
return
}
n.DOMEventHandlers[name] = h
}
// InsertBefore inserts newChild as a child of n, immediately before oldChild
// in the sequence of n's children. oldChild may be nil, in which case newChild
// is appended to the end of n's children.
//
// It will panic if newChild already has a parent or siblings.
func (n *VGNode) InsertBefore(newChild, oldChild *VGNode) {
if newChild.Parent != nil || newChild.PrevSibling != nil || newChild.NextSibling != nil {
panic("html: InsertBefore called for an attached child Node")
}
var prev, next *VGNode
if oldChild != nil {
prev, next = oldChild.PrevSibling, oldChild
} else {
prev = n.LastChild
}
if prev != nil {
prev.NextSibling = newChild
} else {
n.FirstChild = newChild
}
if next != nil {
next.PrevSibling = newChild
} else {
n.LastChild = newChild
}
newChild.Parent = n
newChild.PrevSibling = prev
newChild.NextSibling = next
}
// AppendChild adds a node c as a child of n.
//
// It will panic if c already has a parent or siblings.
func (n *VGNode) AppendChild(c *VGNode) {
if c.Parent != nil || c.PrevSibling != nil || c.NextSibling != nil {
panic("html: AppendChild called for an attached child Node")
}
last := n.LastChild
if last != nil {
last.NextSibling = c
} else {
n.FirstChild = c
}
n.LastChild = c
c.Parent = n
c.PrevSibling = last
}
// RemoveChild removes a node c that is a child of n. Afterwards, c will have
// no parent and no siblings.
//
// It will panic if c's parent is not n.
func (n *VGNode) RemoveChild(c *VGNode) {
if c.Parent != n {
panic("html: RemoveChild called for a non-child Node")
}
if n.FirstChild == c {
n.FirstChild = c.NextSibling
}
if c.NextSibling != nil {
c.NextSibling.PrevSibling = c.PrevSibling
}
if n.LastChild == c {
n.LastChild = c.PrevSibling
}
if c.PrevSibling != nil {
c.PrevSibling.NextSibling = c.NextSibling
}
c.Parent = nil
c.PrevSibling = nil
c.NextSibling = nil
}
// type IfFunc func(data interface{}) (bool, error)
// Walk will walk the tree under a VGNode using the specified callback function.
// If the function provided returns a non-nil error then walking will be stopped
// and this error will be returned. Only FirstChild and NextSibling are used
// while walking and so with well-formed documents should not loop. (But loops
// created manually by modifying FirstChild or NextSibling pointers could cause
// this function to recurse indefinitely.) Note that f may modify nodes as it
// visits them with predictable results as long as it does not modify elements
// higher on the tree (up, toward the parent); it is safe to modify self and children.
func (vgn *VGNode) Walk(f func(*VGNode) error) error {
if vgn == nil {
return nil
}
err := f(vgn)
if err != nil {
return err
}
err = vgn.FirstChild.Walk(f)
if err != nil {
return err
}
err = vgn.NextSibling.Walk(f)
if err != nil {
return err
}
return nil
}
// positionHash calculates a hash based on position in the tree only (specifically it does not consider element attributes),
// stores the result in positionHashVal and returns it.
// The same element position will have the same hash, regardless of element contents. Each unique position in the vdom should have
// a unique positionHash value, allowing for the usual hash collision caveat.
// (subsequent calls return positionHashVal). Special case: root nodes (Parent==nil) always return 0.
// This is used to efficiently answer the question "is this vdom element structurally in the same position as ...".
func (vgn *VGNode) positionHash() uint64 {
if vgn.positionHashVal != 0 {
return vgn.positionHashVal
}
// root element always returns 0
if vgn.Parent == nil {
return 0
}
b8 := make([]byte, 8)
h := xxhash.New()
// hash in parent's positionHash
binary.BigEndian.PutUint64(b8, vgn.Parent.positionHash())
h.Write(b8)
// calculate our sibling depth
var n uint64
for prev := vgn.PrevSibling; prev != nil; prev = prev.PrevSibling {
n++
}
// hash in sibling depth
binary.BigEndian.PutUint64(b8, n)
h.Write(b8)
// that's it
vgn.positionHashVal = h.Sum64()
return vgn.positionHashVal
}
// elementHash calculates and returns a hash of just the contents of this element - it's type, Data, Attrs and Props and InnerHTML,
// it specifically does not include element position data like any of the Parent, NextSibling, etc pointers.
// The same element at different positions in the tree, assuming the same start param, will result in the same hash.
// FIXME: will need to add events here.
// The return value is not cached, it is calculated newly each time.
// A starting point to be hashed in can be provided also if needed, otherwise pass 0.
func (vgn *VGNode) elementHash(start uint64) uint64 {
b8 := make([]byte, 8)
h := xxhash.New()
if start != 0 {
binary.BigEndian.PutUint64(b8, start)
h.Write(b8)
}
// type (element, text, comment)
binary.BigEndian.PutUint64(b8, uint64(vgn.Type))
h.Write(b8)
// name of the element or text content
fmt.Fprint(h, vgn.Data)
// hash static attrs
for _, a := range vgn.Attr {
fmt.Fprint(h, a.Key)
fmt.Fprint(h, a.Val)
}
// hash props (dynamic attrs)
pks := vgn.Props.OrderedKeys() // stable sequence
for _, pk := range pks {
fmt.Fprint(h, pk) // key goes in as string
// use ComputeHash on the value because we don't know it's type
vh := ComputeHash(vgn.Props[pk])
binary.BigEndian.PutUint64(b8, vh)
h.Write(b8)
}
// hash events
if len(vgn.DOMEventHandlers) > 0 {
keys := make([]string, len(vgn.DOMEventHandlers))
for k := range vgn.DOMEventHandlers {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vh := vgn.DOMEventHandlers[k].hash()
binary.BigEndian.PutUint64(b8, vh)
h.Write(b8)
}
}
// innerHTML if any
if vgn.InnerHTML != "" {
fmt.Fprint(h, vgn.InnerHTML)
}
return h.Sum64()
}
var cruftHtml *html.Node
var cruftBody *html.Node
func init() {
// startTime := time.Now()
// defer func() { log.Printf("init() took %v", time.Since(startTime)) }() // NOTE: 35us on my laptop
n, err := html.Parse(bytes.NewReader([]byte(`<html><body></body></html>`)))
if err != nil {
panic(err)
}
cruftHtml = n
// find the body tag and store in cruftBody
var walk func(n *html.Node)
walk = func(n *html.Node) {
// log.Printf("walk: %#v", n)
if n == nil {
return
}
if n.Type == html.ElementNode && n.Data == "body" {
cruftBody = n
return
}
if n.FirstChild != nil {
walk(n.FirstChild)
}
if n.NextSibling != nil {
walk(n.NextSibling)
}
}
walk(cruftHtml)
if cruftBody == nil {
panic("unable to find <body> tag in html, something went terribly wrong")
}
}