@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
package/dist/list.js ADDED
@@ -0,0 +1,466 @@
1
+ /**
2
+ * Keyed list reconciliation for compiled `.map()` lists.
3
+ *
4
+ * Each list item is a "row": a pair of comment markers around the nodes the
5
+ * map callback rendered, plus an ownership root that holds the row's effects
6
+ * and cleanups. When the source array changes, rows are matched by key (the
7
+ * `key` prop of the element the callback returns, compared as a string like
8
+ * React; items without a key use their index). Matching rows keep their DOM
9
+ * nodes, component state, effects and refs; only rows whose key disappeared
10
+ * are disposed, only new keys render, and rows are moved with the minimum
11
+ * number of DOM moves (rows on the longest increasing subsequence of old
12
+ * positions stay put).
13
+ *
14
+ * In accessor mode the callback receives `item()` / `index()` getters backed
15
+ * by per-row signals, so a new item object for an existing key updates the
16
+ * row in place and the index updates after a move. In value mode (callbacks
17
+ * the compiler cannot rewrite, such as `.map(renderRow)` or destructured
18
+ * parameters) the callback receives plain values and a row whose item changed
19
+ * is re-rendered.
20
+ *
21
+ * On hydration the server-rendered rows (`<!--k:ID:KEY-->...<!--/k:ID:KEY-->`)
22
+ * are adopted by key: the callback runs in virtual-node mode and its output is
23
+ * bound to the existing DOM instead of replacing it.
24
+ */
25
+ import { createEffect, createRoot, createSignal, onCleanup, untrack } from './signal.js';
26
+ import { krateUnmount, krateWithOwner } from './effects.js';
27
+ import { adoptValue, appendChild, disposeNode, insertAt, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
28
+ /** Canonical key: explicit keys are `$` + String(key); implicit keys are the index. */
29
+ function keyOf(keyFn, item, i) {
30
+ if (!keyFn)
31
+ return String(i);
32
+ const k = keyFn(item, i);
33
+ return k == null ? String(i) : '$' + String(k);
34
+ }
35
+ function decodeKey(s) {
36
+ try {
37
+ return decodeURIComponent(s);
38
+ }
39
+ catch {
40
+ return s;
41
+ }
42
+ }
43
+ function warnDuplicates(dups) {
44
+ const shown = dups.map((k) => (k.charAt(0) === '$' ? k.slice(1) : k));
45
+ console.error('Encountered two children with the same key, `' +
46
+ shown.join('`, `') +
47
+ '`. Keys should be unique so that components maintain their identity across updates. ' +
48
+ 'Krate keeps the first occurrence on its existing row and renders each duplicate as its own row.');
49
+ }
50
+ function newRowMarkers() {
51
+ return [document.createComment(''), document.createComment('')];
52
+ }
53
+ // Run the row's render inside its own ownership root and register the root's
54
+ // disposer on the start marker, so disposeNode(start) unmounts the row.
55
+ function renderInRoot(state, row, item, i, body) {
56
+ createRoot((dispose) => {
57
+ trackEffect(row.start, dispose);
58
+ // The row is an effect owner: components it renders are its children, so
59
+ // removing the row unmounts them (React effect cleanups) in one call.
60
+ const { value, owner } = krateWithOwner(() => {
61
+ if (!state.accessor)
62
+ return state.render(item, i);
63
+ const [getItem, setItem] = createSignal(item);
64
+ const [getIndex, setIndex] = createSignal(i);
65
+ row.setItem = setItem;
66
+ row.setIndex = setIndex;
67
+ return state.render(getItem, getIndex);
68
+ });
69
+ onCleanup(() => krateUnmount(owner));
70
+ body(value);
71
+ });
72
+ }
73
+ function createRow(state, key, item, i) {
74
+ const [start, end] = newRowMarkers();
75
+ const row = { key, item, index: i, start, end, setItem: null, setIndex: null, live: true };
76
+ const frag = document.createDocumentFragment();
77
+ frag.appendChild(start);
78
+ withDOM(() => renderInRoot(state, row, item, i, (v) => appendChild(frag, v)));
79
+ frag.appendChild(end);
80
+ frag.__row = row;
81
+ return frag;
82
+ }
83
+ // Adopt a server-rendered row: render in virtual-node mode and bind the result
84
+ // to the nodes between its markers. If adoption throws (a component that
85
+ // manipulates its own output imperatively, for example), the row is rendered
86
+ // fresh in place.
87
+ function adoptRow(state, row, item, i) {
88
+ row.item = item;
89
+ row.index = i;
90
+ row.live = true;
91
+ const parent = row.start.parentNode;
92
+ try {
93
+ withVNodes(() => renderInRoot(state, row, item, i, (v) => {
94
+ const c = { parent, next: row.start.nextSibling };
95
+ withDOM(() => adoptValue(v, c));
96
+ removeRest(c, row.end);
97
+ }));
98
+ }
99
+ catch (err) {
100
+ console.error(err);
101
+ disposeRange(row.start, row.end, false);
102
+ disposeNode(row.start);
103
+ const frag = createRow(state, row.key, item, i);
104
+ const fresh = frag.__row;
105
+ parent.insertBefore(frag, row.start);
106
+ parent.removeChild(row.start);
107
+ parent.removeChild(row.end);
108
+ Object.assign(row, fresh);
109
+ }
110
+ }
111
+ /** Dispose and remove the nodes between start and end (and the markers when `markers`). */
112
+ function disposeRange(start, end, markers) {
113
+ const parent = start.parentNode;
114
+ if (!parent)
115
+ return;
116
+ let n = start.nextSibling;
117
+ while (n && n !== end) {
118
+ const next = n.nextSibling;
119
+ disposeNode(n);
120
+ parent.removeChild(n);
121
+ n = next;
122
+ }
123
+ if (markers) {
124
+ disposeNode(start);
125
+ parent.removeChild(start);
126
+ if (end.parentNode === parent)
127
+ parent.removeChild(end);
128
+ }
129
+ }
130
+ function removeRow(row) {
131
+ disposeRange(row.start, row.end, true);
132
+ }
133
+ /** Move a row's nodes (markers included) before `ref`. */
134
+ function moveRow(row, ref) {
135
+ const parent = ref.parentNode;
136
+ if (row.end.nextSibling === ref)
137
+ return;
138
+ let n = row.start;
139
+ while (n) {
140
+ const next = n === row.end ? null : n.nextSibling;
141
+ parent.insertBefore(n, ref);
142
+ n = next;
143
+ }
144
+ }
145
+ /**
146
+ * Indices (into `seq`) of a longest strictly increasing subsequence of the
147
+ * non-negative entries. O(n log n).
148
+ */
149
+ export function longestIncreasingSubsequence(seq) {
150
+ const n = seq.length;
151
+ const prev = new Int32Array(n);
152
+ const tails = [];
153
+ for (let i = 0; i < n; i++) {
154
+ const v = seq[i];
155
+ if (v < 0)
156
+ continue;
157
+ let lo = 0;
158
+ let hi = tails.length;
159
+ while (lo < hi) {
160
+ const mid = (lo + hi) >> 1;
161
+ if (seq[tails[mid]] < v)
162
+ lo = mid + 1;
163
+ else
164
+ hi = mid;
165
+ }
166
+ prev[i] = lo > 0 ? tails[lo - 1] : -1;
167
+ tails[lo] = i;
168
+ }
169
+ const out = new Array(tails.length);
170
+ let k = tails.length ? tails[tails.length - 1] : -1;
171
+ for (let j = tails.length - 1; j >= 0; j--) {
172
+ out[j] = k;
173
+ k = prev[k];
174
+ }
175
+ return out;
176
+ }
177
+ function toArray(raw) {
178
+ if (raw == null)
179
+ return [];
180
+ if (Array.isArray(raw))
181
+ return raw;
182
+ if (typeof raw[Symbol.iterator] === 'function') {
183
+ return Array.from(raw);
184
+ }
185
+ return [];
186
+ }
187
+ // Focus and selection survive row moves: a browser blurs an element that is
188
+ // detached even momentarily, so the active element is restored after the
189
+ // update when it is still in the document (React does the same on commit).
190
+ function captureFocus(scope) {
191
+ if (typeof document === 'undefined')
192
+ return null;
193
+ const active = document.activeElement;
194
+ if (!active || active === document.body || !scope || !scope.contains(active))
195
+ return null;
196
+ let sel = null;
197
+ try {
198
+ const input = active;
199
+ if (typeof input.selectionStart === 'number') {
200
+ sel = [input.selectionStart, input.selectionEnd, input.selectionDirection];
201
+ }
202
+ }
203
+ catch {
204
+ sel = null;
205
+ }
206
+ return () => {
207
+ if (document.activeElement === active || !active.isConnected)
208
+ return;
209
+ active.focus({ preventScroll: true });
210
+ if (sel) {
211
+ try {
212
+ active.setSelectionRange(sel[0], sel[1], (sel[2] || undefined));
213
+ }
214
+ catch {
215
+ // Not every input type supports selection ranges.
216
+ }
217
+ }
218
+ };
219
+ }
220
+ function update(state, items) {
221
+ const { end, keyFn } = state;
222
+ const parent = end.parentNode;
223
+ const oldRows = state.rows;
224
+ const n = items.length;
225
+ // Keys, with duplicates made unique: the first occurrence keeps the key.
226
+ const keys = new Array(n);
227
+ const seen = new Map();
228
+ let dups = null;
229
+ for (let i = 0; i < n; i++) {
230
+ let k = keyOf(keyFn, items[i], i);
231
+ const count = seen.get(k);
232
+ if (count !== undefined) {
233
+ (dups || (dups = [])).push(k);
234
+ seen.set(k, count + 1);
235
+ k = k + '\u0000' + count;
236
+ }
237
+ else {
238
+ seen.set(k, 1);
239
+ }
240
+ keys[i] = k;
241
+ }
242
+ if (dups)
243
+ warnDuplicates(dups);
244
+ const oldByKey = new Map();
245
+ for (let i = 0; i < oldRows.length; i++)
246
+ oldByKey.set(oldRows[i].key, i);
247
+ // Server-rendered rows whose key no new item wants are adopted by position,
248
+ // so a key the build could not compute still hydrates without re-rendering.
249
+ for (let i = 0; i < n && i < oldRows.length; i++) {
250
+ const row = oldRows[i];
251
+ if (!row.live && !seen.has(row.key) && !oldByKey.has(keys[i])) {
252
+ oldByKey.delete(row.key);
253
+ row.key = keys[i];
254
+ oldByKey.set(row.key, i);
255
+ }
256
+ }
257
+ const restoreFocus = captureFocus(parent);
258
+ const next = new Array(n);
259
+ const sources = new Int32Array(n).fill(-1);
260
+ const kept = new Uint8Array(oldRows.length);
261
+ for (let i = 0; i < n; i++) {
262
+ const oi = oldByKey.get(keys[i]);
263
+ if (oi === undefined)
264
+ continue;
265
+ const row = oldRows[oi];
266
+ const item = items[i];
267
+ if (row.live && !state.accessor && (row.item !== item || (state.usesIndex && row.index !== i))) {
268
+ // Value mode cannot update a row in place: re-render it.
269
+ continue;
270
+ }
271
+ kept[oi] = 1;
272
+ sources[i] = oi;
273
+ next[i] = row;
274
+ }
275
+ // Unmount removed rows first, so their cleanups run before new rows mount.
276
+ for (let i = 0; i < oldRows.length; i++) {
277
+ if (!kept[i])
278
+ removeRow(oldRows[i]);
279
+ }
280
+ // Update or adopt the rows that stay.
281
+ for (let i = 0; i < n; i++) {
282
+ const row = next[i];
283
+ if (!row)
284
+ continue;
285
+ const item = items[i];
286
+ if (!row.live) {
287
+ adoptRow(state, row, item, i);
288
+ continue;
289
+ }
290
+ if (row.item !== item) {
291
+ row.item = item;
292
+ if (row.setItem)
293
+ row.setItem(() => item);
294
+ }
295
+ if (row.index !== i) {
296
+ row.index = i;
297
+ if (row.setIndex)
298
+ row.setIndex(i);
299
+ }
300
+ }
301
+ // Render new rows in order (so mount effects run in order). Consecutive new
302
+ // rows share one fragment and are inserted with a single DOM operation.
303
+ const runs = new Array(n);
304
+ let run = null;
305
+ for (let i = 0; i < n; i++) {
306
+ if (next[i]) {
307
+ run = null;
308
+ continue;
309
+ }
310
+ const frag = createRow(state, keys[i], items[i], i);
311
+ next[i] = frag.__row;
312
+ if (run) {
313
+ run.appendChild(frag);
314
+ runs[i - 1] = null;
315
+ }
316
+ else {
317
+ run = frag;
318
+ }
319
+ runs[i] = run;
320
+ }
321
+ // Place rows from the end, keeping the longest run of rows already in order.
322
+ const stay = new Uint8Array(n);
323
+ for (const i of longestIncreasingSubsequence(sources))
324
+ stay[i] = 1;
325
+ let anchor = end;
326
+ for (let i = n - 1; i >= 0; i--) {
327
+ const row = next[i];
328
+ const pending = runs[i];
329
+ if (pending) {
330
+ parent.insertBefore(pending, anchor);
331
+ }
332
+ else if (sources[i] >= 0 && !stay[i]) {
333
+ moveRow(row, anchor);
334
+ }
335
+ anchor = row.start;
336
+ }
337
+ state.rows = next;
338
+ if (restoreFocus)
339
+ restoreFocus();
340
+ }
341
+ // Collect the server-rendered rows between the list markers. Anything else
342
+ // between the markers (stray text, unexpected nodes) is removed.
343
+ function collectServerRows(state) {
344
+ const { start, end } = state;
345
+ const parent = start.parentNode;
346
+ const id = (start.nodeValue || '').slice(2);
347
+ const prefix = 'k:' + id + ':';
348
+ const rows = [];
349
+ let n = start.nextSibling;
350
+ while (n && n !== end) {
351
+ const v = n.nodeType === 8 ? n.nodeValue || '' : '';
352
+ if (id && v.indexOf(prefix) === 0) {
353
+ const closeValue = '/' + v;
354
+ let m = n.nextSibling;
355
+ while (m && m !== end && !(m.nodeType === 8 && m.nodeValue === closeValue))
356
+ m = m.nextSibling;
357
+ if (m && m !== end) {
358
+ rows.push({
359
+ key: decodeKey(v.slice(prefix.length)),
360
+ item: undefined,
361
+ index: rows.length,
362
+ start: n,
363
+ end: m,
364
+ setItem: null,
365
+ setIndex: null,
366
+ live: false,
367
+ });
368
+ n = m.nextSibling;
369
+ continue;
370
+ }
371
+ }
372
+ const nextNode = n.nextSibling;
373
+ disposeNode(n);
374
+ parent.removeChild(n);
375
+ n = nextNode;
376
+ }
377
+ // Duplicate server keys: keep the first, drop the rest.
378
+ const seen = new Set();
379
+ state.rows = rows.filter((r) => {
380
+ if (seen.has(r.key)) {
381
+ removeRow(r);
382
+ return false;
383
+ }
384
+ seen.add(r.key);
385
+ return true;
386
+ });
387
+ }
388
+ function run(state, getItems, adopt) {
389
+ let first = true;
390
+ const dispose = createEffect(() => {
391
+ const items = toArray(getItems());
392
+ untrack(() => {
393
+ if (first) {
394
+ first = false;
395
+ if (adopt)
396
+ collectServerRows(state);
397
+ }
398
+ update(state, items);
399
+ });
400
+ });
401
+ trackEffect(state.start, dispose);
402
+ }
403
+ function newState(start, end, keyFn, render, mode) {
404
+ return {
405
+ start,
406
+ end,
407
+ rows: [],
408
+ keyFn,
409
+ render,
410
+ accessor: mode === 1,
411
+ usesIndex: render.length > 1,
412
+ };
413
+ }
414
+ /**
415
+ * Bind a server-rendered list: `start` is its `<!--k:ID-->` marker. Rows are
416
+ * adopted by key and then reconciled whenever `getItems` changes.
417
+ */
418
+ export function krateBindList(start, getItems, keyFn, render, mode) {
419
+ const closeValue = '/' + (start.nodeValue || '');
420
+ let end = start.nextSibling;
421
+ while (end && !(end.nodeType === 8 && end.nodeValue === closeValue))
422
+ end = end.nextSibling;
423
+ if (!end) {
424
+ end = document.createComment(closeValue);
425
+ start.parentNode.insertBefore(end, start.nextSibling);
426
+ }
427
+ run(newState(start, end, keyFn, render, mode), getItems, true);
428
+ }
429
+ /**
430
+ * A list nested in rendered JSX (a `.map()` inside a row or component). It
431
+ * mounts as a fragment with its own markers, or adopts a server-rendered list
432
+ * at the hydration cursor.
433
+ */
434
+ export function krateList(getItems, keyFn, render, mode) {
435
+ return {
436
+ __ka: 1,
437
+ mount() {
438
+ const frag = document.createDocumentFragment();
439
+ const start = document.createComment('');
440
+ const end = document.createComment('');
441
+ frag.appendChild(start);
442
+ frag.appendChild(end);
443
+ run(newState(start, end, keyFn, render, mode), getItems, false);
444
+ return frag;
445
+ },
446
+ adopt(c) {
447
+ // A server-rendered list is a `<!--k:ID-->` ... `<!--/k:ID-->` pair at
448
+ // the cursor (closing markers of preceding slots are skipped).
449
+ let n = c.next;
450
+ while (n && n.nodeType === 8 && (n.nodeValue || '').indexOf('/k:') === 0)
451
+ n = n.nextSibling;
452
+ if (n && n.nodeType === 8 && (n.nodeValue || '').indexOf('k:') === 0) {
453
+ const closeValue = '/' + n.nodeValue;
454
+ let m = n.nextSibling;
455
+ while (m && !(m.nodeType === 8 && m.nodeValue === closeValue))
456
+ m = m.nextSibling;
457
+ if (m) {
458
+ c.next = m.nextSibling;
459
+ withDOM(() => run(newState(n, m, keyFn, render, mode), getItems, true));
460
+ return;
461
+ }
462
+ }
463
+ insertAt(c, withDOM(() => this.mount()));
464
+ },
465
+ };
466
+ }
@@ -0,0 +1 @@
1
+ export {};