-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathcrank.ts
3056 lines (2733 loc) · 80.5 KB
/
crank.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
const NOOP = () => {};
const IDENTITY = <T>(value: T): T => value;
function wrap<T>(value: Array<T> | T | undefined): Array<T> {
return value === undefined ? [] : Array.isArray(value) ? value : [value];
}
function unwrap<T>(arr: Array<T>): Array<T> | T | undefined {
return arr.length === 0 ? undefined : arr.length === 1 ? arr[0] : arr;
}
type NonStringIterable<T> = Iterable<T> & object;
/**
* Ensures a value is an array.
*
* This function does the same thing as wrap() above except it handles nulls
* and iterables, so it is appropriate for wrapping user-provided element
* children.
*/
function arrayify<T>(
value: NonStringIterable<T> | T | null | undefined,
): Array<T> {
return value == null
? []
: Array.isArray(value)
? value
: typeof value === "string" ||
typeof (value as any)[Symbol.iterator] !== "function"
? [value as T]
: [...(value as NonStringIterable<T>)];
}
function isIteratorLike(
value: any,
): value is Iterator<unknown> | AsyncIterator<unknown> {
return value != null && typeof value.next === "function";
}
function isPromiseLike(value: any): value is PromiseLike<unknown> {
return value != null && typeof value.then === "function";
}
/**
* A type which represents all valid values for an element tag.
*/
export type Tag = string | symbol | Component;
/**
* A helper type to map the tag of an element to its expected props.
*
* @template TTag - The tag associated with the props. Can be a string, symbol
* or a component function.
*/
export type TagProps<TTag extends Tag> = TTag extends string
? JSX.IntrinsicElements[TTag]
: TTag extends Component<infer TProps>
? TProps & JSX.IntrinsicAttributes
: Record<string, unknown> & JSX.IntrinsicAttributes;
/***
* SPECIAL TAGS
*
* Crank provides a couple tags which have special meaning for the renderer.
***/
/**
* A special tag for grouping multiple children within the same parent.
*
* All non-string iterables which appear in the element tree are implicitly
* wrapped in a fragment element.
*
* This tag is just the empty string, and you can use the empty string in
* createElement calls or transpiler options directly to avoid having to
* reference this export.
*/
export const Fragment = "";
export type Fragment = typeof Fragment;
// TODO: We assert the following symbol tags as any because TypeScript support
// for symbol tags in JSX doesn’t exist yet.
// https://github.com/microsoft/TypeScript/issues/38367
/**
* A special tag for rendering into a new root node via a root prop.
*
* This tag is useful for creating element trees with multiple roots, for
* things like modals or tooltips.
*
* Renderer.prototype.render() will implicitly wrap top-level element trees in
* a Portal element.
*/
export const Portal = Symbol.for("crank.Portal") as any;
export type Portal = typeof Portal;
/**
* A special tag which preserves whatever was previously rendered in the
* element’s position.
*
* Copy elements are useful for when you want to prevent a subtree from
* rerendering as a performance optimization. Copy elements can also be keyed,
* in which case the previously rendered keyed element will be copied.
*/
export const Copy = Symbol.for("crank.Copy") as any;
export type Copy = typeof Copy;
/**
* A special tag for injecting raw nodes or strings via a value prop.
*
* Renderer.prototype.raw() is called with the value prop.
*/
export const Raw = Symbol.for("crank.Raw") as any;
export type Raw = typeof Raw;
/**
* Describes all valid values of an element tree, excluding iterables.
*
* Arbitrary objects can also be safely rendered, but will be converted to a
* string using the toString() method. We exclude them from this type to catch
* potential mistakes.
*/
export type Child = Element | string | number | boolean | null | undefined;
/**
* An arbitrarily nested iterable of Child values.
*
* We use a recursive interface here rather than making the Children type
* directly recursive because recursive type aliases were added in TypeScript
* 3.7.
*
* You should avoid referencing this type directly, as it is mainly exported to
* prevent TypeScript errors.
*/
export interface ChildIterable extends Iterable<Child | ChildIterable> {}
/**
* Describes all valid values of an element tree, including arbitrarily nested
* iterables of such values.
*/
export type Children = Child | ChildIterable;
/**
* Represents all functions which can be used as a component.
*
* @template [TProps=*] - The expected props for the component.
*/
export type Component<TProps extends Record<string, unknown> = any> = (
this: Context<TProps>,
props: TProps,
ctx: Context<TProps>,
) =>
| Children
| PromiseLike<Children>
// The return type of iterators must include void because TypeScript will
// infer generators which return implicitly as having a void return type.
| Iterator<Children, Children | void, any>
| AsyncIterator<Children, Children | void, any>;
type ChildrenIteratorResult = IteratorResult<Children, Children | void>;
/**
* A type to keep track of keys. Any value can be a key, though null and
* undefined are ignored.
*/
type Key = unknown;
const ElementSymbol = Symbol.for("crank.Element");
// To maximize compatibility between Crank versions, starting with 0.2.0, any
// changes to the Element properties will be considered a breaking change.
export interface Element<TTag extends Tag = Tag> {
/**
* @internal
* A unique symbol to identify elements as elements across versions and
* realms, and to protect against basic injection attacks.
* https://overreacted.io/why-do-react-elements-have-typeof-property/
*
* This property is defined on the element prototype rather than per
* instance, because it is the same for every Element.
*/
$$typeof: typeof ElementSymbol;
/**
* The tag of the element. Can be a string, symbol or function.
*/
tag: TTag;
/**
* An object containing the "properties" of an element. These correspond to
* the attribute syntax from JSX.
*/
props: TagProps<TTag>;
}
/**
* Elements are the basic building blocks of Crank applications. They are
* JavaScript objects which are interpreted by special classes called renderers
* to produce and manage stateful nodes.
*
* @template {Tag} [TTag=Tag] - The type of the tag of the element.
*
* @example
* // specific element types
* let div: Element<"div">;
* let portal: Element<Portal>;
* let myEl: Element<MyComponent>;
*
* // general element types
* let host: Element<string | symbol>;
* let component: Element<Component>;
*
* Typically, you use a helper function like createElement to create elements
* rather than instatiating this class directly.
*/
export class Element<TTag extends Tag = Tag> {
constructor(tag: TTag, props: TagProps<TTag>) {
this.tag = tag;
this.props = props;
}
get key(): Key {
return this.props.key;
}
get ref(): unknown {
return this.props.ref;
}
get copy(): boolean {
return !!this.props.copy;
}
}
// See Element interface
Element.prototype.$$typeof = ElementSymbol;
export function isElement(value: any): value is Element {
return value != null && value.$$typeof === ElementSymbol;
}
const DEPRECATED_PROP_PREFIXES = ["crank-", "c-", "$"];
const DEPRECATED_SPECIAL_PROP_BASES = ["key", "ref", "static"];
const SPECIAL_PROPS = new Set(["children", "key", "ref", "copy"]);
for (const propPrefix of DEPRECATED_PROP_PREFIXES) {
for (const propBase of DEPRECATED_SPECIAL_PROP_BASES) {
SPECIAL_PROPS.add(propPrefix + propBase);
}
}
/**
* Creates an element with the specified tag, props and children.
*
* This function is usually used as a transpilation target for JSX transpilers,
* but it can also be called directly. It additionally extracts special props so
* they aren’t accessible to renderer methods or components, and assigns the
* children prop according to any additional arguments passed to the function.
*/
export function createElement<TTag extends Tag>(
tag: TTag,
props?: TagProps<TTag> | null | undefined,
...children: Array<unknown>
): Element<TTag> {
if (props == null) {
props = {} as TagProps<TTag>;
}
for (let i = 0; i < DEPRECATED_PROP_PREFIXES.length; i++) {
const propPrefix = DEPRECATED_PROP_PREFIXES[i];
for (let j = 0; j < DEPRECATED_SPECIAL_PROP_BASES.length; j++) {
const propBase = DEPRECATED_SPECIAL_PROP_BASES[j];
const deprecatedPropName = propPrefix + propBase;
const targetPropBase = propBase === "static" ? "copy" : propBase;
if (deprecatedPropName in (props as TagProps<TTag>)) {
console.warn(
`The \`${deprecatedPropName}\` prop is deprecated. Use \`${targetPropBase}\` instead.`,
);
(props as TagProps<TTag>)[targetPropBase] = (props as TagProps<TTag>)[
deprecatedPropName
];
}
}
}
if (children.length > 1) {
(props as TagProps<TTag>).children = children;
} else if (children.length === 1) {
(props as TagProps<TTag>).children = children[0];
}
return new Element(tag, props as TagProps<TTag>);
}
/** Clones a given element, shallowly copying the props object. */
export function cloneElement<TTag extends Tag>(
el: Element<TTag>,
): Element<TTag> {
if (!isElement(el)) {
throw new TypeError("Cannot clone non-element");
}
return new Element(el.tag, {...el.props});
}
/*** ELEMENT UTILITIES ***/
// WHAT ARE WE DOING TO THE CHILDREN???
/**
* All values in the element tree are narrowed from the union in Child to
* NarrowedChild during rendering, to simplify element diffing.
*/
type NarrowedChild = Element | string | undefined;
function narrow(value: Children): NarrowedChild {
if (typeof value === "boolean" || value == null) {
return undefined;
} else if (typeof value === "string" || isElement(value)) {
return value;
} else if (typeof (value as any)[Symbol.iterator] === "function") {
return createElement(Fragment, null, value);
}
return value.toString();
}
/**
* A helper type which repesents all possible rendered values of an element.
*
* @template TNode - The node type for the element provided by the renderer.
*
* When asking the question, what is the "value" of a specific element, the
* answer varies depending on the tag:
*
* For host elements, the value is the nodes created for the element, e.g. the
* DOM node in the case of the DOMRenderer.
*
* For fragments, the value is the value of the
*
* For portals, the value is undefined, because a Portal element’s root and
* children are opaque to its parent.
*
* For components, the value can be any of the above, because the value of a
* component is determined by its immediate children.
*
* Rendered values can also be strings or arrays of nodes and strings, in the
* case of component or fragment elements with strings or multiple children.
*
* All of these possible values are reflected in this utility type.
*/
export type ElementValue<TNode> =
| Array<TNode | string>
| TNode
| string
| undefined;
/**
* Takes an array of element values and normalizes the output as an array of
* nodes and strings.
*
* @returns Normalized array of nodes and/or strings.
*
* Normalize will flatten only one level of nested arrays, because it is
* designed to be called once at each level of the tree. It will also
* concatenate adjacent strings and remove all undefined values.
*/
function normalize<TNode>(
values: Array<ElementValue<TNode>>,
): Array<TNode | string> {
const result: Array<TNode | string> = [];
let buffer: string | undefined;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (!value) {
// pass
} else if (typeof value === "string") {
buffer = (buffer || "") + value;
} else if (!Array.isArray(value)) {
if (buffer) {
result.push(buffer);
buffer = undefined;
}
result.push(value);
} else {
// We could use recursion here but it’s just easier to do it inline.
for (let j = 0; j < value.length; j++) {
const value1 = value[j];
if (!value1) {
// pass
} else if (typeof value1 === "string") {
buffer = (buffer || "") + value1;
} else {
if (buffer) {
result.push(buffer);
buffer = undefined;
}
result.push(value1);
}
}
}
}
if (buffer) {
result.push(buffer);
}
return result;
}
/**
* @internal
* The internal nodes which are cached and diffed against new elements when
* rendering element trees.
*/
class Retainer<TNode> {
/**
* The element associated with this retainer.
*/
declare el: Element;
/**
* The context associated with this element. Will only be defined for
* component elements.
*/
declare ctx: ContextImpl<TNode> | undefined;
/**
* The retainer children of this element. Retainers form a tree which mirrors
* elements. Can be a single child or undefined as a memory optimization.
*/
declare children: Array<RetainerChild<TNode>> | RetainerChild<TNode>;
/**
* The value associated with this element.
*/
declare value: ElementValue<TNode>;
/**
* The cached child values of this element. Only host and component elements
* will use this property.
*/
declare cachedChildValues: ElementValue<TNode>;
/**
* The child which this retainer replaces. This property is used when an
* async retainer tree replaces previously rendered elements, so that the
* previously rendered elements can remain visible until the async tree
* fulfills. Will be set to undefined once this subtree fully renders.
*/
declare fallbackValue: RetainerChild<TNode>;
declare inflightValue: Promise<ElementValue<TNode>> | undefined;
declare onNextValues: Function | undefined;
constructor(el: Element) {
this.el = el;
this.ctx = undefined;
this.children = undefined;
this.value = undefined;
this.cachedChildValues = undefined;
this.fallbackValue = undefined;
this.inflightValue = undefined;
this.onNextValues = undefined;
}
}
/**
* The retainer equivalent of ElementValue
*/
type RetainerChild<TNode> = Retainer<TNode> | string | undefined;
/**
* Finds the value of the element according to its type.
*
* @returns The value of the element.
*/
function getValue<TNode>(ret: Retainer<TNode>): ElementValue<TNode> {
if (typeof ret.fallbackValue !== "undefined") {
return typeof ret.fallbackValue === "object"
? getValue(ret.fallbackValue)
: ret.fallbackValue;
} else if (ret.el.tag === Portal) {
return;
} else if (typeof ret.el.tag !== "function" && ret.el.tag !== Fragment) {
return ret.value;
}
return unwrap(getChildValues(ret));
}
/**
* Walks an element’s children to find its child values.
*
* @returns A normalized array of nodes and strings.
*/
function getChildValues<TNode>(ret: Retainer<TNode>): Array<TNode | string> {
if (ret.cachedChildValues) {
return wrap(ret.cachedChildValues);
}
const values: Array<ElementValue<TNode>> = [];
const children = wrap(ret.children);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child) {
values.push(typeof child === "string" ? child : getValue(child));
}
}
const values1 = normalize(values);
const tag = ret.el.tag;
if (typeof tag === "function" || (tag !== Fragment && tag !== Raw)) {
ret.cachedChildValues = unwrap(values1);
}
return values1;
}
export interface HydrationData<TNode> {
props: Record<string, unknown>;
children: Array<TNode | string>;
}
// TODO: Document the interface and methods
export interface RendererImpl<
TNode,
TScope,
TRoot extends TNode = TNode,
TResult = ElementValue<TNode>,
> {
scope<TTag extends string | symbol>(
scope: TScope | undefined,
tag: TTag,
props: TagProps<TTag>,
): TScope | undefined;
create<TTag extends string | symbol>(
tag: TTag,
props: TagProps<TTag>,
scope: TScope | undefined,
): TNode;
hydrate<TTag extends string | symbol>(
tag: TTag,
node: TNode | TRoot,
props: TagProps<TTag>,
): HydrationData<TNode> | undefined;
/**
* Called when an element’s rendered value is exposed via render, schedule,
* refresh, refs, or generator yield expressions.
*
* @param value - The value of the element being read. Can be a node, a
* string, undefined, or an array of nodes and strings, depending on the
* element.
*
* @returns Varies according to the specific renderer subclass. By default,
* it exposes the element’s value.
*
* This is useful for renderers which don’t want to expose their internal
* nodes. For instance, the HTML renderer will convert all internal nodes to
* strings.
*/
read(value: ElementValue<TNode>): TResult;
/**
* Called for each string in an element tree.
*
* @param text - The string child.
* @param scope - The current scope.
*
* @returns A string to be passed to arrange.
*
* Rather than returning Text nodes as we would in the DOM case, for example,
* we delay that step for Renderer.prototype.arrange. We do this so that
* adjacent strings can be concatenated, and the actual element tree can be
* rendered in normalized form.
*/
text(
text: string,
scope: TScope | undefined,
hydration: HydrationData<TNode> | undefined,
): string;
/**
* Called for each Raw element whose value prop is a string.
*
* @param text - The string child.
* @param scope - The current scope.
*
* @returns The parsed node or string.
*/
raw(
value: string | TNode,
scope: TScope | undefined,
hydration: HydrationData<TNode> | undefined,
): ElementValue<TNode>;
patch<TTag extends string | symbol, TName extends string>(
tag: TTag,
node: TNode,
name: TName,
value: unknown,
oldValue: unknown,
scope: TScope,
): unknown;
arrange<TTag extends string | symbol>(
tag: TTag,
node: TNode,
props: Record<string, unknown>,
children: Array<TNode | string>,
oldProps: Record<string, unknown> | undefined,
oldChildren: Array<TNode | string> | undefined,
): unknown;
dispose<TTag extends string | symbol>(
tag: TTag,
node: TNode,
props: Record<string, unknown>,
): unknown;
flush(root: TRoot): unknown;
}
const defaultRendererImpl: RendererImpl<unknown, unknown, unknown, unknown> = {
create() {
throw new Error("Not implemented");
},
hydrate() {
throw new Error("Not implemented");
},
scope: IDENTITY,
read: IDENTITY,
text: IDENTITY,
raw: IDENTITY,
patch: NOOP,
arrange: NOOP,
dispose: NOOP,
flush: NOOP,
};
const _RendererImpl = Symbol.for("crank.RendererImpl");
/**
* An abstract class which is subclassed to render to different target
* environments. Subclasses will typically call super() with a custom
* RendererImpl. This class is responsible for kicking off the rendering
* process and caching previous trees by root.
*
* @template TNode - The type of the node for a rendering environment.
* @template TScope - Data which is passed down the tree.
* @template TRoot - The type of the root for a rendering environment.
* @template TResult - The type of exposed values.
*/
export class Renderer<
TNode extends object = object,
TScope = unknown,
TRoot extends TNode = TNode,
TResult = ElementValue<TNode>,
> {
/**
* @internal
* A weakmap which stores element trees by root.
*/
declare cache: WeakMap<object, Retainer<TNode>>;
declare [_RendererImpl]: RendererImpl<TNode, TScope, TRoot, TResult>;
constructor(impl: Partial<RendererImpl<TNode, TScope, TRoot, TResult>>) {
this.cache = new WeakMap();
this[_RendererImpl] = {
...(defaultRendererImpl as RendererImpl<TNode, TScope, TRoot, TResult>),
...impl,
};
}
/**
* Renders an element tree into a specific root.
*
* @param children - An element tree. You can render null with a previously
* used root to delete the previously rendered element tree from the cache.
* @param root - The node to be rendered into. The renderer will cache
* element trees per root.
* @param bridge - An optional context that will be the ancestor context of all
* elements in the tree. Useful for connecting different renderers so that
* events/provisions properly propagate. The context for a given root must be
* the same or an error will be thrown.
*
* @returns The result of rendering the children, or a possible promise of
* the result if the element tree renders asynchronously.
*/
render(
children: Children,
root?: TRoot | undefined,
bridge?: Context | undefined,
): Promise<TResult> | TResult {
let ret: Retainer<TNode> | undefined;
const ctx = bridge && (bridge[_ContextImpl] as ContextImpl<TNode>);
if (typeof root === "object" && root !== null) {
ret = this.cache.get(root);
}
let oldProps: Record<string, any> | undefined;
if (ret === undefined) {
ret = new Retainer(createElement(Portal, {children, root}));
ret.value = root;
ret.ctx = ctx;
if (typeof root === "object" && root !== null && children != null) {
this.cache.set(root, ret);
}
} else if (ret.ctx !== ctx) {
throw new Error("Context mismatch");
} else {
oldProps = ret.el.props;
ret.el = createElement(Portal, {children, root});
if (typeof root === "object" && root !== null && children == null) {
this.cache.delete(root);
}
}
const impl = this[_RendererImpl];
const childValues = diffChildren(
impl,
root,
ret,
ctx,
impl.scope(undefined, Portal, ret.el.props),
ret,
children,
undefined, // hydration data
);
// We return the child values of the portal because portal elements
// themselves have no readable value.
if (isPromiseLike(childValues)) {
return childValues.then((childValues) =>
commitRootRender(impl, root, ctx, ret!, childValues, oldProps),
);
}
return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
}
hydrate(
children: Children,
root: TRoot,
bridge?: Context | undefined,
): Promise<TResult> | TResult {
const impl = this[_RendererImpl];
const ctx = bridge && (bridge[_ContextImpl] as ContextImpl<TNode>);
let ret: Retainer<TNode> | undefined;
ret = this.cache.get(root);
if (ret !== undefined) {
// If there is a retainer for the root, hydration is not necessary.
return this.render(children, root, bridge);
}
let oldProps: Record<string, any> | undefined;
ret = new Retainer(createElement(Portal, {children, root}));
ret.value = root;
if (typeof root === "object" && root !== null && children != null) {
this.cache.set(root, ret);
}
const hydrationData = impl.hydrate(Portal, root, {});
const childValues = diffChildren(
impl,
root,
ret,
ctx,
impl.scope(undefined, Portal, ret.el.props),
ret,
children,
hydrationData,
);
// We return the child values of the portal because portal elements
// themselves have no readable value.
if (isPromiseLike(childValues)) {
return childValues.then((childValues) =>
commitRootRender(impl, root, ctx, ret!, childValues, oldProps),
);
}
return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
}
}
/*** PRIVATE RENDERER FUNCTIONS ***/
function commitRootRender<TNode, TRoot extends TNode, TResult>(
renderer: RendererImpl<TNode, unknown, TRoot, TResult>,
root: TRoot | undefined,
ctx: ContextImpl<TNode> | undefined,
ret: Retainer<TNode>,
childValues: Array<TNode | string>,
oldProps: Record<string, any> | undefined,
): TResult {
// element is a host or portal element
if (root != null) {
renderer.arrange(
Portal,
root,
ret.el.props,
childValues,
oldProps,
wrap(ret.cachedChildValues),
);
flush(renderer, root);
}
ret.cachedChildValues = unwrap(childValues);
if (root == null) {
unmount(renderer, ret, ctx, ret);
}
return renderer.read(ret.cachedChildValues);
}
function diffChildren<TNode, TScope, TRoot extends TNode, TResult>(
renderer: RendererImpl<TNode, TScope, TRoot, TResult>,
root: TRoot | undefined,
host: Retainer<TNode>,
ctx: ContextImpl<TNode, TScope, TRoot, TResult> | undefined,
scope: TScope | undefined,
parent: Retainer<TNode>,
children: Children,
hydrationData: HydrationData<TNode> | undefined,
): Promise<Array<TNode | string>> | Array<TNode | string> {
const oldRetained = wrap(parent.children);
const newRetained: typeof oldRetained = [];
const newChildren = arrayify(children);
const values: Array<Promise<ElementValue<TNode>> | ElementValue<TNode>> = [];
let graveyard: Array<Retainer<TNode>> | undefined;
let childrenByKey: Map<Key, Retainer<TNode>> | undefined;
let seenKeys: Set<Key> | undefined;
let isAsync = false;
// When hydrating, sibling element trees must be rendered in order, because
// we do not know how many DOM nodes an element will render.
let hydrationBlock: Promise<unknown> | undefined;
let oi = 0;
let oldLength = oldRetained.length;
for (let ni = 0, newLength = newChildren.length; ni < newLength; ni++) {
// length checks to prevent index out of bounds deoptimizations.
let ret = oi >= oldLength ? undefined : oldRetained[oi];
let child = narrow(newChildren[ni]);
{
// aligning new children with old retainers
let oldKey = typeof ret === "object" ? ret.el.key : undefined;
let newKey = typeof child === "object" ? child.key : undefined;
if (newKey !== undefined && seenKeys && seenKeys.has(newKey)) {
console.error("Duplicate key", newKey);
newKey = undefined;
}
if (oldKey === newKey) {
if (childrenByKey !== undefined && newKey !== undefined) {
childrenByKey.delete(newKey);
}
oi++;
} else {
childrenByKey = childrenByKey || createChildrenByKey(oldRetained, oi);
if (newKey === undefined) {
while (ret !== undefined && oldKey !== undefined) {
oi++;
ret = oldRetained[oi];
oldKey = typeof ret === "object" ? ret.el.key : undefined;
}
oi++;
} else {
ret = childrenByKey.get(newKey);
if (ret !== undefined) {
childrenByKey.delete(newKey);
}
(seenKeys = seenKeys || new Set()).add(newKey);
}
}
}
// Updating
let value: Promise<ElementValue<TNode>> | ElementValue<TNode>;
if (typeof child === "object") {
if (child.tag === Copy || (typeof ret === "object" && ret.el === child)) {
value = getInflightValue(ret);
} else {
let oldProps: Record<string, any> | undefined;
let copy = false;
if (typeof ret === "object" && ret.el.tag === child.tag) {
oldProps = ret.el.props;
ret.el = child;
if (child.copy) {
value = getInflightValue(ret);
copy = true;
}
} else {
if (typeof ret === "object") {
(graveyard = graveyard || []).push(ret);
}
const fallback = ret;
ret = new Retainer<TNode>(child);
ret.fallbackValue = fallback;
}
if (copy) {
// pass
} else if (child.tag === Raw) {
value = hydrationBlock
? hydrationBlock.then(() =>
updateRaw(
renderer,
ret as Retainer<TNode>,
scope,
oldProps,
hydrationData,
),
)
: updateRaw(renderer, ret, scope, oldProps, hydrationData);
} else if (child.tag === Fragment) {
value = hydrationBlock
? hydrationBlock.then(() =>
updateFragment(
renderer,
root,
host,
ctx,
scope,
ret as Retainer<TNode>,
hydrationData,
),
)
: updateFragment(
renderer,
root,
host,
ctx,
scope,
ret,
hydrationData,
);
} else if (typeof child.tag === "function") {
value = hydrationBlock
? hydrationBlock.then(() =>
updateComponent(
renderer,
root,
host,
ctx,
scope,
ret as Retainer<TNode>,
oldProps,
hydrationData,
),
)
: updateComponent(
renderer,
root,
host,
ctx,
scope,
ret,
oldProps,
hydrationData,
);
} else {
value = hydrationBlock
? hydrationBlock.then(() =>
updateHost(
renderer,
root,
ctx,
scope,
ret as Retainer<TNode>,
oldProps,
hydrationData,
),
)
: updateHost(
renderer,
root,
ctx,
scope,
ret,
oldProps,
hydrationData,
);
}
}
if (isPromiseLike(value)) {
isAsync = true;
if (hydrationData !== undefined) {
hydrationBlock = value;
}
}
} else {
// child is a string or undefined
if (typeof ret === "object") {
(graveyard = graveyard || []).push(ret);
}
if (typeof child === "string") {
value = ret = renderer.text(child, scope, hydrationData);
} else {