@b9g/crank 0.5.0-beta.4 → 0.5.0-beta.6

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