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