-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
1793 lines (1599 loc) · 52.1 KB
/
index.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
/*
A type that wraps a reference.
*/
export type ForgoRef<T> = {
value?: T;
};
/*
We have two types of elements:
1. DOM Elements
2. Component Elements
*/
export type ForgoElementProps = {
children?: ForgoNode | ForgoNode[];
};
export type ForgoDOMElementProps = {
xmlns?: string;
ref?: ForgoRef<Element>;
dangerouslySetInnerHTML?: { __html: string };
} & ForgoElementProps;
export type ForgoComponentProps = {} & ForgoElementProps;
/*
This is the constructor of a ForgoComponent, called a 'Component Constructor'.
The terminology is different from React here.
For example, in <MyComponent />, the MyComponent is the Component Constructor.
The Component Constructor is defined by the type ForgoComponentCtor,
and it returns a Component (of type ForgoComponent).
*/
export type ForgoCtorArgs = {
environment: ForgoEnvType;
};
export type ForgoComponentCtor<TProps extends ForgoComponentProps> = (
props: TProps,
args: ForgoCtorArgs
) => ForgoComponent<TProps>;
export type ForgoElementArg = {
node?: ChildNode;
componentIndex: number;
};
export type ForgoRenderArgs = {
element: ForgoElementArg;
update: (props?: any) => RenderResult;
};
export type ForgoErrorArgs = ForgoRenderArgs & {
error: any;
};
export type ForgoAfterRenderArgs = ForgoRenderArgs & {
previousNode?: ChildNode;
};
/*
ForgoComponent contains three functions.
1. render() returns the actual DOM to render.
2. error() is called with a subcomponent throws an error.
3. mount() is optional. Gets called when attached to a real DOM Node.
4. unmount() is optional. Gets called just before unmount.
5. shouldUpdate() is optional. Let's you bail out of a render().
*/
export type ForgoComponent<TProps extends ForgoComponentProps> = {
render: (props: TProps, args: ForgoRenderArgs) => ForgoNode | ForgoNode[];
afterRender?: (props: TProps, args: ForgoAfterRenderArgs) => void;
error?: (props: TProps, args: ForgoErrorArgs) => ForgoNode;
mount?: (props: TProps, args: ForgoRenderArgs) => void;
unmount?: (props: TProps, args: ForgoRenderArgs) => void;
shouldUpdate?: (newProps: TProps, oldProps: TProps) => boolean;
};
/*
A ForgoNode is the output of the render() function.
It can represent:
- a primitive type which becomes a DOM Text Node
- a DOM Element
- or a Component.
If the ForgoNode is a string, number etc, it's a primitive type.
eg: "hello"
If ForgoNode has a type property which is a string, it represents a native DOM element.
eg: The type will be "div" for <div>Hello</div>
If the ForgoElement represents a Component, then the type points to a ForgoComponentCtor.
eg: The type will be MyComponent for <MyComponent />
*/
export type ForgoElementBase<TProps extends ForgoElementProps> = {
key?: any;
props: TProps;
__is_forgo_element__: true;
};
export type ForgoDOMElement<TProps extends ForgoDOMElementProps> =
ForgoElementBase<TProps> & {
type: string;
};
export type ForgoComponentElement<TProps extends ForgoComponentProps> =
ForgoElementBase<TProps> & {
type: ForgoComponentCtor<TProps>;
};
export type ForgoFragment = {
type: typeof Fragment;
props: { children?: ForgoNode | ForgoNode[] };
__is_forgo_element__: true;
};
export type ForgoElement<TProps> =
| ForgoDOMElement<TProps>
| ForgoComponentElement<TProps>;
export type ForgoNonEmptyPrimitiveNode =
| string
| number
| boolean
| object
| BigInt;
export type ForgoPrimitiveNode = ForgoNonEmptyPrimitiveNode | null | undefined;
export type ForgoNode = ForgoPrimitiveNode | ForgoElement<any> | ForgoFragment;
/*
Forgo stores Component state on the element on which it is mounted.
Say Custom1 renders Custom2 which renders Custom3 which renders <div>Hello</div>.
In this case, the components Custom1, Custom2 and Custom3 are stored on the div.
You can also see that it gets passed around as pendingStates in the render methods.
That's because when Custom1 renders Custom2, there isn't a real DOM node available to attach the state to.
So the states are passed around until the last component renders a real DOM node or nodes.
In addition it holds a bunch of other things.
Like for example, a key which uniquely identifies a child element when rendering a list.
*/
export type NodeAttachedComponentState<TProps> = {
key?: any;
ctor: ForgoComponentCtor<TProps>;
component: ForgoComponent<TProps>;
props: TProps;
args: ForgoRenderArgs;
nodes: ChildNode[];
isMounted: boolean;
};
/*
This is the state data structure which gets stored on a node.
See explanation for NodeAttachedComponentState<TProps>
*/
export type NodeAttachedState = {
key?: string | number;
props?: { [key: string]: any };
components: NodeAttachedComponentState<any>[];
style?: { [key: string]: any };
};
// CSS types lifted from preact.
export type DOMCSSProperties = {
[key in keyof Omit<
CSSStyleDeclaration,
| "item"
| "setProperty"
| "removeProperty"
| "getPropertyValue"
| "getPropertyPriority"
>]?: string | number | null | undefined;
};
export type AllCSSProperties = {
[key: string]: string | number | null | undefined;
};
export interface CSSProperties extends AllCSSProperties, DOMCSSProperties {
cssText?: string | null;
}
/*
The following adds support for injecting test environment objects.
Such as JSDOM.
*/
export type ForgoEnvType = {
window: Window;
document: Document;
__internal: {
HTMLElement: typeof HTMLElement;
Text: typeof Text;
};
};
/*
NodeInsertionOptions decide how nodes get attached by the callee function.
type = "detached" does not attach the node to the parent.
type = "search" requires the callee function to search for a compatible replacement.
*/
export type DetachedNodeInsertionOptions = {
type: "detached";
};
export type SearchableNodeInsertionOptions = {
type: "search";
parentElement: Element;
currentNodeIndex: number;
length: number;
};
export type NodeInsertionOptions =
| DetachedNodeInsertionOptions
| SearchableNodeInsertionOptions;
/*
These are child nodes which have been removed from the tree (within the
render-child loop for an element).
When a compatible node is found for rendering, the previous incompatible nodes
are removed from the parent. But when a keyed child node has been removed earlier
in the loop and a later forgoElement has the same key, it needs to be
reattached and it should no longer be unmounted. Otherwise, at the end of the cycle
all unloadable nodes are fully unmounted.
*/
export type UnloadableChildNode = {
node: ChildNode;
pendingAttachStates: NodeAttachedComponentState<any>[];
};
/*
Result of the render functions.
*/
export type RenderResult = {
nodes: ChildNode[];
};
/*
Fragment constructor.
We simply use it as a marker in jsx-runtime.
*/
export const Fragment: unique symbol = Symbol.for("FORGO_FRAGMENT");
/*
HTML Namespaces
*/
const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
const MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
/*
The element types we care about.
As defined by the standards.
*/
const ELEMENT_NODE_TYPE = 1;
const ATTRIBUTE_NODE_TYPE = 2;
const TEXT_NODE_TYPE = 3;
/*
jsxFactory function
*/
export function createElement<TProps extends ForgoElementProps & { key?: any }>(
type: string | ForgoComponentCtor<TProps>,
props: TProps
) {
props = props ?? {};
props.children =
arguments.length > 3
? flatten(Array.from(arguments).slice(2))
: arguments.length === 3
? flatten(arguments[2])
: undefined;
const key = props.key ?? undefined;
return { type, props, key, __is_forgo_element__: true };
}
export const h = createElement;
/*
HACK: Chrome fires onblur (if defined) immediately after a node.remove().
This is bad news for us, since a rerender() inside the onblur handler
will run on an unattached node. So, disable onblur if node is set to be removed.
*/
function handlerDisabledOnNodeDelete(node: ChildNode, value: any) {
return (e: any) => {
if (!node.__forgo_deleted) {
return value(e);
}
};
}
export function createForgoInstance(customEnv: any) {
const env: ForgoEnvType = customEnv;
env.__internal = env.__internal ?? {
Text: (env.window as any).Text,
HTMLElement: (env.window as any).HTMLElement,
};
/*
This is the main render function. forgoNode is the node to render.
nodeInsertionOptions specify which nodes need to be replaced by the new node(s),
or whether the new node should be created detached from the DOM (without replacement).
pendingAttachStates is the list of Component State objects which will be attached to the element.
*/
function internalRender(
forgoNode: ForgoNode | ForgoNode[],
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
): RenderResult {
// Array of Nodes
if (Array.isArray(forgoNode)) {
return renderArray(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
}
// Primitive Nodes
else if (!isForgoElement(forgoNode)) {
return forgoNode === undefined || forgoNode === null
? renderNothing(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
)
: renderText(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
}
// HTML Element
else if (isForgoDOMElement(forgoNode)) {
return renderDOMElement(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
} else if (isForgoFragment(forgoNode)) {
return renderFragment(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
}
// Component.
else {
return renderComponent(
forgoNode,
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
}
}
/*
Renders undefined and null
*/
function renderNothing(
forgoNode: undefined | null,
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
) {
return { nodes: [] };
}
/*
Render a string.
Such as in the render function below:
function MyComponent() {
return {
render() {
return "Hello world"
}
}
}
*/
function renderText(
forgoNode: ForgoNonEmptyPrimitiveNode,
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
): RenderResult {
// We need to create a detached node.
if (nodeInsertionOptions.type === "detached") {
// Text nodes will always be recreated.
const textNode: ChildNode = env.document.createTextNode(
stringOfPrimitiveNode(forgoNode)
);
syncStateAndProps(
forgoNode,
textNode,
true,
pendingAttachStates,
undefined
);
return { nodes: [textNode] };
}
// We have to find a node to replace.
else {
// Text nodes will always be recreated.
const textNode: ChildNode = env.document.createTextNode(
stringOfPrimitiveNode(forgoNode)
);
// If we're searching in a list, we replace if the current node is a text node.
const childNodes = nodeInsertionOptions.parentElement.childNodes;
if (nodeInsertionOptions.length) {
let targetNode = childNodes[nodeInsertionOptions.currentNodeIndex];
if (targetNode.nodeType === TEXT_NODE_TYPE) {
targetNode.replaceWith(textNode);
const oldComponentState = getForgoState(targetNode)?.components;
syncStateAndProps(
forgoNode,
textNode,
true,
pendingAttachStates,
oldComponentState
);
return { nodes: [textNode] };
} else {
const nextNode = childNodes[nodeInsertionOptions.currentNodeIndex];
nodeInsertionOptions.parentElement.insertBefore(textNode, nextNode);
syncStateAndProps(
forgoNode,
textNode,
true,
pendingAttachStates,
undefined
);
return { nodes: [textNode] };
}
}
// There are no target nodes available.
else {
const childNodes = nodeInsertionOptions.parentElement.childNodes;
if (
childNodes.length === 0 ||
nodeInsertionOptions.currentNodeIndex === 0
) {
nodeInsertionOptions.parentElement.prepend(textNode);
} else {
const nextNode = childNodes[nodeInsertionOptions.currentNodeIndex];
nodeInsertionOptions.parentElement.insertBefore(textNode, nextNode);
}
syncStateAndProps(
forgoNode,
textNode,
true,
pendingAttachStates,
undefined
);
return { nodes: [textNode] };
}
}
}
/*
Render a DOM element.
Such as in the render function below:
function MyComponent() {
return {
render() {
return <div>Hello world</div>
}
}
}
*/
function renderDOMElement<TProps extends ForgoDOMElementProps>(
forgoElement: ForgoDOMElement<TProps>,
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
): RenderResult {
// We need to create a detached node
if (nodeInsertionOptions.type === "detached") {
return addElement(undefined, null);
}
// We have to find a node to replace.
else {
const childNodes = nodeInsertionOptions.parentElement.childNodes;
if (nodeInsertionOptions.length) {
const searchResult = findReplacementCandidateForElement(
forgoElement,
childNodes,
nodeInsertionOptions.currentNodeIndex,
nodeInsertionOptions.length
);
if (searchResult.found) {
return renderExistingElement(
searchResult.index,
childNodes,
nodeInsertionOptions
);
} else {
return addElement(
nodeInsertionOptions.parentElement,
childNodes[nodeInsertionOptions.currentNodeIndex]
);
}
} else {
return addElement(
nodeInsertionOptions.parentElement,
childNodes[nodeInsertionOptions.currentNodeIndex]
);
}
}
function renderChildNodes(parentElement: Element) {
if (forgoElement.props.dangerouslySetInnerHTML) {
parentElement.innerHTML =
forgoElement.props.dangerouslySetInnerHTML.__html;
} else {
const forgoChildrenObj = forgoElement.props.children;
// Children will not be an array if single item.
const forgoChildren = flatten(
(Array.isArray(forgoChildrenObj)
? forgoChildrenObj
: [forgoChildrenObj]
).filter((x) => x !== undefined && x !== null)
);
let currentChildNodeIndex = 0;
for (const forgoChild of forgoChildren) {
const { nodes } = internalRender(
forgoChild,
{
type: "search",
parentElement,
currentNodeIndex: currentChildNodeIndex,
length: parentElement.childNodes.length - currentChildNodeIndex,
},
[],
mountOnPreExistingDOM
);
currentChildNodeIndex += nodes.length;
}
// Get rid the the remaining nodes.
const nodesToRemove = sliceNodes(
parentElement.childNodes,
currentChildNodeIndex,
parentElement.childNodes.length
);
if (nodesToRemove.length) {
unloadNodes(nodesToRemove, []);
}
}
}
function renderExistingElement(
insertAt: number,
childNodes: NodeListOf<ChildNode>,
nodeInsertionOptions: SearchableNodeInsertionOptions
): RenderResult {
// Get rid of unwanted nodes.
const nodesToRemove = sliceNodes(
childNodes,
nodeInsertionOptions.currentNodeIndex,
insertAt
);
unloadNodes(nodesToRemove, pendingAttachStates);
const targetElement = childNodes[
nodeInsertionOptions.currentNodeIndex
] as Element;
renderChildNodes(targetElement);
const oldComponentState = getForgoState(targetElement)?.components;
syncStateAndProps(
forgoElement,
targetElement,
false,
pendingAttachStates,
oldComponentState
);
return { nodes: [targetElement] };
}
function addElement(
parentElement: Element | undefined,
oldNode: ChildNode | null
): RenderResult {
const newElement = createElement(forgoElement, parentElement);
if (parentElement) {
parentElement.insertBefore(newElement, oldNode);
}
if (forgoElement.props.ref) {
forgoElement.props.ref.value = newElement;
}
renderChildNodes(newElement);
syncStateAndProps(
forgoElement,
newElement,
true,
pendingAttachStates,
undefined
);
return { nodes: [newElement] };
}
}
/*
Render a Component.
Such as <MySideBar size="large" />
*/
function renderComponent<TProps extends ForgoDOMElementProps>(
forgoElement: ForgoComponentElement<TProps>,
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
// boundary: ForgoComponent<any> | undefined
): RenderResult {
const componentIndex = pendingAttachStates.length;
// We need to create a detached node.
if (nodeInsertionOptions.type === "detached") {
return addComponent();
}
// We have to find a node to replace.
else {
if (nodeInsertionOptions.length) {
if (mountOnPreExistingDOM) {
return addComponent();
} else {
const childNodes = nodeInsertionOptions.parentElement.childNodes;
const searchResult = findReplacementCandidateForComponent(
forgoElement,
childNodes,
nodeInsertionOptions.currentNodeIndex,
nodeInsertionOptions.length,
pendingAttachStates.length
);
if (searchResult.found) {
return renderExistingComponent(
searchResult.index,
childNodes,
nodeInsertionOptions
);
}
// No matching node found.
else {
return addComponent();
}
}
}
// No nodes in target node list.
// Nothing to unload.
else {
return addComponent();
}
}
function renderExistingComponent(
insertAt: number,
childNodes: NodeListOf<ChildNode>,
nodeInsertionOptions: SearchableNodeInsertionOptions
): RenderResult {
const targetNode = childNodes[insertAt];
const state = getExistingForgoState(targetNode);
const componentState = state.components[componentIndex];
// Get rid of unwanted nodes.
const nodesToRemove = sliceNodes(
childNodes,
nodeInsertionOptions.currentNodeIndex,
insertAt
);
unloadNodes(nodesToRemove, pendingAttachStates.concat(componentState));
if (
!componentState.component.shouldUpdate ||
componentState.component.shouldUpdate(
forgoElement.props,
componentState.props
)
) {
// Since we have compatible state already stored,
// we'll push the savedComponentState into pending states for later attachment.
const updatedComponentState = {
...componentState,
props: forgoElement.props,
};
// Get a new element by calling render on existing component.
const newForgoNode = updatedComponentState.component.render(
forgoElement.props,
updatedComponentState.args
);
const statesToAttach = pendingAttachStates.concat(
updatedComponentState
);
const previousNode = componentState.args.element.node;
const boundary = updatedComponentState.component.error
? updatedComponentState.component
: undefined;
const renderResult = withErrorBoundary(
forgoElement.props,
updatedComponentState.args,
statesToAttach,
boundary,
() => {
// Create new node insertion options.
const insertionOptions: NodeInsertionOptions = {
type: "search",
currentNodeIndex: nodeInsertionOptions.currentNodeIndex,
length: updatedComponentState.nodes.length,
parentElement: nodeInsertionOptions.parentElement,
};
return renderComponentAndRemoveStaleNodes(
newForgoNode,
insertionOptions,
statesToAttach,
updatedComponentState,
mountOnPreExistingDOM
);
}
);
if (updatedComponentState.component.afterRender) {
updatedComponentState.component.afterRender(forgoElement.props, {
...updatedComponentState.args,
previousNode,
});
}
return renderResult;
}
// shouldUpdate() returned false
else {
let indexOfNode = findNodeIndex(
nodeInsertionOptions.parentElement.childNodes,
componentState.args.element.node
);
return {
nodes: sliceNodes(
nodeInsertionOptions.parentElement.childNodes,
indexOfNode,
indexOfNode + componentState.nodes.length
),
};
}
}
function addComponent(): RenderResult {
const args: ForgoRenderArgs = {
element: { componentIndex },
update: (props) => rerender(args.element, props),
};
const ctor = forgoElement.type;
const component = ctor(forgoElement.props, { environment: env });
assertIsComponent(ctor, component);
const boundary = component.error ? component : undefined;
// Create new component state
// ... and push it to pendingAttachStates
const newComponentState: NodeAttachedComponentState<any> = {
key: forgoElement.key,
ctor,
component,
props: forgoElement.props,
args,
nodes: [],
isMounted: false,
};
const statesToAttach = pendingAttachStates.concat(newComponentState);
return withErrorBoundary(
forgoElement.props,
args,
statesToAttach,
boundary,
() => {
// Create an element by rendering the component
const newForgoElement = component.render(forgoElement.props, args);
// Create new node insertion options.
const insertionOptions: NodeInsertionOptions =
nodeInsertionOptions.type === "detached"
? nodeInsertionOptions
: {
type: "search",
currentNodeIndex: nodeInsertionOptions.currentNodeIndex,
length: mountOnPreExistingDOM
? nodeInsertionOptions.length
: 0,
parentElement: nodeInsertionOptions.parentElement,
};
// Pass it on for rendering...
const renderResult = internalRender(
newForgoElement,
insertionOptions,
statesToAttach,
mountOnPreExistingDOM
);
// In case we rendered an array, set the node to the first node.
// We do this because args.element.node would be set to the last node otherwise.
newComponentState.nodes = renderResult.nodes;
if (renderResult.nodes.length > 1) {
newComponentState.args.element.node = renderResult.nodes[0];
}
if (component.afterRender) {
// No previousNode since new component. So just args and not afterRenderArgs.
component.afterRender(forgoElement.props, args);
}
return renderResult;
}
);
}
function withErrorBoundary(
props: TProps,
args: ForgoRenderArgs,
statesToAttach: NodeAttachedComponentState<any>[],
boundary: ForgoComponent<any> | undefined,
exec: () => RenderResult
): RenderResult {
try {
return exec();
} catch (error) {
if (boundary && boundary.error) {
const errorArgs = { ...args, error };
const newForgoElement = boundary.error(props, errorArgs);
return internalRender(
newForgoElement,
nodeInsertionOptions,
statesToAttach,
mountOnPreExistingDOM
);
} else {
throw error;
}
}
}
}
function renderComponentAndRemoveStaleNodes<TProps>(
forgoNode: ForgoNode,
insertionOptions: SearchableNodeInsertionOptions,
statesToAttach: NodeAttachedComponentState<any>[],
componentState: NodeAttachedComponentState<TProps>,
mountOnPreExistingDOM: boolean
): RenderResult {
const totalNodesBeforeRender =
insertionOptions.parentElement.childNodes.length;
// Pass it on for rendering...
const renderResult = internalRender(
forgoNode,
insertionOptions,
statesToAttach,
mountOnPreExistingDOM
);
const totalNodesAfterRender =
insertionOptions.parentElement.childNodes.length;
const numNodesReused =
totalNodesBeforeRender +
renderResult.nodes.length -
totalNodesAfterRender;
const newIndex =
insertionOptions.currentNodeIndex + renderResult.nodes.length;
const nodesToRemove = sliceNodes(
insertionOptions.parentElement.childNodes,
newIndex,
newIndex + componentState.nodes.length - numNodesReused
);
// If renderResult returned no nodes (ie, null or undefined), then all state will be discarded.
const statesThatWillBeAttached =
renderResult.nodes.length > 0 ? statesToAttach : [];
unloadNodes(nodesToRemove, statesThatWillBeAttached);
// In case we rendered an array, set the node to the first node.
// We do this because args.element.node would be set to the last node otherwise.
componentState.nodes = renderResult.nodes;
if (renderResult.nodes.length > 1) {
componentState.args.element.node = renderResult.nodes[0];
}
return renderResult;
}
/*
Render an array of components.
Called when a Component returns an array (or fragment) in its render method.
*/
function renderArray(
forgoNodes: ForgoNode[],
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
): RenderResult {
const flattenedNodes = flatten(forgoNodes);
if (nodeInsertionOptions.type === "detached") {
throw new Error(
"Arrays and fragments cannot be rendered at the top level."
);
} else {
let allNodes: ChildNode[] = [];
let currentNodeIndex = nodeInsertionOptions.currentNodeIndex;
let numNodes = nodeInsertionOptions.length;
for (const forgoNode of flattenedNodes) {
const totalNodesBeforeRender =
nodeInsertionOptions.parentElement.childNodes.length;
const insertionOptions: SearchableNodeInsertionOptions = {
...nodeInsertionOptions,
currentNodeIndex,
length: numNodes,
};
const { nodes } = internalRender(
forgoNode,
insertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
allNodes = allNodes.concat(nodes);
const totalNodesAfterRender =
nodeInsertionOptions.parentElement.childNodes.length;
const numNodesRemoved =
totalNodesBeforeRender + nodes.length - totalNodesAfterRender;
currentNodeIndex += nodes.length;
numNodes -= numNodesRemoved;
}
return { nodes: allNodes };
}
}
/*
Render a Fragment
*/
function renderFragment(
fragment: ForgoFragment,
nodeInsertionOptions: NodeInsertionOptions,
pendingAttachStates: NodeAttachedComponentState<any>[],
mountOnPreExistingDOM: boolean
): RenderResult {
return renderArray(
flatten(fragment),
nodeInsertionOptions,
pendingAttachStates,
mountOnPreExistingDOM
);
}
/*
Sync component states and props between a newNode and an oldNode.
*/
function syncStateAndProps(