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