/
vnode.ts
1984 lines (1865 loc) · 64.5 KB
/
vnode.ts
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { printError } from "./debug";
import { SvgNamespace, VNodeFlags, VNodeDebugFlags, ComponentDescriptorFlags, setAttr } from "./misc";
import { Component, ComponentDescriptor, updateComponent } from "./component";
import { ElementDescriptor } from "./element_descriptor";
/**
* Virtual DOM Node.
*
* VNode object is the core object in kivi Virtual DOM, it can represent any node type.
*
* The easiest way to create VNode instances is to use factory functions:
*
* // HTMLElement
* const htmlElement = createVElement("div");
* // SVGElement
* const svgElement = createVSvgElement("a");
* // Text node
* const textNode = createVText("text content");
* // Component's root node
* const root = createVRoot();
*
* VNode instances can't be reused to represent multiple DOM nodes.
*
* @final
*/
export class VNode {
/**
* Flags, see `VNodeFlags` for details.
*/
_flags: VNodeFlags;
/**
* Tag name of the element, reference to an ElementDescriptor, or ComponentDescriptor if this node represents a
* component.
*/
_tag: string | ElementDescriptor<any> | ComponentDescriptor<any, any> | null;
/**
* Children reconciliation algorithm is using key property to find the same node in the previous children array. Key
* should be unique among its siblings.
*/
_key: any;
/**
* Properties.
*
* When virtual node represents an element, props property is used to set properties directly on DOM node:
*
* e: HTMLElement;
* e.propertyName = propertyValue;
*
* When virtual node is mounted on top of existing HTML, all properties will be assigned during mounting phase.
*/
_props: any;
/**
* Attributes.
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*/
_attrs: { [key: string]: any } | null;
/**
* Style in css string format.
*
* Style is assigned to DOM nodes with `style.cssText` property, if virtual node represents an element from svg
* namespace, style will be assigned with `setAttribute("style", "cssText")` method.
*/
_style: string | null;
/**
* Class name.
*
* Class name is assigned to DOM nodes with `className` property, if virtual node represents an element from svg
* namespace, class name will be assigned with `setAttribute("class", "className")` method.
*/
_className: string | null;
/**
* Children property can contain flat array of children virtual nodes, or text if it contains a single text node
* child. If virtual node represents an input field, children property will contain input value.
*/
_children: VNode[] | VNode | string | boolean | null;
/**
* Reference to HTML Node. It will be available after virtual node is created or synced. Each time VNode is synced,
* reference to the HTML Node is transferred from old virtual node to the new one.
*/
ref: Node | null;
/**
* Reference to a Component. If virtual node is a Component, then cref will be available after virtual node is
* created or synced. Each time virtual node is synced, reference to a Component is transferred from old virtual
* node to the new one.
*/
cref: Component<any, any> | null;
/**
* Flags used in DEBUG mode.
*
* See `VNodeDebugFlags` for details.
*/
_debugFlags: number;
constructor(flags: number, tag: string | ElementDescriptor<any> | ComponentDescriptor<any, any> | null, props: any) {
this._flags = flags;
this._tag = tag;
this._key = null;
this._props = props;
this._attrs = null;
this._style = null;
this._className = null;
this._children = null;
this.ref = null;
this.cref = null;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
this._debugFlags = 0;
}
}
/**
* Set key.
*
* Children reconciliation algorithm is using key property to find the same node in the previous children array. Key
* should be unique among its siblings.
*
* This method is available in all virtual node types.
*/
key(key: any): VNode {
this._key = key;
return this;
}
/**
* Set properties with static shape.
*
* Each time virtual node representing the same DOM node is created, it should have properties with exactly the same
* shape. Values can be different, but all keys should be the same. For example:
*
* const a = createVElement("div").props({"id": "Main", "title": "Title"});
* const b = createVElement("div").props({"id": "Main", "title": "New Title"});
*
* Props property is used to set properties directly on DOM node:
*
* e: HTMLElement;
* e.propertyName = propertyValue;
*
* When virtual node is mounted on top of existing HTML, all properties will be assigned during mounting phase.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
props(props: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set props on VNode: props method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set props on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._props !== null) {
const keys = Object.keys(props);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._props.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set props on VNode: VNode is using ElementDescriptor that uses the same` +
` property "${keys[i]}".`);
}
}
}
}
}
this._props = props;
return this;
}
/**
* Set attributes with static shape.
*
* Each time virtual node representing the same DOM node is created, it should have attributes with exactly the same
* shape. Values can be different, but all keys should be the same. For example:
*
* const a = createVElement("div").attrs({"id": "Main", "title": "Title"});
* const b = createVElement("div").attrs({"id": "Main", "title": "New Title"});
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
attrs(attrs: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set attrs on VNode: attrs method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set attrs on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._attrs !== null) {
const keys = Object.keys(attrs);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._attrs.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set attrs on VNode: VNode is using ElementDescriptor that uses the same` +
` attribute "${keys[i]}".`);
}
}
}
}
}
this._attrs = attrs;
return this;
}
/**
* Set attributes with dynamic shape.
*
* Attributes can have different set of keys, when reconciliation algorithm updates attribute values, it will remove
* attributes with `removeAttribute` method for all missing keys.
*
* const a = createVElement("div").props({"id": "Main", "title": "Title"});
* const b = createVElement("div").props({"id": "Main"});
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
dynamicShapeAttrs(attrs?: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set attrs on VNode: attrs method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set attrs on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._attrs !== null) {
const keys = Object.keys(attrs);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._attrs.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set attrs on VNode: VNode is using ElementDescriptor that uses the same` +
` attribute "${keys[i]}".`);
}
}
}
}
}
this._flags |= VNodeFlags.DynamicShapeAttrs;
this._attrs = attrs === undefined ? null : attrs;
return this;
}
/**
* Set data for ElementDescriptor update handler.
*
* This method is available on element and component's root virtual node types.
*/
data(data: any): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root | VNodeFlags.ElementDescriptor)) === 0) {
throw new Error("Failed to set data on VNode: data method should be called on element or component" +
" root nodes represented by ElementDescriptors only.");
}
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {
throw new Error("Failed to set data on VNode: VNode should be using ElementDescriptor with update handler.");
}
}
this._props = data;
return this;
}
/**
* Set style in css string format.
*
* Style is assigned to DOM nodes with `style.cssText` property, if virtual node represents an element from svg
* namespace, style will be assigned with `setAttribute("style", "cssText")` method.
*
* This method is available on element and component's root virtual node types.
*/
style(style: string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set style on VNode: style method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with custom update handler.");
}
if (((this._tag as ElementDescriptor<any>)._style) !== null) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with assigned style.");
}
}
}
this._style = style;
return this;
}
/**
* Set className.
*
* Class name is assigned to DOM nodes with `className` property, if virtual node represents an element from svg
* namespace, class name will be assigned with `setAttribute("class", "className")` method.
*
* This method is available on element and component's root virtual node types.
*/
className(className: string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set className on VNode: className method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with update handler.");
}
if (((this._tag as ElementDescriptor<any>)._className) !== null) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with assigned className.");
}
}
}
this._className = className;
return this;
}
/**
* Set single child.
*
* This method is available on element and component's root virtual node types.
*/
child(child: VNode | string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set child on VNode: child method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set child on VNode: input elements can't have children.");
}
}
this._children = child;
return this;
}
/**
* Set children.
*
* This method is available on element and component's root virtual node types.
*/
children(children: VNode[] | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set children on VNode: children method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set children on VNode: input elements can't have children.");
}
}
this._flags |= VNodeFlags.ArrayChildren;
this._children = children;
return this;
}
/**
* Set children as an innerHTML string. It is potentially vulnerable to XSS attacks.
*
* This method is available on element and component's root virtual node types.
*/
unsafeHTML(html: string): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set unsafeHTML on VNode: unsafeHTML method should be called on element or" +
" component root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set unsafeHTML on VNode: input elements can't have children.");
}
}
this._flags |= VNodeFlags.UnsafeHTML;
this._children = html;
return this;
}
/**
* Set children and enable track by key reconciliation algorithm. Children parameter should be a flat array of
* virtual nodes with assigned key properties.
*
* This method is available on element and component's root virtual node types.
*/
trackByKeyChildren(children: VNode[] | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set children on VNode: children method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set children on VNode: input elements can't have children.");
}
if (children !== null) {
for (let i = 0; i < children.length; i++) {
if (children[i]._key === null) {
throw new Error("Failed to set children on VNode: trackByKeyChildren method expects all children to" +
" have a key.");
}
}
}
}
this._flags |= VNodeFlags.ArrayChildren | VNodeFlags.TrackByKeyChildren;
this._children = children;
return this;
}
/**
* Set text value for Input Elements.
*
* This method is available on text input element node type.
*/
value(value: string): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (this._children !== null) {
throw new Error("Failed to set value on VNode: VNode is already have either children or checked property.");
}
}
this._flags |= VNodeFlags.TextInputElement;
this._children = value;
return this;
}
/**
* Set checked value for Input Elements.
*
* This method is available on checked input element node type.
*/
checked(value: boolean): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (this._children !== null) {
throw new Error("Failed to set checked on VNode: VNode is already have either children or value property.");
}
}
this._flags |= VNodeFlags.CheckedInputElement;
this._children = value;
return this;
}
/**
* Prevents component node from syncing.
*
* This method is available on component node type.
*/
bindOnce(): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & VNodeFlags.Component) === 0) {
throw new Error("Failed to set bindOnce on VNode: bindOnce method should be called on component nodes only.");
}
}
this._flags |= VNodeFlags.BindOnce;
return this;
}
/**
* Keep alive node when removing from the document. Keep alive nodes will be detached instead of disposed when they
* are removed from virtual dom tree.
*
* Keep alive nodes should be manually disposed by owning component.
*/
keepAlive(component: Component<any, any>): VNode {
this._flags |= VNodeFlags.KeepAlive;
this.ref = component.element as Node;
this.cref = component;
return this;
}
/**
* Disable children shape errors in DEBUG mode.
*/
disableChildrenShapeError(): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to disable children shape error on VNode: disableChildrenShapeError method should" +
" be called on element or component root nodes only.");
}
this._debugFlags |= VNodeDebugFlags.DisabledChildrenShapeError;
}
return this;
}
}
/**
* Recursively attach all nodes.
*/
export function vNodeAttach(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Attached) !== 0) {
throw new Error("Failed to attach VNode: VNode is already attached.");
}
vnode._debugFlags |= VNodeDebugFlags.Attached;
vnode._debugFlags &= ~VNodeDebugFlags.Detached;
}
if ((vnode._flags & VNodeFlags.Component) === 0) {
const children = vnode._children;
if (children !== null && typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeAttach((children as VNode[])[i]);
}
}
} else {
(vnode.cref as Component<any, any>).attach();
}
}
/**
* This method should be invoked when node is attached, we don't use recursive implementation because we appending
* nodes to the document as soon as they created and children nodes aren"t attached at this time.
*/
export function vNodeAttached(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Attached) !== 0) {
throw new Error("Failed to attach VNode: VNode is already attached.");
}
vnode._debugFlags |= VNodeDebugFlags.Attached;
vnode._debugFlags &= ~VNodeDebugFlags.Detached;
}
if ((vnode._flags & VNodeFlags.Component) !== 0) {
(vnode.cref as Component<any, any>).attach();
}
}
/**
* Recursively detach all nodes.
*/
export function vNodeDetach(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Detached) !== 0) {
throw new Error("Failed to detach VNode: VNode is already detached.");
}
vnode._debugFlags |= VNodeDebugFlags.Detached;
vnode._debugFlags &= ~VNodeDebugFlags.Attached;
}
if ((vnode._flags & VNodeFlags.Component) === 0) {
const children = vnode._children;
if (children !== null && typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeDetach((children as VNode[])[i]);
}
}
} else {
(vnode.cref as Component<any, any>).detach();
}
}
/**
* Recursively dispose all nodes.
*/
export function vNodeDispose(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Disposed) !== 0) {
throw new Error("Failed to dispose VNode: VNode is already disposed.");
}
if ((vnode._debugFlags & (VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted)) === 0) {
throw new Error("Failed to dispose VNode: VNode should be rendered or mounted before disposing.");
}
vnode._debugFlags |= VNodeDebugFlags.Disposed;
}
if ((vnode._flags & VNodeFlags.KeepAlive) === 0) {
if ((vnode._flags & VNodeFlags.Component) !== 0) {
(vnode.cref as Component<any, any>).dispose();
} else if (vnode._children !== null) {
const children = vnode._children;
if (typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeDispose((children as VNode[])[i]);
}
}
}
} else {
vNodeDetach(vnode);
}
}
/**
* Instantiate a DOM Node or Component from the Virtual DOM Node.
*
* This method doesn't set any attributes, or create children, to render internal representation of the virtual node,
* use `vNodeRender` method.
*/
export function vNodeInstantiate(vnode: VNode, owner: Component<any, any> | undefined): void {
const flags = vnode._flags;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref !== null) {
throw new Error("Failed to create VNode: VNode already has a reference to the DOM node.");
}
}
if ((flags & VNodeFlags.Text) !== 0) {
vnode.ref = document.createTextNode(vnode._props);
} else if ((flags & VNodeFlags.Element) !== 0) {
if ((flags & VNodeFlags.ElementDescriptor) === 0) {
if ((flags & VNodeFlags.Svg) === 0) {
vnode.ref = document.createElement(vnode._tag as string) as Node;
} else {
vnode.ref = document.createElementNS(SvgNamespace, vnode._tag as string) as Node;
}
} else {
vnode.ref = (vnode._tag as ElementDescriptor<any>).createElement() as Node;
}
} else if ((flags & VNodeFlags.KeepAlive) === 0) {
const c = (vnode._tag as ComponentDescriptor<any, any>).createComponent(owner, vnode._props);
vnode.ref = c.element as Node;
vnode.cref = c;
}
}
/**
* Render internal representation of the Virtual DOM Node.
*/
export function vNodeRender(vnode: VNode, owner: Component<any, any> | undefined): void {
let i: number;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref === null) {
throw new Error("Failed to render VNode: VNode should be created before render.");
}
if ((vnode._flags & VNodeFlags.Root) !== 0 && owner === undefined) {
throw new Error("Failed to render VNode: VNode component root should have an owner.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Rendered) !== 0) {
throw new Error("Failed to render VNode: VNode cannot be rendered twice.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Mounted) !== 0) {
throw new Error("Failed to render VNode: VNode cannot be rendered after mount.");
}
vnode._debugFlags |= VNodeDebugFlags.Mounted;
}
let il: number;
let key: any;
let keys: any[];
const flags = vnode._flags;
let ref: Element;
if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
ref = vnode.ref as Element;
if ((flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {
const props = vnode._props;
if (props !== null) {
keys = Object.keys(props);
for (i = 0, il = keys.length; i < il; i++) {
key = keys[i];
(ref as any)[key] = props[key];
}
}
if (vnode._attrs !== null) {
keys = Object.keys(vnode._attrs);
for (i = 0, il = keys.length; i < il; i++) {
key = keys[i];
setAttr(ref, key, (vnode._attrs as any)[key]);
}
}
if (vnode._style !== null) {
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).style.cssText = vnode._style;
} else {
ref.setAttribute("style", vnode._style);
}
}
if (vnode._className !== null) {
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).className = vnode._className;
} else {
ref.setAttribute("class", vnode._className);
}
}
} else {
if ((flags & VNodeFlags.Root) === 0) {
(vnode._tag as ElementDescriptor<any>)._update!(ref, undefined, vnode._props);
} else {
(owner!.descriptor._tag as ElementDescriptor<any>)._update!(ref, undefined, vnode._props);
}
}
const children = vnode._children;
if (children !== null) {
if ((flags & VNodeFlags.UnsafeHTML) === 0) {
if ((flags & VNodeFlags.InputElement) === 0) {
if ((flags & VNodeFlags.ArrayChildren) === 0) {
if (typeof children === "string") {
ref.textContent = children;
} else {
vNodeInsertChild(vnode, children as VNode, null, owner);
}
} else {
for (i = 0, il = (children as VNode[]).length; i < il; i++) {
vNodeInsertChild(vnode, (children as VNode[])[i], null, owner);
}
}
} else {
if ((vnode._flags & VNodeFlags.TextInputElement) !== 0) {
(vnode.ref as HTMLInputElement).value = vnode._children as string;
} else { // ((vnode.flags & VNodeFlags.CheckedInputElement) !== 0)
(vnode.ref as HTMLInputElement).checked = vnode._children as boolean;
}
}
} else {
ref.innerHTML = children as string;
}
}
} else if ((flags & VNodeFlags.Component) !== 0) {
updateComponent(vnode.cref as Component<any, any>);
}
}
/**
* Mount VNode on top of existing html document.
*/
export function vNodeMount(vnode: VNode, node: Node, owner: Component<any, any> | undefined): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref !== null) {
throw new Error("Failed to mount VNode: VNode cannot be mounted if it already has a reference to DOM Node.");
}
if ((vnode._flags & VNodeFlags.Root) !== 0 && owner === undefined) {
throw new Error("Failed to render VNode: VNode component root should have an owner.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Rendered) !== 0) {
throw new Error("Failed to mount VNode: VNode cannot be mounted after render.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Mounted) !== 0) {
throw new Error("Failed to mount VNode: VNode cannot be mounted twice.");
}
vnode._debugFlags |= VNodeDebugFlags.Mounted;
}
const flags = vnode._flags;
const children = vnode._children;
let keys: string[];
let key: string;
let i: number;
vnode.ref = node;
if ((flags & VNodeFlags.Component) !== 0) {
const cref = vnode.cref = (vnode._tag as ComponentDescriptor<any, any>)
.mountComponent(node as Element, owner, vnode._props);
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
const dflags = cref.descriptor._flags;
if (node.nodeType !== 1) {
throw new Error("Failed to mount VNode: invalid node type, components can be mounted on element nodes only.");
}
const eTagName = ((node as Element).tagName).toLowerCase();
let cTagName: string;
if ((dflags & ComponentDescriptorFlags.ElementDescriptor) !== 0) {
cTagName = (cref.descriptor._tag as ElementDescriptor<any>)._tagName.toLowerCase();
if (cTagName !== eTagName) {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "${cTagName}", but` +
` found "${eTagName}".`);
}
} else if ((dflags & ComponentDescriptorFlags.Canvas2D) !== 0) {
if (eTagName !== "canvas") {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "canvas", but` +
` found "${eTagName}".`);
}
} else {
cTagName = (cref.descriptor._tag as string).toLowerCase();
if (cTagName !== eTagName) {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "${cTagName}", but` +
` found "${eTagName}".`);
}
}
}
updateComponent(cref);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
if (node.nodeType !== 1) {
throw new Error("Failed to mount VNode: invalid node type, VNode expects Element node.");
}
if (vnode._className !== null) {
const eClassName = (node as Element).getAttribute("class");
if (vnode._className !== eClassName) {
throw new Error(`Failed to mount VNode: invalid className, VNode expects className` +
` "${vnode._className}", but found "${eClassName}".`);
}
}
if (vnode._style !== null) {
const eStyle = (node as Element).getAttribute("style");
if (vnode._style !== eStyle) {
throw new Error(`Failed to mount VNode: invalid style, VNode expects style` +
` "${vnode._style}", but found "${eStyle}".`);
}
}
} else {
if (node.nodeType !== 3) {
throw new Error("Failed to mount VNode: invalid node type, VNode expects Text node.");
}
const text = node.nodeValue;
if (vnode._props !== text) {
throw new Error(`Failed to mount VNode: invalid text, VNode expects text "${vnode._props}", but found` +
` "${text}".`);
}
}
}
if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
// Assign properties on mount, because they don't exist in html markup.
if ((flags & VNodeFlags.ElementDescriptor) !== 0) {
const eDescriptor = vnode._tag as ElementDescriptor<any>;
if (eDescriptor._props !== null) {
keys = Object.keys(eDescriptor._props);
for (i = 0; i < keys.length; i++) {
key = keys[i];
(node as any)[key] = eDescriptor._props[key];
}
}
}
if (vnode._props !== null) {
keys = Object.keys(vnode._props);
for (i = 0; i < keys.length; i++) {
key = keys[i];
(node as any)[key] = vnode._props[key];
}
}
if (children !== null) {
if ((flags & VNodeFlags.ArrayChildren) === 0) {
if (typeof children !== "string") {
let child = node.firstChild;
// Adjacent text nodes should be separated by Comment node "<!---->", so we can properly mount them.
let commentNode: Node;
while (child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
vNodeMount(children as VNode, child, owner);
}
} else if ((children as VNode[]).length > 0) {
let child = node.firstChild;
// Adjacent text nodes should be separated by Comment node "<!---->", so we can properly mount them.
let commentNode: Node;
while (child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
for (i = 0; i < (children as VNode[]).length; i++) {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (!child) {
throw new Error("Failed to mount VNode: cannot find matching node.");
}
}
vNodeMount((children as VNode[])[i], child, owner);
child = child.nextSibling;
while (child !== null && child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
}
}
}
}
}
}
function vNodeInsertChild(parent: VNode, node: VNode, nextRef: Node | null, owner?: Component<any, any>): void {
const container = parent.ref as Element;
if (node.ref === null) {
vNodeInstantiate(node, owner);
vNodeAttached(node);
vNodeRender(node, owner);
container.insertBefore(node.ref!, nextRef!);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((node._flags & VNodeFlags.KeepAlive) === 0) {
throw new Error("Failed to replace node: VNode instance already has been used to create DOM node.");
}
}
container.insertBefore(node.ref, nextRef!);
vNodeAttach(node);
updateComponent(node.cref as Component<any, any>,
(node._flags & VNodeFlags.BindOnce) === 0 ? node._props : null);
}
}
function vNodeReplaceChild(parent: VNode, newNode: VNode, refNode: VNode, owner?: Component<any, any>): void {
const container = parent.ref as Element;
if (newNode.ref === null) {
vNodeInstantiate(newNode, owner);
vNodeAttached(newNode);
vNodeRender(newNode, owner);
container.replaceChild(newNode.ref!, refNode.ref!);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((newNode._flags & VNodeFlags.KeepAlive) === 0) {
throw new Error("Failed to replace node: VNode instance already has been used to create DOM node.");
}
}
container.replaceChild(newNode.ref, refNode.ref!);
vNodeAttach(newNode);
updateComponent(newNode.cref as Component<any, any>,
(newNode._flags & VNodeFlags.BindOnce) === 0 ? newNode._props : null);
}
vNodeDispose(refNode);
}
function vNodeMoveChild(parent: VNode, node: VNode, nextRef: Node | null): void {
(parent.ref as Element).insertBefore(node.ref!, nextRef!);
}
function vNodeRemoveChild(parent: VNode, node: VNode): void {
(parent.ref as Element).removeChild(node.ref!);
vNodeDispose(node);
}
function vNodeRemoveAllChildren(parent: VNode, nodes: VNode[]): void {
parent.ref!.textContent = "";
for (let i = 0; i < nodes.length; i++) {
vNodeDispose(nodes[i]);
}
}
/**
* Sync two VNodes
*
* When node `a` is synced with node `b`, `a` node should be considered as destroyed, and any access to it after sync
* is an undefined behavior.
*/
export function syncVNodes(a: VNode, b: VNode, owner?: Component<any, any>): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((a._debugFlags & (VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted)) === 0) {
throw new Error("Failed to sync VNode: VNode should be rendered or mounted before sync.");
}
b._debugFlags |= a._debugFlags &
(VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted |
VNodeDebugFlags.Attached | VNodeDebugFlags.Detached);
}
const ref = a.ref as Element;
const flags = a._flags;
let component: Component<any, any>;
let className: string;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (a._flags !== b._flags) {
throw new Error(`Failed to sync VNode: flags does not match (old: ${a._flags}, new: ${b._flags}).`);
}
if (a._tag !== b._tag) {
throw new Error(`Failed to sync VNode: tags does not match (old: ${a._tag}, new: ${b._tag}).`);
}
if (a._key !== b._key) {
throw new Error(`Failed to sync VNode: keys does not match (old: ${a._key}, new: ${b._key}).`);
}
if (b.ref !== null && a.ref !== b.ref) {
throw new Error("Failed to sync VNode: reusing VNodes isn't allowed unless it has the same ref.");
}
}
b.ref = a.ref;
if ((flags & VNodeFlags.Text) !== 0) {
if (a._props !== b._props) {
a.ref!.nodeValue = b._props as string;
}
} else if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
if ((flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {