@b9g/crank 0.6.1 → 0.7.0

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