@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.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 (155) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +279 -17
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/slot.d.ts +12 -0
  63. package/dist/slot.js +23 -0
  64. package/dist/slot.test.js +25 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/base-path.test.js +0 -88
  72. package/dist/class-component.test.js +0 -462
  73. package/dist/class-helpers.test.js +0 -169
  74. package/dist/context.test.js +0 -57
  75. package/dist/derived.test.js +0 -140
  76. package/dist/dev-overlay.test.js +0 -165
  77. package/dist/discrete.test.js +0 -100
  78. package/dist/dom.test.js +0 -39
  79. package/dist/effect-errors.test.d.ts +0 -1
  80. package/dist/effect-errors.test.js +0 -199
  81. package/dist/effects.test.d.ts +0 -1
  82. package/dist/effects.test.js +0 -485
  83. package/dist/handler-routing.test.d.ts +0 -1
  84. package/dist/handler-routing.test.js +0 -99
  85. package/dist/highlight-bind.test.d.ts +0 -1
  86. package/dist/highlight-bind.test.js +0 -124
  87. package/dist/highlight.test.d.ts +0 -1
  88. package/dist/highlight.test.js +0 -56
  89. package/dist/lanes.test.d.ts +0 -1
  90. package/dist/lanes.test.js +0 -59
  91. package/dist/list.test.d.ts +0 -1
  92. package/dist/list.test.js +0 -435
  93. package/dist/metadata.test.d.ts +0 -1
  94. package/dist/metadata.test.js +0 -167
  95. package/dist/navigation.test.d.ts +0 -1
  96. package/dist/navigation.test.js +0 -130
  97. package/dist/optimistic-lanes.test.d.ts +0 -1
  98. package/dist/optimistic-lanes.test.js +0 -45
  99. package/dist/patterns.test.d.ts +0 -1
  100. package/dist/patterns.test.js +0 -125
  101. package/dist/portal.test.d.ts +0 -1
  102. package/dist/portal.test.js +0 -99
  103. package/dist/react-effects.test.d.ts +0 -1
  104. package/dist/react-effects.test.js +0 -133
  105. package/dist/react-suspense.test.d.ts +0 -1
  106. package/dist/react-suspense.test.js +0 -194
  107. package/dist/react.test.d.ts +0 -1
  108. package/dist/react.test.js +0 -60
  109. package/dist/react19.test.d.ts +0 -1
  110. package/dist/react19.test.js +0 -176
  111. package/dist/reactivity-core.test.d.ts +0 -1
  112. package/dist/reactivity-core.test.js +0 -152
  113. package/dist/reconcile.test.d.ts +0 -1
  114. package/dist/reconcile.test.js +0 -110
  115. package/dist/refs.test.d.ts +0 -1
  116. package/dist/refs.test.js +0 -257
  117. package/dist/router-layout.test.d.ts +0 -1
  118. package/dist/router-layout.test.js +0 -249
  119. package/dist/router-slots.test.d.ts +0 -1
  120. package/dist/router-slots.test.js +0 -144
  121. package/dist/router-speculation.test.d.ts +0 -1
  122. package/dist/router-speculation.test.js +0 -25
  123. package/dist/router-styles.test.d.ts +0 -1
  124. package/dist/router-styles.test.js +0 -98
  125. package/dist/router.test.d.ts +0 -1
  126. package/dist/router.test.js +0 -36
  127. package/dist/server-async.test.d.ts +0 -1
  128. package/dist/server-async.test.js +0 -216
  129. package/dist/server-highlight.test.d.ts +0 -1
  130. package/dist/server-highlight.test.js +0 -32
  131. package/dist/signal-lanes.test.d.ts +0 -1
  132. package/dist/signal-lanes.test.js +0 -32
  133. package/dist/slots.test.d.ts +0 -1
  134. package/dist/slots.test.js +0 -187
  135. package/dist/snapshots.test.d.ts +0 -1
  136. package/dist/snapshots.test.js +0 -208
  137. package/dist/ssr-core.test.d.ts +0 -1
  138. package/dist/ssr-core.test.js +0 -324
  139. package/dist/static-memory.test.d.ts +0 -1
  140. package/dist/static-memory.test.js +0 -26
  141. package/dist/storage.test.d.ts +0 -1
  142. package/dist/storage.test.js +0 -46
  143. package/dist/suspense-actions.test.d.ts +0 -1
  144. package/dist/suspense-actions.test.js +0 -72
  145. package/dist/suspense.test.d.ts +0 -1
  146. package/dist/suspense.test.js +0 -556
  147. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  148. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  149. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  150. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  151. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  152. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  153. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  154. /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
  155. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,130 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
- import { createEffect, createRoot, krateFlushSync, krateHook } from './index';
3
- import { krateResetNavigation, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, } from './navigation';
4
- import * as serverNav from './navigation-server';
5
- const REQUEST_STORE = Symbol.for('krate.request.store');
6
- function setURL(url, route = '') {
7
- history.replaceState(null, '', url);
8
- globalThis.__KRATE_ROUTE__ = route;
9
- }
10
- function navigated() {
11
- window.dispatchEvent(new CustomEvent('krate:navigate-end'));
12
- }
13
- beforeEach(() => {
14
- krateResetNavigation();
15
- setURL('/');
16
- });
17
- afterEach(() => {
18
- delete globalThis.__KRATE_ROUTE__;
19
- delete globalThis[REQUEST_STORE];
20
- });
21
- describe('client router hooks', () => {
22
- it('usePathname follows the URL without the trailing slash', () => {
23
- setURL('/blog/hello/');
24
- const pathname = krateHook(usePathname());
25
- expect(pathname()).toBe('/blog/hello');
26
- setURL('/');
27
- navigated();
28
- expect(pathname()).toBe('/');
29
- setURL('/about/?x=1');
30
- navigated();
31
- expect(pathname()).toBe('/about');
32
- });
33
- it('is reactive: an effect runs again after a navigation, back and forward included', () => {
34
- setURL('/a/');
35
- const seen = [];
36
- createRoot(() => {
37
- const pathname = krateHook(usePathname());
38
- createEffect(() => {
39
- seen.push(pathname());
40
- });
41
- });
42
- setURL('/b/');
43
- navigated();
44
- krateFlushSync();
45
- setURL('/a/');
46
- navigated();
47
- krateFlushSync();
48
- expect(seen).toEqual(['/a', '/b', '/a']);
49
- });
50
- it('useSearchParams reads the live query', () => {
51
- setURL('/s/?q=one&tag=a&tag=b');
52
- const search = krateHook(useSearchParams());
53
- expect(search().get('q')).toBe('one');
54
- expect(search().getAll('tag')).toEqual(['a', 'b']);
55
- setURL('/s/?q=two');
56
- navigated();
57
- expect(search().get('q')).toBe('two');
58
- expect(search().has('tag')).toBe(false);
59
- });
60
- it('useParams matches the route pattern of the page', () => {
61
- setURL('/blog/hello/', '/blog/[slug]');
62
- const params = krateHook(useParams());
63
- expect(params()).toEqual({ slug: 'hello' });
64
- setURL('/blog/caf%C3%A9/', '/blog/[slug]');
65
- navigated();
66
- expect(params()).toEqual({ slug: 'café' });
67
- setURL('/docs/a/b/c/', '/docs/[...rest]');
68
- navigated();
69
- expect(params()).toEqual({ rest: ['a', 'b', 'c'] });
70
- setURL('/shop/', '/shop/[[...path]]');
71
- navigated();
72
- expect(params()).toEqual({});
73
- setURL('/about/', '');
74
- navigated();
75
- expect(params()).toEqual({});
76
- });
77
- it('a hook result reads as its value when it was not lowered', () => {
78
- setURL('/blog/hello/', '/blog/[slug]');
79
- expect(`${usePathname()}`).toBe('/blog/hello');
80
- expect(JSON.stringify({ p: useParams() })).toBe('{"p":{"slug":"hello"}}');
81
- expect(String(useSearchParams())).toBe('');
82
- });
83
- it('useSelectedLayoutSegment(s) count from the layout depth', () => {
84
- setURL('/dash/settings/profile/');
85
- const all = krateHook(useSelectedLayoutSegments());
86
- const fromDash = krateHook(useSelectedLayoutSegments(undefined, 1));
87
- const first = krateHook(useSelectedLayoutSegment(undefined, 1));
88
- const own = krateHook(useSelectedLayoutSegment(undefined, 3));
89
- expect(all()).toEqual(['dash', 'settings', 'profile']);
90
- expect(fromDash()).toEqual(['settings', 'profile']);
91
- expect(first()).toBe('settings');
92
- expect(own()).toBeNull();
93
- });
94
- it('useRouter has push, replace, back, forward, refresh and prefetch', () => {
95
- const router = useRouter();
96
- for (const m of ['push', 'replace', 'back', 'forward', 'refresh', 'prefetch']) {
97
- expect(typeof router[m]).toBe('function');
98
- }
99
- });
100
- });
101
- describe('router hooks while rendering a request', () => {
102
- function request(url, params, searchParams = {}) {
103
- globalThis[REQUEST_STORE] = {
104
- getStore: () => ({ url, method: 'GET', headers: new Headers(), cookies: new Map(), params, searchParams }),
105
- };
106
- }
107
- it('return plain values for the request, from the client entry or the server entry', () => {
108
- request('/post/[id]', { id: 'abc' }, { tab: 'info' });
109
- for (const nav of [{ usePathname, useParams, useSearchParams }, serverNav]) {
110
- expect(nav.usePathname()).toBe('/post/abc');
111
- expect(nav.useParams()).toEqual({ id: 'abc' });
112
- expect(nav.useSearchParams().get('tab')).toBe('info');
113
- }
114
- });
115
- it('fill catch-all params as arrays and as path parts', () => {
116
- request('/docs/[...rest]', { rest: 'a/b' });
117
- expect(usePathname()).toBe('/docs/a/b');
118
- expect(useParams()).toEqual({ rest: ['a', 'b'] });
119
- request('/shop/[[...path]]', {});
120
- expect(usePathname()).toBe('/shop');
121
- expect(useParams()).toEqual({});
122
- });
123
- it('segments count from the layout depth and useRouter methods throw', () => {
124
- request('/dash/settings', {});
125
- expect(useSelectedLayoutSegments(undefined, 1)).toEqual(['settings']);
126
- expect(useSelectedLayoutSegment(undefined, 0)).toBe('dash');
127
- expect(useSelectedLayoutSegment(undefined, 2)).toBeNull();
128
- expect(() => useRouter().push('/x')).toThrow(/browser/);
129
- });
130
- });
@@ -1 +0,0 @@
1
- import './effects';
@@ -1,45 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { createSignal, createEffect, disposeAll, krateHookState } from './signal';
3
- import './effects';
4
- import { __krateOptimistic, runActionTransition } from './actions';
5
- const tick = () => new Promise((r) => setTimeout(r, 0));
6
- async function settle() {
7
- for (let i = 0; i < 6; i++)
8
- await tick();
9
- }
10
- describe('state written at the end of an async action', () => {
11
- beforeEach(() => disposeAll());
12
- // The update cascades through several effects (optimistic state, a list
13
- // binding, row bindings). The action settles, and its optimistic revert
14
- // reads the committed state, in a microtask that used to run between two
15
- // passes of that cascade, before the state was committed.
16
- for (const hops of [0, 1, 2, 3, 4])
17
- it('survives an unrelated plain signal write in a later microtask (' + hops + ' hops)', async () => {
18
- const [messages, setMessages] = createSignal([{ text: 'hi' }], krateHookState);
19
- const [optimistic, setOptimistic] = createSignal(messages());
20
- const add = __krateOptimistic(() => messages(), setOptimistic, (s, text) => [...s, { text, sending: true }]);
21
- const [rows, setRows] = createSignal([]);
22
- createEffect(() => setRows(optimistic().map((m) => m.text + (m.sending ? '*' : ''))));
23
- const [label, setLabel] = createSignal('');
24
- createEffect(() => setLabel(rows().join(',')));
25
- const shown = [];
26
- createEffect(() => void shown.push(label()));
27
- await settle();
28
- void runActionTransition(async () => {
29
- add('hello');
30
- await new Promise((r) => setTimeout(r, 5));
31
- // A startTransition that writes its own pending signal afterwards.
32
- const s = createSignal(true);
33
- setMessages((m) => [...m, { text: 'hello' }]);
34
- queueMicrotask(() => s[1](false));
35
- // The action resolves a few microtasks later (the form action wrapper).
36
- for (let i = 0; i < hops; i++)
37
- await null;
38
- });
39
- await settle();
40
- await new Promise((r) => setTimeout(r, 20));
41
- expect(messages().map((m) => m.text)).toEqual(['hi', 'hello']);
42
- expect(optimistic().map((m) => m.text)).toEqual(['hi', 'hello']);
43
- expect(shown[shown.length - 1]).toBe('hi,hello');
44
- });
45
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,125 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { h, krateSpread } from './dom';
3
- import { createContext, krateContextRows } from './context';
4
- import { createSignal, krateDerived } from './signal';
5
- import { krateParam } from './hook-args';
6
- import { krateCondSwap } from './slots';
7
- import { krateOn } from './events';
8
- const tick = () => new Promise((r) => setTimeout(r, 0));
9
- const SVG_NS = 'http://www.w3.org/2000/svg';
10
- describe('SVG elements created by h()', () => {
11
- it('uses the SVG namespace for SVG-only tags and their children', () => {
12
- const svg = h('svg', { width: '10' }, h('g', null, h('circle', { r: '2' })));
13
- expect(svg.namespaceURI).toBe(SVG_NS);
14
- const circle = svg.querySelector('circle');
15
- expect(circle.namespaceURI).toBe(SVG_NS);
16
- expect(circle.parentElement.localName).toBe('g');
17
- });
18
- it('re-creates an ambiguous tag appended to an SVG parent in the SVG namespace', () => {
19
- const svg = h('svg', null, h('a', { href: '#x' }, h('path', { d: 'M0 0' })));
20
- const a = svg.querySelector('a');
21
- expect(a.namespaceURI).toBe(SVG_NS);
22
- expect(a.getAttribute('href')).toBe('#x');
23
- expect(a.firstElementChild.namespaceURI).toBe(SVG_NS);
24
- });
25
- it('keeps HTML inside a foreignObject', () => {
26
- const fo = h('svg', null, h('foreignObject', null, h('a', { href: '#y' }, 'x')));
27
- expect(fo.querySelector('a').namespaceURI).toBe('http://www.w3.org/1999/xhtml');
28
- });
29
- });
30
- describe('krateCondSwap with an SVG template', () => {
31
- it('unwraps the <svg> wrapper so the branch keeps the SVG namespace', () => {
32
- document.body.innerHTML =
33
- '<svg id="s"><!--k:c--><!--/k:c--></svg><template data-kc="c" data-kb="c" data-kns="svg"><svg><g id="grp"><path d="M0 0"></path></g></svg></template>';
34
- const start = document.querySelector('svg').firstChild;
35
- const tpl = document.querySelector('template');
36
- krateCondSwap(start, true, tpl);
37
- const g = document.getElementById('grp');
38
- expect(g.namespaceURI).toBe(SVG_NS);
39
- expect(g.parentElement.id).toBe('s');
40
- expect(g.firstElementChild.namespaceURI).toBe(SVG_NS);
41
- });
42
- });
43
- describe('krateSpread', () => {
44
- it('applies attributes and handlers and removes keys that disappear', async () => {
45
- const [on, setOn] = createSignal(true);
46
- const el = document.createElement('button');
47
- document.body.appendChild(el);
48
- let clicks = 0;
49
- krateSpread(el, () => (on() ? { title: 'x', className: 'a', onClick: () => clicks++ } : { className: 'b' }));
50
- expect(el.getAttribute('title')).toBe('x');
51
- expect(el.getAttribute('class')).toBe('a');
52
- el.dispatchEvent(new Event('click', { bubbles: true }));
53
- expect(clicks).toBe(1);
54
- setOn(false);
55
- await tick();
56
- expect(el.hasAttribute('title')).toBe(false);
57
- expect(el.getAttribute('class')).toBe('b');
58
- el.dispatchEvent(new Event('click', { bubbles: true }));
59
- expect(clicks).toBe(1);
60
- });
61
- });
62
- describe('krateSpread with function values', () => {
63
- it('writes no attribute for a function and binds on* handlers as events', async () => {
64
- const [n, setN] = createSignal(1);
65
- const el = document.createElement('div');
66
- document.body.appendChild(el);
67
- let clicks = 0;
68
- const props = { id: 'd', title: n, 'data-count': () => 1, onClick: () => clicks++, onclick2: () => 0 };
69
- krateSpread(el, () => props);
70
- expect(el.id).toBe('d');
71
- expect(el.hasAttribute('title')).toBe(false);
72
- expect(el.hasAttribute('data-count')).toBe(false);
73
- expect(el.hasAttribute('onclick2')).toBe(false);
74
- expect(el.outerHTML).not.toContain('=>');
75
- el.dispatchEvent(new Event('click', { bubbles: true }));
76
- expect(clicks).toBe(1);
77
- // A string that later becomes a function drops the attribute.
78
- const [v, setV] = createSignal('t');
79
- const el2 = document.createElement('div');
80
- document.body.appendChild(el2);
81
- krateSpread(el2, () => ({ title: v() }));
82
- expect(el2.getAttribute('title')).toBe('t');
83
- setV(() => () => 5);
84
- await tick();
85
- expect(el2.hasAttribute('title')).toBe(false);
86
- setN(2);
87
- });
88
- });
89
- describe('krateContextRows', () => {
90
- it('shows live provider values to rows created under it', async () => {
91
- const Sel = createContext('');
92
- const [sel, setSel] = createSignal('a');
93
- const row = krateContextRows([[Sel, () => sel()]], () => Sel.useContextLive());
94
- const read = row();
95
- expect(read()).toBe('a');
96
- setSel('b');
97
- expect(read()).toBe('b');
98
- // Outside the rows the context has its default again.
99
- expect(Sel.useContext()).toBe('');
100
- });
101
- });
102
- describe('krateParam', () => {
103
- it('unwraps a derived getter argument and passes other values through', () => {
104
- const [n, setN] = createSignal(1);
105
- const arg = krateDerived(() => n() * 2);
106
- expect(krateParam(arg)).toBe(2);
107
- setN(2);
108
- expect(krateParam(arg)).toBe(4);
109
- expect(krateParam(5)).toBe(5);
110
- const fn = () => 1;
111
- expect(krateParam(fn)).toBe(fn);
112
- });
113
- });
114
- describe('krateOn unaffected by spread removal', () => {
115
- it('removes a handler with null', () => {
116
- const el = document.createElement('div');
117
- document.body.appendChild(el);
118
- let n = 0;
119
- krateOn(el, 'onClick', () => n++);
120
- el.dispatchEvent(new Event('click', { bubbles: true }));
121
- krateOn(el, 'onClick', null);
122
- el.dispatchEvent(new Event('click', { bubbles: true }));
123
- expect(n).toBe(1);
124
- });
125
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,99 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { krateMountPortals, kratePortalFind, kratePortalReset, kratePortalScan, kratePortalTarget } from './portal';
3
- import { krateCondSwap } from './slots';
4
- import { krateOn } from './events';
5
- import { disposeNode } from './dom';
6
- import { createPortal } from './react';
7
- function startMarker(root, id) {
8
- const w = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
9
- while (w.nextNode()) {
10
- if (w.currentNode.nodeValue === 'k:' + id)
11
- return w.currentNode;
12
- }
13
- throw new Error('marker not found: ' + id);
14
- }
15
- const bodyChildren = () => Array.from(document.body.children).map((el) => el.id || el.tagName.toLowerCase());
16
- describe('portals', () => {
17
- beforeEach(() => {
18
- kratePortalReset();
19
- document.body.innerHTML = '';
20
- });
21
- it('mounts portal content into body and bubbles events through the React tree', () => {
22
- document.body.innerHTML =
23
- '<div id="root"><div id="host"><template data-krate-portal="p1"><div id="toast"><button id="btn">ok</button></div></template></div></div>';
24
- const host = document.getElementById('host');
25
- const btn = document.querySelector('template').content.querySelector('#btn');
26
- const seen = [];
27
- krateOn(btn, 'onClick', () => seen.push('button'));
28
- krateOn(host, 'onClick', () => seen.push('host'));
29
- krateMountPortals();
30
- expect(bodyChildren()).toEqual(['root', 'toast']);
31
- expect(document.getElementById('btn')).toBe(btn);
32
- btn.click();
33
- expect(seen).toEqual(['button', 'host']);
34
- });
35
- it('mounts into a selector or registered container', () => {
36
- document.body.innerHTML =
37
- '<div id="root"><template data-krate-portal="a" data-krate-portal-target="#modal-root"><p id="a">a</p></template>' +
38
- '<template data-krate-portal="b"><p id="b">b</p></template></div><div id="modal-root"></div><div id="side"></div>';
39
- kratePortalTarget('b', () => document.getElementById('side'));
40
- krateMountPortals();
41
- expect(document.getElementById('a').parentElement.id).toBe('modal-root');
42
- expect(document.getElementById('b').parentElement.id).toBe('side');
43
- });
44
- it('follows its conditional branch: unmounts when hidden, remounts when shown', () => {
45
- document.body.innerHTML =
46
- '<div id="root"><!--k:c--><!--/k:c--></div>' +
47
- '<template data-kc="c" data-kb="c"><template data-krate-portal="m"><div id="modal">hi</div></template></template>';
48
- const start = startMarker(document.body, 'c');
49
- const tpl = document.querySelector('template[data-kc]');
50
- krateCondSwap(start, false, tpl);
51
- krateMountPortals();
52
- expect(document.getElementById('modal')).toBeNull();
53
- krateCondSwap(start, true, tpl);
54
- expect(bodyChildren()).toContain('modal');
55
- const modal = document.getElementById('modal');
56
- krateCondSwap(start, false, tpl);
57
- expect(document.getElementById('modal')).toBeNull();
58
- krateCondSwap(start, true, tpl);
59
- expect(document.getElementById('modal')).toBe(modal);
60
- });
61
- it('drops the content when the anchor is disposed', () => {
62
- document.body.innerHTML = '<div id="root"><span id="wrap"><template data-krate-portal="d"><i id="x">x</i></template></span></div>';
63
- krateMountPortals();
64
- expect(document.getElementById('x')).not.toBeNull();
65
- disposeNode(document.getElementById('wrap'));
66
- expect(document.getElementById('x')).toBeNull();
67
- });
68
- it('finds bound nodes in portal templates before and after mounting', () => {
69
- document.body.innerHTML = '<div id="root"><template data-krate-portal="f"><b data-k="k:9">b</b><!--k:8--><!--/k:8--></template></div>';
70
- const root = document.getElementById('root');
71
- const before = kratePortalFind('[data-k="k:9"]', [root]);
72
- expect(before).not.toBeNull();
73
- const comments = [];
74
- kratePortalScan([root], (content) => {
75
- const w = document.createTreeWalker(content, NodeFilter.SHOW_COMMENT);
76
- while (w.nextNode())
77
- comments.push(String(w.currentNode.nodeValue));
78
- });
79
- expect(comments).toContain('k:8');
80
- krateMountPortals();
81
- expect(kratePortalFind('[data-k="k:9"]', [root])).toBe(before);
82
- });
83
- it('runtime createPortal returns an anchor and removes content on dispose', () => {
84
- document.body.innerHTML = '<div id="root"><div id="host"></div></div>';
85
- const host = document.getElementById('host');
86
- const content = document.createElement('p');
87
- content.id = 'rt';
88
- const seen = [];
89
- krateOn(host, 'onClick', () => seen.push('host'));
90
- const anchor = createPortal(content, document.body);
91
- host.appendChild(anchor);
92
- expect(anchor.nodeType).toBe(8);
93
- expect(content.parentNode).toBe(document.body);
94
- content.click();
95
- expect(seen).toEqual(['host']);
96
- disposeNode(anchor);
97
- expect(document.getElementById('rt')).toBeNull();
98
- });
99
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,133 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { useEffect, useLayoutEffect, useInsertionEffect, useState, useReducer, useMemo, useCallback, useImperativeHandle, createElement, } from './react';
3
- import { disposeAll } from './signal';
4
- import { flushPassive } from './effects';
5
- import { disposeNode } from './dom';
6
- const tick = () => new Promise((r) => setTimeout(r, 0));
7
- async function settle() {
8
- for (let i = 0; i < 3; i++)
9
- await tick();
10
- }
11
- describe('React compat hooks (unlowered code paths)', () => {
12
- beforeEach(() => disposeAll());
13
- it('runs insertion, layout and passive effects in React order', async () => {
14
- const log = [];
15
- const Child = () => {
16
- useEffect(() => void log.push('child passive'), []);
17
- useLayoutEffect(() => void log.push('child layout'), []);
18
- useInsertionEffect(() => void log.push('child insertion'), []);
19
- return createElement('i', null);
20
- };
21
- const Parent = () => {
22
- useEffect(() => void log.push('parent passive'), []);
23
- useLayoutEffect(() => void log.push('parent layout'), []);
24
- return createElement('div', null, createElement(Child, null));
25
- };
26
- createElement(Parent, null);
27
- await settle();
28
- expect(log).toEqual(['child insertion', 'child layout', 'parent layout', 'child passive', 'parent passive']);
29
- });
30
- it('honours dependency arrays whose elements are state getters', async () => {
31
- const log = [];
32
- let setCount;
33
- let other;
34
- const Comp = () => {
35
- const [count, set] = useState(0);
36
- const [, setOther] = useState(0);
37
- setCount = set;
38
- other = setOther;
39
- useEffect(() => void log.push(count()), [count]);
40
- return createElement('span', null);
41
- };
42
- createElement(Comp, null);
43
- await settle();
44
- other(1);
45
- await settle();
46
- expect(log).toEqual([0]);
47
- setCount(1);
48
- await settle();
49
- expect(log).toEqual([0, 1]);
50
- });
51
- it('runs cleanups when the component unmounts', async () => {
52
- const log = [];
53
- const Comp = () => {
54
- useEffect(() => () => void log.push('passive cleanup'), []);
55
- useLayoutEffect(() => () => void log.push('layout cleanup'), []);
56
- return createElement('span', null);
57
- };
58
- const node = createElement(Comp, null);
59
- await settle();
60
- disposeNode(node);
61
- await settle();
62
- expect(log).toEqual(['layout cleanup', 'passive cleanup']);
63
- });
64
- it('keeps useMemo and useCallback values stable for the component lifetime', () => {
65
- let calls = 0;
66
- const fn = () => 1;
67
- const memo = useMemo(() => ++calls, [1]);
68
- expect(memo).toBe(1);
69
- expect(useCallback(fn, [])).toBe(fn);
70
- });
71
- it('supports the useReducer lazy initializer and bail-out', async () => {
72
- const [state, dispatch] = useReducer((s, a) => (a === 0 ? s : s + a), 2, (n) => n * 3);
73
- expect(state()).toBe(6);
74
- let runs = 0;
75
- useEffect(() => void runs++, [state]);
76
- await settle();
77
- dispatch(0);
78
- await settle();
79
- expect(runs).toBe(1);
80
- dispatch(1);
81
- await settle();
82
- expect(runs).toBe(2);
83
- });
84
- it('attaches imperative handles in the layout phase and detaches on unmount', async () => {
85
- const ref = { current: null };
86
- const Comp = () => {
87
- useImperativeHandle(ref, () => ({ focus: () => 'focused' }), []);
88
- return createElement('input', null);
89
- };
90
- const node = createElement(Comp, null);
91
- expect(ref.current).toBe(null);
92
- await Promise.resolve();
93
- expect(ref.current?.focus()).toBe('focused');
94
- disposeNode(node);
95
- expect(ref.current).toBe(null);
96
- });
97
- it('a passive cleanup that throws does not drop the effects queued behind it', async () => {
98
- const log = [];
99
- let set;
100
- const A = () => {
101
- const [n, s] = useState(0);
102
- set = s;
103
- useEffect(() => {
104
- log.push('A setup ' + n());
105
- return () => {
106
- log.push('A cleanup');
107
- throw new Error('cleanup boom');
108
- };
109
- }, [n]);
110
- return createElement('i', null);
111
- };
112
- const B = () => {
113
- const [m] = useState(0);
114
- useEffect(() => {
115
- log.push('B setup');
116
- return () => void log.push('B cleanup');
117
- }, [m]);
118
- return createElement('b', null);
119
- };
120
- createElement('div', null, createElement(A, null), createElement(B, null));
121
- await settle();
122
- set(1);
123
- // The passive phase reports the error after running everything queued.
124
- let failure;
125
- const onError = (e) => (failure = e);
126
- process.once('uncaughtException', onError);
127
- await settle();
128
- process.off('uncaughtException', onError);
129
- expect(String(failure)).toContain('cleanup boom');
130
- expect(log).toEqual(['A setup 0', 'B setup', 'A cleanup', 'A setup 1']);
131
- flushPassive();
132
- });
133
- });
@@ -1 +0,0 @@
1
- export {};