@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.4

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.
Files changed (105) hide show
  1. package/dist/action-context.d.ts +56 -0
  2. package/dist/action-context.js +73 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +550 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +417 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/cache-scope.d.ts +118 -0
  12. package/dist/cache-scope.js +311 -0
  13. package/dist/cache.d.ts +55 -0
  14. package/dist/cache.js +155 -0
  15. package/dist/cache.test.d.ts +1 -0
  16. package/dist/cache.test.js +217 -0
  17. package/dist/class-component.d.ts +66 -0
  18. package/dist/class-component.js +633 -0
  19. package/dist/class-component.test.d.ts +1 -0
  20. package/dist/class-component.test.js +411 -0
  21. package/dist/context.d.ts +13 -0
  22. package/dist/context.js +58 -32
  23. package/dist/context.test.d.ts +1 -0
  24. package/dist/context.test.js +57 -0
  25. package/dist/derived.test.d.ts +1 -0
  26. package/dist/derived.test.js +140 -0
  27. package/dist/discrete.test.d.ts +1 -0
  28. package/dist/discrete.test.js +100 -0
  29. package/dist/dom.d.ts +55 -0
  30. package/dist/dom.js +414 -63
  31. package/dist/effects.d.ts +88 -0
  32. package/dist/effects.js +790 -0
  33. package/dist/effects.test.d.ts +1 -0
  34. package/dist/effects.test.js +485 -0
  35. package/dist/events.d.ts +58 -0
  36. package/dist/events.js +503 -0
  37. package/dist/events.test.d.ts +1 -0
  38. package/dist/events.test.js +447 -0
  39. package/dist/index.d.ts +14 -4
  40. package/dist/index.js +9 -3
  41. package/dist/jsx-types.d.ts +2 -0
  42. package/dist/krate-hydrate-lite.js +7 -1
  43. package/dist/krate-hydrate.js +7 -1
  44. package/dist/krate-runtime.js +7 -1
  45. package/dist/krate-suspense.js +2 -0
  46. package/dist/lanes.test.d.ts +1 -0
  47. package/dist/lanes.test.js +59 -0
  48. package/dist/list.d.ts +20 -0
  49. package/dist/list.js +466 -0
  50. package/dist/list.test.d.ts +1 -0
  51. package/dist/list.test.js +344 -0
  52. package/dist/optimistic-lanes.test.d.ts +1 -0
  53. package/dist/optimistic-lanes.test.js +45 -0
  54. package/dist/portal.d.ts +47 -0
  55. package/dist/portal.js +189 -0
  56. package/dist/portal.test.d.ts +1 -0
  57. package/dist/portal.test.js +99 -0
  58. package/dist/react-effects.test.d.ts +1 -0
  59. package/dist/react-effects.test.js +96 -0
  60. package/dist/react-suspense.test.d.ts +1 -0
  61. package/dist/react-suspense.test.js +194 -0
  62. package/dist/react.d.ts +132 -32
  63. package/dist/react.js +335 -81
  64. package/dist/react.test.js +12 -2
  65. package/dist/reconcile.js +13 -0
  66. package/dist/refs.d.ts +33 -0
  67. package/dist/refs.js +142 -0
  68. package/dist/refs.test.d.ts +1 -0
  69. package/dist/refs.test.js +257 -0
  70. package/dist/request-context.d.ts +62 -0
  71. package/dist/request-context.js +107 -0
  72. package/dist/resource.js +20 -1
  73. package/dist/router-layout.test.d.ts +1 -0
  74. package/dist/router-layout.test.js +179 -0
  75. package/dist/router-lite.d.ts +25 -0
  76. package/dist/router-lite.js +73 -0
  77. package/dist/router-nav.test.d.ts +1 -0
  78. package/dist/router-nav.test.js +399 -0
  79. package/dist/router-slots.test.d.ts +1 -0
  80. package/dist/router-slots.test.js +144 -0
  81. package/dist/router.d.ts +66 -2
  82. package/dist/router.js +1535 -650
  83. package/dist/server-async.test.d.ts +1 -0
  84. package/dist/server-async.test.js +174 -0
  85. package/dist/server-renderer.js +494 -119
  86. package/dist/server.d.ts +27 -1
  87. package/dist/server.js +187 -1
  88. package/dist/server.test.js +20 -0
  89. package/dist/signal-lanes.test.d.ts +1 -0
  90. package/dist/signal-lanes.test.js +32 -0
  91. package/dist/signal.d.ts +186 -1
  92. package/dist/signal.js +896 -66
  93. package/dist/slots.d.ts +22 -0
  94. package/dist/slots.js +134 -0
  95. package/dist/slots.test.d.ts +1 -0
  96. package/dist/slots.test.js +169 -0
  97. package/dist/snapshots.test.d.ts +1 -0
  98. package/dist/snapshots.test.js +208 -0
  99. package/dist/suspense-actions.test.d.ts +1 -0
  100. package/dist/suspense-actions.test.js +72 -0
  101. package/dist/suspense.d.ts +220 -0
  102. package/dist/suspense.js +901 -0
  103. package/dist/suspense.test.d.ts +1 -0
  104. package/dist/suspense.test.js +518 -0
  105. package/package.json +5 -1
@@ -0,0 +1,790 @@
1
+ // React-style effect scheduling on top of signals.
2
+ //
3
+ // Krate components run once, so there is no render to hang effects on.
4
+ // Instead each lowered useEffect/useLayoutEffect/useInsertionEffect is a
5
+ // "hook effect": a tiny tracker effect re-reads the dependency thunk whenever a
6
+ // signal it reads changes and, when the dependency array differs (Object.is
7
+ // per element), marks the hook dirty. Dirty hooks run in a commit that follows
8
+ // the signal flush, after the DOM bindings have been updated:
9
+ //
10
+ // mutation per component (children before parents): insertion cleanup,
11
+ // insertion setup, layout cleanup
12
+ // layout layout setups, children before parents
13
+ // passive (a macrotask later, after paint) all passive cleanups, then all
14
+ // passive setups, children before parents
15
+ //
16
+ // A pending passive phase is always flushed before the next update is
17
+ // processed, as React does. Unmounting a component runs its cleanups parent before child:
18
+ // insertion and layout cleanups immediately, passive cleanups in the passive
19
+ // phase. Component boundaries come from owners: hydration scripts declare
20
+ // them with krateOwner and runtime-created components get one from h().
21
+ import { createEffect, krateGetOwner, krateSetOwner, krateOnAfterFlush, krateOnBeforeFlush, krateOnDispose, kratePendingFlush, runAfterFlush, untrack, krateCommitting, krateDisposeOwner, krateEpoch, kratePruneSnapshots, krateReadAt, krateTakeSyncLane, krateCurrentScope, krateTagOwner, krateScopeOfId, } from './signal.js';
22
+ const root = newOwner(null, null);
23
+ const byId = new Map();
24
+ // Last branch shown by each dynamic conditional slot, as reported by kbindCond.
25
+ const condShown = new Map();
26
+ // Content slots whose server-rendered content was replaced on the client.
27
+ const replacedSlots = new Set();
28
+ const dirty = new Set();
29
+ let seq = 0;
30
+ let commitQueued = false;
31
+ let passiveTimer = null;
32
+ // Passive work of the last commit, run in order by flushPassive.
33
+ let passiveCleanups = [];
34
+ let passiveSetups = [];
35
+ const records = [];
36
+ // Mounted hooks per snapshot epoch, so old snapshots can be pruned.
37
+ const liveEpochs = new Map();
38
+ const unmountHooks = [];
39
+ function newOwner(id, parent) {
40
+ // Components inherit the route scope of their parent component; top-level
41
+ // hydrated components take the scope their hydration code runs in.
42
+ const scope = parent && parent.parent !== null ? parent.scope : parent ? krateCurrentScope() : null;
43
+ const owner = { id, parent, children: [], hooks: [], disposed: false, shown: true, conds: [], slot: null, record: null, scope };
44
+ if (parent)
45
+ krateTagOwner(owner, scope);
46
+ return owner;
47
+ }
48
+ /**
49
+ * Registers fn to run whenever a component owner unmounts (parent first),
50
+ * after its effect cleanups and before its bindings are disposed. Lets other
51
+ * lowerings (class component lifecycles) observe unmount and remount.
52
+ */
53
+ export function krateOnUnmount(fn) {
54
+ unmountHooks.push(fn);
55
+ }
56
+ /** The id of a component owner (null for runtime-created components). */
57
+ export function krateOwnerId(owner) {
58
+ return ownerOf(owner).id;
59
+ }
60
+ function ownerOf(value) {
61
+ return value && typeof value === 'object' && 'hooks' in value ? value : root;
62
+ }
63
+ function isActive(owner) {
64
+ for (let o = owner; o; o = o.parent) {
65
+ if (o.disposed || !o.shown)
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+ function condVisible(owner) {
71
+ for (const [id, branch] of owner.conds) {
72
+ const shown = condShown.get(id);
73
+ if (shown !== undefined && shown !== branch)
74
+ return false;
75
+ }
76
+ return true;
77
+ }
78
+ /**
79
+ * Starts a hydrated component scope (emitted at the top of each component's
80
+ * hydration script). `parentId` names the enclosing component, `conds` the
81
+ * conditional branches `[slotId, "c" | "a", initiallyShown]` it renders
82
+ * inside, and `slot` the content slot (list) whose client-side replacement
83
+ * unmounts it. `krateOwner(null)` ends hydration scopes.
84
+ */
85
+ export function krateOwner(id, parentId, conds, slot) {
86
+ if (id == null) {
87
+ krateSetOwner(null);
88
+ return;
89
+ }
90
+ let owner = byId.get(id);
91
+ if (!owner) {
92
+ const parent = (parentId != null && byId.get(parentId)) || root;
93
+ owner = newOwner(id, parent);
94
+ // A component inside an unmounted one is unmounted too.
95
+ for (let o = parent; o; o = o.parent) {
96
+ if (o.disposed)
97
+ owner.disposed = true;
98
+ }
99
+ parent.children.push(owner);
100
+ byId.set(id, owner);
101
+ for (const [cid, branch, initially] of conds || []) {
102
+ owner.conds.push([cid, branch]);
103
+ if (!condShown.has(cid)) {
104
+ // No binding reported this conditional yet: trust the server markup.
105
+ condShown.set(cid, initially ? branch : branch === 'c' ? 'a' : 'c');
106
+ }
107
+ }
108
+ owner.shown = condVisible(owner);
109
+ if (slot) {
110
+ owner.slot = slot;
111
+ // The list was already re-rendered by its binding: this server-rendered
112
+ // instance no longer exists, so its effects must never run.
113
+ if (replacedSlots.has(slot))
114
+ owner.disposed = true;
115
+ }
116
+ }
117
+ krateSetOwner(owner);
118
+ }
119
+ /** Runs fn as the body of a new child component of the current owner. */
120
+ export function krateWithOwner(fn) {
121
+ const parent = ownerOf(krateGetOwner());
122
+ const owner = newOwner(null, parent);
123
+ parent.children.push(owner);
124
+ const prev = krateSetOwner(owner);
125
+ try {
126
+ return { value: fn(), owner };
127
+ }
128
+ finally {
129
+ krateSetOwner(prev);
130
+ }
131
+ }
132
+ /**
133
+ * Unmounts a component created by krateWithOwner/krateOwner: cleanups run
134
+ * parent before child (insertion and layout now, passive in the passive
135
+ * phase) and its hooks never run again.
136
+ */
137
+ export function krateUnmount(value) {
138
+ const owner = ownerOf(value);
139
+ if (owner === root || owner.disposed)
140
+ return;
141
+ const wasActive = isActive(owner);
142
+ const passive = [];
143
+ disposeTree(owner, wasActive, passive);
144
+ if (owner.parent) {
145
+ const list = owner.parent.children;
146
+ const i = list.indexOf(owner);
147
+ if (i >= 0)
148
+ list.splice(i, 1);
149
+ }
150
+ if (passive.length) {
151
+ passiveCleanups.push(...passive);
152
+ schedulePassive();
153
+ }
154
+ }
155
+ function disposeTree(owner, active, passive) {
156
+ // Disposed owners stay in byId so hydration scopes declared later inside
157
+ // them resolve their (unmounted) parent instead of the root.
158
+ owner.disposed = true;
159
+ for (const hook of owner.hooks) {
160
+ hook.stop();
161
+ dirty.delete(hook);
162
+ if (!active) {
163
+ // Hidden, so its cleanup already ran (or never will): just release it.
164
+ if (hook.mounted) {
165
+ hook.mounted = false;
166
+ hook.cleanup = null;
167
+ releaseEpoch(hook.epoch);
168
+ }
169
+ continue;
170
+ }
171
+ if (hook.phase === 'passive') {
172
+ const c = takeCleanup(hook);
173
+ if (c)
174
+ passive.push(c);
175
+ }
176
+ else {
177
+ runCleanup(hook);
178
+ }
179
+ }
180
+ for (const fn of unmountHooks)
181
+ fn(owner, owner.id);
182
+ // Bindings, refs and top-level cleanups of the component go with it.
183
+ krateDisposeOwner(owner);
184
+ if (owner.record && owner.record.owner === owner)
185
+ owner.record.owner = null;
186
+ for (const child of owner.children.slice()) {
187
+ disposeTree(child, active && child.shown, passive);
188
+ }
189
+ }
190
+ /**
191
+ * Unmounts the hydrated component `id` and forgets it, so running its
192
+ * hydration scope again (a remount by the class/boundary owner tree in
193
+ * boundary.ts) creates a fresh owner whose effects mount again.
194
+ */
195
+ export function krateForgetOwner(id) {
196
+ const owner = byId.get(id);
197
+ if (!owner)
198
+ return;
199
+ krateUnmount(owner);
200
+ byId.delete(id);
201
+ }
202
+ /**
203
+ * Declares a remountable hydrated component (emitted for components inside
204
+ * a conditional branch). `fn` is the component's hydration scope; it runs now
205
+ * when the branch is shown, and again, as a fresh instance, every time the
206
+ * branch is shown after being hidden. Hiding the branch unmounts it:
207
+ * cleanups run, refs and bindings are released and its state is discarded.
208
+ */
209
+ export function krateMount(id, parentId, conds, slot, fn) {
210
+ const rec = { id, parentId, conds: [], slot: slot || null, fn, owner: null };
211
+ for (const [cid, branch, initially] of conds || []) {
212
+ rec.conds.push([cid, branch]);
213
+ if (!condShown.has(cid)) {
214
+ condShown.set(cid, initially ? branch : branch === 'c' ? 'a' : 'c');
215
+ }
216
+ }
217
+ records.push(rec);
218
+ if (recordVisible(rec))
219
+ mountRecord(rec);
220
+ }
221
+ function recordParent(rec) {
222
+ if (rec.parentId == null)
223
+ return root;
224
+ const p = byId.get(rec.parentId);
225
+ if (!p)
226
+ return root;
227
+ for (let o = p; o; o = o.parent) {
228
+ if (o.disposed)
229
+ return null;
230
+ }
231
+ return p;
232
+ }
233
+ function recordVisible(rec) {
234
+ if (rec.slot && replacedSlots.has(rec.slot))
235
+ return false;
236
+ for (const [cid, branch] of rec.conds) {
237
+ const shown = condShown.get(cid);
238
+ if (shown !== undefined && shown !== branch)
239
+ return false;
240
+ }
241
+ return recordParent(rec) !== null;
242
+ }
243
+ function mountRecord(rec) {
244
+ const parent = recordParent(rec) || root;
245
+ const owner = newOwner(rec.id, parent);
246
+ owner.record = rec;
247
+ owner.slot = rec.slot;
248
+ parent.children.push(owner);
249
+ byId.set(rec.id, owner);
250
+ rec.owner = owner;
251
+ const prev = krateSetOwner(owner);
252
+ try {
253
+ // The scope may run inside a binding (a conditional swap); its reads must
254
+ // not subscribe that binding.
255
+ untrack(rec.fn);
256
+ }
257
+ finally {
258
+ krateSetOwner(prev);
259
+ }
260
+ }
261
+ /**
262
+ * Reports that the hydrated content of slot `id` was replaced by its binding
263
+ * (a list re-render): hydrated components inside it are unmounted.
264
+ */
265
+ export function krateSlotReplaced(id) {
266
+ if (replacedSlots.has(id))
267
+ return;
268
+ replacedSlots.add(id);
269
+ for (const owner of Array.from(byId.values())) {
270
+ if (owner.slot === id)
271
+ krateUnmount(owner);
272
+ }
273
+ }
274
+ /**
275
+ * Reports which branch ("c" consequent, "a" alternate) conditional slot `id`
276
+ * shows. Components in the hidden branch keep their state but have their
277
+ * effects cleaned up (React's Activity semantics); showing the branch again
278
+ * re-runs every effect setup in the next commit.
279
+ */
280
+ export function krateCondActivity(id, branch) {
281
+ if (condShown.get(id) === branch)
282
+ return;
283
+ condShown.set(id, branch);
284
+ // Remountable components: unmount the ones that left (parents first), then
285
+ // mount fresh instances of the ones that entered (parents first).
286
+ for (const rec of records) {
287
+ if (rec.owner && !rec.owner.disposed && !recordVisible(rec))
288
+ krateUnmount(rec.owner);
289
+ }
290
+ for (const rec of records) {
291
+ if (!rec.owner && recordVisible(rec))
292
+ mountRecord(rec);
293
+ }
294
+ const affected = [];
295
+ for (const owner of byId.values()) {
296
+ if (!owner.record && owner.conds.some(([cid]) => cid === id))
297
+ affected.push(owner);
298
+ }
299
+ let passive = [];
300
+ for (const owner of affected) {
301
+ const visible = condVisible(owner);
302
+ if (visible === owner.shown)
303
+ continue;
304
+ const before = isActive(owner);
305
+ owner.shown = visible;
306
+ const after = isActive(owner);
307
+ if (before && !after)
308
+ hideTree(owner, passive);
309
+ else if (!before && after)
310
+ showTree(owner);
311
+ }
312
+ if (passive.length) {
313
+ passiveCleanups.push(...passive);
314
+ passive = [];
315
+ schedulePassive();
316
+ }
317
+ scheduleCommit();
318
+ }
319
+ function hideTree(owner, passive) {
320
+ for (const hook of owner.hooks) {
321
+ dirty.delete(hook);
322
+ if (hook.phase === 'passive') {
323
+ const c = takeCleanup(hook);
324
+ if (c)
325
+ passive.push(c);
326
+ }
327
+ else {
328
+ runCleanup(hook);
329
+ }
330
+ }
331
+ for (const child of owner.children) {
332
+ if (child.shown && !child.disposed)
333
+ hideTree(child, passive);
334
+ }
335
+ }
336
+ function showTree(owner) {
337
+ for (const hook of owner.hooks) {
338
+ markDirty(hook);
339
+ }
340
+ for (const child of owner.children) {
341
+ if (child.shown && !child.disposed)
342
+ showTree(child);
343
+ }
344
+ }
345
+ function depsEqual(a, b) {
346
+ if (!a || !b || a.length !== b.length)
347
+ return false;
348
+ for (let i = 0; i < a.length; i++) {
349
+ if (!Object.is(a[i], b[i]))
350
+ return false;
351
+ }
352
+ return true;
353
+ }
354
+ function toDeps(value) {
355
+ if (value == null)
356
+ return undefined;
357
+ return Array.isArray(value) ? value : Array.from(value);
358
+ }
359
+ function markDirty(hook) {
360
+ hook.dirty = true;
361
+ dirty.add(hook);
362
+ scheduleCommit();
363
+ }
364
+ function scheduleCommit() {
365
+ if (commitQueued)
366
+ return;
367
+ commitQueued = true;
368
+ queueMicrotask(() => {
369
+ // A pending signal flush runs the commit itself once it settles.
370
+ if (!kratePendingFlush()) {
371
+ flushPassive();
372
+ runAfterFlush();
373
+ }
374
+ });
375
+ }
376
+ /**
377
+ * Registers a React effect. `deps` returns the dependency array (read inside
378
+ * a tracking scope, so signal getters it calls are subscribed); the effect
379
+ * re-runs in the next commit when any element changed by Object.is. A null
380
+ * thunk means "no dependency array" and the effect runs only on mount here;
381
+ * the compiler synthesizes the component's state and props as dependencies
382
+ * for that case instead. `fn` may return a cleanup function.
383
+ */
384
+ export function createEffectDeps(fn, deps, phase = 'passive') {
385
+ const owner = ownerOf(krateGetOwner());
386
+ const hook = {
387
+ owner,
388
+ phase,
389
+ fn,
390
+ deps: deps || null,
391
+ prev: undefined,
392
+ hasPrev: false,
393
+ cleanup: null,
394
+ mounted: false,
395
+ epoch: 0,
396
+ dirty: false,
397
+ seq: seq++,
398
+ stop: () => { },
399
+ scope: owner === root ? krateCurrentScope() : owner.scope,
400
+ };
401
+ owner.hooks.push(hook);
402
+ if (owner.disposed)
403
+ return;
404
+ hook.stop = createEffect(() => {
405
+ const next = hook.deps ? toDeps(hook.deps()) : [];
406
+ if (hook.hasPrev && depsEqual(hook.prev, next))
407
+ return;
408
+ hook.prev = next;
409
+ hook.hasPrev = true;
410
+ if (isActive(hook.owner))
411
+ markDirty(hook);
412
+ });
413
+ }
414
+ function runSetup(hook, at) {
415
+ if (hook.owner.disposed)
416
+ return;
417
+ let ret;
418
+ try {
419
+ // The setup sees the state of the commit it belongs to.
420
+ ret = krateReadAt(at, () => untrack(hook.fn));
421
+ }
422
+ catch (err) {
423
+ reportHookError(err, hook.owner);
424
+ return;
425
+ }
426
+ hook.cleanup = typeof ret === 'function' ? ret : null;
427
+ hook.mounted = true;
428
+ hook.epoch = at;
429
+ liveEpochs.set(at, (liveEpochs.get(at) || 0) + 1);
430
+ }
431
+ // Error boundaries (boundary.ts) receive errors thrown by effect setups and
432
+ // cleanups, as React's do. Without a handler the error is rethrown.
433
+ let hookErrorHandler = null;
434
+ /** Installs the handler for errors thrown by hook effects (internal). */
435
+ export function krateOnHookError(fn) {
436
+ hookErrorHandler = fn;
437
+ }
438
+ function reportHookError(err, owner) {
439
+ let id = null;
440
+ for (let o = owner; o && id === null; o = o.parent)
441
+ id = o.id;
442
+ if (!(hookErrorHandler && hookErrorHandler(err, id)))
443
+ throw err;
444
+ }
445
+ function runGuarded(fn, owner) {
446
+ try {
447
+ untrack(fn);
448
+ }
449
+ catch (err) {
450
+ reportHookError(err, owner);
451
+ }
452
+ }
453
+ // Detaches the cleanup of the last setup, bound to that setup's snapshot so
454
+ // it reads the values of the render it belongs to (React closure semantics).
455
+ function takeCleanup(hook) {
456
+ if (!hook.mounted)
457
+ return null;
458
+ hook.mounted = false;
459
+ const at = hook.epoch;
460
+ const c = hook.cleanup;
461
+ hook.cleanup = null;
462
+ if (!c) {
463
+ releaseEpoch(at);
464
+ return null;
465
+ }
466
+ // The snapshot stays live until the (possibly deferred) cleanup ran.
467
+ return () => {
468
+ try {
469
+ krateReadAt(at, () => untrack(c));
470
+ }
471
+ finally {
472
+ releaseEpoch(at);
473
+ }
474
+ };
475
+ }
476
+ function releaseEpoch(at) {
477
+ const n = (liveEpochs.get(at) || 1) - 1;
478
+ if (n > 0)
479
+ liveEpochs.set(at, n);
480
+ else
481
+ liveEpochs.delete(at);
482
+ }
483
+ function runCleanup(hook) {
484
+ const c = takeCleanup(hook);
485
+ if (c)
486
+ runGuarded(c, hook.owner);
487
+ }
488
+ function pruneSnapshots() {
489
+ let min = krateEpoch();
490
+ for (const e of liveEpochs.keys())
491
+ if (e < min)
492
+ min = e;
493
+ kratePruneSnapshots(min);
494
+ }
495
+ // Orders hooks children-before-parents (post-order over the owner tree),
496
+ // declaration order within a component.
497
+ function orderHooks(hooks) {
498
+ const rank = new Map();
499
+ let n = 0;
500
+ const visit = (o) => {
501
+ for (const c of o.children)
502
+ visit(c);
503
+ rank.set(o, n++);
504
+ };
505
+ for (const c of root.children)
506
+ visit(c);
507
+ rank.set(root, n++);
508
+ return Array.from(hooks).sort((a, b) => {
509
+ const ra = rank.get(a.owner) ?? n;
510
+ const rb = rank.get(b.owner) ?? n;
511
+ return ra !== rb ? ra - rb : a.seq - b.seq;
512
+ });
513
+ }
514
+ // Callbacks run in every commit's layout phase, after layout effects and
515
+ // before passive ones (class component lifecycles, see class-component.ts).
516
+ const layoutHooks = [];
517
+ /** Registers fn to run in the layout phase of every commit (internal). */
518
+ export function krateOnLayoutCommit(fn) {
519
+ layoutHooks.push(fn);
520
+ }
521
+ function runLayoutHooks() {
522
+ for (const fn of layoutHooks)
523
+ fn();
524
+ }
525
+ function commit() {
526
+ commitQueued = false;
527
+ // runAfterFlush recorded the React state this commit rendered.
528
+ const at = krateEpoch();
529
+ const sync = krateTakeSyncLane();
530
+ if (dirty.size === 0) {
531
+ runLayoutHooks();
532
+ if (sync)
533
+ flushPassive();
534
+ pruneSnapshots();
535
+ return;
536
+ }
537
+ const hooks = orderHooks(dirty).filter((h) => isActive(h.owner));
538
+ dirty.clear();
539
+ for (const h of hooks)
540
+ h.dirty = false;
541
+ krateCommitting(true);
542
+ try {
543
+ // Mutation phase, per component in order: insertion cleanup + setup,
544
+ // then layout cleanup.
545
+ let i = 0;
546
+ while (i < hooks.length) {
547
+ const owner = hooks[i].owner;
548
+ let j = i;
549
+ while (j < hooks.length && hooks[j].owner === owner)
550
+ j++;
551
+ for (let k = i; k < j; k++) {
552
+ if (hooks[k].phase === 'insertion') {
553
+ runCleanup(hooks[k]);
554
+ runSetup(hooks[k], at);
555
+ }
556
+ }
557
+ for (let k = i; k < j; k++) {
558
+ if (hooks[k].phase === 'layout')
559
+ runCleanup(hooks[k]);
560
+ }
561
+ i = j;
562
+ }
563
+ // Layout phase.
564
+ for (const h of hooks) {
565
+ if (h.phase === 'layout')
566
+ runSetup(h, at);
567
+ }
568
+ runLayoutHooks();
569
+ // Passive phase, after paint.
570
+ let queued = false;
571
+ for (const h of hooks) {
572
+ if (h.phase !== 'passive')
573
+ continue;
574
+ const c = takeCleanup(h);
575
+ if (c)
576
+ passiveCleanups.push(c);
577
+ passiveSetups.push([h, at]);
578
+ queued = true;
579
+ }
580
+ if (queued)
581
+ schedulePassive();
582
+ // A discrete event's update runs its passive effects before the event
583
+ // returns (React's SyncLane), ahead of microtasks the handler queued.
584
+ if (sync)
585
+ flushPassive();
586
+ }
587
+ finally {
588
+ krateCommitting(false);
589
+ }
590
+ pruneSnapshots();
591
+ }
592
+ function schedulePassive() {
593
+ if (passiveTimer !== null)
594
+ return;
595
+ passiveTimer = setTimeout(flushPassive, 0);
596
+ }
597
+ /** Runs pending passive effect cleanups and setups now. */
598
+ export function flushPassive() {
599
+ if (passiveTimer !== null) {
600
+ clearTimeout(passiveTimer);
601
+ passiveTimer = null;
602
+ }
603
+ // Loop: a passive cleanup or setup may unmount components, queueing more.
604
+ while (passiveCleanups.length || passiveSetups.length) {
605
+ const cleanups = passiveCleanups;
606
+ const setups = passiveSetups;
607
+ passiveCleanups = [];
608
+ passiveSetups = [];
609
+ krateCommitting(true);
610
+ try {
611
+ for (const c of cleanups)
612
+ c();
613
+ for (const [h, at] of setups) {
614
+ if (isActive(h.owner))
615
+ runSetup(h, at);
616
+ }
617
+ }
618
+ finally {
619
+ krateCommitting(false);
620
+ }
621
+ }
622
+ }
623
+ /**
624
+ * React's useMemo with a dependency array: the getter recomputes
625
+ * synchronously, on read, when the dependency array changed (Object.is), so
626
+ * the value is current within the same update. Signals read by `fn` are not
627
+ * tracked; only the dependencies are.
628
+ */
629
+ export function createMemoDeps(fn, deps) {
630
+ let prev;
631
+ let has = false;
632
+ let value;
633
+ return () => {
634
+ const next = toDeps(deps()) || [];
635
+ if (!has || !depsEqual(prev, next)) {
636
+ prev = next;
637
+ has = true;
638
+ value = untrack(fn);
639
+ }
640
+ return value;
641
+ };
642
+ }
643
+ /**
644
+ * React's useCallback with a dependency array: a getter for the callback
645
+ * whose identity only changes when the dependency array changes.
646
+ */
647
+ export function createCallbackDeps(fn, deps) {
648
+ // The source closure is created once, so a new identity per dependency
649
+ // change is modelled by a fresh forwarding wrapper.
650
+ let first = true;
651
+ return createMemoDeps(() => {
652
+ if (first) {
653
+ first = false;
654
+ return fn;
655
+ }
656
+ const base = fn;
657
+ return function (...args) {
658
+ return base.apply(this, args);
659
+ };
660
+ }, deps);
661
+ }
662
+ /**
663
+ * Dependency values of a component parameter: every own property of a props
664
+ * object (read live, so prop getters subscribe) except children, or the
665
+ * value itself for anything else (a custom hook argument).
666
+ */
667
+ export function krateDepsOf(value) {
668
+ if (value && typeof value === 'object') {
669
+ const proto = Object.getPrototypeOf(value);
670
+ if (proto === Object.prototype || proto === null) {
671
+ const out = [];
672
+ for (const k of Object.keys(value)) {
673
+ if (k !== 'children')
674
+ out.push(value[k]);
675
+ }
676
+ return out;
677
+ }
678
+ }
679
+ return [value];
680
+ }
681
+ // Partial teardown (soft navigation keeping layouts mounted): unmount every
682
+ // component of a torn-down route scope and forget its slot state.
683
+ function unmountExcept(gone) {
684
+ const passive = [];
685
+ for (const child of root.children.slice()) {
686
+ if (!gone(child.scope))
687
+ continue;
688
+ disposeTree(child, child.shown, passive);
689
+ const i = root.children.indexOf(child);
690
+ if (i >= 0)
691
+ root.children.splice(i, 1);
692
+ }
693
+ const keptHooks = [];
694
+ for (const hook of root.hooks) {
695
+ if (!gone(hook.scope)) {
696
+ keptHooks.push(hook);
697
+ continue;
698
+ }
699
+ hook.stop();
700
+ dirty.delete(hook);
701
+ if (hook.phase === 'passive') {
702
+ const c = takeCleanup(hook);
703
+ if (c)
704
+ passive.push(c);
705
+ }
706
+ else {
707
+ runCleanup(hook);
708
+ }
709
+ }
710
+ root.hooks = keptHooks;
711
+ for (const [id, owner] of Array.from(byId)) {
712
+ if (owner.disposed || gone(owner.scope))
713
+ byId.delete(id);
714
+ }
715
+ // Slot ids of a layout start with its scope id (the layout's ID prefix).
716
+ const keptId = (id) => !gone(krateScopeOfId(id));
717
+ for (const id of Array.from(condShown.keys()))
718
+ if (!keptId(id))
719
+ condShown.delete(id);
720
+ for (const id of Array.from(replacedSlots))
721
+ if (!keptId(id))
722
+ replacedSlots.delete(id);
723
+ for (let i = records.length - 1; i >= 0; i--) {
724
+ if (!keptId(records[i].id))
725
+ records.splice(i, 1);
726
+ }
727
+ for (const hook of Array.from(dirty))
728
+ if (hook.owner.disposed)
729
+ dirty.delete(hook);
730
+ passiveSetups = passiveSetups.filter(([h]) => !h.owner.disposed && !(h.owner === root && gone(h.scope)));
731
+ for (const c of passive) {
732
+ try {
733
+ untrack(c);
734
+ }
735
+ catch {
736
+ // Keep tearing down.
737
+ }
738
+ }
739
+ krateSetOwner(null);
740
+ }
741
+ function unmountAll(gone) {
742
+ if (gone) {
743
+ unmountExcept(gone);
744
+ return;
745
+ }
746
+ // Page teardown: everything unmounts now, layout before passive.
747
+ const passive = [];
748
+ for (const child of root.children.slice()) {
749
+ disposeTree(child, child.shown, passive);
750
+ }
751
+ for (const hook of root.hooks) {
752
+ hook.stop();
753
+ if (hook.phase === 'passive') {
754
+ const c = takeCleanup(hook);
755
+ if (c)
756
+ passive.push(c);
757
+ }
758
+ else {
759
+ runCleanup(hook);
760
+ }
761
+ }
762
+ root.children.length = 0;
763
+ root.hooks.length = 0;
764
+ byId.clear();
765
+ condShown.clear();
766
+ replacedSlots.clear();
767
+ dirty.clear();
768
+ passiveSetups = [];
769
+ const pendingCleanups = passiveCleanups.concat(passive);
770
+ passiveCleanups = [];
771
+ if (passiveTimer !== null) {
772
+ clearTimeout(passiveTimer);
773
+ passiveTimer = null;
774
+ }
775
+ for (const c of pendingCleanups) {
776
+ try {
777
+ untrack(c);
778
+ }
779
+ catch {
780
+ // Keep tearing down.
781
+ }
782
+ }
783
+ commitQueued = false;
784
+ krateSetOwner(null);
785
+ }
786
+ // React flushes the previous commit's passive effects before a new update
787
+ // is processed, so the flush that starts an update runs them first.
788
+ krateOnBeforeFlush(flushPassive);
789
+ krateOnAfterFlush(commit);
790
+ krateOnDispose(unmountAll);