@krate/runtime 0.5.0-alpha.1 → 0.5.0-alpha.3

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 (87) hide show
  1. package/dist/action-context.d.ts +49 -0
  2. package/dist/action-context.js +37 -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 +533 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +391 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/class-component.d.ts +66 -0
  12. package/dist/class-component.js +633 -0
  13. package/dist/class-component.test.d.ts +1 -0
  14. package/dist/class-component.test.js +411 -0
  15. package/dist/context.d.ts +13 -0
  16. package/dist/context.js +58 -32
  17. package/dist/context.test.d.ts +1 -0
  18. package/dist/context.test.js +57 -0
  19. package/dist/derived.test.d.ts +1 -0
  20. package/dist/derived.test.js +140 -0
  21. package/dist/discrete.test.d.ts +1 -0
  22. package/dist/discrete.test.js +100 -0
  23. package/dist/dom.d.ts +55 -0
  24. package/dist/dom.js +414 -63
  25. package/dist/effects.d.ts +88 -0
  26. package/dist/effects.js +719 -0
  27. package/dist/effects.test.d.ts +1 -0
  28. package/dist/effects.test.js +485 -0
  29. package/dist/events.d.ts +58 -0
  30. package/dist/events.js +503 -0
  31. package/dist/events.test.d.ts +1 -0
  32. package/dist/events.test.js +447 -0
  33. package/dist/index.d.ts +12 -2
  34. package/dist/index.js +8 -2
  35. package/dist/jsx-types.d.ts +2 -0
  36. package/dist/krate-hydrate-lite.js +8 -0
  37. package/dist/krate-hydrate.js +7 -1
  38. package/dist/krate-runtime.js +7 -1
  39. package/dist/krate-suspense.js +2 -0
  40. package/dist/lanes.test.d.ts +1 -0
  41. package/dist/lanes.test.js +59 -0
  42. package/dist/list.d.ts +20 -0
  43. package/dist/list.js +466 -0
  44. package/dist/list.test.d.ts +1 -0
  45. package/dist/list.test.js +344 -0
  46. package/dist/optimistic-lanes.test.d.ts +1 -0
  47. package/dist/optimistic-lanes.test.js +45 -0
  48. package/dist/portal.d.ts +43 -0
  49. package/dist/portal.js +178 -0
  50. package/dist/portal.test.d.ts +1 -0
  51. package/dist/portal.test.js +99 -0
  52. package/dist/react-effects.test.d.ts +1 -0
  53. package/dist/react-effects.test.js +96 -0
  54. package/dist/react-suspense.test.d.ts +1 -0
  55. package/dist/react-suspense.test.js +194 -0
  56. package/dist/react.d.ts +132 -32
  57. package/dist/react.js +335 -81
  58. package/dist/react.test.js +12 -2
  59. package/dist/reconcile.js +13 -0
  60. package/dist/refs.d.ts +33 -0
  61. package/dist/refs.js +142 -0
  62. package/dist/refs.test.d.ts +1 -0
  63. package/dist/refs.test.js +257 -0
  64. package/dist/resource.js +20 -1
  65. package/dist/router-lite.d.ts +8 -0
  66. package/dist/router-lite.js +11 -0
  67. package/dist/server-renderer.js +39 -1
  68. package/dist/server.d.ts +4 -1
  69. package/dist/server.js +30 -1
  70. package/dist/server.test.js +20 -0
  71. package/dist/signal-lanes.test.d.ts +1 -0
  72. package/dist/signal-lanes.test.js +32 -0
  73. package/dist/signal.d.ts +150 -1
  74. package/dist/signal.js +750 -65
  75. package/dist/slots.d.ts +18 -0
  76. package/dist/slots.js +108 -0
  77. package/dist/slots.test.d.ts +1 -0
  78. package/dist/slots.test.js +169 -0
  79. package/dist/snapshots.test.d.ts +1 -0
  80. package/dist/snapshots.test.js +208 -0
  81. package/dist/suspense-actions.test.d.ts +1 -0
  82. package/dist/suspense-actions.test.js +72 -0
  83. package/dist/suspense.d.ts +220 -0
  84. package/dist/suspense.js +901 -0
  85. package/dist/suspense.test.d.ts +1 -0
  86. package/dist/suspense.test.js +518 -0
  87. package/package.json +1 -1
@@ -0,0 +1,18 @@
1
+ export * from './portal.js';
2
+ /** Fragments holding currently hidden conditional branches. */
3
+ export declare function krateCondDetached(): DocumentFragment[];
4
+ /** Forgets hidden branches of the previous page (called on slot rescans). */
5
+ export declare function krateCondReset(): void;
6
+ /**
7
+ * Shows the consequent (`show` true) or alternate branch of the conditional
8
+ * whose start marker is `start`. `tpl` is the conditional's hoisted template
9
+ * (null when it is missing, in which case the other branch is empty and the
10
+ * markers are assumed to hold the branch matching the first call). Template
11
+ * content is only taken when first shown, so its nodes stay findable by
12
+ * hydration bindings registered after kbindCond.
13
+ */
14
+ export declare function krateCondSwap(start: Comment, show: boolean, tpl: HTMLTemplateElement | null): void;
15
+ /** The replacement React 19 (and the Krate compiler) uses for javascript: URLs. */
16
+ export declare const BLOCKED_URL = "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
17
+ /** Neutralizes a javascript: URL written to a URL-valued attribute. */
18
+ export declare function krateSanitizeAttr(attr: string, value: string): string;
package/dist/slots.js ADDED
@@ -0,0 +1,108 @@
1
+ // Hydration helpers for compiler-emitted slot markers.
2
+ //
3
+ // Conditionals are emitted as comment markers around the active branch only:
4
+ //
5
+ // <!--k:ID-->active branch<!--/k:ID-->
6
+ //
7
+ // with the inactive branch in a hoisted `<template data-kc="ID" data-kb="c|a">`
8
+ // (data-kb names the branch the template holds: c = consequent, a = alternate).
9
+ // The hydration bootstrap binds nodes inside template content too, so swapping
10
+ // moves the very nodes that were bound: handlers and nested bindings of both
11
+ // branches keep working across toggles.
12
+ import { krateRefsEnter, krateRefsLeave } from './refs.js';
13
+ import { krateMountFields } from './events.js';
14
+ import { kratePortalsEnter, kratePortalsIn, kratePortalsLeave } from './portal.js';
15
+ export * from './portal.js';
16
+ // Branches swapped out of the document. Hydration lookups (findSlot) search
17
+ // them too, so a binding registered after a swap still finds its node.
18
+ const detached = new Set();
19
+ /** Fragments holding currently hidden conditional branches. */
20
+ export function krateCondDetached() {
21
+ return Array.from(detached);
22
+ }
23
+ /** Forgets hidden branches of the previous page (called on slot rescans). */
24
+ export function krateCondReset() {
25
+ detached.clear();
26
+ }
27
+ function findCondEnd(start) {
28
+ const want = '/' + (start.nodeValue || '');
29
+ for (let n = start.nextSibling; n; n = n.nextSibling) {
30
+ if (n.nodeType === 8 && n.nodeValue === want)
31
+ return n;
32
+ }
33
+ return null;
34
+ }
35
+ /**
36
+ * Shows the consequent (`show` true) or alternate branch of the conditional
37
+ * whose start marker is `start`. `tpl` is the conditional's hoisted template
38
+ * (null when it is missing, in which case the other branch is empty and the
39
+ * markers are assumed to hold the branch matching the first call). Template
40
+ * content is only taken when first shown, so its nodes stay findable by
41
+ * hydration bindings registered after kbindCond.
42
+ */
43
+ export function krateCondSwap(start, show, tpl) {
44
+ const node = start;
45
+ const want = show ? 'c' : 'a';
46
+ let st = node.__krateCond;
47
+ if (!st) {
48
+ const held = tpl ? tpl.getAttribute('data-kb') : null;
49
+ const shown = held === 'c' ? 'a' : held === 'a' ? 'c' : want;
50
+ st = { shown, other: null, tpl, end: findCondEnd(start) };
51
+ node.__krateCond = st;
52
+ }
53
+ if (st.shown === want)
54
+ return;
55
+ const parent = start.parentNode;
56
+ if (!parent)
57
+ return;
58
+ if (!st.end || st.end.parentNode !== parent)
59
+ st.end = findCondEnd(start);
60
+ const end = st.end;
61
+ const out = document.createDocumentFragment();
62
+ let n = start.nextSibling;
63
+ while (n && n !== end) {
64
+ const next = n.nextSibling;
65
+ out.appendChild(n);
66
+ n = next;
67
+ }
68
+ // React order: refs of the outgoing branch detach before the incoming
69
+ // branch's refs attach.
70
+ krateRefsLeave(out);
71
+ // A hidden branch takes its portal content with it.
72
+ kratePortalsLeave(out);
73
+ let incoming = st.other;
74
+ if (!incoming) {
75
+ incoming = document.createDocumentFragment();
76
+ if (st.tpl)
77
+ incoming.appendChild(st.tpl.content);
78
+ }
79
+ detached.delete(incoming);
80
+ // React focuses an autoFocus element when it mounts (and renders no
81
+ // autofocus attribute on the client).
82
+ const auto = incoming.querySelector('[autofocus]');
83
+ krateMountFields(incoming);
84
+ const portals = kratePortalsIn(incoming);
85
+ parent.insertBefore(incoming, end);
86
+ kratePortalsEnter(portals);
87
+ st.other = out;
88
+ detached.add(out);
89
+ st.shown = want;
90
+ krateRefsEnter();
91
+ if (auto) {
92
+ auto.removeAttribute('autofocus');
93
+ auto.focus();
94
+ }
95
+ }
96
+ const URL_ATTRS = { href: true, src: true, action: true, formaction: true, 'xlink:href': true };
97
+ // Matches React 19's isJavaScriptProtocol: leading C0 controls/spaces, and
98
+ // tab/CR/LF anywhere inside the scheme, case-insensitively.
99
+ // eslint-disable-next-line no-control-regex
100
+ const JS_URL = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
101
+ /** The replacement React 19 (and the Krate compiler) uses for javascript: URLs. */
102
+ export const BLOCKED_URL = "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
103
+ /** Neutralizes a javascript: URL written to a URL-valued attribute. */
104
+ export function krateSanitizeAttr(attr, value) {
105
+ if (URL_ATTRS[attr.toLowerCase()] && JS_URL.test(value))
106
+ return BLOCKED_URL;
107
+ return value;
108
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,169 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { krateCondSwap, krateCondDetached, krateCondReset, krateSanitizeAttr, BLOCKED_URL } from './slots';
6
+ import { createSignal, createEffect } from './signal';
7
+ import { reconcileTrees } from './reconcile';
8
+ const tick = () => new Promise((r) => setTimeout(r, 0));
9
+ function startMarker(root, id) {
10
+ const w = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
11
+ while (w.nextNode()) {
12
+ if (w.currentNode.nodeValue === 'k:' + id)
13
+ return w.currentNode;
14
+ }
15
+ throw new Error('marker not found: ' + id);
16
+ }
17
+ describe('krateCondSwap', () => {
18
+ // happy-dom does not parse <tr> inside <template> per spec, so the
19
+ // table-context case is covered by the Go emitter tests and the browser
20
+ // conformance suite; the swap mechanics are identical for any element.
21
+ it('swaps the active branch with the template branch', () => {
22
+ document.body.innerHTML =
23
+ '<ol><!--k:c1--><li>yes</li><!--/k:c1--></ol>' +
24
+ '<template data-kc="c1" data-kb="a"><li>no</li></template>';
25
+ const start = startMarker(document.body, 'c1');
26
+ const tpl = document.querySelector('template[data-kc="c1"]');
27
+ const tbody = document.querySelector('ol');
28
+ const yesRow = tbody.querySelector('li');
29
+ krateCondSwap(start, true, tpl);
30
+ expect(tbody.textContent).toBe('yes');
31
+ krateCondSwap(start, false, tpl);
32
+ expect(tbody.querySelectorAll('li').length).toBe(1);
33
+ expect(tbody.textContent).toBe('no');
34
+ krateCondSwap(start, true, tpl);
35
+ // The original (hydrated) node comes back, not a clone.
36
+ expect(tbody.querySelector('li')).toBe(yesRow);
37
+ });
38
+ it('keeps bindings made on template content alive after the swap', async () => {
39
+ document.body.innerHTML =
40
+ '<ul><!--k:c2--><li>a</li><!--/k:c2--></ul><template data-kc="c2" data-kb="a"><li><button>b</button></li></template>';
41
+ const tpl = document.querySelector('template');
42
+ const btn = tpl.content.querySelector('button');
43
+ let clicks = 0;
44
+ btn.addEventListener('click', () => clicks++);
45
+ const [on, setOn] = createSignal(true);
46
+ const start = startMarker(document.body, 'c2');
47
+ createEffect(() => krateCondSwap(start, !!on(), tpl));
48
+ expect(document.querySelector('ul').textContent).toBe('a');
49
+ setOn(false);
50
+ await tick();
51
+ const live = document.querySelector('ul button');
52
+ expect(live).toBe(btn);
53
+ live.click();
54
+ expect(clicks).toBe(1);
55
+ });
56
+ it('starts from the consequent when the template holds it', () => {
57
+ document.body.innerHTML = '<p><!--k:c3--><i>no</i><!--/k:c3--></p><template data-kc="c3" data-kb="c"><b>yes</b></template>';
58
+ const start = startMarker(document.body, 'c3');
59
+ const tpl = document.querySelector('template');
60
+ krateCondSwap(start, false, tpl);
61
+ expect(document.querySelector('p').innerHTML).toBe('<!--k:c3--><i>no</i><!--/k:c3-->');
62
+ krateCondSwap(start, true, tpl);
63
+ expect(document.querySelector('p').innerHTML).toBe('<!--k:c3--><b>yes</b><!--/k:c3-->');
64
+ });
65
+ it('treats a missing template as an empty branch', () => {
66
+ document.body.innerHTML = '<div><!--k:c4--><b>x</b><!--/k:c4--></div>';
67
+ const start = startMarker(document.body, 'c4');
68
+ krateCondSwap(start, true, null);
69
+ krateCondSwap(start, false, null);
70
+ expect(document.querySelector('div').innerHTML).toBe('<!--k:c4--><!--/k:c4-->');
71
+ krateCondSwap(start, true, null);
72
+ expect(document.querySelector('div').textContent).toBe('x');
73
+ });
74
+ });
75
+ describe('krateSanitizeAttr', () => {
76
+ it('blocks javascript: URLs like React 19', () => {
77
+ expect(krateSanitizeAttr('href', 'javascript:alert(1)')).toBe(BLOCKED_URL);
78
+ expect(krateSanitizeAttr('src', ' \tJaVa\nScript:x')).toBe(BLOCKED_URL);
79
+ expect(krateSanitizeAttr('xlink:href', 'javascript:x')).toBe(BLOCKED_URL);
80
+ expect(krateSanitizeAttr('href', '/safe')).toBe('/safe');
81
+ expect(krateSanitizeAttr('title', 'javascript:x')).toBe('javascript:x');
82
+ });
83
+ });
84
+ describe('reconcile with conditional templates', () => {
85
+ it('replaces a template whose content changed', () => {
86
+ document.body.innerHTML = '<div id="root"><p>x</p><template data-kc="c1" data-kb="a"><b>old</b></template></div>';
87
+ const root = document.getElementById('root');
88
+ const next = document.createElement('div');
89
+ next.id = 'root';
90
+ next.innerHTML = '<p>x</p><template data-kc="c1" data-kb="a"><b>new</b></template>';
91
+ reconcileTrees(root, next);
92
+ const tpl = root.querySelector('template');
93
+ expect(tpl.innerHTML).toBe('<b>new</b>');
94
+ });
95
+ });
96
+ // The hydration bootstrap ships as a Go string constant appended to the
97
+ // runtime chunk; run the real source against compiler-shaped markup.
98
+ function loadBootstrap() {
99
+ const here = dirname(fileURLToPath(import.meta.url));
100
+ const src = readFileSync(resolve(here, '../../compiler/internal/renderer/newhydrate.go'), 'utf8');
101
+ const start = src.indexOf('const HydrationBootstrapJS = `') + 'const HydrationBootstrapJS = `'.length;
102
+ const end = src.indexOf('`\n', start);
103
+ return src.slice(start, end);
104
+ }
105
+ describe('hydration bootstrap', () => {
106
+ beforeEach(() => {
107
+ const w = window;
108
+ w.createEffect = createEffect;
109
+ w.krateCondSwap = krateCondSwap;
110
+ w.krateCondDetached = krateCondDetached;
111
+ w.krateCondReset = krateCondReset;
112
+ w.krateSanitizeAttr = krateSanitizeAttr;
113
+ });
114
+ it('binds handlers and text inside the inactive branch template, then toggles', async () => {
115
+ document.body.innerHTML =
116
+ '<div id="root"><ul><!--k:c--><li>on</li><!--/k:c--></ul>' +
117
+ '<template data-kc="c" data-kb="a"><li><button data-k="k:btn">off</button><!--k:t-->0<!--/k:t--></li></template></div>';
118
+ new Function(loadBootstrap())();
119
+ const w = window;
120
+ const [on, setOn] = createSignal(true);
121
+ const [n, setN] = createSignal(0);
122
+ let clicked = 0;
123
+ w.kbindCond('c', () => on());
124
+ w.kbindText('t', () => n());
125
+ expect(w.findSlot('btn')).not.toBe(null);
126
+ w.kbindEvent('btn', 'click', () => clicked++, false);
127
+ expect(w.__krateErrs).toEqual([]);
128
+ setN(5);
129
+ setOn(false);
130
+ await tick();
131
+ const tbody = document.querySelector('ul');
132
+ expect(tbody.textContent).toBe('off5');
133
+ tbody.querySelector('button').click();
134
+ expect(clicked).toBe(1);
135
+ setOn(true);
136
+ await tick();
137
+ expect(tbody.textContent).toBe('on');
138
+ setN(7);
139
+ setOn(false);
140
+ await tick();
141
+ expect(tbody.textContent).toBe('off7');
142
+ });
143
+ it('finds nodes of a branch swapped out before its binding ran', async () => {
144
+ document.body.innerHTML =
145
+ '<div id="root"><p><!--k:c--><button data-k="k:b">ssr</button><!--/k:c--></p>' +
146
+ '<template data-kc="c" data-kb="a"><i>client</i></template></div>';
147
+ new Function(loadBootstrap())();
148
+ const w = window;
149
+ // The client state disagrees with the SSR state: the first run swaps.
150
+ w.kbindCond('c', () => false);
151
+ expect(document.querySelector('p').textContent).toBe('client');
152
+ let clicks = 0;
153
+ w.kbindEvent('b', 'click', () => clicks++, false);
154
+ expect(w.findSlot('b')).not.toBe(null);
155
+ w.findSlot('b').click();
156
+ expect(clicks).toBe(1);
157
+ });
158
+ it('neutralizes javascript: URLs set by attribute bindings', async () => {
159
+ document.body.innerHTML = '<div id="root"><a data-k="k:a">x</a></div>';
160
+ new Function(loadBootstrap())();
161
+ const [href, setHref] = createSignal('/ok');
162
+ window.kbindAttr('a', 'href', () => href());
163
+ const a = document.querySelector('a');
164
+ expect(a.getAttribute('href')).toBe('/ok');
165
+ setHref('javascript:alert(1)');
166
+ await tick();
167
+ expect(a.getAttribute('href')).toBe(BLOCKED_URL);
168
+ });
169
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,208 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { createSignal, createReducer, createEffect, disposeAll, krateHookState, krateFlushSync } from './signal';
3
+ import { createEffectDeps, krateOwner, krateMount, krateCondActivity, krateOnUnmount } from './effects';
4
+ const tick = () => new Promise((r) => setTimeout(r, 0));
5
+ async function settle() {
6
+ for (let i = 0; i < 4; i++)
7
+ await tick();
8
+ }
9
+ // Runs fn as if inside a native click listener (a discrete event).
10
+ function inClick(fn) {
11
+ const btn = document.createElement('button');
12
+ document.body.appendChild(btn);
13
+ // Browsers expose the event being dispatched as window.event; happy-dom
14
+ // does not, so provide it the way a browser would.
15
+ btn.addEventListener('click', (e) => {
16
+ const w = window;
17
+ const prev = w.event;
18
+ w.event = e;
19
+ try {
20
+ fn();
21
+ }
22
+ finally {
23
+ w.event = prev;
24
+ }
25
+ });
26
+ btn.click();
27
+ btn.remove();
28
+ }
29
+ describe('render snapshots for React state', () => {
30
+ beforeEach(() => disposeAll());
31
+ it('reads the committed value in handlers, so repeated setState(x + 1) adds one', async () => {
32
+ const [count, setCount] = createSignal(0, krateHookState);
33
+ inClick(() => {
34
+ setCount(count() + 1);
35
+ setCount(count() + 1);
36
+ setCount(count() + 1);
37
+ });
38
+ await settle();
39
+ expect(count()).toBe(1);
40
+ });
41
+ it('keeps functional updaters on the latest pending value', async () => {
42
+ const [count, setCount] = createSignal(0, krateHookState);
43
+ inClick(() => {
44
+ setCount((c) => c + 1);
45
+ setCount((c) => c + 1);
46
+ expect(count()).toBe(0); // still the render's snapshot
47
+ });
48
+ await settle();
49
+ expect(count()).toBe(2);
50
+ });
51
+ it('lets bindings (the render phase) see the latest value', async () => {
52
+ const [count, setCount] = createSignal(0, krateHookState);
53
+ const seen = [];
54
+ createEffect(() => void seen.push(count()));
55
+ inClick(() => setCount(5));
56
+ await settle();
57
+ expect(seen).toEqual([0, 5]);
58
+ });
59
+ it('runs cleanups with the values of the render their effect ran for', async () => {
60
+ const [room, setRoom] = createSignal('general', krateHookState);
61
+ const log = [];
62
+ createEffectDeps(() => {
63
+ log.push('connect ' + room());
64
+ return () => log.push('disconnect ' + room());
65
+ }, () => [room()]);
66
+ await settle();
67
+ inClick(() => setRoom('random'));
68
+ await settle();
69
+ inClick(() => setRoom('music'));
70
+ await settle();
71
+ expect(log).toEqual(['connect general', 'disconnect general', 'connect random', 'disconnect random', 'connect music']);
72
+ });
73
+ it('gives a second effect the committed value while the first sets state', async () => {
74
+ const [text] = createSignal('hello', krateHookState);
75
+ const [words, setWords] = createSignal(0, krateHookState);
76
+ const log = [];
77
+ createEffectDeps(() => {
78
+ log.push('count ' + text());
79
+ setWords(1);
80
+ }, () => [text()]);
81
+ createEffectDeps(() => void log.push('words ' + words()), () => [words()]);
82
+ await settle();
83
+ expect(log).toEqual(['count hello', 'words 0', 'words 1']);
84
+ });
85
+ it('does not change native signal semantics', () => {
86
+ const [n, setN] = createSignal(0);
87
+ setN(n() + 1);
88
+ setN(n() + 1);
89
+ expect(n()).toBe(2);
90
+ });
91
+ it('applies reducer options and the lazy initializer', async () => {
92
+ const [s, dispatch] = createReducer((st, a) => st + a, 2, (x) => x * 10, krateHookState);
93
+ expect(s()).toBe(20);
94
+ inClick(() => {
95
+ dispatch(1);
96
+ expect(s()).toBe(20);
97
+ });
98
+ await settle();
99
+ expect(s()).toBe(21);
100
+ });
101
+ });
102
+ describe('update lanes', () => {
103
+ beforeEach(() => disposeAll());
104
+ it('flushes passive effects of a discrete update before the handler microtask', async () => {
105
+ const [n, setN] = createSignal(0, krateHookState);
106
+ const log = [];
107
+ createEffectDeps(() => void log.push('passive ' + n()), () => [n()]);
108
+ await settle();
109
+ log.length = 0;
110
+ inClick(() => {
111
+ setN((v) => v + 1);
112
+ queueMicrotask(() => log.push('microtask'));
113
+ });
114
+ await settle();
115
+ expect(log).toEqual(['passive 1', 'microtask']);
116
+ });
117
+ it('commits a non-discrete update after the microtasks queued with it', async () => {
118
+ const [n, setN] = createSignal(0, krateHookState);
119
+ const log = [];
120
+ createEffectDeps(() => void log.push('layout ' + n()), () => [n()], 'layout');
121
+ await settle();
122
+ log.length = 0;
123
+ setTimeout(() => {
124
+ setN(10);
125
+ queueMicrotask(() => log.push('microtask'));
126
+ }, 0);
127
+ await settle();
128
+ expect(log).toEqual(['microtask', 'layout 10']);
129
+ });
130
+ it('flushes synchronously on demand', () => {
131
+ const [n, setN] = createSignal(0, krateHookState);
132
+ const seen = [];
133
+ createEffect(() => void seen.push(n()));
134
+ setN(3);
135
+ krateFlushSync();
136
+ expect(seen).toEqual([0, 3]);
137
+ expect(n()).toBe(3);
138
+ });
139
+ });
140
+ describe('remountable conditional branches', () => {
141
+ beforeEach(() => disposeAll());
142
+ it('unmounts on hide and mounts a fresh instance on show', async () => {
143
+ const log = [];
144
+ const setters = [];
145
+ const getters = [];
146
+ const unmounted = [];
147
+ krateOnUnmount((_owner, id) => unmounted.push(id));
148
+ krateOwner('P', null);
149
+ krateMount('C', 'P', [['5', 'c', 1]], null, () => {
150
+ const [count, setCount] = createSignal(0, krateHookState);
151
+ setters.push(setCount);
152
+ getters.push(count);
153
+ createEffectDeps(() => {
154
+ log.push('mount ' + count());
155
+ return () => log.push('unmount ' + count());
156
+ }, () => []);
157
+ });
158
+ krateOwner(null);
159
+ await settle();
160
+ setters[0](2);
161
+ await settle();
162
+ expect(getters[0]()).toBe(2);
163
+ krateCondActivity('5', 'a');
164
+ await settle();
165
+ krateCondActivity('5', 'c');
166
+ await settle();
167
+ expect(getters.length).toBe(2);
168
+ expect(getters[1]()).toBe(0);
169
+ expect(log).toEqual(['mount 0', 'unmount 0', 'mount 0']);
170
+ expect(unmounted).toEqual(['C']);
171
+ });
172
+ it('defers a component in the initially hidden branch until it is shown', async () => {
173
+ let runs = 0;
174
+ krateOwner('P', null);
175
+ krateCondActivity('9', 'c');
176
+ krateMount('Alt', 'P', [['9', 'a', 0]], null, () => {
177
+ runs++;
178
+ });
179
+ krateOwner(null);
180
+ await settle();
181
+ expect(runs).toBe(0);
182
+ krateCondActivity('9', 'a');
183
+ expect(runs).toBe(1);
184
+ });
185
+ it('remounts nested components under their fresh parent', async () => {
186
+ const order = [];
187
+ krateOwner('P', null);
188
+ krateMount('C', 'P', [['5', 'c', 1]], null, () => void order.push('C'));
189
+ krateMount('G', 'C', [['5', 'c', 1]], null, () => void order.push('G'));
190
+ krateOwner(null);
191
+ krateCondActivity('5', 'a');
192
+ krateCondActivity('5', 'c');
193
+ expect(order).toEqual(['C', 'G', 'C', 'G']);
194
+ });
195
+ it('disposes the bindings of an unmounted instance', async () => {
196
+ const [n, setN] = createSignal(0);
197
+ const seen = [];
198
+ krateOwner('P', null);
199
+ krateMount('C', 'P', [['5', 'c', 1]], null, () => {
200
+ createEffect(() => void seen.push(n()));
201
+ });
202
+ krateOwner(null);
203
+ krateCondActivity('5', 'a');
204
+ setN(1);
205
+ await settle();
206
+ expect(seen).toEqual([0]);
207
+ });
208
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,72 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { createSignal } from './signal.js';
3
+ import { __krateBeginAction, isActionPending, runActionTransition, setActionTransitionRunner, } from './actions.js';
4
+ import { createOwner, runWithOwner, setBoundary } from './boundary.js';
5
+ import { __krateBoundary, __krateRead, __krateTransitionStarter, connectErrorBoundaries, connectActionTransitions, isInTransition, setSuspenseErrorHandler, } from './suspense.js';
6
+ afterEach(() => {
7
+ setActionTransitionRunner(null);
8
+ connectErrorBoundaries(null);
9
+ setSuspenseErrorHandler(null);
10
+ vi.useRealTimers();
11
+ });
12
+ describe('one transition scope for transitions and actions', () => {
13
+ it('keeps the action scope open while a useTransition async action runs', async () => {
14
+ vi.useFakeTimers();
15
+ connectActionTransitions({ setActionTransitionRunner, __krateBeginAction });
16
+ const [pending, setPending] = createSignal(false);
17
+ const start = __krateTransitionStarter(setPending);
18
+ start(() => new Promise((r) => setTimeout(r, 100)));
19
+ expect(isActionPending()).toBe(true);
20
+ await vi.advanceTimersByTimeAsync(110);
21
+ expect(pending()).toBe(false);
22
+ expect(isActionPending()).toBe(false);
23
+ });
24
+ it('runs form actions as transitions with their value and error', async () => {
25
+ connectActionTransitions({ setActionTransitionRunner, __krateBeginAction });
26
+ const reported = [];
27
+ setSuspenseErrorHandler((e) => {
28
+ reported.push(e);
29
+ return true;
30
+ });
31
+ let inTransition = false;
32
+ const value = await runActionTransition(async () => {
33
+ inTransition = isInTransition();
34
+ return 42;
35
+ });
36
+ expect(value).toBe(42);
37
+ expect(inTransition).toBe(true);
38
+ await expect(runActionTransition(async () => Promise.reject(new Error('nope')))).rejects.toThrow('nope');
39
+ await expect(runActionTransition(() => {
40
+ throw new Error('sync');
41
+ })).rejects.toThrow('sync');
42
+ // The action runtime reports action errors; the transition does not again.
43
+ expect(reported).toHaveLength(0);
44
+ expect(isActionPending()).toBe(false);
45
+ });
46
+ });
47
+ describe('error boundaries', () => {
48
+ it('routes a rejected use() promise to the error boundary of the component', async () => {
49
+ const { getOwner, handleError } = await import('./boundary.js');
50
+ connectErrorBoundaries({ getOwner, handleError: (e, o) => handleError(e, o) });
51
+ const caught = [];
52
+ const parent = createOwner('Boundary', null);
53
+ setBoundary(parent, (error) => {
54
+ caught.push(error);
55
+ return true;
56
+ });
57
+ const child = createOwner('Child', parent);
58
+ let reject;
59
+ const p = new Promise((_, rej) => {
60
+ reject = rej;
61
+ });
62
+ runWithOwner(child, () => {
63
+ __krateBoundary(null, () => {
64
+ __krateRead(p);
65
+ });
66
+ });
67
+ reject(new Error('boom'));
68
+ for (let i = 0; i < 20; i++)
69
+ await Promise.resolve();
70
+ expect(caught.map((e) => e.message)).toEqual(['boom']);
71
+ });
72
+ });