-
Notifications
You must be signed in to change notification settings - Fork 175
/
renderer-js.go
675 lines (524 loc) · 18.9 KB
/
renderer-js.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
package domrender
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"github.com/vugu/vjson"
"github.com/vugu/vugu"
js "github.com/vugu/vugu/js"
)
//go:generate go run renderer-js-script-maker.go
// NewJSRenderer is an alias for New.
//
// Deprecated: Use New instead.
func NewJSRenderer(mountPointSelector string) (*JSRenderer, error) {
return New(mountPointSelector)
}
// New will create a new JSRenderer with the speicifc mount point selector.
// If an empty string is passed then the root component should include a top level <html> tag
// and the entire page will be rendered.
func New(mountPointSelector string) (*JSRenderer, error) {
ret := &JSRenderer{
MountPointSelector: mountPointSelector,
}
ret.instructionBuffer = make([]byte, 16384)
// ret.instructionTypedArray = js.TypedArrayOf(ret.instructionBuffer)
ret.window = js.Global().Get("window")
ret.window.Call("eval", jsHelperScript)
ret.instructionBufferJS = ret.window.Call("vuguGetRenderArray")
ret.instructionList = newInstructionList(ret.instructionBuffer, func(il *instructionList) error {
// call vuguRender to have the instructions processed in JS
ret.instructionBuffer[il.pos] = 0 // ensure zero terminator
// copy the data over
js.CopyBytesToJS(ret.instructionBufferJS, ret.instructionBuffer)
// then call vuguRender
ret.window.Call("vuguRender" /*, ret.instructionBufferJS*/)
return nil
})
// enable debug logging
// ret.instructionList.logWriter = os.Stdout
ret.eventHandlerBuffer = make([]byte, 16384)
// ret.eventHandlerTypedArray = js.TypedArrayOf(ret.eventHandlerBuffer)
ret.eventHandlerFunc = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) != 1 {
panic(fmt.Errorf("eventHandlerFunc got arg slice not exactly 1 element in length: %#v", args))
}
n := js.CopyBytesToGo(ret.eventHandlerBuffer, args[0])
if n >= len(ret.eventHandlerBuffer) {
panic(errors.New("event data is too large, cannot continue, len: " + strconv.Itoa(n)))
}
ret.handleDOMEvent() // discard this and args, all data should be in eventHandlerBuffer; avoid using js.Value
return nil
// return jsEnv.handleRawDOMEvent(this, args)
})
// wire up the event handler func and the array that we used to communicate with instead of js.Value
// ret.window.Call("vuguSetEventHandlerAndBuffer", ret.eventHandlerFunc, ret.eventHandlerTypedArray)
// wire up callback handler
ret.window.Call("vuguSetCallbackHandler", js.FuncOf(ret.handleCallback))
// wire up the event handler func
ret.window.Call("vuguSetEventHandler", ret.eventHandlerFunc)
// log.Printf("ret.window: %#v", ret.window)
// log.Printf("eval: %#v", ret.window.Get("eval"))
ret.eventWaitCh = make(chan bool, 64)
ret.eventEnv = vugu.NewEventEnvImpl(
&ret.eventRWMU,
ret.eventWaitCh,
)
return ret, nil
}
type jsRenderState struct {
// stores positionID to slice of DOMEventHandlerSpec
domHandlerMap map[string][]vugu.DOMEventHandlerSpec
// callback stuff is handled by callbackManager
callbackManager callbackManager
}
func newJsRenderState() *jsRenderState {
return &jsRenderState{
domHandlerMap: make(map[string][]vugu.DOMEventHandlerSpec, 8),
}
}
// JSRenderer implements Renderer against the browser's DOM.
type JSRenderer struct {
MountPointSelector string
eventWaitCh chan bool // events send to this and EventWait receives from it
eventRWMU sync.RWMutex // make sure Render and event handling are not attempted at the same time (not totally sure if this is necessary in terms of the wasm threading model but enforce it with a rwmutex all the same)
eventEnv *vugu.EventEnvImpl // our EventEnv implementation that exposes eventRWMU and eventWaitCh to events in a clean way
eventHandlerFunc js.Func // the callback function for DOM events
eventHandlerBuffer []byte
// eventHandlerTypedArray js.TypedArray
instructionBuffer []byte // our local instruction buffer
instructionBufferJS js.Value // a Uint8Array on the JS side that we copy into
instructionList *instructionList
window js.Value
jsRenderState *jsRenderState
}
// EventEnv returns an EventEnv that can be used for synchronizing updates.
func (r *JSRenderer) EventEnv() vugu.EventEnv {
return r.eventEnv
}
// Release calls release on any resources that this renderer allocated.
func (r *JSRenderer) Release() {
// NOTE: seems sensible to leave this here in case we do need something to be released, better than
// omitting it and people getting used to no release being needed and then requiring it later.
// r.instructionTypedArray.Release()
}
// Render implements Renderer.
func (r *JSRenderer) render(buildResults *vugu.BuildResults) error {
bo := buildResults.Out
if !js.Global().Truthy() {
return errors.New("js environment not available")
}
if bo == nil {
return errors.New("BuildOut is nil")
}
if len(bo.Out) != 1 {
return errors.New("BuildOut.Out has bad len " + strconv.Itoa(len(bo.Out)))
}
if bo.Out[0].Type != vugu.ElementNode {
return errors.New("BuildOut.Out[0].Type is not vugu.ElementNode: " + strconv.Itoa(int(bo.Out[0].Type)))
}
// always make sure we have at least a non-nil render state
if r.jsRenderState == nil {
r.jsRenderState = newJsRenderState()
}
state := r.jsRenderState
state.callbackManager.startRender()
defer state.callbackManager.doneRender()
// TODO: move this next chunk out to it's own func at least
visitCSSList := func(cssList []*vugu.VGNode) error {
// CSS stuff first
for _, cssEl := range cssList {
// some basic sanity checking
if cssEl.Type != vugu.ElementNode || !(cssEl.Data == "style" || cssEl.Data == "link") {
return errors.New("CSS output must be link or style tag")
}
var textBuf bytes.Buffer
for childN := cssEl.FirstChild; childN != nil; childN = childN.NextSibling {
if childN.Type != vugu.TextNode {
return fmt.Errorf("CSS tag must contain only text children, found %v instead: %#v", childN.Type, childN)
}
textBuf.WriteString(childN.Data)
}
var attrPairs []string
if len(cssEl.Attr) > 0 {
attrPairs = make([]string, 0, len(cssEl.Attr)*2)
for _, attr := range cssEl.Attr {
attrPairs = append(attrPairs, attr.Key, attr.Val)
}
}
err := r.instructionList.writeSetCSSTag(cssEl.Data, textBuf.Bytes(), attrPairs)
if err != nil {
return err
}
}
return nil
}
var walkCSSBuildOut func(buildOut *vugu.BuildOut) error
walkCSSBuildOut = func(buildOut *vugu.BuildOut) error {
err := visitCSSList(buildOut.CSS)
if err != nil {
return err
}
for _, c := range buildOut.Components {
// nextBuildOut := buildResults.AllOut[c]
nextBuildOut := buildResults.ResultFor(c)
if nextBuildOut == nil {
panic(fmt.Errorf("walkCSSBuildOut nextBuildOut was nil for %#v", c))
}
err := walkCSSBuildOut(nextBuildOut)
if err != nil {
return err
}
}
return nil
}
err := walkCSSBuildOut(bo)
if err != nil {
return err
}
err = r.instructionList.writeRemoveOtherCSSTags()
if err != nil {
return err
}
// main output
err = r.visitFirst(state, bo, buildResults, bo.Out[0], []byte("0"))
if err != nil {
return err
}
// // JS stuff last
// // log.Printf("TODO: handle JS")
err = r.instructionList.flush()
if err != nil {
return err
}
return nil
}
// EventWait blocks until an event has occurred which causes a re-render.
// It returns true if the render loop should continue or false if it should exit.
func (r *JSRenderer) EventWait() (ok bool) {
// make sure the JS environment is still available, returning false otherwise
if !js.Global().Truthy() {
return false
}
// FIXME: this should probably have some sort of "debouncing" on it to handle the case of
// several events in rapid succession causing multiple renders - maybe we read from eventWaitCH
// continuously until it's empty, with a max of like 20ms pause between each or something, and then
// only return after we don't see anything for that time frame.
ok = <-r.eventWaitCh
return
}
// var window js.Value
// func init() {
// window = js.Global().Get("window")
// if window.Truthy() {
// js.Global().Call("eval", jsHelperScript)
// }
// }
func (r *JSRenderer) visitFirst(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
// log.Printf("TODO: We need to go through and optimize away unneeded calls to create elements, set attributes, set event handlers, etc. for cases where they are the same per hash")
// log.Printf("JSRenderer.visitFirst")
if n.Type != vugu.ElementNode {
return errors.New("root of component must be element")
}
err := r.instructionList.writeClearEl()
if err != nil {
return err
}
// first tag is html
if strings.ToLower(n.Data) == "html" {
err := r.syncHtml(state, n, []byte("html"))
if err != nil {
return err
}
for nchild := n.FirstChild; nchild != nil; nchild = nchild.NextSibling {
if strings.ToLower(nchild.Data) == "head" {
err := r.visitHead(state, bo, br, nchild, []byte("head"))
if err != nil {
return err
}
} else if strings.ToLower(nchild.Data) == "body" {
err := r.visitBody(state, bo, br, nchild, []byte("body"))
if err != nil {
return err
}
} else {
return fmt.Errorf("unexpected tag inside html %q (VGNode=%#v)", nchild.Data, nchild)
}
}
return nil
}
// else, first tag is anything else - try again as the element to be mounted
return r.visitMount(state, bo, br, n, positionID)
}
func (r *JSRenderer) syncHtml(state *jsRenderState, n *vugu.VGNode, positionID []byte) error {
err := r.instructionList.writeSelectQuery("html")
if err != nil {
return err
}
return r.syncElement(state, n, positionID)
}
func (r *JSRenderer) visitHead(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
err := r.instructionList.writeSelectQuery("head")
if err != nil {
return err
}
err = r.syncElement(state, n, positionID)
if err != nil {
return err
}
return nil
}
func (r *JSRenderer) visitBody(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
err := r.instructionList.writeSelectQuery("body")
if err != nil {
return err
}
err = r.syncElement(state, n, positionID)
if err != nil {
return err
}
if !(n.FirstChild != nil && n.FirstChild.NextSibling == nil) {
return errors.New("body tag must contain exactly one element child")
}
return r.visitMount(state, bo, br, n.FirstChild, positionID)
}
func (r *JSRenderer) visitMount(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
// log.Printf("visitMount got here")
err := r.instructionList.writeSelectMountPoint(r.MountPointSelector, n.Data)
if err != nil {
return err
}
return r.visitSyncElementEtc(state, bo, br, n, positionID)
}
func (r *JSRenderer) visitSyncNode(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
// log.Printf("visitSyncNode")
var err error
// check for Component, in which case we descend into it instead of processing like a regular node
if n.Component != nil {
compBuildOut := br.ResultFor(n.Component)
if len(compBuildOut.Out) != 1 {
return fmt.Errorf("component %#v expected exactly one Out element but got %d instead",
n.Component, len(compBuildOut.Out))
}
return r.visitSyncNode(state, compBuildOut, br, compBuildOut.Out[0], positionID)
}
// check for template (used by vg-template and vg-slot) in which case we process the children directly and ignore n
if n.IsTemplate() {
childIndex := 1
for nchild := n.FirstChild; nchild != nil; nchild = nchild.NextSibling {
// use a different character here for the position to ensure it's unique
childPositionID := append(positionID, []byte(fmt.Sprintf("_t_%d", childIndex))...)
err = r.visitSyncNode(state, bo, br, nchild, childPositionID)
if err != nil {
return err
}
// if there are more children, advance to the next
if nchild.NextSibling != nil {
err = r.instructionList.writeMoveToNextSibling()
if err != nil {
return err
}
}
childIndex++
}
// element is fully handled
return nil
}
switch n.Type {
case vugu.ElementNode:
// check if this element has a namespace set
if ns := namespaceToURI(n.Namespace); ns != "" {
err = r.instructionList.writeSetElementNS(n.Data, ns)
} else {
err = r.instructionList.writeSetElement(n.Data)
}
if err != nil {
return err
}
case vugu.TextNode:
return r.instructionList.writeSetText(n.Data) // no children possible, just return
case vugu.CommentNode:
return r.instructionList.writeSetComment(n.Data) // no children possible, just return
default:
return errors.New("unknown node type: " + strconv.Itoa(int(n.Type)))
}
// only elements have attributes, child or events
return r.visitSyncElementEtc(state, bo, br, n, positionID)
}
// visitSyncElementEtc syncs the rest of the stuff that only applies to elements
func (r *JSRenderer) visitSyncElementEtc(state *jsRenderState, bo *vugu.BuildOut, br *vugu.BuildResults, n *vugu.VGNode, positionID []byte) error {
err := r.syncElement(state, n, positionID)
if err != nil {
return err
}
if n.InnerHTML != nil {
return r.instructionList.writeSetInnerHTML(*n.InnerHTML)
}
// tell callbackManager about the create and populate functions
// (if present, otherwise this is a nop and will return 0,0)
cid, pid := state.callbackManager.addCreateAndPopulateHandlers(n.JSCreateHandler, n.JSPopulateHandler)
// for vg-js-create, send an instruction to call us back when this element is created
// (handled by callbackManager)
if cid != 0 {
err := r.instructionList.writeCallbackLastElement(cid)
if err != nil {
return err
}
}
if n.FirstChild != nil {
err = r.instructionList.writeMoveToFirstChild()
if err != nil {
return err
}
childIndex := 1
for nchild := n.FirstChild; nchild != nil; nchild = nchild.NextSibling {
childPositionID := append(positionID, []byte(fmt.Sprintf("_%d", childIndex))...)
err = r.visitSyncNode(state, bo, br, nchild, childPositionID)
if err != nil {
return err
}
// log.Printf("GOT HERE X: %#v", n)
err = r.instructionList.writeMoveToNextSibling()
if err != nil {
return err
}
childIndex++
}
err = r.instructionList.writeMoveToParent()
if err != nil {
return err
}
}
// for vg-js-populate, send an instruction to call us back again with the populate flag for this same one
// (handled by callbackManager)
if pid != 0 {
err := r.instructionList.writeCallback(pid)
if err != nil {
return err
}
}
return nil
}
func (r *JSRenderer) syncElement(state *jsRenderState, n *vugu.VGNode, positionID []byte) error {
if namespaceToURI(n.Namespace) != "" {
for _, a := range n.Attr {
ns := namespaceToURI(a.Namespace)
// FIXME: we skip Namespace="" && Key = "xmlns" here, because this WILL cause an js exception
// the correct way would be, to parse the xmlns attribute in the generator, set the namespace of the holding element
// and then forget about this attribute
if ns == "" && a.Key == "xmlns" {
continue
}
err := r.instructionList.writeSetAttrNSStr(ns, a.Key, a.Val)
if err != nil {
return err
}
}
} else {
for _, a := range n.Attr {
err := r.instructionList.writeSetAttrStr(a.Key, a.Val)
if err != nil {
return err
}
}
}
err := r.instructionList.writeRemoveOtherAttrs()
if err != nil {
return err
}
// do any JS properties
for _, p := range n.Prop {
err := r.instructionList.writeSetProperty(p.Key, []byte(p.JSONVal))
if err != nil {
return err
}
}
if len(n.DOMEventHandlerSpecList) > 0 {
// store in domHandlerMap
state.domHandlerMap[string(positionID)] = n.DOMEventHandlerSpecList
for _, hs := range n.DOMEventHandlerSpecList {
err := r.instructionList.writeSetEventListener(positionID, hs.EventType, hs.Capture, hs.Passive)
if err != nil {
return err
}
}
}
// always write the remove for event listeners so any previous ones are taken away
return r.instructionList.writeRemoveOtherEventListeners(positionID)
}
// // writeAllStaticAttrs is a helper to write all the static attrs from a VGNode
// func (r *JSRenderer) writeAllStaticAttrs(n *vugu.VGNode) error {
// for _, a := range n.Attr {
// err := r.instructionList.writeSetAttrStr(a.Key, a.Val)
// if err != nil {
// return err
// }
// }
// return nil
// }
func (r *JSRenderer) handleCallback(this js.Value, args []js.Value) interface{} {
return r.jsRenderState.callbackManager.callback(this, args)
}
func (r *JSRenderer) handleDOMEvent() {
strlen := binary.BigEndian.Uint32(r.eventHandlerBuffer[:4])
b := r.eventHandlerBuffer[4 : strlen+4]
// log.Printf("handleDOMEvent JSON from event buffer: %q", b)
// var ee eventEnv
// rwmu *sync.RWMutex
// requestRenderCH chan bool
var eventDetail struct {
PositionID string // `json:"position_id"`
EventType string // `json:"event_type"`
Capture bool // `json:"capture"`
Passive bool // `json:"passive"`
// the event object data as extracted above
EventSummary map[string]interface{} // `json:"event_summary"`
}
edm := make(map[string]interface{}, 6)
// err := json.Unmarshal(b, &eventDetail)
err := vjson.Unmarshal(b, &edm)
if err != nil {
panic(err)
}
// manually extract fields
eventDetail.PositionID, _ = edm["position_id"].(string)
eventDetail.EventType, _ = edm["event_type"].(string)
eventDetail.Capture, _ = edm["capture"].(bool)
eventDetail.Passive, _ = edm["passive"].(bool)
eventDetail.EventSummary, _ = edm["event_summary"].(map[string]interface{})
domEvent := vugu.NewDOMEvent(r.eventEnv, eventDetail.EventSummary)
// log.Printf("eventDetail: %#v", eventDetail)
// it is important that we lock around accessing anything that might change (domHandlerMap)
// and around the invokation of the handler call itself
r.eventRWMU.Lock()
handlers := r.jsRenderState.domHandlerMap[eventDetail.PositionID]
var f func(vugu.DOMEvent)
for _, h := range handlers {
if h.EventType == eventDetail.EventType && h.Capture == eventDetail.Capture {
f = h.Func
break
}
}
// make sure we found something, panic if not
if f == nil {
r.eventRWMU.Unlock()
panic(fmt.Errorf("Unable to find event handler for positionID=%q, eventType=%q, capture=%v",
eventDetail.PositionID, eventDetail.EventType, eventDetail.Capture))
}
// NOTE: For tinygo support we are not using defer here for now - it would probably be better to do so since
// the handler can panic. However, Vugu program behavior after panicing from an event is currently
// undefined so whatever for now. We'll have to make a decision later about whether or not Vugu
// programs should keep running after an event handler panics. They do in JS after an exception,
// but... this is not JS. Needs more thought.
// invoke handler
f(domEvent)
r.eventRWMU.Unlock()
// TODO: Also give this more thought: For now we just do a non-blocking push to the
// eventWaitCh, telling the render loop that a render is required, but if a bunch
// of them stack up we don't wait
r.sendEventWaitCh()
}