@b9g/crank 0.5.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/crank.js CHANGED
@@ -1,1988 +1,2013 @@
1
1
  /// <reference types="crank.d.ts" />
2
- const NOOP = () => { };
3
- const IDENTITY = (value) => value;
4
- function wrap(value) {
5
- return value === undefined ? [] : Array.isArray(value) ? value : [value];
6
- }
7
- function unwrap(arr) {
8
- return arr.length === 0 ? undefined : arr.length === 1 ? arr[0] : arr;
9
- }
10
- /**
11
- * Ensures a value is an array.
12
- *
13
- * This function does the same thing as wrap() above except it handles nulls
14
- * and iterables, so it is appropriate for wrapping user-provided element
15
- * children.
16
- */
17
- function arrayify(value) {
18
- return value == null
19
- ? []
20
- : Array.isArray(value)
21
- ? value
22
- : typeof value === "string" ||
23
- typeof value[Symbol.iterator] !== "function"
24
- ? [value]
25
- : // TODO: inference broke in TypeScript 3.9.
26
- [...value];
27
- }
28
- function isIteratorLike(value) {
29
- return value != null && typeof value.next === "function";
30
- }
31
- function isPromiseLike(value) {
32
- return value != null && typeof value.then === "function";
33
- }
34
- /***
35
- * SPECIAL TAGS
36
- *
37
- * Crank provides a couple tags which have special meaning for the renderer.
38
- ***/
39
- /**
40
- * A special tag for grouping multiple children within the same parent.
41
- *
42
- * All non-string iterables which appear in the element tree are implicitly
43
- * wrapped in a fragment element.
44
- *
45
- * This tag is just the empty string, and you can use the empty string in
46
- * createElement calls or transpiler options directly to avoid having to
47
- * reference this export.
48
- */
49
- const Fragment = "";
50
- // TODO: We assert the following symbol tags as any because TypeScript support
51
- // for symbol tags in JSX doesn’t exist yet.
52
- // https://github.com/microsoft/TypeScript/issues/38367
53
- /**
54
- * A special tag for rendering into a new root node via a root prop.
55
- *
56
- * This tag is useful for creating element trees with multiple roots, for
57
- * things like modals or tooltips.
58
- *
59
- * Renderer.prototype.render() will implicitly wrap top-level element trees in
60
- * a Portal element.
61
- */
62
- const Portal = Symbol.for("crank.Portal");
63
- /**
64
- * A special tag which preserves whatever was previously rendered in the
65
- * element’s position.
66
- *
67
- * Copy elements are useful for when you want to prevent a subtree from
68
- * rerendering as a performance optimization. Copy elements can also be keyed,
69
- * in which case the previously rendered keyed element will be copied.
70
- */
71
- const Copy = Symbol.for("crank.Copy");
72
- /**
73
- * A special tag for injecting raw nodes or strings via a value prop.
74
- *
75
- * Renderer.prototype.raw() is called with the value prop.
76
- */
77
- const Raw = Symbol.for("crank.Raw");
78
- const ElementSymbol = Symbol.for("crank.Element");
79
- /**
80
- * Elements are the basic building blocks of Crank applications. They are
81
- * JavaScript objects which are interpreted by special classes called renderers
82
- * to produce and manage stateful nodes.
83
- *
84
- * @template {Tag} [TTag=Tag] - The type of the tag of the element.
85
- *
86
- * @example
87
- * // specific element types
88
- * let div: Element<"div">;
89
- * let portal: Element<Portal>;
90
- * let myEl: Element<MyComponent>;
91
- *
92
- * // general element types
93
- * let host: Element<string | symbol>;
94
- * let component: Element<Component>;
95
- *
96
- * Typically, you use a helper function like createElement to create elements
97
- * rather than instatiating this class directly.
98
- */
99
- class Element {
100
- constructor(tag, props, key, ref, static_) {
101
- this.tag = tag;
102
- this.props = props;
103
- this.key = key;
104
- this.ref = ref;
105
- this.static_ = static_;
106
- }
107
- }
108
- // See Element interface
109
- Element.prototype.$$typeof = ElementSymbol;
110
- function isElement(value) {
111
- return value != null && value.$$typeof === ElementSymbol;
112
- }
113
- /**
114
- * Creates an element with the specified tag, props and children.
115
- *
116
- * This function is usually used as a transpilation target for JSX transpilers,
117
- * but it can also be called directly. It additionally extracts special props so
118
- * they aren’t accessible to renderer methods or components, and assigns the
119
- * children prop according to any additional arguments passed to the function.
120
- */
121
- function createElement(tag, props, ...children) {
122
- let key;
123
- let ref;
124
- let static_ = false;
125
- const props1 = {};
126
- if (props != null) {
127
- for (const name in props) {
128
- switch (name) {
129
- case "crank-key":
130
- case "c-key":
131
- case "$key":
132
- // We have to make sure we don’t assign null to the key because we
133
- // don’t check for null keys in the diffing functions.
134
- if (props[name] != null) {
135
- key = props[name];
136
- }
137
- break;
138
- case "crank-ref":
139
- case "c-ref":
140
- case "$ref":
141
- if (typeof props[name] === "function") {
142
- ref = props[name];
143
- }
144
- break;
145
- case "crank-static":
146
- case "c-static":
147
- case "$static":
148
- static_ = !!props[name];
149
- break;
150
- default:
151
- props1[name] = props[name];
152
- }
153
- }
154
- }
155
- if (children.length > 1) {
156
- props1.children = children;
157
- }
158
- else if (children.length === 1) {
159
- props1.children = children[0];
160
- }
161
- return new Element(tag, props1, key, ref, static_);
162
- }
163
- /** Clones a given element, shallowly copying the props object. */
164
- function cloneElement(el) {
165
- if (!isElement(el)) {
166
- throw new TypeError("Cannot clone non-element");
167
- }
168
- return new Element(el.tag, { ...el.props }, el.key, el.ref);
169
- }
170
- function narrow(value) {
171
- if (typeof value === "boolean" || value == null) {
172
- return undefined;
173
- }
174
- else if (typeof value === "string" || isElement(value)) {
175
- return value;
176
- }
177
- else if (typeof value[Symbol.iterator] === "function") {
178
- return createElement(Fragment, null, value);
179
- }
180
- return value.toString();
181
- }
182
- /**
183
- * Takes an array of element values and normalizes the output as an array of
184
- * nodes and strings.
185
- *
186
- * @returns Normalized array of nodes and/or strings.
187
- *
188
- * Normalize will flatten only one level of nested arrays, because it is
189
- * designed to be called once at each level of the tree. It will also
190
- * concatenate adjacent strings and remove all undefined values.
191
- */
192
- function normalize(values) {
193
- const result = [];
194
- let buffer;
195
- for (let i = 0; i < values.length; i++) {
196
- const value = values[i];
197
- if (!value) ;
198
- else if (typeof value === "string") {
199
- buffer = (buffer || "") + value;
200
- }
201
- else if (!Array.isArray(value)) {
202
- if (buffer) {
203
- result.push(buffer);
204
- buffer = undefined;
205
- }
206
- result.push(value);
207
- }
208
- else {
209
- // We could use recursion here but it’s just easier to do it inline.
210
- for (let j = 0; j < value.length; j++) {
211
- const value1 = value[j];
212
- if (!value1) ;
213
- else if (typeof value1 === "string") {
214
- buffer = (buffer || "") + value1;
215
- }
216
- else {
217
- if (buffer) {
218
- result.push(buffer);
219
- buffer = undefined;
220
- }
221
- result.push(value1);
222
- }
223
- }
224
- }
225
- }
226
- if (buffer) {
227
- result.push(buffer);
228
- }
229
- return result;
230
- }
231
- /**
232
- * @internal
233
- * The internal nodes which are cached and diffed against new elements when
234
- * rendering element trees.
235
- */
236
- class Retainer {
237
- constructor(el) {
238
- this.el = el;
239
- this.ctx = undefined;
240
- this.children = undefined;
241
- this.value = undefined;
242
- this.cachedChildValues = undefined;
243
- this.fallbackValue = undefined;
244
- this.inflightValue = undefined;
245
- this.onNextValues = undefined;
246
- }
247
- }
248
- /**
249
- * Finds the value of the element according to its type.
250
- *
251
- * @returns The value of the element.
252
- */
253
- function getValue(ret) {
254
- if (typeof ret.fallbackValue !== "undefined") {
255
- return typeof ret.fallbackValue === "object"
256
- ? getValue(ret.fallbackValue)
257
- : ret.fallbackValue;
258
- }
259
- else if (ret.el.tag === Portal) {
260
- return;
261
- }
262
- else if (typeof ret.el.tag !== "function" && ret.el.tag !== Fragment) {
263
- return ret.value;
264
- }
265
- return unwrap(getChildValues(ret));
266
- }
267
- /**
268
- * Walks an element’s children to find its child values.
269
- *
270
- * @returns A normalized array of nodes and strings.
271
- */
272
- function getChildValues(ret) {
273
- if (ret.cachedChildValues) {
274
- return wrap(ret.cachedChildValues);
275
- }
276
- const values = [];
277
- const children = wrap(ret.children);
278
- for (let i = 0; i < children.length; i++) {
279
- const child = children[i];
280
- if (child) {
281
- values.push(typeof child === "string" ? child : getValue(child));
282
- }
283
- }
284
- const values1 = normalize(values);
285
- const tag = ret.el.tag;
286
- if (typeof tag === "function" || (tag !== Fragment && tag !== Raw)) {
287
- ret.cachedChildValues = unwrap(values1);
288
- }
289
- return values1;
290
- }
291
- const defaultRendererImpl = {
292
- create() {
293
- throw new Error("Not implemented");
294
- },
295
- hydrate() {
296
- throw new Error("Not implemented");
297
- },
298
- scope: IDENTITY,
299
- read: IDENTITY,
300
- text: IDENTITY,
301
- raw: IDENTITY,
302
- patch: NOOP,
303
- arrange: NOOP,
304
- dispose: NOOP,
305
- flush: NOOP,
306
- };
307
- const _RendererImpl = Symbol.for("crank.RendererImpl");
308
- /**
309
- * An abstract class which is subclassed to render to different target
310
- * environments. This class is responsible for kicking off the rendering
311
- * process and caching previous trees by root.
312
- *
313
- * @template TNode - The type of the node for a rendering environment.
314
- * @template TScope - Data which is passed down the tree.
315
- * @template TRoot - The type of the root for a rendering environment.
316
- * @template TResult - The type of exposed values.
317
- */
318
- class Renderer {
319
- constructor(impl) {
320
- this.cache = new WeakMap();
321
- this[_RendererImpl] = {
322
- ...defaultRendererImpl,
323
- ...impl,
324
- };
325
- }
326
- /**
327
- * Renders an element tree into a specific root.
328
- *
329
- * @param children - An element tree. You can render null with a previously
330
- * used root to delete the previously rendered element tree from the cache.
331
- * @param root - The node to be rendered into. The renderer will cache
332
- * element trees per root.
333
- * @param bridge - An optional context that will be the ancestor context of all
334
- * elements in the tree. Useful for connecting different renderers so that
335
- * events/provisions properly propagate. The context for a given root must be
336
- * the same or an error will be thrown.
337
- *
338
- * @returns The result of rendering the children, or a possible promise of
339
- * the result if the element tree renders asynchronously.
340
- */
341
- render(children, root, bridge) {
342
- let ret;
343
- const ctx = bridge && bridge[_ContextImpl];
344
- if (typeof root === "object" && root !== null) {
345
- ret = this.cache.get(root);
346
- }
347
- let oldProps;
348
- if (ret === undefined) {
349
- ret = new Retainer(createElement(Portal, { children, root }));
350
- ret.value = root;
351
- ret.ctx = ctx;
352
- if (typeof root === "object" && root !== null && children != null) {
353
- this.cache.set(root, ret);
354
- }
355
- }
356
- else if (ret.ctx !== ctx) {
357
- throw new Error("Context mismatch");
358
- }
359
- else {
360
- oldProps = ret.el.props;
361
- ret.el = createElement(Portal, { children, root });
362
- if (typeof root === "object" && root !== null && children == null) {
363
- this.cache.delete(root);
364
- }
365
- }
366
- const impl = this[_RendererImpl];
367
- const childValues = diffChildren(impl, root, ret, ctx, impl.scope(undefined, Portal, ret.el.props), ret, children, undefined);
368
- // We return the child values of the portal because portal elements
369
- // themselves have no readable value.
370
- if (isPromiseLike(childValues)) {
371
- return childValues.then((childValues) => commitRootRender(impl, root, ctx, ret, childValues, oldProps));
372
- }
373
- return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
374
- }
375
- hydrate(children, root, bridge) {
376
- const impl = this[_RendererImpl];
377
- const ctx = bridge && bridge[_ContextImpl];
378
- let ret;
379
- ret = this.cache.get(root);
380
- if (ret !== undefined) {
381
- // If there is a retainer for the root, hydration is not necessary.
382
- return this.render(children, root, bridge);
383
- }
384
- let oldProps;
385
- ret = new Retainer(createElement(Portal, { children, root }));
386
- ret.value = root;
387
- if (typeof root === "object" && root !== null && children != null) {
388
- this.cache.set(root, ret);
389
- }
390
- const hydrationData = impl.hydrate(Portal, root, {});
391
- const childValues = diffChildren(impl, root, ret, ctx, impl.scope(undefined, Portal, ret.el.props), ret, children, hydrationData);
392
- // We return the child values of the portal because portal elements
393
- // themselves have no readable value.
394
- if (isPromiseLike(childValues)) {
395
- return childValues.then((childValues) => commitRootRender(impl, root, ctx, ret, childValues, oldProps));
396
- }
397
- return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
398
- }
399
- }
400
- /*** PRIVATE RENDERER FUNCTIONS ***/
401
- function commitRootRender(renderer, root, ctx, ret, childValues, oldProps) {
402
- // element is a host or portal element
403
- if (root != null) {
404
- renderer.arrange(Portal, root, ret.el.props, childValues, oldProps, wrap(ret.cachedChildValues));
405
- flush(renderer, root);
406
- }
407
- ret.cachedChildValues = unwrap(childValues);
408
- if (root == null) {
409
- unmount(renderer, ret, ctx, ret);
410
- }
411
- return renderer.read(ret.cachedChildValues);
412
- }
413
- function diffChildren(renderer, root, host, ctx, scope, parent, children, hydrationData) {
414
- const oldRetained = wrap(parent.children);
415
- const newRetained = [];
416
- const newChildren = arrayify(children);
417
- const values = [];
418
- let graveyard;
419
- let childrenByKey;
420
- let seenKeys;
421
- let isAsync = false;
422
- let hydrationBlock;
423
- let oi = 0;
424
- let oldLength = oldRetained.length;
425
- for (let ni = 0, newLength = newChildren.length; ni < newLength; ni++) {
426
- // length checks to prevent index out of bounds deoptimizations.
427
- let ret = oi >= oldLength ? undefined : oldRetained[oi];
428
- let child = narrow(newChildren[ni]);
429
- {
430
- // aligning new children with old retainers
431
- let oldKey = typeof ret === "object" ? ret.el.key : undefined;
432
- let newKey = typeof child === "object" ? child.key : undefined;
433
- if (newKey !== undefined && seenKeys && seenKeys.has(newKey)) {
434
- console.error("Duplicate key", newKey);
435
- newKey = undefined;
436
- }
437
- if (oldKey === newKey) {
438
- if (childrenByKey !== undefined && newKey !== undefined) {
439
- childrenByKey.delete(newKey);
440
- }
441
- oi++;
442
- }
443
- else {
444
- childrenByKey = childrenByKey || createChildrenByKey(oldRetained, oi);
445
- if (newKey === undefined) {
446
- while (ret !== undefined && oldKey !== undefined) {
447
- oi++;
448
- ret = oldRetained[oi];
449
- oldKey = typeof ret === "object" ? ret.el.key : undefined;
450
- }
451
- oi++;
452
- }
453
- else {
454
- ret = childrenByKey.get(newKey);
455
- if (ret !== undefined) {
456
- childrenByKey.delete(newKey);
457
- }
458
- (seenKeys = seenKeys || new Set()).add(newKey);
459
- }
460
- }
461
- }
462
- // Updating
463
- let value;
464
- if (typeof child === "object") {
465
- if (child.tag === Copy) {
466
- value = getInflightValue(ret);
467
- }
468
- else {
469
- let oldProps;
470
- let static_ = false;
471
- if (typeof ret === "object" && ret.el.tag === child.tag) {
472
- oldProps = ret.el.props;
473
- ret.el = child;
474
- if (child.static_) {
475
- value = getInflightValue(ret);
476
- static_ = true;
477
- }
478
- }
479
- else {
480
- if (typeof ret === "object") {
481
- (graveyard = graveyard || []).push(ret);
482
- }
483
- const fallback = ret;
484
- ret = new Retainer(child);
485
- ret.fallbackValue = fallback;
486
- }
487
- if (static_) ;
488
- else if (child.tag === Raw) {
489
- value = hydrationBlock
490
- ? hydrationBlock.then(() => updateRaw(renderer, ret, scope, oldProps, hydrationData))
491
- : updateRaw(renderer, ret, scope, oldProps, hydrationData);
492
- }
493
- else if (child.tag === Fragment) {
494
- value = hydrationBlock
495
- ? hydrationBlock.then(() => updateFragment(renderer, root, host, ctx, scope, ret, hydrationData))
496
- : updateFragment(renderer, root, host, ctx, scope, ret, hydrationData);
497
- }
498
- else if (typeof child.tag === "function") {
499
- value = hydrationBlock
500
- ? hydrationBlock.then(() => updateComponent(renderer, root, host, ctx, scope, ret, oldProps, hydrationData))
501
- : updateComponent(renderer, root, host, ctx, scope, ret, oldProps, hydrationData);
502
- }
503
- else {
504
- value = hydrationBlock
505
- ? hydrationBlock.then(() => updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData))
506
- : updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData);
507
- }
508
- }
509
- const ref = child.ref;
510
- if (isPromiseLike(value)) {
511
- isAsync = true;
512
- if (typeof ref === "function") {
513
- value = value.then((value) => {
514
- ref(renderer.read(value));
515
- return value;
516
- });
517
- }
518
- if (hydrationData !== undefined) {
519
- hydrationBlock = value;
520
- }
521
- }
522
- else {
523
- if (typeof ref === "function") {
524
- ref(renderer.read(value));
525
- }
526
- }
527
- }
528
- else {
529
- // child is a string or undefined
530
- if (typeof ret === "object") {
531
- (graveyard = graveyard || []).push(ret);
532
- }
533
- if (typeof child === "string") {
534
- value = ret = renderer.text(child, scope, hydrationData);
535
- }
536
- else {
537
- ret = undefined;
538
- }
539
- }
540
- values[ni] = value;
541
- newRetained[ni] = ret;
542
- }
543
- // cleanup remaining retainers
544
- for (; oi < oldLength; oi++) {
545
- const ret = oldRetained[oi];
546
- if (typeof ret === "object" &&
547
- (typeof ret.el.key === "undefined" ||
548
- !seenKeys ||
549
- !seenKeys.has(ret.el.key))) {
550
- (graveyard = graveyard || []).push(ret);
551
- }
552
- }
553
- if (childrenByKey !== undefined && childrenByKey.size > 0) {
554
- (graveyard = graveyard || []).push(...childrenByKey.values());
555
- }
556
- parent.children = unwrap(newRetained);
557
- if (isAsync) {
558
- let childValues1 = Promise.all(values).finally(() => {
559
- if (graveyard) {
560
- for (let i = 0; i < graveyard.length; i++) {
561
- unmount(renderer, host, ctx, graveyard[i]);
562
- }
563
- }
564
- });
565
- let onChildValues;
566
- childValues1 = Promise.race([
567
- childValues1,
568
- new Promise((resolve) => (onChildValues = resolve)),
569
- ]);
570
- if (parent.onNextValues) {
571
- parent.onNextValues(childValues1);
572
- }
573
- parent.onNextValues = onChildValues;
574
- return childValues1.then((childValues) => {
575
- parent.inflightValue = parent.fallbackValue = undefined;
576
- return normalize(childValues);
577
- });
578
- }
579
- else {
580
- if (graveyard) {
581
- for (let i = 0; i < graveyard.length; i++) {
582
- unmount(renderer, host, ctx, graveyard[i]);
583
- }
584
- }
585
- if (parent.onNextValues) {
586
- parent.onNextValues(values);
587
- parent.onNextValues = undefined;
588
- }
589
- parent.inflightValue = parent.fallbackValue = undefined;
590
- // We can assert there are no promises in the array because isAsync is false
591
- return normalize(values);
592
- }
593
- }
594
- function createChildrenByKey(children, offset) {
595
- const childrenByKey = new Map();
596
- for (let i = offset; i < children.length; i++) {
597
- const child = children[i];
598
- if (typeof child === "object" && typeof child.el.key !== "undefined") {
599
- childrenByKey.set(child.el.key, child);
600
- }
601
- }
602
- return childrenByKey;
603
- }
604
- function getInflightValue(child) {
605
- if (typeof child !== "object") {
606
- return child;
607
- }
608
- const ctx = typeof child.el.tag === "function" ? child.ctx : undefined;
609
- if (ctx && ctx.f & IsUpdating && ctx.inflightValue) {
610
- return ctx.inflightValue;
611
- }
612
- else if (child.inflightValue) {
613
- return child.inflightValue;
614
- }
615
- return getValue(child);
616
- }
617
- function updateRaw(renderer, ret, scope, oldProps, hydrationData) {
618
- const props = ret.el.props;
619
- if (!oldProps || oldProps.value !== props.value) {
620
- ret.value = renderer.raw(props.value, scope, hydrationData);
621
- }
622
- return ret.value;
623
- }
624
- function updateFragment(renderer, root, host, ctx, scope, ret, hydrationData) {
625
- const childValues = diffChildren(renderer, root, host, ctx, scope, ret, ret.el.props.children, hydrationData);
626
- if (isPromiseLike(childValues)) {
627
- ret.inflightValue = childValues.then((childValues) => unwrap(childValues));
628
- return ret.inflightValue;
629
- }
630
- return unwrap(childValues);
631
- }
632
- function updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData) {
633
- const el = ret.el;
634
- const tag = el.tag;
635
- let hydrationValue;
636
- if (el.tag === Portal) {
637
- root = ret.value = el.props.root;
638
- }
639
- else {
640
- if (hydrationData !== undefined) {
641
- const value = hydrationData.children.shift();
642
- hydrationValue = value;
643
- }
644
- }
645
- scope = renderer.scope(scope, tag, el.props);
646
- let childHydrationData;
647
- if (hydrationValue != null && typeof hydrationValue !== "string") {
648
- childHydrationData = renderer.hydrate(tag, hydrationValue, el.props);
649
- if (childHydrationData === undefined) {
650
- hydrationValue = undefined;
651
- }
652
- }
653
- const childValues = diffChildren(renderer, root, ret, ctx, scope, ret, ret.el.props.children, childHydrationData);
654
- if (isPromiseLike(childValues)) {
655
- ret.inflightValue = childValues.then((childValues) => commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue));
656
- return ret.inflightValue;
657
- }
658
- return commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue);
659
- }
660
- function commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue) {
661
- const tag = ret.el.tag;
662
- let value = ret.value;
663
- if (hydrationValue != null) {
664
- value = ret.value = hydrationValue;
665
- }
666
- let props = ret.el.props;
667
- let copied;
668
- if (tag !== Portal) {
669
- if (value == null) {
670
- // This assumes that renderer.create does not return nullish values.
671
- value = ret.value = renderer.create(tag, props, scope);
672
- }
673
- for (const propName in { ...oldProps, ...props }) {
674
- const propValue = props[propName];
675
- if (propValue === Copy) {
676
- // TODO: The Copy tag doubles as a way to skip the patching of a prop.
677
- // Not sure about this feature. Should probably be removed.
678
- (copied = copied || new Set()).add(propName);
679
- }
680
- else if (propName !== "children") {
681
- renderer.patch(tag, value, propName, propValue, oldProps && oldProps[propName], scope);
682
- }
683
- }
684
- }
685
- if (copied) {
686
- props = { ...ret.el.props };
687
- for (const name of copied) {
688
- props[name] = oldProps && oldProps[name];
689
- }
690
- ret.el = new Element(tag, props, ret.el.key, ret.el.ref);
691
- }
692
- renderer.arrange(tag, value, props, childValues, oldProps, wrap(ret.cachedChildValues));
693
- ret.cachedChildValues = unwrap(childValues);
694
- if (tag === Portal) {
695
- flush(renderer, ret.value);
696
- return;
697
- }
698
- return value;
699
- }
700
- function flush(renderer, root, initiator) {
701
- renderer.flush(root);
702
- if (typeof root !== "object" || root === null) {
703
- return;
704
- }
705
- const flushMap = flushMaps.get(root);
706
- if (flushMap) {
707
- if (initiator) {
708
- const flushMap1 = new Map();
709
- for (let [ctx, callbacks] of flushMap) {
710
- if (!ctxContains(initiator, ctx)) {
711
- flushMap.delete(ctx);
712
- flushMap1.set(ctx, callbacks);
713
- }
714
- }
715
- if (flushMap1.size) {
716
- flushMaps.set(root, flushMap1);
717
- }
718
- else {
719
- flushMaps.delete(root);
720
- }
721
- }
722
- else {
723
- flushMaps.delete(root);
724
- }
725
- for (const [ctx, callbacks] of flushMap) {
726
- const value = renderer.read(getValue(ctx.ret));
727
- for (const callback of callbacks) {
728
- callback(value);
729
- }
730
- }
731
- }
732
- }
733
- function unmount(renderer, host, ctx, ret) {
734
- if (typeof ret.el.tag === "function") {
735
- ctx = ret.ctx;
736
- unmountComponent(ctx);
737
- }
738
- else if (ret.el.tag === Portal) {
739
- host = ret;
740
- renderer.arrange(Portal, host.value, host.el.props, [], host.el.props, wrap(host.cachedChildValues));
741
- flush(renderer, host.value);
742
- }
743
- else if (ret.el.tag !== Fragment) {
744
- if (isEventTarget(ret.value)) {
745
- const records = getListenerRecords(ctx, host);
746
- for (let i = 0; i < records.length; i++) {
747
- const record = records[i];
748
- ret.value.removeEventListener(record.type, record.callback, record.options);
749
- }
750
- }
751
- renderer.dispose(ret.el.tag, ret.value, ret.el.props);
752
- host = ret;
753
- }
754
- const children = wrap(ret.children);
755
- for (let i = 0; i < children.length; i++) {
756
- const child = children[i];
757
- if (typeof child === "object") {
758
- unmount(renderer, host, ctx, child);
759
- }
760
- }
761
- }
762
- /*** CONTEXT FLAGS ***/
763
- /**
764
- * A flag which is true when the component is initialized or updated by an
765
- * ancestor component or the root render call.
766
- *
767
- * Used to determine things like whether the nearest host ancestor needs to be
768
- * rearranged.
769
- */
770
- const IsUpdating = 1 << 0;
771
- /**
772
- * A flag which is true when the component is synchronously executing.
773
- *
774
- * Used to guard against components triggering stack overflow or generator error.
775
- */
776
- const IsSyncExecuting = 1 << 1;
777
- /**
778
- * A flag which is true when the component is in a for...of loop.
779
- */
780
- const IsInForOfLoop = 1 << 2;
781
- /**
782
- * A flag which is true when the component is in a for await...of loop.
783
- */
784
- const IsInForAwaitOfLoop = 1 << 3;
785
- /**
786
- * A flag which is true when the component starts the render loop but has not
787
- * yielded yet.
788
- *
789
- * Used to make sure that components yield at least once per loop.
790
- */
791
- const NeedsToYield = 1 << 4;
792
- /**
793
- * A flag used by async generator components in conjunction with the
794
- * onAvailable callback to mark whether new props can be pulled via the context
795
- * async iterator. See the Symbol.asyncIterator method and the
796
- * resumeCtxIterator function.
797
- */
798
- const PropsAvailable = 1 << 5;
799
- /**
800
- * A flag which is set when a component errors.
801
- *
802
- * NOTE: This is mainly used to prevent some false positives in component
803
- * yields or returns undefined warnings. The reason we’re using this versus
804
- * IsUnmounted is a very troubling test (cascades sync generator parent and
805
- * sync generator child) where synchronous code causes a stack overflow error
806
- * in a non-deterministic way. Deeply disturbing stuff.
807
- */
808
- const IsErrored = 1 << 6;
809
- /**
810
- * A flag which is set when the component is unmounted. Unmounted components
811
- * are no longer in the element tree and cannot refresh or rerender.
812
- */
813
- const IsUnmounted = 1 << 7;
814
- /**
815
- * A flag which indicates that the component is a sync generator component.
816
- */
817
- const IsSyncGen = 1 << 8;
818
- /**
819
- * A flag which indicates that the component is an async generator component.
820
- */
821
- const IsAsyncGen = 1 << 9;
822
- /**
823
- * A flag which is set while schedule callbacks are called.
824
- */
825
- const IsScheduling = 1 << 10;
826
- /**
827
- * A flag which is set when a schedule callback calls refresh.
828
- */
829
- const IsSchedulingRefresh = 1 << 11;
830
- const provisionMaps = new WeakMap();
831
- const scheduleMap = new WeakMap();
832
- const cleanupMap = new WeakMap();
833
- // keys are roots
834
- const flushMaps = new WeakMap();
835
- /**
836
- * @internal
837
- * The internal class which holds context data.
838
- */
839
- class ContextImpl {
840
- constructor(renderer, root, host, parent, scope, ret) {
841
- this.f = 0;
842
- this.owner = new Context(this);
843
- this.renderer = renderer;
844
- this.root = root;
845
- this.host = host;
846
- this.parent = parent;
847
- this.scope = scope;
848
- this.ret = ret;
849
- this.iterator = undefined;
850
- this.inflightBlock = undefined;
851
- this.inflightValue = undefined;
852
- this.enqueuedBlock = undefined;
853
- this.enqueuedValue = undefined;
854
- this.onProps = undefined;
855
- this.onPropsRequested = undefined;
856
- }
857
- }
858
- const _ContextImpl = Symbol.for("crank.ContextImpl");
859
- /**
860
- * A class which is instantiated and passed to every component as its this
861
- * value. Contexts form a tree just like elements and all components in the
862
- * element tree are connected via contexts. Components can use this tree to
863
- * communicate data upwards via events and downwards via provisions.
864
- *
865
- * @template [T=*] - The expected shape of the props passed to the component,
866
- * or a component function. Used to strongly type the Context iterator methods.
867
- * @template [TResult=*] - The readable element value type. It is used in
868
- * places such as the return value of refresh and the argument passed to
869
- * schedule and cleanup callbacks.
870
- */
871
- class Context {
872
- // TODO: If we could make the constructor function take a nicer value, it
873
- // would be useful for testing purposes.
874
- constructor(impl) {
875
- this[_ContextImpl] = impl;
876
- }
877
- /**
878
- * The current props of the associated element.
879
- *
880
- * Typically, you should read props either via the first parameter of the
881
- * component or via the context iterator methods. This property is mainly for
882
- * plugins or utilities which wrap contexts.
883
- */
884
- get props() {
885
- return this[_ContextImpl].ret.el.props;
886
- }
887
- // TODO: Should we rename this???
888
- /**
889
- * The current value of the associated element.
890
- *
891
- * Typically, you should read values via refs, generator yield expressions,
892
- * or the refresh, schedule, cleanup, or flush methods. This property is
893
- * mainly for plugins or utilities which wrap contexts.
894
- */
895
- get value() {
896
- return this[_ContextImpl].renderer.read(getValue(this[_ContextImpl].ret));
897
- }
898
- *[Symbol.iterator]() {
899
- const ctx = this[_ContextImpl];
900
- try {
901
- ctx.f |= IsInForOfLoop;
902
- while (!(ctx.f & IsUnmounted)) {
903
- if (ctx.f & NeedsToYield) {
904
- throw new Error("Context iterated twice without a yield");
905
- }
906
- else {
907
- ctx.f |= NeedsToYield;
908
- }
909
- yield ctx.ret.el.props;
910
- }
911
- }
912
- finally {
913
- ctx.f &= ~IsInForOfLoop;
914
- }
915
- }
916
- async *[Symbol.asyncIterator]() {
917
- const ctx = this[_ContextImpl];
918
- if (ctx.f & IsSyncGen) {
919
- throw new Error("Use for...of in sync generator components");
920
- }
921
- try {
922
- ctx.f |= IsInForAwaitOfLoop;
923
- while (!(ctx.f & IsUnmounted)) {
924
- if (ctx.f & NeedsToYield) {
925
- throw new Error("Context iterated twice without a yield");
926
- }
927
- else {
928
- ctx.f |= NeedsToYield;
929
- }
930
- if (ctx.f & PropsAvailable) {
931
- ctx.f &= ~PropsAvailable;
932
- yield ctx.ret.el.props;
933
- }
934
- else {
935
- const props = await new Promise((resolve) => (ctx.onProps = resolve));
936
- if (ctx.f & IsUnmounted) {
937
- break;
938
- }
939
- yield props;
940
- }
941
- if (ctx.onPropsRequested) {
942
- ctx.onPropsRequested();
943
- ctx.onPropsRequested = undefined;
944
- }
945
- }
946
- }
947
- finally {
948
- ctx.f &= ~IsInForAwaitOfLoop;
949
- if (ctx.onPropsRequested) {
950
- ctx.onPropsRequested();
951
- ctx.onPropsRequested = undefined;
952
- }
953
- }
954
- }
955
- /**
956
- * Re-executes a component.
957
- *
958
- * @returns The rendered value of the component or a promise thereof if the
959
- * component or its children execute asynchronously.
960
- *
961
- * The refresh method works a little differently for async generator
962
- * components, in that it will resume the Context’s props async iterator
963
- * rather than resuming execution. This is because async generator components
964
- * are perpetually resumed independent of updates, and rely on the props
965
- * async iterator to suspend.
966
- */
967
- refresh() {
968
- const ctx = this[_ContextImpl];
969
- if (ctx.f & IsUnmounted) {
970
- console.error("Component is unmounted");
971
- return ctx.renderer.read(undefined);
972
- }
973
- else if (ctx.f & IsSyncExecuting) {
974
- console.error("Component is already executing");
975
- return this.value;
976
- }
977
- const value = enqueueComponentRun(ctx);
978
- if (isPromiseLike(value)) {
979
- return value.then((value) => ctx.renderer.read(value));
980
- }
981
- return ctx.renderer.read(value);
982
- }
983
- /**
984
- * Registers a callback which fires when the component commits. Will only
985
- * fire once per callback and update.
986
- */
987
- schedule(callback) {
988
- const ctx = this[_ContextImpl];
989
- let callbacks = scheduleMap.get(ctx);
990
- if (!callbacks) {
991
- callbacks = new Set();
992
- scheduleMap.set(ctx, callbacks);
993
- }
994
- callbacks.add(callback);
995
- }
996
- /**
997
- * Registers a callback which fires when the component’s children are
998
- * rendered into the root. Will only fire once per callback and render.
999
- */
1000
- flush(callback) {
1001
- const ctx = this[_ContextImpl];
1002
- if (typeof ctx.root !== "object" || ctx.root === null) {
1003
- return;
1004
- }
1005
- let flushMap = flushMaps.get(ctx.root);
1006
- if (!flushMap) {
1007
- flushMap = new Map();
1008
- flushMaps.set(ctx.root, flushMap);
1009
- }
1010
- let callbacks = flushMap.get(ctx);
1011
- if (!callbacks) {
1012
- callbacks = new Set();
1013
- flushMap.set(ctx, callbacks);
1014
- }
1015
- callbacks.add(callback);
1016
- }
1017
- /**
1018
- * Registers a callback which fires when the component unmounts. Will only
1019
- * fire once per callback.
1020
- */
1021
- cleanup(callback) {
1022
- const ctx = this[_ContextImpl];
1023
- if (ctx.f & IsUnmounted) {
1024
- const value = ctx.renderer.read(getValue(ctx.ret));
1025
- callback(value);
1026
- return;
1027
- }
1028
- let callbacks = cleanupMap.get(ctx);
1029
- if (!callbacks) {
1030
- callbacks = new Set();
1031
- cleanupMap.set(ctx, callbacks);
1032
- }
1033
- callbacks.add(callback);
1034
- }
1035
- consume(key) {
1036
- for (let ctx = this[_ContextImpl].parent; ctx !== undefined; ctx = ctx.parent) {
1037
- const provisions = provisionMaps.get(ctx);
1038
- if (provisions && provisions.has(key)) {
1039
- return provisions.get(key);
1040
- }
1041
- }
1042
- }
1043
- provide(key, value) {
1044
- const ctx = this[_ContextImpl];
1045
- let provisions = provisionMaps.get(ctx);
1046
- if (!provisions) {
1047
- provisions = new Map();
1048
- provisionMaps.set(ctx, provisions);
1049
- }
1050
- provisions.set(key, value);
1051
- }
1052
- addEventListener(type, listener, options) {
1053
- const ctx = this[_ContextImpl];
1054
- let listeners;
1055
- if (!isListenerOrListenerObject(listener)) {
1056
- return;
1057
- }
1058
- else {
1059
- const listeners1 = listenersMap.get(ctx);
1060
- if (listeners1) {
1061
- listeners = listeners1;
1062
- }
1063
- else {
1064
- listeners = [];
1065
- listenersMap.set(ctx, listeners);
1066
- }
1067
- }
1068
- options = normalizeListenerOptions(options);
1069
- let callback;
1070
- if (typeof listener === "object") {
1071
- callback = () => listener.handleEvent.apply(listener, arguments);
1072
- }
1073
- else {
1074
- callback = listener;
1075
- }
1076
- const record = { type, listener, callback, options };
1077
- if (options.once) {
1078
- record.callback = function () {
1079
- const i = listeners.indexOf(record);
1080
- if (i !== -1) {
1081
- listeners.splice(i, 1);
1082
- }
1083
- return callback.apply(this, arguments);
1084
- };
1085
- }
1086
- if (listeners.some((record1) => record.type === record1.type &&
1087
- record.listener === record1.listener &&
1088
- !record.options.capture === !record1.options.capture)) {
1089
- return;
1090
- }
1091
- listeners.push(record);
1092
- // TODO: is it possible to separate out the EventTarget delegation logic
1093
- for (const value of getChildValues(ctx.ret)) {
1094
- if (isEventTarget(value)) {
1095
- value.addEventListener(record.type, record.callback, record.options);
1096
- }
1097
- }
1098
- }
1099
- removeEventListener(type, listener, options) {
1100
- const ctx = this[_ContextImpl];
1101
- const listeners = listenersMap.get(ctx);
1102
- if (listeners == null || !isListenerOrListenerObject(listener)) {
1103
- return;
1104
- }
1105
- const options1 = normalizeListenerOptions(options);
1106
- const i = listeners.findIndex((record) => record.type === type &&
1107
- record.listener === listener &&
1108
- !record.options.capture === !options1.capture);
1109
- if (i === -1) {
1110
- return;
1111
- }
1112
- const record = listeners[i];
1113
- listeners.splice(i, 1);
1114
- // TODO: is it possible to separate out the EventTarget delegation logic
1115
- for (const value of getChildValues(ctx.ret)) {
1116
- if (isEventTarget(value)) {
1117
- value.removeEventListener(record.type, record.callback, record.options);
1118
- }
1119
- }
1120
- }
1121
- dispatchEvent(ev) {
1122
- const ctx = this[_ContextImpl];
1123
- const path = [];
1124
- for (let parent = ctx.parent; parent !== undefined; parent = parent.parent) {
1125
- path.push(parent);
1126
- }
1127
- // We patch the stopImmediatePropagation method because ev.cancelBubble
1128
- // only informs us if stopPropagation was called and there are no
1129
- // properties which inform us if stopImmediatePropagation was called.
1130
- let immediateCancelBubble = false;
1131
- const stopImmediatePropagation = ev.stopImmediatePropagation;
1132
- setEventProperty(ev, "stopImmediatePropagation", () => {
1133
- immediateCancelBubble = true;
1134
- return stopImmediatePropagation.call(ev);
1135
- });
1136
- setEventProperty(ev, "target", ctx.owner);
1137
- // The only possible errors in this block are errors thrown by callbacks,
1138
- // and dispatchEvent will only log these errors rather than throwing
1139
- // them. Therefore, we place all code in a try block, log errors in the
1140
- // catch block, and use an unsafe return statement in the finally block.
1141
- //
1142
- // Each early return within the try block returns true because while the
1143
- // return value is overridden in the finally block, TypeScript
1144
- // (justifiably) does not recognize the unsafe return statement.
1145
- try {
1146
- setEventProperty(ev, "eventPhase", CAPTURING_PHASE);
1147
- for (let i = path.length - 1; i >= 0; i--) {
1148
- const target = path[i];
1149
- const listeners = listenersMap.get(target);
1150
- if (listeners) {
1151
- setEventProperty(ev, "currentTarget", target.owner);
1152
- for (const record of listeners) {
1153
- if (record.type === ev.type && record.options.capture) {
1154
- try {
1155
- record.callback.call(target.owner, ev);
1156
- }
1157
- catch (err) {
1158
- console.error(err);
1159
- }
1160
- if (immediateCancelBubble) {
1161
- return true;
1162
- }
1163
- }
1164
- }
1165
- }
1166
- if (ev.cancelBubble) {
1167
- return true;
1168
- }
1169
- }
1170
- {
1171
- setEventProperty(ev, "eventPhase", AT_TARGET);
1172
- setEventProperty(ev, "currentTarget", ctx.owner);
1173
- const propCallback = ctx.ret.el.props["on" + ev.type];
1174
- if (propCallback != null) {
1175
- propCallback(ev);
1176
- if (immediateCancelBubble || ev.cancelBubble) {
1177
- return true;
1178
- }
1179
- }
1180
- const listeners = listenersMap.get(ctx);
1181
- if (listeners) {
1182
- for (const record of listeners) {
1183
- if (record.type === ev.type) {
1184
- try {
1185
- record.callback.call(ctx.owner, ev);
1186
- }
1187
- catch (err) {
1188
- console.error(err);
1189
- }
1190
- if (immediateCancelBubble) {
1191
- return true;
1192
- }
1193
- }
1194
- }
1195
- if (ev.cancelBubble) {
1196
- return true;
1197
- }
1198
- }
1199
- }
1200
- if (ev.bubbles) {
1201
- setEventProperty(ev, "eventPhase", BUBBLING_PHASE);
1202
- for (let i = 0; i < path.length; i++) {
1203
- const target = path[i];
1204
- const listeners = listenersMap.get(target);
1205
- if (listeners) {
1206
- setEventProperty(ev, "currentTarget", target.owner);
1207
- for (const record of listeners) {
1208
- if (record.type === ev.type && !record.options.capture) {
1209
- try {
1210
- record.callback.call(target.owner, ev);
1211
- }
1212
- catch (err) {
1213
- console.error(err);
1214
- }
1215
- if (immediateCancelBubble) {
1216
- return true;
1217
- }
1218
- }
1219
- }
1220
- }
1221
- if (ev.cancelBubble) {
1222
- return true;
1223
- }
1224
- }
1225
- }
1226
- }
1227
- finally {
1228
- setEventProperty(ev, "eventPhase", NONE);
1229
- setEventProperty(ev, "currentTarget", null);
1230
- // eslint-disable-next-line no-unsafe-finally
1231
- return !ev.defaultPrevented;
1232
- }
1233
- }
1234
- }
1235
- /*** PRIVATE CONTEXT FUNCTIONS ***/
1236
- function ctxContains(parent, child) {
1237
- for (let current = child; current !== undefined; current = current.parent) {
1238
- if (current === parent) {
1239
- return true;
1240
- }
1241
- }
1242
- return false;
1243
- }
1244
- function updateComponent(renderer, root, host, parent, scope, ret, oldProps, hydrationData) {
1245
- let ctx;
1246
- if (oldProps) {
1247
- ctx = ret.ctx;
1248
- if (ctx.f & IsSyncExecuting) {
1249
- console.error("Component is already executing");
1250
- return ret.cachedChildValues;
1251
- }
1252
- }
1253
- else {
1254
- ctx = ret.ctx = new ContextImpl(renderer, root, host, parent, scope, ret);
1255
- }
1256
- ctx.f |= IsUpdating;
1257
- return enqueueComponentRun(ctx, hydrationData);
1258
- }
1259
- function updateComponentChildren(ctx, children, hydrationData) {
1260
- if (ctx.f & IsUnmounted) {
1261
- return;
1262
- }
1263
- else if (ctx.f & IsErrored) {
1264
- // This branch is necessary for some race conditions where this function is
1265
- // called after iterator.throw() in async generator components.
1266
- return;
1267
- }
1268
- else if (children === undefined) {
1269
- console.error("A component has returned or yielded undefined. If this was intentional, return or yield null instead.");
1270
- }
1271
- let childValues;
1272
- try {
1273
- // TODO: WAT
1274
- // We set the isExecuting flag in case a child component dispatches an event
1275
- // which bubbles to this component and causes a synchronous refresh().
1276
- ctx.f |= IsSyncExecuting;
1277
- childValues = diffChildren(ctx.renderer, ctx.root, ctx.host, ctx, ctx.scope, ctx.ret, narrow(children), hydrationData);
1278
- }
1279
- finally {
1280
- ctx.f &= ~IsSyncExecuting;
1281
- }
1282
- if (isPromiseLike(childValues)) {
1283
- ctx.ret.inflightValue = childValues.then((childValues) => commitComponent(ctx, childValues));
1284
- return ctx.ret.inflightValue;
1285
- }
1286
- return commitComponent(ctx, childValues);
1287
- }
1288
- function commitComponent(ctx, values) {
1289
- if (ctx.f & IsUnmounted) {
1290
- return;
1291
- }
1292
- const listeners = listenersMap.get(ctx);
1293
- if (listeners && listeners.length) {
1294
- for (let i = 0; i < values.length; i++) {
1295
- const value = values[i];
1296
- if (isEventTarget(value)) {
1297
- for (let j = 0; j < listeners.length; j++) {
1298
- const record = listeners[j];
1299
- value.addEventListener(record.type, record.callback, record.options);
1300
- }
1301
- }
1302
- }
1303
- }
1304
- const oldValues = wrap(ctx.ret.cachedChildValues);
1305
- let value = (ctx.ret.cachedChildValues = unwrap(values));
1306
- if (ctx.f & IsScheduling) {
1307
- ctx.f |= IsSchedulingRefresh;
1308
- }
1309
- else if (!(ctx.f & IsUpdating)) {
1310
- // If we’re not updating the component, which happens when components are
1311
- // refreshed, or when async generator components iterate, we have to do a
1312
- // little bit housekeeping when a component’s child values have changed.
1313
- if (!arrayEqual(oldValues, values)) {
1314
- const records = getListenerRecords(ctx.parent, ctx.host);
1315
- if (records.length) {
1316
- for (let i = 0; i < values.length; i++) {
1317
- const value = values[i];
1318
- if (isEventTarget(value)) {
1319
- for (let j = 0; j < records.length; j++) {
1320
- const record = records[j];
1321
- value.addEventListener(record.type, record.callback, record.options);
1322
- }
1323
- }
1324
- }
1325
- }
1326
- // rearranging the nearest ancestor host element
1327
- const host = ctx.host;
1328
- const oldHostValues = wrap(host.cachedChildValues);
1329
- invalidate(ctx, host);
1330
- const hostValues = getChildValues(host);
1331
- ctx.renderer.arrange(host.el.tag, host.value, host.el.props, hostValues,
1332
- // props and oldProps are the same because the host isn’t updated.
1333
- host.el.props, oldHostValues);
1334
- }
1335
- flush(ctx.renderer, ctx.root, ctx);
1336
- }
1337
- const callbacks = scheduleMap.get(ctx);
1338
- if (callbacks) {
1339
- scheduleMap.delete(ctx);
1340
- ctx.f |= IsScheduling;
1341
- const value1 = ctx.renderer.read(value);
1342
- for (const callback of callbacks) {
1343
- callback(value1);
1344
- }
1345
- ctx.f &= ~IsScheduling;
1346
- // Handles an edge case where refresh() is called during a schedule().
1347
- if (ctx.f & IsSchedulingRefresh) {
1348
- ctx.f &= ~IsSchedulingRefresh;
1349
- value = getValue(ctx.ret);
1350
- }
1351
- }
1352
- ctx.f &= ~IsUpdating;
1353
- return value;
1354
- }
1355
- function invalidate(ctx, host) {
1356
- for (let parent = ctx.parent; parent !== undefined && parent.host === host; parent = parent.parent) {
1357
- parent.ret.cachedChildValues = undefined;
1358
- }
1359
- host.cachedChildValues = undefined;
1360
- }
1361
- function arrayEqual(arr1, arr2) {
1362
- if (arr1.length !== arr2.length) {
1363
- return false;
1364
- }
1365
- for (let i = 0; i < arr1.length; i++) {
1366
- const value1 = arr1[i];
1367
- const value2 = arr2[i];
1368
- if (value1 !== value2) {
1369
- return false;
1370
- }
1371
- }
1372
- return true;
1373
- }
1374
- /** Enqueues and executes the component associated with the context. */
1375
- function enqueueComponentRun(ctx, hydrationData) {
1376
- if (ctx.f & IsAsyncGen && !(ctx.f & IsInForOfLoop)) {
1377
- if (hydrationData !== undefined) {
1378
- throw new Error("Hydration error");
1379
- }
1380
- // This branch will run for non-initial renders of async generator
1381
- // components when they are not in for...of loops. When in a for...of loop,
1382
- // async generator components will behave normally.
1383
- //
1384
- // Async gen componennts can be in one of three states:
1385
- //
1386
- // 1. propsAvailable flag is true: "available"
1387
- //
1388
- // The component is suspended somewhere in the loop. When the component
1389
- // reaches the bottom of the loop, it will run again with the next props.
1390
- //
1391
- // 2. onAvailable callback is defined: "suspended"
1392
- //
1393
- // The component has suspended at the bottom of the loop and is waiting
1394
- // for new props.
1395
- //
1396
- // 3. neither 1 or 2: "Running"
1397
- //
1398
- // The component is suspended somewhere in the loop. When the component
1399
- // reaches the bottom of the loop, it will suspend.
1400
- //
1401
- // Components will never be both available and suspended at
1402
- // the same time.
1403
- //
1404
- // If the component is at the loop bottom, this means that the next value
1405
- // produced by the component will have the most up to date props, so we can
1406
- // simply return the current inflight value. Otherwise, we have to wait for
1407
- // the bottom of the loop to be reached before returning the inflight
1408
- // value.
1409
- const isAtLoopbottom = ctx.f & IsInForAwaitOfLoop && !ctx.onProps;
1410
- resumePropsIterator(ctx);
1411
- if (isAtLoopbottom) {
1412
- if (ctx.inflightBlock == null) {
1413
- ctx.inflightBlock = new Promise((resolve) => (ctx.onPropsRequested = resolve));
1414
- }
1415
- return ctx.inflightBlock.then(() => {
1416
- ctx.inflightBlock = undefined;
1417
- return ctx.inflightValue;
1418
- });
1419
- }
1420
- return ctx.inflightValue;
1421
- }
1422
- else if (!ctx.inflightBlock) {
1423
- try {
1424
- const [block, value] = runComponent(ctx, hydrationData);
1425
- if (block) {
1426
- ctx.inflightBlock = block
1427
- // TODO: there is some fuckery going on here related to async
1428
- // generator components resuming when they’re meant to be returned.
1429
- .then((v) => v)
1430
- .finally(() => advanceComponent(ctx));
1431
- // stepComponent will only return a block if the value is asynchronous
1432
- ctx.inflightValue = value;
1433
- }
1434
- return value;
1435
- }
1436
- catch (err) {
1437
- if (!(ctx.f & IsUpdating)) {
1438
- if (!ctx.parent) {
1439
- throw err;
1440
- }
1441
- return propagateError(ctx.parent, err);
1442
- }
1443
- throw err;
1444
- }
1445
- }
1446
- else if (!ctx.enqueuedBlock) {
1447
- if (hydrationData !== undefined) {
1448
- throw new Error("Hydration error");
1449
- }
1450
- // We need to assign enqueuedBlock and enqueuedValue synchronously, hence
1451
- // the Promise constructor call here.
1452
- let resolveEnqueuedBlock;
1453
- ctx.enqueuedBlock = new Promise((resolve) => (resolveEnqueuedBlock = resolve));
1454
- ctx.enqueuedValue = ctx.inflightBlock.then(() => {
1455
- try {
1456
- const [block, value] = runComponent(ctx);
1457
- if (block) {
1458
- resolveEnqueuedBlock(block.finally(() => advanceComponent(ctx)));
1459
- }
1460
- return value;
1461
- }
1462
- catch (err) {
1463
- if (!(ctx.f & IsUpdating)) {
1464
- if (!ctx.parent) {
1465
- throw err;
1466
- }
1467
- return propagateError(ctx.parent, err);
1468
- }
1469
- throw err;
1470
- }
1471
- });
1472
- }
1473
- return ctx.enqueuedValue;
1474
- }
1475
- /** Called when the inflight block promise settles. */
1476
- function advanceComponent(ctx) {
1477
- if (ctx.f & IsAsyncGen && !(ctx.f & IsInForOfLoop)) {
1478
- return;
1479
- }
1480
- ctx.inflightBlock = ctx.enqueuedBlock;
1481
- ctx.inflightValue = ctx.enqueuedValue;
1482
- ctx.enqueuedBlock = undefined;
1483
- ctx.enqueuedValue = undefined;
1484
- }
1485
- /**
1486
- * This function is responsible for executing the component and handling all
1487
- * the different component types. We cannot identify whether a component is a
1488
- * generator or async without calling it and inspecting the return value.
1489
- *
1490
- * @returns {[block, value]} A tuple where
1491
- * block - A possible promise which represents the duration during which the
1492
- * component is blocked from updating.
1493
- * value - A possible promise resolving to the rendered value of children.
1494
- *
1495
- * Each component type will block according to the type of the component.
1496
- * - Sync function components never block and will transparently pass updates
1497
- * to children.
1498
- * - Async function components and async generator components block while
1499
- * executing itself, but will not block for async children.
1500
- * - Sync generator components block while any children are executing, because
1501
- * they are expected to only resume when they’ve actually rendered.
1502
- */
1503
- function runComponent(ctx, hydrationData) {
1504
- const ret = ctx.ret;
1505
- const initial = !ctx.iterator;
1506
- if (initial) {
1507
- resumePropsIterator(ctx);
1508
- ctx.f |= IsSyncExecuting;
1509
- clearEventListeners(ctx);
1510
- let result;
1511
- try {
1512
- result = ret.el.tag.call(ctx.owner, ret.el.props);
1513
- }
1514
- catch (err) {
1515
- ctx.f |= IsErrored;
1516
- throw err;
1517
- }
1518
- finally {
1519
- ctx.f &= ~IsSyncExecuting;
1520
- }
1521
- if (isIteratorLike(result)) {
1522
- ctx.iterator = result;
1523
- }
1524
- else if (isPromiseLike(result)) {
1525
- // async function component
1526
- const result1 = result instanceof Promise ? result : Promise.resolve(result);
1527
- const value = result1.then((result) => updateComponentChildren(ctx, result, hydrationData), (err) => {
1528
- ctx.f |= IsErrored;
1529
- throw err;
1530
- });
1531
- return [result1.catch(NOOP), value];
1532
- }
1533
- else {
1534
- // sync function component
1535
- return [
1536
- undefined,
1537
- updateComponentChildren(ctx, result, hydrationData),
1538
- ];
1539
- }
1540
- }
1541
- else if (hydrationData !== undefined) {
1542
- throw new Error("Hydration error");
1543
- }
1544
- let iteration;
1545
- if (initial) {
1546
- try {
1547
- ctx.f |= IsSyncExecuting;
1548
- iteration = ctx.iterator.next();
1549
- }
1550
- catch (err) {
1551
- ctx.f |= IsErrored;
1552
- throw err;
1553
- }
1554
- finally {
1555
- ctx.f &= ~IsSyncExecuting;
1556
- }
1557
- if (isPromiseLike(iteration)) {
1558
- ctx.f |= IsAsyncGen;
1559
- }
1560
- else {
1561
- ctx.f |= IsSyncGen;
1562
- }
1563
- }
1564
- if (ctx.f & IsSyncGen) {
1565
- ctx.f &= ~NeedsToYield;
1566
- // sync generator component
1567
- if (!initial) {
1568
- try {
1569
- ctx.f |= IsSyncExecuting;
1570
- iteration = ctx.iterator.next(ctx.renderer.read(getValue(ret)));
1571
- }
1572
- catch (err) {
1573
- ctx.f |= IsErrored;
1574
- throw err;
1575
- }
1576
- finally {
1577
- ctx.f &= ~IsSyncExecuting;
1578
- }
1579
- }
1580
- if (isPromiseLike(iteration)) {
1581
- throw new Error("Mixed generator component");
1582
- }
1583
- if (iteration.done) {
1584
- ctx.f &= ~IsSyncGen;
1585
- ctx.iterator = undefined;
1586
- }
1587
- let value;
1588
- try {
1589
- value = updateComponentChildren(ctx,
1590
- // Children can be void so we eliminate that here
1591
- iteration.value, hydrationData);
1592
- if (isPromiseLike(value)) {
1593
- value = value.catch((err) => handleChildError(ctx, err));
1594
- }
1595
- }
1596
- catch (err) {
1597
- value = handleChildError(ctx, err);
1598
- }
1599
- const block = isPromiseLike(value) ? value.catch(NOOP) : undefined;
1600
- return [block, value];
1601
- }
1602
- else if (ctx.f & IsInForOfLoop) {
1603
- // TODO: does this need to be done async?
1604
- ctx.f &= ~NeedsToYield;
1605
- // we are in a for...of loop for async generator
1606
- if (!initial) {
1607
- try {
1608
- ctx.f |= IsSyncExecuting;
1609
- iteration = ctx.iterator.next(ctx.renderer.read(getValue(ret)));
1610
- }
1611
- catch (err) {
1612
- ctx.f |= IsErrored;
1613
- throw err;
1614
- }
1615
- finally {
1616
- ctx.f &= ~IsSyncExecuting;
1617
- }
1618
- }
1619
- if (!isPromiseLike(iteration)) {
1620
- throw new Error("Mixed generator component");
1621
- }
1622
- const block = iteration.catch(NOOP);
1623
- const value = iteration.then((iteration) => {
1624
- let value;
1625
- if (!(ctx.f & IsInForOfLoop)) {
1626
- runAsyncGenComponent(ctx, Promise.resolve(iteration), hydrationData);
1627
- }
1628
- try {
1629
- value = updateComponentChildren(ctx,
1630
- // Children can be void so we eliminate that here
1631
- iteration.value, hydrationData);
1632
- if (isPromiseLike(value)) {
1633
- value = value.catch((err) => handleChildError(ctx, err));
1634
- }
1635
- }
1636
- catch (err) {
1637
- value = handleChildError(ctx, err);
1638
- }
1639
- return value;
1640
- }, (err) => {
1641
- ctx.f |= IsErrored;
1642
- throw err;
1643
- });
1644
- return [block, value];
1645
- }
1646
- else {
1647
- runAsyncGenComponent(ctx, iteration, hydrationData);
1648
- // async generator component
1649
- return [ctx.inflightBlock, ctx.inflightValue];
1650
- }
1651
- }
1652
- async function runAsyncGenComponent(ctx, iterationP, hydrationData) {
1653
- let done = false;
1654
- try {
1655
- while (!done) {
1656
- if (ctx.f & IsInForOfLoop) {
1657
- break;
1658
- }
1659
- // inflightValue must be set synchronously.
1660
- let onValue;
1661
- ctx.inflightValue = new Promise((resolve) => (onValue = resolve));
1662
- if (ctx.f & IsUpdating) {
1663
- // We should not swallow unhandled promise rejections if the component is
1664
- // updating independently.
1665
- // TODO: Does this handle this.refresh() calls?
1666
- ctx.inflightValue.catch(NOOP);
1667
- }
1668
- let iteration;
1669
- try {
1670
- iteration = await iterationP;
1671
- }
1672
- catch (err) {
1673
- done = true;
1674
- ctx.f |= IsErrored;
1675
- onValue(Promise.reject(err));
1676
- break;
1677
- }
1678
- finally {
1679
- ctx.f &= ~NeedsToYield;
1680
- if (!(ctx.f & IsInForAwaitOfLoop)) {
1681
- ctx.f &= ~PropsAvailable;
1682
- }
1683
- }
1684
- done = !!iteration.done;
1685
- let value;
1686
- try {
1687
- value = updateComponentChildren(ctx, iteration.value, hydrationData);
1688
- hydrationData = undefined;
1689
- if (isPromiseLike(value)) {
1690
- value = value.catch((err) => handleChildError(ctx, err));
1691
- }
1692
- }
1693
- catch (err) {
1694
- // Do we need to catch potential errors here in the case of unhandled
1695
- // promise rejections?
1696
- value = handleChildError(ctx, err);
1697
- }
1698
- finally {
1699
- onValue(value);
1700
- }
1701
- // TODO: this can be done more elegantly
1702
- let oldValue;
1703
- if (ctx.ret.inflightValue) {
1704
- // The value passed back into the generator as the argument to the next
1705
- // method is a promise if an async generator component has async
1706
- // children. Sync generator components only resume when their children
1707
- // have fulfilled so the element’s inflight child values will never be
1708
- // defined.
1709
- oldValue = ctx.ret.inflightValue.then((value) => ctx.renderer.read(value));
1710
- oldValue.catch((err) => {
1711
- if (ctx.f & IsUpdating) {
1712
- return;
1713
- }
1714
- if (!ctx.parent) {
1715
- throw err;
1716
- }
1717
- return propagateError(ctx.parent, err);
1718
- });
1719
- }
1720
- else {
1721
- oldValue = ctx.renderer.read(getValue(ctx.ret));
1722
- }
1723
- if (ctx.f & IsUnmounted) {
1724
- if (ctx.f & IsInForAwaitOfLoop) {
1725
- try {
1726
- ctx.f |= IsSyncExecuting;
1727
- iterationP = ctx.iterator.next(oldValue);
1728
- }
1729
- finally {
1730
- ctx.f &= ~IsSyncExecuting;
1731
- }
1732
- }
1733
- else {
1734
- returnComponent(ctx);
1735
- break;
1736
- }
1737
- }
1738
- else if (!done && !(ctx.f & IsInForOfLoop)) {
1739
- try {
1740
- ctx.f |= IsSyncExecuting;
1741
- iterationP = ctx.iterator.next(oldValue);
1742
- }
1743
- finally {
1744
- ctx.f &= ~IsSyncExecuting;
1745
- }
1746
- }
1747
- }
1748
- }
1749
- finally {
1750
- if (done) {
1751
- ctx.f &= ~IsAsyncGen;
1752
- ctx.iterator = undefined;
1753
- }
1754
- }
1755
- }
1756
- /**
1757
- * Called to resume the props async iterator for async generator components.
1758
- */
1759
- function resumePropsIterator(ctx) {
1760
- if (ctx.onProps) {
1761
- ctx.onProps(ctx.ret.el.props);
1762
- ctx.onProps = undefined;
1763
- ctx.f &= ~PropsAvailable;
1764
- }
1765
- else {
1766
- ctx.f |= PropsAvailable;
1767
- }
1768
- }
1769
- // TODO: async unmounting
1770
- function unmountComponent(ctx) {
1771
- if (ctx.f & IsUnmounted) {
1772
- return;
1773
- }
1774
- clearEventListeners(ctx);
1775
- const callbacks = cleanupMap.get(ctx);
1776
- if (callbacks) {
1777
- cleanupMap.delete(ctx);
1778
- const value = ctx.renderer.read(getValue(ctx.ret));
1779
- for (const callback of callbacks) {
1780
- callback(value);
1781
- }
1782
- }
1783
- ctx.f |= IsUnmounted;
1784
- if (ctx.iterator) {
1785
- if (ctx.f & IsSyncGen) {
1786
- let value;
1787
- if (ctx.f & IsInForOfLoop) {
1788
- value = enqueueComponentRun(ctx);
1789
- }
1790
- if (isPromiseLike(value)) {
1791
- value.then(() => {
1792
- if (ctx.f & IsInForOfLoop) {
1793
- unmountComponent(ctx);
1794
- }
1795
- else {
1796
- returnComponent(ctx);
1797
- }
1798
- }, (err) => {
1799
- if (!ctx.parent) {
1800
- throw err;
1801
- }
1802
- return propagateError(ctx.parent, err);
1803
- });
1804
- }
1805
- else {
1806
- if (ctx.f & IsInForOfLoop) {
1807
- unmountComponent(ctx);
1808
- }
1809
- else {
1810
- returnComponent(ctx);
1811
- }
1812
- }
1813
- }
1814
- else if (ctx.f & IsAsyncGen) {
1815
- if (ctx.f & IsInForOfLoop) {
1816
- const value = enqueueComponentRun(ctx);
1817
- value.then(() => {
1818
- if (ctx.f & IsInForOfLoop) {
1819
- unmountComponent(ctx);
1820
- }
1821
- else {
1822
- returnComponent(ctx);
1823
- }
1824
- }, (err) => {
1825
- if (!ctx.parent) {
1826
- throw err;
1827
- }
1828
- return propagateError(ctx.parent, err);
1829
- });
1830
- }
1831
- else {
1832
- // The logic for unmounting async generator components is in the
1833
- // runAsyncGenComponent function.
1834
- resumePropsIterator(ctx);
1835
- }
1836
- }
1837
- }
1838
- }
1839
- function returnComponent(ctx) {
1840
- resumePropsIterator(ctx);
1841
- if (ctx.iterator && typeof ctx.iterator.return === "function") {
1842
- try {
1843
- ctx.f |= IsSyncExecuting;
1844
- const iteration = ctx.iterator.return();
1845
- if (isPromiseLike(iteration)) {
1846
- iteration.catch((err) => {
1847
- if (!ctx.parent) {
1848
- throw err;
1849
- }
1850
- return propagateError(ctx.parent, err);
1851
- });
1852
- }
1853
- }
1854
- finally {
1855
- ctx.f &= ~IsSyncExecuting;
1856
- }
1857
- }
1858
- }
1859
- /*** EVENT TARGET UTILITIES ***/
1860
- // EVENT PHASE CONSTANTS
1861
- // https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
1862
- const NONE = 0;
1863
- const CAPTURING_PHASE = 1;
1864
- const AT_TARGET = 2;
1865
- const BUBBLING_PHASE = 3;
1866
- const listenersMap = new WeakMap();
1867
- function isListenerOrListenerObject(value) {
1868
- return (typeof value === "function" ||
1869
- (value !== null &&
1870
- typeof value === "object" &&
1871
- typeof value.handleEvent === "function"));
1872
- }
1873
- function normalizeListenerOptions(options) {
1874
- if (typeof options === "boolean") {
1875
- return { capture: options };
1876
- }
1877
- else if (options == null) {
1878
- return {};
1879
- }
1880
- return options;
1881
- }
1882
- function isEventTarget(value) {
1883
- return (value != null &&
1884
- typeof value.addEventListener === "function" &&
1885
- typeof value.removeEventListener === "function" &&
1886
- typeof value.dispatchEvent === "function");
1887
- }
1888
- function setEventProperty(ev, key, value) {
1889
- Object.defineProperty(ev, key, { value, writable: false, configurable: true });
1890
- }
1891
- // TODO: Maybe we can pass in the current context directly, rather than
1892
- // starting from the parent?
1893
- /**
1894
- * A function to reconstruct an array of every listener given a context and a
1895
- * host element.
1896
- *
1897
- * This function exploits the fact that contexts retain their nearest ancestor
1898
- * host element. We can determine all the contexts which are directly listening
1899
- * to an element by traversing up the context tree and checking that the host
1900
- * element passed in matches the parent context’s host element.
1901
- */
1902
- function getListenerRecords(ctx, ret) {
1903
- let listeners = [];
1904
- while (ctx !== undefined && ctx.host === ret) {
1905
- const listeners1 = listenersMap.get(ctx);
1906
- if (listeners1) {
1907
- listeners = listeners.concat(listeners1);
1908
- }
1909
- ctx = ctx.parent;
1910
- }
1911
- return listeners;
1912
- }
1913
- function clearEventListeners(ctx) {
1914
- const listeners = listenersMap.get(ctx);
1915
- if (listeners && listeners.length) {
1916
- for (const value of getChildValues(ctx.ret)) {
1917
- if (isEventTarget(value)) {
1918
- for (const record of listeners) {
1919
- value.removeEventListener(record.type, record.callback, record.options);
1920
- }
1921
- }
1922
- }
1923
- listeners.length = 0;
1924
- }
1925
- }
1926
- /*** ERROR HANDLING UTILITIES ***/
1927
- function handleChildError(ctx, err) {
1928
- if (!ctx.iterator || typeof ctx.iterator.throw !== "function") {
1929
- throw err;
1930
- }
1931
- resumePropsIterator(ctx);
1932
- let iteration;
1933
- try {
1934
- ctx.f |= IsSyncExecuting;
1935
- iteration = ctx.iterator.throw(err);
1936
- }
1937
- catch (err) {
1938
- ctx.f |= IsErrored;
1939
- throw err;
1940
- }
1941
- finally {
1942
- ctx.f &= ~IsSyncExecuting;
1943
- }
1944
- if (isPromiseLike(iteration)) {
1945
- return iteration.then((iteration) => {
1946
- if (iteration.done) {
1947
- ctx.f &= ~IsAsyncGen;
1948
- ctx.iterator = undefined;
1949
- }
1950
- return updateComponentChildren(ctx, iteration.value);
1951
- }, (err) => {
1952
- ctx.f |= IsErrored;
1953
- throw err;
1954
- });
1955
- }
1956
- if (iteration.done) {
1957
- ctx.f &= ~IsSyncGen;
1958
- ctx.f &= ~IsAsyncGen;
1959
- ctx.iterator = undefined;
1960
- }
1961
- return updateComponentChildren(ctx, iteration.value);
1962
- }
1963
- function propagateError(ctx, err) {
1964
- let result;
1965
- try {
1966
- result = handleChildError(ctx, err);
1967
- }
1968
- catch (err) {
1969
- if (!ctx.parent) {
1970
- throw err;
1971
- }
1972
- return propagateError(ctx.parent, err);
1973
- }
1974
- if (isPromiseLike(result)) {
1975
- return result.catch((err) => {
1976
- if (!ctx.parent) {
1977
- throw err;
1978
- }
1979
- return propagateError(ctx.parent, err);
1980
- });
1981
- }
1982
- return result;
1983
- }
1984
- // Some JSX transpilation tools expect these functions to be defined on the
1985
- // default export. Prefer named exports when importing directly.
2
+ const NOOP = () => { };
3
+ const IDENTITY = (value) => value;
4
+ function wrap(value) {
5
+ return value === undefined ? [] : Array.isArray(value) ? value : [value];
6
+ }
7
+ function unwrap(arr) {
8
+ return arr.length === 0 ? undefined : arr.length === 1 ? arr[0] : arr;
9
+ }
10
+ /**
11
+ * Ensures a value is an array.
12
+ *
13
+ * This function does the same thing as wrap() above except it handles nulls
14
+ * and iterables, so it is appropriate for wrapping user-provided element
15
+ * children.
16
+ */
17
+ function arrayify(value) {
18
+ return value == null
19
+ ? []
20
+ : Array.isArray(value)
21
+ ? value
22
+ : typeof value === "string" ||
23
+ typeof value[Symbol.iterator] !== "function"
24
+ ? [value]
25
+ : // TODO: inference broke in TypeScript 3.9.
26
+ [...value];
27
+ }
28
+ function isIteratorLike(value) {
29
+ return value != null && typeof value.next === "function";
30
+ }
31
+ function isPromiseLike(value) {
32
+ return value != null && typeof value.then === "function";
33
+ }
34
+ /***
35
+ * SPECIAL TAGS
36
+ *
37
+ * Crank provides a couple tags which have special meaning for the renderer.
38
+ ***/
39
+ /**
40
+ * A special tag for grouping multiple children within the same parent.
41
+ *
42
+ * All non-string iterables which appear in the element tree are implicitly
43
+ * wrapped in a fragment element.
44
+ *
45
+ * This tag is just the empty string, and you can use the empty string in
46
+ * createElement calls or transpiler options directly to avoid having to
47
+ * reference this export.
48
+ */
49
+ const Fragment = "";
50
+ // TODO: We assert the following symbol tags as any because TypeScript support
51
+ // for symbol tags in JSX doesn’t exist yet.
52
+ // https://github.com/microsoft/TypeScript/issues/38367
53
+ /**
54
+ * A special tag for rendering into a new root node via a root prop.
55
+ *
56
+ * This tag is useful for creating element trees with multiple roots, for
57
+ * things like modals or tooltips.
58
+ *
59
+ * Renderer.prototype.render() will implicitly wrap top-level element trees in
60
+ * a Portal element.
61
+ */
62
+ const Portal = Symbol.for("crank.Portal");
63
+ /**
64
+ * A special tag which preserves whatever was previously rendered in the
65
+ * element’s position.
66
+ *
67
+ * Copy elements are useful for when you want to prevent a subtree from
68
+ * rerendering as a performance optimization. Copy elements can also be keyed,
69
+ * in which case the previously rendered keyed element will be copied.
70
+ */
71
+ const Copy = Symbol.for("crank.Copy");
72
+ /**
73
+ * A special tag for injecting raw nodes or strings via a value prop.
74
+ *
75
+ * Renderer.prototype.raw() is called with the value prop.
76
+ */
77
+ const Raw = Symbol.for("crank.Raw");
78
+ const ElementSymbol = Symbol.for("crank.Element");
79
+ /**
80
+ * Elements are the basic building blocks of Crank applications. They are
81
+ * JavaScript objects which are interpreted by special classes called renderers
82
+ * to produce and manage stateful nodes.
83
+ *
84
+ * @template {Tag} [TTag=Tag] - The type of the tag of the element.
85
+ *
86
+ * @example
87
+ * // specific element types
88
+ * let div: Element<"div">;
89
+ * let portal: Element<Portal>;
90
+ * let myEl: Element<MyComponent>;
91
+ *
92
+ * // general element types
93
+ * let host: Element<string | symbol>;
94
+ * let component: Element<Component>;
95
+ *
96
+ * Typically, you use a helper function like createElement to create elements
97
+ * rather than instatiating this class directly.
98
+ */
99
+ class Element {
100
+ constructor(tag, props) {
101
+ this.tag = tag;
102
+ this.props = props;
103
+ }
104
+ get key() {
105
+ return this.props.key;
106
+ }
107
+ get ref() {
108
+ return this.props.ref;
109
+ }
110
+ get copy() {
111
+ return !!this.props.copy;
112
+ }
113
+ }
114
+ // See Element interface
115
+ Element.prototype.$$typeof = ElementSymbol;
116
+ function isElement(value) {
117
+ return value != null && value.$$typeof === ElementSymbol;
118
+ }
119
+ const DEPRECATED_PROP_PREFIXES = ["crank-", "c-", "$"];
120
+ const DEPRECATED_SPECIAL_PROP_BASES = ["key", "ref", "static"];
121
+ const SPECIAL_PROPS = new Set(["children", "key", "ref", "copy"]);
122
+ for (const propPrefix of DEPRECATED_PROP_PREFIXES) {
123
+ for (const propBase of DEPRECATED_SPECIAL_PROP_BASES) {
124
+ SPECIAL_PROPS.add(propPrefix + propBase);
125
+ }
126
+ }
127
+ /**
128
+ * Creates an element with the specified tag, props and children.
129
+ *
130
+ * This function is usually used as a transpilation target for JSX transpilers,
131
+ * but it can also be called directly. It additionally extracts special props so
132
+ * they aren’t accessible to renderer methods or components, and assigns the
133
+ * children prop according to any additional arguments passed to the function.
134
+ */
135
+ function createElement(tag, props, ...children) {
136
+ if (props == null) {
137
+ props = {};
138
+ }
139
+ for (let i = 0; i < DEPRECATED_PROP_PREFIXES.length; i++) {
140
+ const propPrefix = DEPRECATED_PROP_PREFIXES[i];
141
+ for (let j = 0; j < DEPRECATED_SPECIAL_PROP_BASES.length; j++) {
142
+ const propBase = DEPRECATED_SPECIAL_PROP_BASES[j];
143
+ const deprecatedPropName = propPrefix + propBase;
144
+ const targetPropBase = propBase === "static" ? "copy" : propBase;
145
+ if (deprecatedPropName in props) {
146
+ console.warn(`The \`${deprecatedPropName}\` prop is deprecated. Use \`${targetPropBase}\` instead.`);
147
+ props[targetPropBase] = props[deprecatedPropName];
148
+ }
149
+ }
150
+ }
151
+ if (children.length > 1) {
152
+ props.children = children;
153
+ }
154
+ else if (children.length === 1) {
155
+ props.children = children[0];
156
+ }
157
+ return new Element(tag, props);
158
+ }
159
+ /** Clones a given element, shallowly copying the props object. */
160
+ function cloneElement(el) {
161
+ if (!isElement(el)) {
162
+ throw new TypeError("Cannot clone non-element");
163
+ }
164
+ return new Element(el.tag, { ...el.props });
165
+ }
166
+ function narrow(value) {
167
+ if (typeof value === "boolean" || value == null) {
168
+ return undefined;
169
+ }
170
+ else if (typeof value === "string" || isElement(value)) {
171
+ return value;
172
+ }
173
+ else if (typeof value[Symbol.iterator] === "function") {
174
+ return createElement(Fragment, null, value);
175
+ }
176
+ return value.toString();
177
+ }
178
+ /**
179
+ * Takes an array of element values and normalizes the output as an array of
180
+ * nodes and strings.
181
+ *
182
+ * @returns Normalized array of nodes and/or strings.
183
+ *
184
+ * Normalize will flatten only one level of nested arrays, because it is
185
+ * designed to be called once at each level of the tree. It will also
186
+ * concatenate adjacent strings and remove all undefined values.
187
+ */
188
+ function normalize(values) {
189
+ const result = [];
190
+ let buffer;
191
+ for (let i = 0; i < values.length; i++) {
192
+ const value = values[i];
193
+ if (!value) ;
194
+ else if (typeof value === "string") {
195
+ buffer = (buffer || "") + value;
196
+ }
197
+ else if (!Array.isArray(value)) {
198
+ if (buffer) {
199
+ result.push(buffer);
200
+ buffer = undefined;
201
+ }
202
+ result.push(value);
203
+ }
204
+ else {
205
+ // We could use recursion here but it’s just easier to do it inline.
206
+ for (let j = 0; j < value.length; j++) {
207
+ const value1 = value[j];
208
+ if (!value1) ;
209
+ else if (typeof value1 === "string") {
210
+ buffer = (buffer || "") + value1;
211
+ }
212
+ else {
213
+ if (buffer) {
214
+ result.push(buffer);
215
+ buffer = undefined;
216
+ }
217
+ result.push(value1);
218
+ }
219
+ }
220
+ }
221
+ }
222
+ if (buffer) {
223
+ result.push(buffer);
224
+ }
225
+ return result;
226
+ }
227
+ /**
228
+ * @internal
229
+ * The internal nodes which are cached and diffed against new elements when
230
+ * rendering element trees.
231
+ */
232
+ class Retainer {
233
+ constructor(el) {
234
+ this.el = el;
235
+ this.ctx = undefined;
236
+ this.children = undefined;
237
+ this.value = undefined;
238
+ this.cachedChildValues = undefined;
239
+ this.fallbackValue = undefined;
240
+ this.inflightValue = undefined;
241
+ this.onNextValues = undefined;
242
+ }
243
+ }
244
+ /**
245
+ * Finds the value of the element according to its type.
246
+ *
247
+ * @returns The value of the element.
248
+ */
249
+ function getValue(ret) {
250
+ if (typeof ret.fallbackValue !== "undefined") {
251
+ return typeof ret.fallbackValue === "object"
252
+ ? getValue(ret.fallbackValue)
253
+ : ret.fallbackValue;
254
+ }
255
+ else if (ret.el.tag === Portal) {
256
+ return;
257
+ }
258
+ else if (typeof ret.el.tag !== "function" && ret.el.tag !== Fragment) {
259
+ return ret.value;
260
+ }
261
+ return unwrap(getChildValues(ret));
262
+ }
263
+ /**
264
+ * Walks an element’s children to find its child values.
265
+ *
266
+ * @returns A normalized array of nodes and strings.
267
+ */
268
+ function getChildValues(ret) {
269
+ if (ret.cachedChildValues) {
270
+ return wrap(ret.cachedChildValues);
271
+ }
272
+ const values = [];
273
+ const children = wrap(ret.children);
274
+ for (let i = 0; i < children.length; i++) {
275
+ const child = children[i];
276
+ if (child) {
277
+ values.push(typeof child === "string" ? child : getValue(child));
278
+ }
279
+ }
280
+ const values1 = normalize(values);
281
+ const tag = ret.el.tag;
282
+ if (typeof tag === "function" || (tag !== Fragment && tag !== Raw)) {
283
+ ret.cachedChildValues = unwrap(values1);
284
+ }
285
+ return values1;
286
+ }
287
+ const defaultRendererImpl = {
288
+ create() {
289
+ throw new Error("Not implemented");
290
+ },
291
+ hydrate() {
292
+ throw new Error("Not implemented");
293
+ },
294
+ scope: IDENTITY,
295
+ read: IDENTITY,
296
+ text: IDENTITY,
297
+ raw: IDENTITY,
298
+ patch: NOOP,
299
+ arrange: NOOP,
300
+ dispose: NOOP,
301
+ flush: NOOP,
302
+ };
303
+ const _RendererImpl = Symbol.for("crank.RendererImpl");
304
+ /**
305
+ * An abstract class which is subclassed to render to different target
306
+ * environments. Subclasses will typically call super() with a custom
307
+ * RendererImpl. This class is responsible for kicking off the rendering
308
+ * process and caching previous trees by root.
309
+ *
310
+ * @template TNode - The type of the node for a rendering environment.
311
+ * @template TScope - Data which is passed down the tree.
312
+ * @template TRoot - The type of the root for a rendering environment.
313
+ * @template TResult - The type of exposed values.
314
+ */
315
+ class Renderer {
316
+ constructor(impl) {
317
+ this.cache = new WeakMap();
318
+ this[_RendererImpl] = {
319
+ ...defaultRendererImpl,
320
+ ...impl,
321
+ };
322
+ }
323
+ /**
324
+ * Renders an element tree into a specific root.
325
+ *
326
+ * @param children - An element tree. You can render null with a previously
327
+ * used root to delete the previously rendered element tree from the cache.
328
+ * @param root - The node to be rendered into. The renderer will cache
329
+ * element trees per root.
330
+ * @param bridge - An optional context that will be the ancestor context of all
331
+ * elements in the tree. Useful for connecting different renderers so that
332
+ * events/provisions properly propagate. The context for a given root must be
333
+ * the same or an error will be thrown.
334
+ *
335
+ * @returns The result of rendering the children, or a possible promise of
336
+ * the result if the element tree renders asynchronously.
337
+ */
338
+ render(children, root, bridge) {
339
+ let ret;
340
+ const ctx = bridge && bridge[_ContextImpl];
341
+ if (typeof root === "object" && root !== null) {
342
+ ret = this.cache.get(root);
343
+ }
344
+ let oldProps;
345
+ if (ret === undefined) {
346
+ ret = new Retainer(createElement(Portal, { children, root }));
347
+ ret.value = root;
348
+ ret.ctx = ctx;
349
+ if (typeof root === "object" && root !== null && children != null) {
350
+ this.cache.set(root, ret);
351
+ }
352
+ }
353
+ else if (ret.ctx !== ctx) {
354
+ throw new Error("Context mismatch");
355
+ }
356
+ else {
357
+ oldProps = ret.el.props;
358
+ ret.el = createElement(Portal, { children, root });
359
+ if (typeof root === "object" && root !== null && children == null) {
360
+ this.cache.delete(root);
361
+ }
362
+ }
363
+ const impl = this[_RendererImpl];
364
+ const childValues = diffChildren(impl, root, ret, ctx, impl.scope(undefined, Portal, ret.el.props), ret, children, undefined);
365
+ // We return the child values of the portal because portal elements
366
+ // themselves have no readable value.
367
+ if (isPromiseLike(childValues)) {
368
+ return childValues.then((childValues) => commitRootRender(impl, root, ctx, ret, childValues, oldProps));
369
+ }
370
+ return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
371
+ }
372
+ hydrate(children, root, bridge) {
373
+ const impl = this[_RendererImpl];
374
+ const ctx = bridge && bridge[_ContextImpl];
375
+ let ret;
376
+ ret = this.cache.get(root);
377
+ if (ret !== undefined) {
378
+ // If there is a retainer for the root, hydration is not necessary.
379
+ return this.render(children, root, bridge);
380
+ }
381
+ let oldProps;
382
+ ret = new Retainer(createElement(Portal, { children, root }));
383
+ ret.value = root;
384
+ if (typeof root === "object" && root !== null && children != null) {
385
+ this.cache.set(root, ret);
386
+ }
387
+ const hydrationData = impl.hydrate(Portal, root, {});
388
+ const childValues = diffChildren(impl, root, ret, ctx, impl.scope(undefined, Portal, ret.el.props), ret, children, hydrationData);
389
+ // We return the child values of the portal because portal elements
390
+ // themselves have no readable value.
391
+ if (isPromiseLike(childValues)) {
392
+ return childValues.then((childValues) => commitRootRender(impl, root, ctx, ret, childValues, oldProps));
393
+ }
394
+ return commitRootRender(impl, root, ctx, ret, childValues, oldProps);
395
+ }
396
+ }
397
+ /*** PRIVATE RENDERER FUNCTIONS ***/
398
+ function commitRootRender(renderer, root, ctx, ret, childValues, oldProps) {
399
+ // element is a host or portal element
400
+ if (root != null) {
401
+ renderer.arrange(Portal, root, ret.el.props, childValues, oldProps, wrap(ret.cachedChildValues));
402
+ flush(renderer, root);
403
+ }
404
+ ret.cachedChildValues = unwrap(childValues);
405
+ if (root == null) {
406
+ unmount(renderer, ret, ctx, ret);
407
+ }
408
+ return renderer.read(ret.cachedChildValues);
409
+ }
410
+ function diffChildren(renderer, root, host, ctx, scope, parent, children, hydrationData) {
411
+ const oldRetained = wrap(parent.children);
412
+ const newRetained = [];
413
+ const newChildren = arrayify(children);
414
+ const values = [];
415
+ let graveyard;
416
+ let childrenByKey;
417
+ let seenKeys;
418
+ let isAsync = false;
419
+ // When hydrating, sibling element trees must be rendered in order, because
420
+ // we do not know how many DOM nodes an element will render.
421
+ let hydrationBlock;
422
+ let oi = 0;
423
+ let oldLength = oldRetained.length;
424
+ for (let ni = 0, newLength = newChildren.length; ni < newLength; ni++) {
425
+ // length checks to prevent index out of bounds deoptimizations.
426
+ let ret = oi >= oldLength ? undefined : oldRetained[oi];
427
+ let child = narrow(newChildren[ni]);
428
+ {
429
+ // aligning new children with old retainers
430
+ let oldKey = typeof ret === "object" ? ret.el.key : undefined;
431
+ let newKey = typeof child === "object" ? child.key : undefined;
432
+ if (newKey !== undefined && seenKeys && seenKeys.has(newKey)) {
433
+ console.error("Duplicate key", newKey);
434
+ newKey = undefined;
435
+ }
436
+ if (oldKey === newKey) {
437
+ if (childrenByKey !== undefined && newKey !== undefined) {
438
+ childrenByKey.delete(newKey);
439
+ }
440
+ oi++;
441
+ }
442
+ else {
443
+ childrenByKey = childrenByKey || createChildrenByKey(oldRetained, oi);
444
+ if (newKey === undefined) {
445
+ while (ret !== undefined && oldKey !== undefined) {
446
+ oi++;
447
+ ret = oldRetained[oi];
448
+ oldKey = typeof ret === "object" ? ret.el.key : undefined;
449
+ }
450
+ oi++;
451
+ }
452
+ else {
453
+ ret = childrenByKey.get(newKey);
454
+ if (ret !== undefined) {
455
+ childrenByKey.delete(newKey);
456
+ }
457
+ (seenKeys = seenKeys || new Set()).add(newKey);
458
+ }
459
+ }
460
+ }
461
+ // Updating
462
+ let value;
463
+ if (typeof child === "object") {
464
+ if (child.tag === Copy || (typeof ret === "object" && ret.el === child)) {
465
+ value = getInflightValue(ret);
466
+ }
467
+ else {
468
+ let oldProps;
469
+ let copy = false;
470
+ if (typeof ret === "object" && ret.el.tag === child.tag) {
471
+ oldProps = ret.el.props;
472
+ ret.el = child;
473
+ if (child.copy) {
474
+ value = getInflightValue(ret);
475
+ copy = true;
476
+ }
477
+ }
478
+ else {
479
+ if (typeof ret === "object") {
480
+ (graveyard = graveyard || []).push(ret);
481
+ }
482
+ const fallback = ret;
483
+ ret = new Retainer(child);
484
+ ret.fallbackValue = fallback;
485
+ }
486
+ if (copy) ;
487
+ else if (child.tag === Raw) {
488
+ value = hydrationBlock
489
+ ? hydrationBlock.then(() => updateRaw(renderer, ret, scope, oldProps, hydrationData))
490
+ : updateRaw(renderer, ret, scope, oldProps, hydrationData);
491
+ }
492
+ else if (child.tag === Fragment) {
493
+ value = hydrationBlock
494
+ ? hydrationBlock.then(() => updateFragment(renderer, root, host, ctx, scope, ret, hydrationData))
495
+ : updateFragment(renderer, root, host, ctx, scope, ret, hydrationData);
496
+ }
497
+ else if (typeof child.tag === "function") {
498
+ value = hydrationBlock
499
+ ? hydrationBlock.then(() => updateComponent(renderer, root, host, ctx, scope, ret, oldProps, hydrationData))
500
+ : updateComponent(renderer, root, host, ctx, scope, ret, oldProps, hydrationData);
501
+ }
502
+ else {
503
+ value = hydrationBlock
504
+ ? hydrationBlock.then(() => updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData))
505
+ : updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData);
506
+ }
507
+ }
508
+ if (isPromiseLike(value)) {
509
+ isAsync = true;
510
+ if (hydrationData !== undefined) {
511
+ hydrationBlock = value;
512
+ }
513
+ }
514
+ }
515
+ else {
516
+ // child is a string or undefined
517
+ if (typeof ret === "object") {
518
+ (graveyard = graveyard || []).push(ret);
519
+ }
520
+ if (typeof child === "string") {
521
+ value = ret = renderer.text(child, scope, hydrationData);
522
+ }
523
+ else {
524
+ ret = undefined;
525
+ }
526
+ }
527
+ values[ni] = value;
528
+ newRetained[ni] = ret;
529
+ }
530
+ // cleanup remaining retainers
531
+ for (; oi < oldLength; oi++) {
532
+ const ret = oldRetained[oi];
533
+ if (typeof ret === "object" &&
534
+ (typeof ret.el.key === "undefined" ||
535
+ !seenKeys ||
536
+ !seenKeys.has(ret.el.key))) {
537
+ (graveyard = graveyard || []).push(ret);
538
+ }
539
+ }
540
+ if (childrenByKey !== undefined && childrenByKey.size > 0) {
541
+ (graveyard = graveyard || []).push(...childrenByKey.values());
542
+ }
543
+ parent.children = unwrap(newRetained);
544
+ if (isAsync) {
545
+ let childValues1 = Promise.all(values).finally(() => {
546
+ if (graveyard) {
547
+ for (let i = 0; i < graveyard.length; i++) {
548
+ unmount(renderer, host, ctx, graveyard[i]);
549
+ }
550
+ }
551
+ });
552
+ let onChildValues;
553
+ childValues1 = Promise.race([
554
+ childValues1,
555
+ new Promise((resolve) => (onChildValues = resolve)),
556
+ ]);
557
+ if (parent.onNextValues) {
558
+ parent.onNextValues(childValues1);
559
+ }
560
+ parent.onNextValues = onChildValues;
561
+ return childValues1.then((childValues) => {
562
+ parent.inflightValue = parent.fallbackValue = undefined;
563
+ return normalize(childValues);
564
+ });
565
+ }
566
+ else {
567
+ if (graveyard) {
568
+ for (let i = 0; i < graveyard.length; i++) {
569
+ unmount(renderer, host, ctx, graveyard[i]);
570
+ }
571
+ }
572
+ if (parent.onNextValues) {
573
+ parent.onNextValues(values);
574
+ parent.onNextValues = undefined;
575
+ }
576
+ parent.inflightValue = parent.fallbackValue = undefined;
577
+ // We can assert there are no promises in the array because isAsync is false
578
+ return normalize(values);
579
+ }
580
+ }
581
+ function createChildrenByKey(children, offset) {
582
+ const childrenByKey = new Map();
583
+ for (let i = offset; i < children.length; i++) {
584
+ const child = children[i];
585
+ if (typeof child === "object" && typeof child.el.key !== "undefined") {
586
+ childrenByKey.set(child.el.key, child);
587
+ }
588
+ }
589
+ return childrenByKey;
590
+ }
591
+ function getInflightValue(child) {
592
+ if (typeof child !== "object") {
593
+ return child;
594
+ }
595
+ const ctx = typeof child.el.tag === "function" ? child.ctx : undefined;
596
+ if (ctx && ctx.f & IsUpdating && ctx.inflightValue) {
597
+ return ctx.inflightValue;
598
+ }
599
+ else if (child.inflightValue) {
600
+ return child.inflightValue;
601
+ }
602
+ return getValue(child);
603
+ }
604
+ function updateRaw(renderer, ret, scope, oldProps, hydrationData) {
605
+ const props = ret.el.props;
606
+ if (!oldProps || oldProps.value !== props.value) {
607
+ ret.value = renderer.raw(props.value, scope, hydrationData);
608
+ if (typeof ret.el.ref === "function") {
609
+ ret.el.ref(ret.value);
610
+ }
611
+ }
612
+ return ret.value;
613
+ }
614
+ function updateFragment(renderer, root, host, ctx, scope, ret, hydrationData) {
615
+ const childValues = diffChildren(renderer, root, host, ctx, scope, ret, ret.el.props.children, hydrationData);
616
+ if (isPromiseLike(childValues)) {
617
+ ret.inflightValue = childValues.then((childValues) => unwrap(childValues));
618
+ return ret.inflightValue;
619
+ }
620
+ return unwrap(childValues);
621
+ }
622
+ function updateHost(renderer, root, ctx, scope, ret, oldProps, hydrationData) {
623
+ const el = ret.el;
624
+ const tag = el.tag;
625
+ let hydrationValue;
626
+ if (el.tag === Portal) {
627
+ root = ret.value = el.props.root;
628
+ }
629
+ else {
630
+ if (hydrationData !== undefined) {
631
+ const value = hydrationData.children.shift();
632
+ hydrationValue = value;
633
+ }
634
+ }
635
+ scope = renderer.scope(scope, tag, el.props);
636
+ let childHydrationData;
637
+ if (hydrationValue != null && typeof hydrationValue !== "string") {
638
+ childHydrationData = renderer.hydrate(tag, hydrationValue, el.props);
639
+ if (childHydrationData === undefined) {
640
+ hydrationValue = undefined;
641
+ }
642
+ }
643
+ const childValues = diffChildren(renderer, root, ret, ctx, scope, ret, ret.el.props.children, childHydrationData);
644
+ if (isPromiseLike(childValues)) {
645
+ ret.inflightValue = childValues.then((childValues) => commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue));
646
+ return ret.inflightValue;
647
+ }
648
+ return commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue);
649
+ }
650
+ function commitHost(renderer, scope, ret, childValues, oldProps, hydrationValue) {
651
+ const tag = ret.el.tag;
652
+ let value = ret.value;
653
+ if (hydrationValue != null) {
654
+ value = ret.value = hydrationValue;
655
+ if (typeof ret.el.ref === "function") {
656
+ ret.el.ref(value);
657
+ }
658
+ }
659
+ let props = ret.el.props;
660
+ let copied;
661
+ if (tag !== Portal) {
662
+ if (value == null) {
663
+ // This assumes that renderer.create does not return nullish values.
664
+ value = ret.value = renderer.create(tag, props, scope);
665
+ if (typeof ret.el.ref === "function") {
666
+ ret.el.ref(value);
667
+ }
668
+ }
669
+ for (const propName in { ...oldProps, ...props }) {
670
+ const propValue = props[propName];
671
+ if (propValue === Copy) {
672
+ // TODO: The Copy tag doubles as a way to skip the patching of a prop.
673
+ // Not sure about this feature. Should probably be removed.
674
+ (copied = copied || new Set()).add(propName);
675
+ }
676
+ else if (!SPECIAL_PROPS.has(propName)) {
677
+ renderer.patch(tag, value, propName, propValue, oldProps && oldProps[propName], scope);
678
+ }
679
+ }
680
+ }
681
+ if (copied) {
682
+ props = { ...ret.el.props };
683
+ for (const name of copied) {
684
+ props[name] = oldProps && oldProps[name];
685
+ }
686
+ ret.el = new Element(tag, props);
687
+ }
688
+ renderer.arrange(tag, value, props, childValues, oldProps, wrap(ret.cachedChildValues));
689
+ ret.cachedChildValues = unwrap(childValues);
690
+ if (tag === Portal) {
691
+ flush(renderer, ret.value);
692
+ return;
693
+ }
694
+ return value;
695
+ }
696
+ function flush(renderer, root, initiator) {
697
+ renderer.flush(root);
698
+ if (typeof root !== "object" || root === null) {
699
+ return;
700
+ }
701
+ const flushMap = flushMaps.get(root);
702
+ if (flushMap) {
703
+ if (initiator) {
704
+ const flushMap1 = new Map();
705
+ for (let [ctx, callbacks] of flushMap) {
706
+ if (!ctxContains(initiator, ctx)) {
707
+ flushMap.delete(ctx);
708
+ flushMap1.set(ctx, callbacks);
709
+ }
710
+ }
711
+ if (flushMap1.size) {
712
+ flushMaps.set(root, flushMap1);
713
+ }
714
+ else {
715
+ flushMaps.delete(root);
716
+ }
717
+ }
718
+ else {
719
+ flushMaps.delete(root);
720
+ }
721
+ for (const [ctx, callbacks] of flushMap) {
722
+ const value = renderer.read(getValue(ctx.ret));
723
+ for (const callback of callbacks) {
724
+ callback(value);
725
+ }
726
+ }
727
+ }
728
+ }
729
+ function unmount(renderer, host, ctx, ret) {
730
+ if (typeof ret.el.tag === "function") {
731
+ ctx = ret.ctx;
732
+ unmountComponent(ctx);
733
+ }
734
+ else if (ret.el.tag === Portal) {
735
+ host = ret;
736
+ renderer.arrange(Portal, host.value, host.el.props, [], host.el.props, wrap(host.cachedChildValues));
737
+ flush(renderer, host.value);
738
+ }
739
+ else if (ret.el.tag !== Fragment) {
740
+ if (isEventTarget(ret.value)) {
741
+ const records = getListenerRecords(ctx, host);
742
+ for (let i = 0; i < records.length; i++) {
743
+ const record = records[i];
744
+ ret.value.removeEventListener(record.type, record.callback, record.options);
745
+ }
746
+ }
747
+ renderer.dispose(ret.el.tag, ret.value, ret.el.props);
748
+ host = ret;
749
+ }
750
+ const children = wrap(ret.children);
751
+ for (let i = 0; i < children.length; i++) {
752
+ const child = children[i];
753
+ if (typeof child === "object") {
754
+ unmount(renderer, host, ctx, child);
755
+ }
756
+ }
757
+ }
758
+ /*** CONTEXT FLAGS ***/
759
+ /**
760
+ * A flag which is true when the component is initialized or updated by an
761
+ * ancestor component or the root render call.
762
+ *
763
+ * Used to determine things like whether the nearest host ancestor needs to be
764
+ * rearranged.
765
+ */
766
+ const IsUpdating = 1 << 0;
767
+ /**
768
+ * A flag which is true when the component is synchronously executing.
769
+ *
770
+ * Used to guard against components triggering stack overflow or generator error.
771
+ */
772
+ const IsSyncExecuting = 1 << 1;
773
+ /**
774
+ * A flag which is true when the component is in a for...of loop.
775
+ */
776
+ const IsInForOfLoop = 1 << 2;
777
+ /**
778
+ * A flag which is true when the component is in a for await...of loop.
779
+ */
780
+ const IsInForAwaitOfLoop = 1 << 3;
781
+ /**
782
+ * A flag which is true when the component starts the render loop but has not
783
+ * yielded yet.
784
+ *
785
+ * Used to make sure that components yield at least once per loop.
786
+ */
787
+ const NeedsToYield = 1 << 4;
788
+ /**
789
+ * A flag used by async generator components in conjunction with the
790
+ * onAvailable callback to mark whether new props can be pulled via the context
791
+ * async iterator. See the Symbol.asyncIterator method and the
792
+ * resumeCtxIterator function.
793
+ */
794
+ const PropsAvailable = 1 << 5;
795
+ /**
796
+ * A flag which is set when a component errors.
797
+ *
798
+ * This is mainly used to prevent some false positives in "component yields or
799
+ * returns undefined" warnings. The reason we’re using this versus IsUnmounted
800
+ * is a very troubling test (cascades sync generator parent and sync generator
801
+ * child) where synchronous code causes a stack overflow error in a
802
+ * non-deterministic way. Deeply disturbing stuff.
803
+ */
804
+ const IsErrored = 1 << 6;
805
+ /**
806
+ * A flag which is set when the component is unmounted. Unmounted components
807
+ * are no longer in the element tree and cannot refresh or rerender.
808
+ */
809
+ const IsUnmounted = 1 << 7;
810
+ /**
811
+ * A flag which indicates that the component is a sync generator component.
812
+ */
813
+ const IsSyncGen = 1 << 8;
814
+ /**
815
+ * A flag which indicates that the component is an async generator component.
816
+ */
817
+ const IsAsyncGen = 1 << 9;
818
+ /**
819
+ * A flag which is set while schedule callbacks are called.
820
+ */
821
+ const IsScheduling = 1 << 10;
822
+ /**
823
+ * A flag which is set when a schedule callback calls refresh.
824
+ */
825
+ const IsSchedulingRefresh = 1 << 11;
826
+ const provisionMaps = new WeakMap();
827
+ const scheduleMap = new WeakMap();
828
+ const cleanupMap = new WeakMap();
829
+ // keys are roots
830
+ const flushMaps = new WeakMap();
831
+ /**
832
+ * @internal
833
+ * The internal class which holds context data.
834
+ */
835
+ class ContextImpl {
836
+ constructor(renderer, root, host, parent, scope, ret) {
837
+ this.f = 0;
838
+ this.owner = new Context(this);
839
+ this.renderer = renderer;
840
+ this.root = root;
841
+ this.host = host;
842
+ this.parent = parent;
843
+ this.scope = scope;
844
+ this.ret = ret;
845
+ this.iterator = undefined;
846
+ this.inflightBlock = undefined;
847
+ this.inflightValue = undefined;
848
+ this.enqueuedBlock = undefined;
849
+ this.enqueuedValue = undefined;
850
+ this.onProps = undefined;
851
+ this.onPropsRequested = undefined;
852
+ }
853
+ }
854
+ const _ContextImpl = Symbol.for("crank.ContextImpl");
855
+ /**
856
+ * A class which is instantiated and passed to every component as its this
857
+ * value. Contexts form a tree just like elements and all components in the
858
+ * element tree are connected via contexts. Components can use this tree to
859
+ * communicate data upwards via events and downwards via provisions.
860
+ *
861
+ * @template [T=*] - The expected shape of the props passed to the component,
862
+ * or a component function. Used to strongly type the Context iterator methods.
863
+ * @template [TResult=*] - The readable element value type. It is used in
864
+ * places such as the return value of refresh and the argument passed to
865
+ * schedule and cleanup callbacks.
866
+ */
867
+ class Context {
868
+ // TODO: If we could make the constructor function take a nicer value, it
869
+ // would be useful for testing purposes.
870
+ constructor(impl) {
871
+ this[_ContextImpl] = impl;
872
+ }
873
+ /**
874
+ * The current props of the associated element.
875
+ */
876
+ get props() {
877
+ return this[_ContextImpl].ret.el.props;
878
+ }
879
+ /**
880
+ * The current value of the associated element.
881
+ *
882
+ * @deprecated
883
+ */
884
+ get value() {
885
+ return this[_ContextImpl].renderer.read(getValue(this[_ContextImpl].ret));
886
+ }
887
+ *[Symbol.iterator]() {
888
+ const ctx = this[_ContextImpl];
889
+ try {
890
+ ctx.f |= IsInForOfLoop;
891
+ while (!(ctx.f & IsUnmounted)) {
892
+ if (ctx.f & NeedsToYield) {
893
+ throw new Error("Context iterated twice without a yield");
894
+ }
895
+ else {
896
+ ctx.f |= NeedsToYield;
897
+ }
898
+ yield ctx.ret.el.props;
899
+ }
900
+ }
901
+ finally {
902
+ ctx.f &= ~IsInForOfLoop;
903
+ }
904
+ }
905
+ async *[Symbol.asyncIterator]() {
906
+ const ctx = this[_ContextImpl];
907
+ if (ctx.f & IsSyncGen) {
908
+ throw new Error("Use for...of in sync generator components");
909
+ }
910
+ try {
911
+ ctx.f |= IsInForAwaitOfLoop;
912
+ while (!(ctx.f & IsUnmounted)) {
913
+ if (ctx.f & NeedsToYield) {
914
+ throw new Error("Context iterated twice without a yield");
915
+ }
916
+ else {
917
+ ctx.f |= NeedsToYield;
918
+ }
919
+ if (ctx.f & PropsAvailable) {
920
+ ctx.f &= ~PropsAvailable;
921
+ yield ctx.ret.el.props;
922
+ }
923
+ else {
924
+ const props = await new Promise((resolve) => (ctx.onProps = resolve));
925
+ if (ctx.f & IsUnmounted) {
926
+ break;
927
+ }
928
+ yield props;
929
+ }
930
+ if (ctx.onPropsRequested) {
931
+ ctx.onPropsRequested();
932
+ ctx.onPropsRequested = undefined;
933
+ }
934
+ }
935
+ }
936
+ finally {
937
+ ctx.f &= ~IsInForAwaitOfLoop;
938
+ if (ctx.onPropsRequested) {
939
+ ctx.onPropsRequested();
940
+ ctx.onPropsRequested = undefined;
941
+ }
942
+ }
943
+ }
944
+ /**
945
+ * Re-executes a component.
946
+ *
947
+ * @returns The rendered value of the component or a promise thereof if the
948
+ * component or its children execute asynchronously.
949
+ *
950
+ * The refresh method works a little differently for async generator
951
+ * components, in that it will resume the Context’s props async iterator
952
+ * rather than resuming execution. This is because async generator components
953
+ * are perpetually resumed independent of updates, and rely on the props
954
+ * async iterator to suspend.
955
+ */
956
+ refresh() {
957
+ const ctx = this[_ContextImpl];
958
+ if (ctx.f & IsUnmounted) {
959
+ console.error("Component is unmounted");
960
+ return ctx.renderer.read(undefined);
961
+ }
962
+ else if (ctx.f & IsSyncExecuting) {
963
+ console.error("Component is already executing");
964
+ return ctx.renderer.read(getValue(ctx.ret));
965
+ }
966
+ const value = enqueueComponentRun(ctx);
967
+ if (isPromiseLike(value)) {
968
+ return value.then((value) => ctx.renderer.read(value));
969
+ }
970
+ return ctx.renderer.read(value);
971
+ }
972
+ /**
973
+ * Registers a callback which fires when the component commits. Will only
974
+ * fire once per callback and update.
975
+ */
976
+ schedule(callback) {
977
+ const ctx = this[_ContextImpl];
978
+ let callbacks = scheduleMap.get(ctx);
979
+ if (!callbacks) {
980
+ callbacks = new Set();
981
+ scheduleMap.set(ctx, callbacks);
982
+ }
983
+ callbacks.add(callback);
984
+ }
985
+ /**
986
+ * Registers a callback which fires when the component’s children are
987
+ * rendered into the root. Will only fire once per callback and render.
988
+ */
989
+ flush(callback) {
990
+ const ctx = this[_ContextImpl];
991
+ if (typeof ctx.root !== "object" || ctx.root === null) {
992
+ return;
993
+ }
994
+ let flushMap = flushMaps.get(ctx.root);
995
+ if (!flushMap) {
996
+ flushMap = new Map();
997
+ flushMaps.set(ctx.root, flushMap);
998
+ }
999
+ let callbacks = flushMap.get(ctx);
1000
+ if (!callbacks) {
1001
+ callbacks = new Set();
1002
+ flushMap.set(ctx, callbacks);
1003
+ }
1004
+ callbacks.add(callback);
1005
+ }
1006
+ /**
1007
+ * Registers a callback which fires when the component unmounts. Will only
1008
+ * fire once per callback.
1009
+ */
1010
+ cleanup(callback) {
1011
+ const ctx = this[_ContextImpl];
1012
+ if (ctx.f & IsUnmounted) {
1013
+ const value = ctx.renderer.read(getValue(ctx.ret));
1014
+ callback(value);
1015
+ return;
1016
+ }
1017
+ let callbacks = cleanupMap.get(ctx);
1018
+ if (!callbacks) {
1019
+ callbacks = new Set();
1020
+ cleanupMap.set(ctx, callbacks);
1021
+ }
1022
+ callbacks.add(callback);
1023
+ }
1024
+ consume(key) {
1025
+ for (let ctx = this[_ContextImpl].parent; ctx !== undefined; ctx = ctx.parent) {
1026
+ const provisions = provisionMaps.get(ctx);
1027
+ if (provisions && provisions.has(key)) {
1028
+ return provisions.get(key);
1029
+ }
1030
+ }
1031
+ }
1032
+ provide(key, value) {
1033
+ const ctx = this[_ContextImpl];
1034
+ let provisions = provisionMaps.get(ctx);
1035
+ if (!provisions) {
1036
+ provisions = new Map();
1037
+ provisionMaps.set(ctx, provisions);
1038
+ }
1039
+ provisions.set(key, value);
1040
+ }
1041
+ addEventListener(type, listener, options) {
1042
+ const ctx = this[_ContextImpl];
1043
+ let listeners;
1044
+ if (!isListenerOrListenerObject(listener)) {
1045
+ return;
1046
+ }
1047
+ else {
1048
+ const listeners1 = listenersMap.get(ctx);
1049
+ if (listeners1) {
1050
+ listeners = listeners1;
1051
+ }
1052
+ else {
1053
+ listeners = [];
1054
+ listenersMap.set(ctx, listeners);
1055
+ }
1056
+ }
1057
+ options = normalizeListenerOptions(options);
1058
+ let callback;
1059
+ if (typeof listener === "object") {
1060
+ callback = () => listener.handleEvent.apply(listener, arguments);
1061
+ }
1062
+ else {
1063
+ callback = listener;
1064
+ }
1065
+ const record = { type, listener, callback, options };
1066
+ if (options.once) {
1067
+ record.callback = function () {
1068
+ const i = listeners.indexOf(record);
1069
+ if (i !== -1) {
1070
+ listeners.splice(i, 1);
1071
+ }
1072
+ return callback.apply(this, arguments);
1073
+ };
1074
+ }
1075
+ if (listeners.some((record1) => record.type === record1.type &&
1076
+ record.listener === record1.listener &&
1077
+ !record.options.capture === !record1.options.capture)) {
1078
+ return;
1079
+ }
1080
+ listeners.push(record);
1081
+ // TODO: is it possible to separate out the EventTarget delegation logic
1082
+ for (const value of getChildValues(ctx.ret)) {
1083
+ if (isEventTarget(value)) {
1084
+ value.addEventListener(record.type, record.callback, record.options);
1085
+ }
1086
+ }
1087
+ }
1088
+ removeEventListener(type, listener, options) {
1089
+ const ctx = this[_ContextImpl];
1090
+ const listeners = listenersMap.get(ctx);
1091
+ if (listeners == null || !isListenerOrListenerObject(listener)) {
1092
+ return;
1093
+ }
1094
+ const options1 = normalizeListenerOptions(options);
1095
+ const i = listeners.findIndex((record) => record.type === type &&
1096
+ record.listener === listener &&
1097
+ !record.options.capture === !options1.capture);
1098
+ if (i === -1) {
1099
+ return;
1100
+ }
1101
+ const record = listeners[i];
1102
+ listeners.splice(i, 1);
1103
+ // TODO: is it possible to separate out the EventTarget delegation logic
1104
+ for (const value of getChildValues(ctx.ret)) {
1105
+ if (isEventTarget(value)) {
1106
+ value.removeEventListener(record.type, record.callback, record.options);
1107
+ }
1108
+ }
1109
+ }
1110
+ dispatchEvent(ev) {
1111
+ const ctx = this[_ContextImpl];
1112
+ const path = [];
1113
+ for (let parent = ctx.parent; parent !== undefined; parent = parent.parent) {
1114
+ path.push(parent);
1115
+ }
1116
+ // We patch the stopImmediatePropagation method because ev.cancelBubble
1117
+ // only informs us if stopPropagation was called and there are no
1118
+ // properties which inform us if stopImmediatePropagation was called.
1119
+ let immediateCancelBubble = false;
1120
+ const stopImmediatePropagation = ev.stopImmediatePropagation;
1121
+ setEventProperty(ev, "stopImmediatePropagation", () => {
1122
+ immediateCancelBubble = true;
1123
+ return stopImmediatePropagation.call(ev);
1124
+ });
1125
+ setEventProperty(ev, "target", ctx.owner);
1126
+ // The only possible errors in this block are errors thrown by callbacks,
1127
+ // and dispatchEvent will only log these errors rather than throwing
1128
+ // them. Therefore, we place all code in a try block, log errors in the
1129
+ // catch block, and use an unsafe return statement in the finally block.
1130
+ //
1131
+ // Each early return within the try block returns true because while the
1132
+ // return value is overridden in the finally block, TypeScript
1133
+ // (justifiably) does not recognize the unsafe return statement.
1134
+ try {
1135
+ setEventProperty(ev, "eventPhase", CAPTURING_PHASE);
1136
+ for (let i = path.length - 1; i >= 0; i--) {
1137
+ const target = path[i];
1138
+ const listeners = listenersMap.get(target);
1139
+ if (listeners) {
1140
+ setEventProperty(ev, "currentTarget", target.owner);
1141
+ for (const record of listeners) {
1142
+ if (record.type === ev.type && record.options.capture) {
1143
+ try {
1144
+ record.callback.call(target.owner, ev);
1145
+ }
1146
+ catch (err) {
1147
+ console.error(err);
1148
+ }
1149
+ if (immediateCancelBubble) {
1150
+ return true;
1151
+ }
1152
+ }
1153
+ }
1154
+ }
1155
+ if (ev.cancelBubble) {
1156
+ return true;
1157
+ }
1158
+ }
1159
+ {
1160
+ setEventProperty(ev, "eventPhase", AT_TARGET);
1161
+ setEventProperty(ev, "currentTarget", ctx.owner);
1162
+ // dispatchEvent calls the prop callback if it exists
1163
+ let propCallback = ctx.ret.el.props["on" + ev.type];
1164
+ if (typeof propCallback === "function") {
1165
+ propCallback(ev);
1166
+ if (immediateCancelBubble || ev.cancelBubble) {
1167
+ return true;
1168
+ }
1169
+ }
1170
+ else {
1171
+ // Checks for camel-cased event props
1172
+ for (const propName in ctx.ret.el.props) {
1173
+ if (propName.toLowerCase() === "on" + ev.type.toLowerCase()) {
1174
+ propCallback = ctx.ret.el.props[propName];
1175
+ if (typeof propCallback === "function") {
1176
+ propCallback(ev);
1177
+ if (immediateCancelBubble || ev.cancelBubble) {
1178
+ return true;
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+ }
1184
+ const listeners = listenersMap.get(ctx);
1185
+ if (listeners) {
1186
+ for (const record of listeners) {
1187
+ if (record.type === ev.type) {
1188
+ try {
1189
+ record.callback.call(ctx.owner, ev);
1190
+ }
1191
+ catch (err) {
1192
+ console.error(err);
1193
+ }
1194
+ if (immediateCancelBubble) {
1195
+ return true;
1196
+ }
1197
+ }
1198
+ }
1199
+ if (ev.cancelBubble) {
1200
+ return true;
1201
+ }
1202
+ }
1203
+ }
1204
+ if (ev.bubbles) {
1205
+ setEventProperty(ev, "eventPhase", BUBBLING_PHASE);
1206
+ for (let i = 0; i < path.length; i++) {
1207
+ const target = path[i];
1208
+ const listeners = listenersMap.get(target);
1209
+ if (listeners) {
1210
+ setEventProperty(ev, "currentTarget", target.owner);
1211
+ for (const record of listeners) {
1212
+ if (record.type === ev.type && !record.options.capture) {
1213
+ try {
1214
+ record.callback.call(target.owner, ev);
1215
+ }
1216
+ catch (err) {
1217
+ console.error(err);
1218
+ }
1219
+ if (immediateCancelBubble) {
1220
+ return true;
1221
+ }
1222
+ }
1223
+ }
1224
+ }
1225
+ if (ev.cancelBubble) {
1226
+ return true;
1227
+ }
1228
+ }
1229
+ }
1230
+ }
1231
+ finally {
1232
+ setEventProperty(ev, "eventPhase", NONE);
1233
+ setEventProperty(ev, "currentTarget", null);
1234
+ // eslint-disable-next-line no-unsafe-finally
1235
+ return !ev.defaultPrevented;
1236
+ }
1237
+ }
1238
+ }
1239
+ /*** PRIVATE CONTEXT FUNCTIONS ***/
1240
+ function ctxContains(parent, child) {
1241
+ for (let current = child; current !== undefined; current = current.parent) {
1242
+ if (current === parent) {
1243
+ return true;
1244
+ }
1245
+ }
1246
+ return false;
1247
+ }
1248
+ function updateComponent(renderer, root, host, parent, scope, ret, oldProps, hydrationData) {
1249
+ let ctx;
1250
+ if (oldProps) {
1251
+ ctx = ret.ctx;
1252
+ if (ctx.f & IsSyncExecuting) {
1253
+ console.error("Component is already executing");
1254
+ return ret.cachedChildValues;
1255
+ }
1256
+ }
1257
+ else {
1258
+ ctx = ret.ctx = new ContextImpl(renderer, root, host, parent, scope, ret);
1259
+ }
1260
+ ctx.f |= IsUpdating;
1261
+ return enqueueComponentRun(ctx, hydrationData);
1262
+ }
1263
+ function updateComponentChildren(ctx, children, hydrationData) {
1264
+ if (ctx.f & IsUnmounted) {
1265
+ return;
1266
+ }
1267
+ else if (ctx.f & IsErrored) {
1268
+ // This branch is necessary for some race conditions where this function is
1269
+ // called after iterator.throw() in async generator components.
1270
+ return;
1271
+ }
1272
+ else if (children === undefined) {
1273
+ console.error("A component has returned or yielded undefined. If this was intentional, return or yield null instead.");
1274
+ }
1275
+ let childValues;
1276
+ try {
1277
+ // TODO: WAT
1278
+ // We set the isExecuting flag in case a child component dispatches an event
1279
+ // which bubbles to this component and causes a synchronous refresh().
1280
+ ctx.f |= IsSyncExecuting;
1281
+ childValues = diffChildren(ctx.renderer, ctx.root, ctx.host, ctx, ctx.scope, ctx.ret, narrow(children), hydrationData);
1282
+ }
1283
+ finally {
1284
+ ctx.f &= ~IsSyncExecuting;
1285
+ }
1286
+ if (isPromiseLike(childValues)) {
1287
+ ctx.ret.inflightValue = childValues.then((childValues) => commitComponent(ctx, childValues));
1288
+ return ctx.ret.inflightValue;
1289
+ }
1290
+ return commitComponent(ctx, childValues);
1291
+ }
1292
+ function commitComponent(ctx, values) {
1293
+ if (ctx.f & IsUnmounted) {
1294
+ return;
1295
+ }
1296
+ const listeners = listenersMap.get(ctx);
1297
+ if (listeners && listeners.length) {
1298
+ for (let i = 0; i < values.length; i++) {
1299
+ const value = values[i];
1300
+ if (isEventTarget(value)) {
1301
+ for (let j = 0; j < listeners.length; j++) {
1302
+ const record = listeners[j];
1303
+ value.addEventListener(record.type, record.callback, record.options);
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+ const oldValues = wrap(ctx.ret.cachedChildValues);
1309
+ let value = (ctx.ret.cachedChildValues = unwrap(values));
1310
+ if (ctx.f & IsScheduling) {
1311
+ ctx.f |= IsSchedulingRefresh;
1312
+ }
1313
+ else if (!(ctx.f & IsUpdating)) {
1314
+ // If we’re not updating the component, which happens when components are
1315
+ // refreshed, or when async generator components iterate, we have to do a
1316
+ // little bit housekeeping when a component’s child values have changed.
1317
+ if (!arrayEqual(oldValues, values)) {
1318
+ const records = getListenerRecords(ctx.parent, ctx.host);
1319
+ if (records.length) {
1320
+ for (let i = 0; i < values.length; i++) {
1321
+ const value = values[i];
1322
+ if (isEventTarget(value)) {
1323
+ for (let j = 0; j < records.length; j++) {
1324
+ const record = records[j];
1325
+ value.addEventListener(record.type, record.callback, record.options);
1326
+ }
1327
+ }
1328
+ }
1329
+ }
1330
+ // rearranging the nearest ancestor host element
1331
+ const host = ctx.host;
1332
+ const oldHostValues = wrap(host.cachedChildValues);
1333
+ invalidate(ctx, host);
1334
+ const hostValues = getChildValues(host);
1335
+ ctx.renderer.arrange(host.el.tag, host.value, host.el.props, hostValues,
1336
+ // props and oldProps are the same because the host isn’t updated.
1337
+ host.el.props, oldHostValues);
1338
+ }
1339
+ flush(ctx.renderer, ctx.root, ctx);
1340
+ }
1341
+ const callbacks = scheduleMap.get(ctx);
1342
+ if (callbacks) {
1343
+ scheduleMap.delete(ctx);
1344
+ ctx.f |= IsScheduling;
1345
+ const value1 = ctx.renderer.read(value);
1346
+ for (const callback of callbacks) {
1347
+ callback(value1);
1348
+ }
1349
+ ctx.f &= ~IsScheduling;
1350
+ // Handles an edge case where refresh() is called during a schedule().
1351
+ if (ctx.f & IsSchedulingRefresh) {
1352
+ ctx.f &= ~IsSchedulingRefresh;
1353
+ value = getValue(ctx.ret);
1354
+ }
1355
+ }
1356
+ ctx.f &= ~IsUpdating;
1357
+ return value;
1358
+ }
1359
+ function invalidate(ctx, host) {
1360
+ for (let parent = ctx.parent; parent !== undefined && parent.host === host; parent = parent.parent) {
1361
+ parent.ret.cachedChildValues = undefined;
1362
+ }
1363
+ host.cachedChildValues = undefined;
1364
+ }
1365
+ function arrayEqual(arr1, arr2) {
1366
+ if (arr1.length !== arr2.length) {
1367
+ return false;
1368
+ }
1369
+ for (let i = 0; i < arr1.length; i++) {
1370
+ const value1 = arr1[i];
1371
+ const value2 = arr2[i];
1372
+ if (value1 !== value2) {
1373
+ return false;
1374
+ }
1375
+ }
1376
+ return true;
1377
+ }
1378
+ /** Enqueues and executes the component associated with the context. */
1379
+ function enqueueComponentRun(ctx, hydrationData) {
1380
+ if (ctx.f & IsAsyncGen && !(ctx.f & IsInForOfLoop)) {
1381
+ if (hydrationData !== undefined) {
1382
+ throw new Error("Hydration error");
1383
+ }
1384
+ // This branch will run for non-initial renders of async generator
1385
+ // components when they are not in for...of loops. When in a for...of loop,
1386
+ // async generator components will behave normally.
1387
+ //
1388
+ // Async gen componennts can be in one of three states:
1389
+ //
1390
+ // 1. propsAvailable flag is true: "available"
1391
+ //
1392
+ // The component is suspended somewhere in the loop. When the component
1393
+ // reaches the bottom of the loop, it will run again with the next props.
1394
+ //
1395
+ // 2. onAvailable callback is defined: "suspended"
1396
+ //
1397
+ // The component has suspended at the bottom of the loop and is waiting
1398
+ // for new props.
1399
+ //
1400
+ // 3. neither 1 or 2: "Running"
1401
+ //
1402
+ // The component is suspended somewhere in the loop. When the component
1403
+ // reaches the bottom of the loop, it will suspend.
1404
+ //
1405
+ // Components will never be both available and suspended at
1406
+ // the same time.
1407
+ //
1408
+ // If the component is at the loop bottom, this means that the next value
1409
+ // produced by the component will have the most up to date props, so we can
1410
+ // simply return the current inflight value. Otherwise, we have to wait for
1411
+ // the bottom of the loop to be reached before returning the inflight
1412
+ // value.
1413
+ const isAtLoopbottom = ctx.f & IsInForAwaitOfLoop && !ctx.onProps;
1414
+ resumePropsAsyncIterator(ctx);
1415
+ if (isAtLoopbottom) {
1416
+ if (ctx.inflightBlock == null) {
1417
+ ctx.inflightBlock = new Promise((resolve) => (ctx.onPropsRequested = resolve));
1418
+ }
1419
+ return ctx.inflightBlock.then(() => {
1420
+ ctx.inflightBlock = undefined;
1421
+ return ctx.inflightValue;
1422
+ });
1423
+ }
1424
+ return ctx.inflightValue;
1425
+ }
1426
+ else if (!ctx.inflightBlock) {
1427
+ try {
1428
+ const [block, value] = runComponent(ctx, hydrationData);
1429
+ if (block) {
1430
+ ctx.inflightBlock = block
1431
+ // TODO: there is some fuckery going on here related to async
1432
+ // generator components resuming when they’re meant to be returned.
1433
+ .then((v) => v)
1434
+ .finally(() => advanceComponent(ctx));
1435
+ // stepComponent will only return a block if the value is asynchronous
1436
+ ctx.inflightValue = value;
1437
+ }
1438
+ return value;
1439
+ }
1440
+ catch (err) {
1441
+ if (!(ctx.f & IsUpdating)) {
1442
+ if (!ctx.parent) {
1443
+ throw err;
1444
+ }
1445
+ return propagateError(ctx.parent, err);
1446
+ }
1447
+ throw err;
1448
+ }
1449
+ }
1450
+ else if (!ctx.enqueuedBlock) {
1451
+ if (hydrationData !== undefined) {
1452
+ throw new Error("Hydration error");
1453
+ }
1454
+ // We need to assign enqueuedBlock and enqueuedValue synchronously, hence
1455
+ // the Promise constructor call here.
1456
+ let resolveEnqueuedBlock;
1457
+ ctx.enqueuedBlock = new Promise((resolve) => (resolveEnqueuedBlock = resolve));
1458
+ ctx.enqueuedValue = ctx.inflightBlock.then(() => {
1459
+ try {
1460
+ const [block, value] = runComponent(ctx);
1461
+ if (block) {
1462
+ resolveEnqueuedBlock(block.finally(() => advanceComponent(ctx)));
1463
+ }
1464
+ return value;
1465
+ }
1466
+ catch (err) {
1467
+ if (!(ctx.f & IsUpdating)) {
1468
+ if (!ctx.parent) {
1469
+ throw err;
1470
+ }
1471
+ return propagateError(ctx.parent, err);
1472
+ }
1473
+ throw err;
1474
+ }
1475
+ });
1476
+ }
1477
+ return ctx.enqueuedValue;
1478
+ }
1479
+ /** Called when the inflight block promise settles. */
1480
+ function advanceComponent(ctx) {
1481
+ if (ctx.f & IsAsyncGen && !(ctx.f & IsInForOfLoop)) {
1482
+ return;
1483
+ }
1484
+ ctx.inflightBlock = ctx.enqueuedBlock;
1485
+ ctx.inflightValue = ctx.enqueuedValue;
1486
+ ctx.enqueuedBlock = undefined;
1487
+ ctx.enqueuedValue = undefined;
1488
+ }
1489
+ /**
1490
+ * This function is responsible for executing the component and handling all
1491
+ * the different component types. We cannot identify whether a component is a
1492
+ * generator or async without calling it and inspecting the return value.
1493
+ *
1494
+ * @returns {[block, value]} A tuple where
1495
+ * block - A possible promise which represents the duration during which the
1496
+ * component is blocked from updating.
1497
+ * value - A possible promise resolving to the rendered value of children.
1498
+ *
1499
+ * Each component type will block according to the type of the component.
1500
+ * - Sync function components never block and will transparently pass updates
1501
+ * to children.
1502
+ * - Async function components and async generator components block while
1503
+ * executing itself, but will not block for async children.
1504
+ * - Sync generator components block while any children are executing, because
1505
+ * they are expected to only resume when they’ve actually rendered.
1506
+ */
1507
+ function runComponent(ctx, hydrationData) {
1508
+ const ret = ctx.ret;
1509
+ const initial = !ctx.iterator;
1510
+ if (initial) {
1511
+ resumePropsAsyncIterator(ctx);
1512
+ ctx.f |= IsSyncExecuting;
1513
+ clearEventListeners(ctx);
1514
+ let result;
1515
+ try {
1516
+ result = ret.el.tag.call(ctx.owner, ret.el.props, ctx.owner);
1517
+ }
1518
+ catch (err) {
1519
+ ctx.f |= IsErrored;
1520
+ throw err;
1521
+ }
1522
+ finally {
1523
+ ctx.f &= ~IsSyncExecuting;
1524
+ }
1525
+ if (isIteratorLike(result)) {
1526
+ ctx.iterator = result;
1527
+ }
1528
+ else if (isPromiseLike(result)) {
1529
+ // async function component
1530
+ const result1 = result instanceof Promise ? result : Promise.resolve(result);
1531
+ const value = result1.then((result) => updateComponentChildren(ctx, result, hydrationData), (err) => {
1532
+ ctx.f |= IsErrored;
1533
+ throw err;
1534
+ });
1535
+ return [result1.catch(NOOP), value];
1536
+ }
1537
+ else {
1538
+ // sync function component
1539
+ return [
1540
+ undefined,
1541
+ updateComponentChildren(ctx, result, hydrationData),
1542
+ ];
1543
+ }
1544
+ }
1545
+ else if (hydrationData !== undefined) {
1546
+ // hydration data should only be passed on the initial render
1547
+ throw new Error("Hydration error");
1548
+ }
1549
+ let iteration;
1550
+ if (initial) {
1551
+ try {
1552
+ ctx.f |= IsSyncExecuting;
1553
+ iteration = ctx.iterator.next();
1554
+ }
1555
+ catch (err) {
1556
+ ctx.f |= IsErrored;
1557
+ throw err;
1558
+ }
1559
+ finally {
1560
+ ctx.f &= ~IsSyncExecuting;
1561
+ }
1562
+ if (isPromiseLike(iteration)) {
1563
+ ctx.f |= IsAsyncGen;
1564
+ }
1565
+ else {
1566
+ ctx.f |= IsSyncGen;
1567
+ }
1568
+ }
1569
+ if (ctx.f & IsSyncGen) {
1570
+ // sync generator component
1571
+ if (!initial) {
1572
+ try {
1573
+ ctx.f |= IsSyncExecuting;
1574
+ iteration = ctx.iterator.next(ctx.renderer.read(getValue(ret)));
1575
+ }
1576
+ catch (err) {
1577
+ ctx.f |= IsErrored;
1578
+ throw err;
1579
+ }
1580
+ finally {
1581
+ ctx.f &= ~IsSyncExecuting;
1582
+ }
1583
+ }
1584
+ if (isPromiseLike(iteration)) {
1585
+ throw new Error("Mixed generator component");
1586
+ }
1587
+ if (ctx.f & IsInForOfLoop &&
1588
+ !(ctx.f & NeedsToYield) &&
1589
+ !(ctx.f & IsUnmounted)) {
1590
+ console.error("Component yielded more than once in for...of loop");
1591
+ }
1592
+ ctx.f &= ~NeedsToYield;
1593
+ if (iteration.done) {
1594
+ ctx.f &= ~IsSyncGen;
1595
+ ctx.iterator = undefined;
1596
+ }
1597
+ let value;
1598
+ try {
1599
+ value = updateComponentChildren(ctx,
1600
+ // Children can be void so we eliminate that here
1601
+ iteration.value, hydrationData);
1602
+ if (isPromiseLike(value)) {
1603
+ value = value.catch((err) => handleChildError(ctx, err));
1604
+ }
1605
+ }
1606
+ catch (err) {
1607
+ value = handleChildError(ctx, err);
1608
+ }
1609
+ const block = isPromiseLike(value) ? value.catch(NOOP) : undefined;
1610
+ return [block, value];
1611
+ }
1612
+ else {
1613
+ if (ctx.f & IsInForOfLoop) {
1614
+ // Async generator component using for...of loops behave similar to sync
1615
+ // generator components. This allows for easier refactoring of sync to
1616
+ // async generator components.
1617
+ if (!initial) {
1618
+ try {
1619
+ ctx.f |= IsSyncExecuting;
1620
+ iteration = ctx.iterator.next(ctx.renderer.read(getValue(ret)));
1621
+ }
1622
+ catch (err) {
1623
+ ctx.f |= IsErrored;
1624
+ throw err;
1625
+ }
1626
+ finally {
1627
+ ctx.f &= ~IsSyncExecuting;
1628
+ }
1629
+ }
1630
+ if (!isPromiseLike(iteration)) {
1631
+ throw new Error("Mixed generator component");
1632
+ }
1633
+ const block = iteration.catch(NOOP);
1634
+ const value = iteration.then((iteration) => {
1635
+ let value;
1636
+ if (!(ctx.f & IsInForOfLoop)) {
1637
+ runAsyncGenComponent(ctx, Promise.resolve(iteration), hydrationData);
1638
+ }
1639
+ else {
1640
+ if (!(ctx.f & NeedsToYield) && !(ctx.f & IsUnmounted)) {
1641
+ console.error("Component yielded more than once in for...of loop");
1642
+ }
1643
+ }
1644
+ ctx.f &= ~NeedsToYield;
1645
+ try {
1646
+ value = updateComponentChildren(ctx,
1647
+ // Children can be void so we eliminate that here
1648
+ iteration.value, hydrationData);
1649
+ if (isPromiseLike(value)) {
1650
+ value = value.catch((err) => handleChildError(ctx, err));
1651
+ }
1652
+ }
1653
+ catch (err) {
1654
+ value = handleChildError(ctx, err);
1655
+ }
1656
+ return value;
1657
+ }, (err) => {
1658
+ ctx.f |= IsErrored;
1659
+ throw err;
1660
+ });
1661
+ return [block, value];
1662
+ }
1663
+ else {
1664
+ runAsyncGenComponent(ctx, iteration, hydrationData, initial);
1665
+ return [ctx.inflightBlock, ctx.inflightValue];
1666
+ }
1667
+ }
1668
+ }
1669
+ async function runAsyncGenComponent(ctx, iterationP, hydrationData, initial = false) {
1670
+ let done = false;
1671
+ try {
1672
+ while (!done) {
1673
+ if (ctx.f & IsInForOfLoop) {
1674
+ break;
1675
+ }
1676
+ // inflightValue must be set synchronously.
1677
+ let onValue;
1678
+ ctx.inflightValue = new Promise((resolve) => (onValue = resolve));
1679
+ if (ctx.f & IsUpdating) {
1680
+ // We should not swallow unhandled promise rejections if the component is
1681
+ // updating independently.
1682
+ // TODO: Does this handle this.refresh() calls?
1683
+ ctx.inflightValue.catch(NOOP);
1684
+ }
1685
+ let iteration;
1686
+ try {
1687
+ iteration = await iterationP;
1688
+ }
1689
+ catch (err) {
1690
+ done = true;
1691
+ ctx.f |= IsErrored;
1692
+ onValue(Promise.reject(err));
1693
+ break;
1694
+ }
1695
+ if (!(ctx.f & IsInForAwaitOfLoop)) {
1696
+ ctx.f &= ~PropsAvailable;
1697
+ }
1698
+ done = !!iteration.done;
1699
+ let value;
1700
+ try {
1701
+ if (!(ctx.f & NeedsToYield) &&
1702
+ ctx.f & PropsAvailable &&
1703
+ ctx.f & IsInForAwaitOfLoop &&
1704
+ !initial &&
1705
+ !done) {
1706
+ // We skip stale iterations in for await...of loops.
1707
+ value = ctx.ret.inflightValue || getValue(ctx.ret);
1708
+ }
1709
+ else {
1710
+ value = updateComponentChildren(ctx, iteration.value, hydrationData);
1711
+ hydrationData = undefined;
1712
+ if (isPromiseLike(value)) {
1713
+ value = value.catch((err) => handleChildError(ctx, err));
1714
+ }
1715
+ }
1716
+ ctx.f &= ~NeedsToYield;
1717
+ }
1718
+ catch (err) {
1719
+ // Do we need to catch potential errors here in the case of unhandled
1720
+ // promise rejections?
1721
+ value = handleChildError(ctx, err);
1722
+ }
1723
+ finally {
1724
+ onValue(value);
1725
+ }
1726
+ let oldResult;
1727
+ if (ctx.ret.inflightValue) {
1728
+ // The value passed back into the generator as the argument to the next
1729
+ // method is a promise if an async generator component has async
1730
+ // children. Sync generator components only resume when their children
1731
+ // have fulfilled so the element’s inflight child values will never be
1732
+ // defined.
1733
+ oldResult = ctx.ret.inflightValue.then((value) => ctx.renderer.read(value));
1734
+ oldResult.catch((err) => {
1735
+ if (ctx.f & IsUpdating) {
1736
+ return;
1737
+ }
1738
+ if (!ctx.parent) {
1739
+ throw err;
1740
+ }
1741
+ return propagateError(ctx.parent, err);
1742
+ });
1743
+ }
1744
+ else {
1745
+ oldResult = ctx.renderer.read(getValue(ctx.ret));
1746
+ }
1747
+ if (ctx.f & IsUnmounted) {
1748
+ if (ctx.f & IsInForAwaitOfLoop) {
1749
+ try {
1750
+ ctx.f |= IsSyncExecuting;
1751
+ iterationP = ctx.iterator.next(oldResult);
1752
+ }
1753
+ finally {
1754
+ ctx.f &= ~IsSyncExecuting;
1755
+ }
1756
+ }
1757
+ else {
1758
+ returnComponent(ctx);
1759
+ break;
1760
+ }
1761
+ }
1762
+ else if (!done && !(ctx.f & IsInForOfLoop)) {
1763
+ try {
1764
+ ctx.f |= IsSyncExecuting;
1765
+ iterationP = ctx.iterator.next(oldResult);
1766
+ }
1767
+ finally {
1768
+ ctx.f &= ~IsSyncExecuting;
1769
+ }
1770
+ }
1771
+ initial = false;
1772
+ }
1773
+ }
1774
+ finally {
1775
+ if (done) {
1776
+ ctx.f &= ~IsAsyncGen;
1777
+ ctx.iterator = undefined;
1778
+ }
1779
+ }
1780
+ }
1781
+ /**
1782
+ * Called to resume the props async iterator for async generator components.
1783
+ */
1784
+ function resumePropsAsyncIterator(ctx) {
1785
+ if (ctx.onProps) {
1786
+ ctx.onProps(ctx.ret.el.props);
1787
+ ctx.onProps = undefined;
1788
+ ctx.f &= ~PropsAvailable;
1789
+ }
1790
+ else {
1791
+ ctx.f |= PropsAvailable;
1792
+ }
1793
+ }
1794
+ // TODO: async unmounting
1795
+ function unmountComponent(ctx) {
1796
+ if (ctx.f & IsUnmounted) {
1797
+ return;
1798
+ }
1799
+ clearEventListeners(ctx);
1800
+ const callbacks = cleanupMap.get(ctx);
1801
+ if (callbacks) {
1802
+ cleanupMap.delete(ctx);
1803
+ const value = ctx.renderer.read(getValue(ctx.ret));
1804
+ for (const callback of callbacks) {
1805
+ callback(value);
1806
+ }
1807
+ }
1808
+ ctx.f |= IsUnmounted;
1809
+ if (ctx.iterator) {
1810
+ if (ctx.f & IsSyncGen) {
1811
+ let value;
1812
+ if (ctx.f & IsInForOfLoop) {
1813
+ value = enqueueComponentRun(ctx);
1814
+ }
1815
+ if (isPromiseLike(value)) {
1816
+ value.then(() => {
1817
+ if (ctx.f & IsInForOfLoop) {
1818
+ unmountComponent(ctx);
1819
+ }
1820
+ else {
1821
+ returnComponent(ctx);
1822
+ }
1823
+ }, (err) => {
1824
+ if (!ctx.parent) {
1825
+ throw err;
1826
+ }
1827
+ return propagateError(ctx.parent, err);
1828
+ });
1829
+ }
1830
+ else {
1831
+ if (ctx.f & IsInForOfLoop) {
1832
+ unmountComponent(ctx);
1833
+ }
1834
+ else {
1835
+ returnComponent(ctx);
1836
+ }
1837
+ }
1838
+ }
1839
+ else if (ctx.f & IsAsyncGen) {
1840
+ if (ctx.f & IsInForOfLoop) {
1841
+ const value = enqueueComponentRun(ctx);
1842
+ value.then(() => {
1843
+ if (ctx.f & IsInForOfLoop) {
1844
+ unmountComponent(ctx);
1845
+ }
1846
+ else {
1847
+ returnComponent(ctx);
1848
+ }
1849
+ }, (err) => {
1850
+ if (!ctx.parent) {
1851
+ throw err;
1852
+ }
1853
+ return propagateError(ctx.parent, err);
1854
+ });
1855
+ }
1856
+ else {
1857
+ // The logic for unmounting async generator components is in the
1858
+ // runAsyncGenComponent function.
1859
+ resumePropsAsyncIterator(ctx);
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+ function returnComponent(ctx) {
1865
+ resumePropsAsyncIterator(ctx);
1866
+ if (ctx.iterator && typeof ctx.iterator.return === "function") {
1867
+ try {
1868
+ ctx.f |= IsSyncExecuting;
1869
+ const iteration = ctx.iterator.return();
1870
+ if (isPromiseLike(iteration)) {
1871
+ iteration.catch((err) => {
1872
+ if (!ctx.parent) {
1873
+ throw err;
1874
+ }
1875
+ return propagateError(ctx.parent, err);
1876
+ });
1877
+ }
1878
+ }
1879
+ finally {
1880
+ ctx.f &= ~IsSyncExecuting;
1881
+ }
1882
+ }
1883
+ }
1884
+ /*** EVENT TARGET UTILITIES ***/
1885
+ // EVENT PHASE CONSTANTS
1886
+ // https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
1887
+ const NONE = 0;
1888
+ const CAPTURING_PHASE = 1;
1889
+ const AT_TARGET = 2;
1890
+ const BUBBLING_PHASE = 3;
1891
+ const listenersMap = new WeakMap();
1892
+ function isListenerOrListenerObject(value) {
1893
+ return (typeof value === "function" ||
1894
+ (value !== null &&
1895
+ typeof value === "object" &&
1896
+ typeof value.handleEvent === "function"));
1897
+ }
1898
+ function normalizeListenerOptions(options) {
1899
+ if (typeof options === "boolean") {
1900
+ return { capture: options };
1901
+ }
1902
+ else if (options == null) {
1903
+ return {};
1904
+ }
1905
+ return options;
1906
+ }
1907
+ function isEventTarget(value) {
1908
+ return (value != null &&
1909
+ typeof value.addEventListener === "function" &&
1910
+ typeof value.removeEventListener === "function" &&
1911
+ typeof value.dispatchEvent === "function");
1912
+ }
1913
+ function setEventProperty(ev, key, value) {
1914
+ Object.defineProperty(ev, key, { value, writable: false, configurable: true });
1915
+ }
1916
+ // TODO: Maybe we can pass in the current context directly, rather than
1917
+ // starting from the parent?
1918
+ /**
1919
+ * A function to reconstruct an array of every listener given a context and a
1920
+ * host element.
1921
+ *
1922
+ * This function exploits the fact that contexts retain their nearest ancestor
1923
+ * host element. We can determine all the contexts which are directly listening
1924
+ * to an element by traversing up the context tree and checking that the host
1925
+ * element passed in matches the parent context’s host element.
1926
+ */
1927
+ function getListenerRecords(ctx, ret) {
1928
+ let listeners = [];
1929
+ while (ctx !== undefined && ctx.host === ret) {
1930
+ const listeners1 = listenersMap.get(ctx);
1931
+ if (listeners1) {
1932
+ listeners = listeners.concat(listeners1);
1933
+ }
1934
+ ctx = ctx.parent;
1935
+ }
1936
+ return listeners;
1937
+ }
1938
+ function clearEventListeners(ctx) {
1939
+ const listeners = listenersMap.get(ctx);
1940
+ if (listeners && listeners.length) {
1941
+ for (const value of getChildValues(ctx.ret)) {
1942
+ if (isEventTarget(value)) {
1943
+ for (const record of listeners) {
1944
+ value.removeEventListener(record.type, record.callback, record.options);
1945
+ }
1946
+ }
1947
+ }
1948
+ listeners.length = 0;
1949
+ }
1950
+ }
1951
+ /*** ERROR HANDLING UTILITIES ***/
1952
+ function handleChildError(ctx, err) {
1953
+ if (!ctx.iterator || typeof ctx.iterator.throw !== "function") {
1954
+ throw err;
1955
+ }
1956
+ resumePropsAsyncIterator(ctx);
1957
+ let iteration;
1958
+ try {
1959
+ ctx.f |= IsSyncExecuting;
1960
+ iteration = ctx.iterator.throw(err);
1961
+ }
1962
+ catch (err) {
1963
+ ctx.f |= IsErrored;
1964
+ throw err;
1965
+ }
1966
+ finally {
1967
+ ctx.f &= ~IsSyncExecuting;
1968
+ }
1969
+ if (isPromiseLike(iteration)) {
1970
+ return iteration.then((iteration) => {
1971
+ if (iteration.done) {
1972
+ ctx.f &= ~IsAsyncGen;
1973
+ ctx.iterator = undefined;
1974
+ }
1975
+ return updateComponentChildren(ctx, iteration.value);
1976
+ }, (err) => {
1977
+ ctx.f |= IsErrored;
1978
+ throw err;
1979
+ });
1980
+ }
1981
+ if (iteration.done) {
1982
+ ctx.f &= ~IsSyncGen;
1983
+ ctx.f &= ~IsAsyncGen;
1984
+ ctx.iterator = undefined;
1985
+ }
1986
+ return updateComponentChildren(ctx, iteration.value);
1987
+ }
1988
+ function propagateError(ctx, err) {
1989
+ let result;
1990
+ try {
1991
+ result = handleChildError(ctx, err);
1992
+ }
1993
+ catch (err) {
1994
+ if (!ctx.parent) {
1995
+ throw err;
1996
+ }
1997
+ return propagateError(ctx.parent, err);
1998
+ }
1999
+ if (isPromiseLike(result)) {
2000
+ return result.catch((err) => {
2001
+ if (!ctx.parent) {
2002
+ throw err;
2003
+ }
2004
+ return propagateError(ctx.parent, err);
2005
+ });
2006
+ }
2007
+ return result;
2008
+ }
2009
+ // Some JSX transpilation tools expect these functions to be defined on the
2010
+ // default export. Prefer named exports when importing directly.
1986
2011
  var crank = { createElement, Fragment };
1987
2012
 
1988
2013
  export { Context, Copy, Element, Fragment, Portal, Raw, Renderer, cloneElement, createElement, crank as default, isElement };