@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.1

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 (57) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +83 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/cache-scope.js +4 -1
  8. package/dist/cache.test.js +16 -0
  9. package/dist/class-helpers.d.ts +4 -4
  10. package/dist/class-helpers.js +357 -32
  11. package/dist/class-helpers.test.d.ts +1 -0
  12. package/dist/class-helpers.test.js +169 -0
  13. package/dist/context.d.ts +16 -2
  14. package/dist/context.js +44 -3
  15. package/dist/dev-overlay.js +75 -2
  16. package/dist/dev-overlay.test.js +22 -0
  17. package/dist/dom.d.ts +7 -0
  18. package/dist/dom.js +69 -3
  19. package/dist/error-overlay.js +4 -4
  20. package/dist/hook-args.d.ts +7 -0
  21. package/dist/hook-args.js +10 -0
  22. package/dist/htmlspec-attributes.d.ts +1 -0
  23. package/dist/htmlspec-attributes.js +159 -0
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.js +1 -0
  26. package/dist/krate-core.js +2 -0
  27. package/dist/krate-dev.js +65 -2
  28. package/dist/krate-f-actions.js +2 -0
  29. package/dist/krate-f-classes.js +8 -0
  30. package/dist/krate-f-helpers.js +2 -0
  31. package/dist/krate-f-list.js +2 -0
  32. package/dist/krate-f-router-lite.js +2 -0
  33. package/dist/krate-f-router.js +2 -0
  34. package/dist/krate-features.json +239 -0
  35. package/dist/krate-hydrate-lite.js +5 -5
  36. package/dist/krate-hydrate.js +5 -5
  37. package/dist/krate-runtime.js +5 -5
  38. package/dist/patterns.test.d.ts +1 -0
  39. package/dist/patterns.test.js +98 -0
  40. package/dist/reactivity-core.test.d.ts +1 -0
  41. package/dist/reactivity-core.test.js +152 -0
  42. package/dist/reconcile.js +4 -2
  43. package/dist/router-nav.test.js +38 -0
  44. package/dist/router-speculation.test.d.ts +1 -0
  45. package/dist/router-speculation.test.js +25 -0
  46. package/dist/router-styles.test.d.ts +1 -0
  47. package/dist/router-styles.test.js +98 -0
  48. package/dist/router.js +116 -32
  49. package/dist/server-async.test.js +20 -0
  50. package/dist/server-renderer.js +109 -22
  51. package/dist/server.d.ts +1 -0
  52. package/dist/server.js +90 -11
  53. package/dist/server.test.js +20 -0
  54. package/dist/signal.d.ts +3 -2
  55. package/dist/signal.js +104 -19
  56. package/dist/slots.js +12 -1
  57. package/package.json +2 -2
@@ -0,0 +1,98 @@
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('krateContextRows', () => {
63
+ it('shows live provider values to rows created under it', async () => {
64
+ const Sel = createContext('');
65
+ const [sel, setSel] = createSignal('a');
66
+ const row = krateContextRows([[Sel, () => sel()]], () => Sel.useContextLive());
67
+ const read = row();
68
+ expect(read()).toBe('a');
69
+ setSel('b');
70
+ expect(read()).toBe('b');
71
+ // Outside the rows the context has its default again.
72
+ expect(Sel.useContext()).toBe('');
73
+ });
74
+ });
75
+ describe('krateParam', () => {
76
+ it('unwraps a derived getter argument and passes other values through', () => {
77
+ const [n, setN] = createSignal(1);
78
+ const arg = krateDerived(() => n() * 2);
79
+ expect(krateParam(arg)).toBe(2);
80
+ setN(2);
81
+ expect(krateParam(arg)).toBe(4);
82
+ expect(krateParam(5)).toBe(5);
83
+ const fn = () => 1;
84
+ expect(krateParam(fn)).toBe(fn);
85
+ });
86
+ });
87
+ describe('krateOn unaffected by spread removal', () => {
88
+ it('removes a handler with null', () => {
89
+ const el = document.createElement('div');
90
+ document.body.appendChild(el);
91
+ let n = 0;
92
+ krateOn(el, 'onClick', () => n++);
93
+ el.dispatchEvent(new Event('click', { bubbles: true }));
94
+ krateOn(el, 'onClick', null);
95
+ el.dispatchEvent(new Event('click', { bubbles: true }));
96
+ expect(n).toBe(1);
97
+ });
98
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,152 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { createSignal, createEffect, createMemo, disposeAll, krateFlushSync, onCleanup } from './signal';
3
+ const tick = () => new Promise((r) => setTimeout(r, 0));
4
+ describe('effect update loops', () => {
5
+ beforeEach(() => disposeAll());
6
+ it('throws Maximum update depth exceeded for two effects that feed each other', () => {
7
+ const [a, setA] = createSignal(0);
8
+ const [b, setB] = createSignal(0);
9
+ createEffect(() => setB(a() + 1));
10
+ createEffect(() => setA(b() + 1));
11
+ expect(() => krateFlushSync()).toThrow(/Maximum update depth exceeded/);
12
+ // The queue was dropped: nothing is pending and later writes still work.
13
+ expect(() => krateFlushSync()).not.toThrow();
14
+ let seen = -1;
15
+ createEffect(() => {
16
+ seen = 1;
17
+ });
18
+ expect(seen).toBe(1);
19
+ });
20
+ it('keeps the event loop responsive after the loop is reported', async () => {
21
+ const [a, setA] = createSignal(0);
22
+ const [b, setB] = createSignal(0);
23
+ createEffect(() => setB(a() + 1));
24
+ createEffect(() => setA(b() + 1));
25
+ try {
26
+ krateFlushSync();
27
+ }
28
+ catch {
29
+ // reported
30
+ }
31
+ let ticked = false;
32
+ setTimeout(() => (ticked = true), 0);
33
+ await tick();
34
+ expect(ticked).toBe(true);
35
+ });
36
+ it('names the looping effect in the message', () => {
37
+ const [a, setA] = createSignal(0);
38
+ createEffect(function bumpCounter() {
39
+ setA(a() + 1);
40
+ });
41
+ // A self-write only reruns once; add a partner to make it loop.
42
+ const [b, setB] = createSignal(0);
43
+ createEffect(function ping() {
44
+ setB(a() + 1);
45
+ });
46
+ createEffect(function pong() {
47
+ setA(b() + 1);
48
+ });
49
+ expect(() => krateFlushSync()).toThrow(/ping|pong|bumpCounter/);
50
+ });
51
+ it('still settles a long but finite cascade', () => {
52
+ const sigs = Array.from({ length: 30 }, () => createSignal(0));
53
+ for (let i = 1; i < sigs.length; i++) {
54
+ createEffect(() => sigs[i][1](sigs[i - 1][0]() + 1));
55
+ }
56
+ sigs[0][1](1);
57
+ krateFlushSync();
58
+ expect(sigs[29][0]()).toBe(30);
59
+ });
60
+ });
61
+ describe('effect dependency tracking', () => {
62
+ beforeEach(() => disposeAll());
63
+ it('drops dependencies the last run did not read', () => {
64
+ const [cond, setCond] = createSignal(true);
65
+ const [x, setX] = createSignal(0);
66
+ const [y] = createSignal(0);
67
+ let runs = 0;
68
+ createEffect(() => {
69
+ runs++;
70
+ cond() ? x() : y();
71
+ });
72
+ expect(runs).toBe(1);
73
+ setCond(false);
74
+ krateFlushSync();
75
+ expect(runs).toBe(2);
76
+ setX(5);
77
+ krateFlushSync();
78
+ setX(6);
79
+ krateFlushSync();
80
+ expect(runs).toBe(2);
81
+ });
82
+ });
83
+ describe('nested effects', () => {
84
+ beforeEach(() => disposeAll());
85
+ it('disposes an inner effect when the parent effect re-runs', () => {
86
+ const [a, setA] = createSignal(0);
87
+ const [b, setB] = createSignal(0);
88
+ let innerRuns = 0;
89
+ createEffect(() => {
90
+ a();
91
+ createEffect(() => {
92
+ b();
93
+ innerRuns++;
94
+ });
95
+ });
96
+ expect(innerRuns).toBe(1);
97
+ setA(1);
98
+ krateFlushSync();
99
+ setA(2);
100
+ krateFlushSync();
101
+ expect(innerRuns).toBe(3);
102
+ innerRuns = 0;
103
+ setB(1);
104
+ krateFlushSync();
105
+ expect(innerRuns).toBe(1);
106
+ });
107
+ it('runs the inner effect cleanup when the parent re-runs', () => {
108
+ const [a, setA] = createSignal(0);
109
+ const log = [];
110
+ createEffect(() => {
111
+ const v = a();
112
+ createEffect(() => {
113
+ onCleanup(() => log.push('clean' + v));
114
+ });
115
+ });
116
+ setA(1);
117
+ krateFlushSync();
118
+ expect(log).toEqual(['clean0']);
119
+ });
120
+ });
121
+ describe('createMemo', () => {
122
+ beforeEach(() => disposeAll());
123
+ it('is current on a synchronous read after a write', () => {
124
+ const [a, setA] = createSignal(1);
125
+ const m = createMemo(() => a() * 10);
126
+ expect(m()).toBe(10);
127
+ setA(5);
128
+ expect(m()).toBe(50);
129
+ });
130
+ it('memoizes between writes and propagates to effects once', () => {
131
+ const [a, setA] = createSignal(1);
132
+ let computes = 0;
133
+ const m = createMemo(() => {
134
+ computes++;
135
+ return a() % 2;
136
+ });
137
+ let runs = 0;
138
+ createEffect(() => {
139
+ m();
140
+ runs++;
141
+ });
142
+ expect(m()).toBe(1);
143
+ expect(m()).toBe(1);
144
+ expect(computes).toBe(1);
145
+ setA(3);
146
+ krateFlushSync();
147
+ expect(runs).toBe(1);
148
+ setA(4);
149
+ krateFlushSync();
150
+ expect(runs).toBe(2);
151
+ });
152
+ });
package/dist/reconcile.js CHANGED
@@ -173,8 +173,9 @@ function syncAttributes(oldEl, newEl) {
173
173
  oldEl.setAttribute(name, value);
174
174
  }
175
175
  }
176
- // Pass 2: remove attributes no longer present.
177
- for (let i = 0; i < oldEl.attributes.length; i++) {
176
+ // Pass 2: remove attributes no longer present. Iterate backwards because
177
+ // removing an attribute shifts the live NamedNodeMap left.
178
+ for (let i = oldEl.attributes.length - 1; i >= 0; i--) {
178
179
  const name = oldEl.attributes[i].name;
179
180
  if (!newNames.has(name)) {
180
181
  oldEl.removeAttribute(name);
@@ -336,6 +337,7 @@ export function reconcileTrees(oldRoot, newRoot) {
336
337
  if (oldEl.tagName !== newEl.tagName) {
337
338
  const imported = document.importNode(newRoot, true);
338
339
  if (oldEl.parentNode) {
340
+ disposeNode(oldEl);
339
341
  oldEl.parentNode.replaceChild(imported, oldEl);
340
342
  }
341
343
  return;
@@ -397,3 +397,41 @@ describe('focus', () => {
397
397
  expect(root.hasAttribute('tabindex')).toBe(false);
398
398
  });
399
399
  });
400
+ describe('fallback fade and reduced motion', () => {
401
+ function stubReducedMotion(reduce) {
402
+ vi.stubGlobal('matchMedia', (q) => ({
403
+ matches: reduce && q.includes('prefers-reduced-motion'),
404
+ media: q,
405
+ addEventListener() { },
406
+ removeEventListener() { },
407
+ addListener() { },
408
+ removeListener() { },
409
+ }));
410
+ window.matchMedia = globalThis.matchMedia;
411
+ }
412
+ async function rootStyleDuringFetch() {
413
+ let release;
414
+ routes['/about'].gate = new Promise((r) => (release = r));
415
+ const p = krateRouter.push('/about');
416
+ await settle();
417
+ const el = document.getElementById('root');
418
+ const seen = { transition: el.style.transition, opacity: el.style.opacity };
419
+ release();
420
+ await p;
421
+ await settle();
422
+ return seen;
423
+ }
424
+ it('applies the opacity fade without View Transitions', async () => {
425
+ stubReducedMotion(false);
426
+ const seen = await rootStyleDuringFetch();
427
+ expect(seen.opacity).toBe('0');
428
+ expect(seen.transition).toContain('opacity');
429
+ });
430
+ it('applies no fade under prefers-reduced-motion', async () => {
431
+ stubReducedMotion(true);
432
+ const seen = await rootStyleDuringFetch();
433
+ expect(seen.opacity).toBe('');
434
+ expect(seen.transition).toBe('');
435
+ expect(document.querySelector('#root h1').textContent).toBe('About');
436
+ });
437
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { describe, it, expect, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter } from './router';
3
+ function boot(head) {
4
+ destroyRouter();
5
+ globalThis.__KRATE_CFG__ = { viewTransitions: false };
6
+ document.head.innerHTML = '<title>x</title>' + head;
7
+ document.body.innerHTML = '<div id="root"></div>';
8
+ initRouter();
9
+ }
10
+ describe('router speculation rules', () => {
11
+ afterEach(() => {
12
+ destroyRouter();
13
+ vi.unstubAllGlobals();
14
+ });
15
+ it('injects the rules when the browser supports them and no CSP meta exists', () => {
16
+ HTMLScriptElement.supports = (t) => t === 'speculationrules';
17
+ boot('');
18
+ expect(document.querySelector('script[type="speculationrules"]')).not.toBeNull();
19
+ });
20
+ it('skips the inline rules under a CSP meta', () => {
21
+ HTMLScriptElement.supports = (t) => t === 'speculationrules';
22
+ boot('<meta http-equiv="Content-Security-Policy" content="script-src \'self\'">');
23
+ expect(document.querySelector('script[type="speculationrules"]')).toBeNull();
24
+ });
25
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,98 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter, navigate } from './router';
3
+ function page(title, head, body) {
4
+ return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
5
+ }
6
+ const sheet = (name) => `<link rel="stylesheet" href="/${name}.css">`;
7
+ let routes;
8
+ function hrefs() {
9
+ return Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map((l) => new URL(l.href).pathname);
10
+ }
11
+ function linkFor(name) {
12
+ return Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find((l) => new URL(l.href).pathname === `/${name}.css`) ?? null;
13
+ }
14
+ async function tick() {
15
+ for (let i = 0; i < 20; i++)
16
+ await Promise.resolve();
17
+ await new Promise((r) => setTimeout(r, 0));
18
+ for (let i = 0; i < 20; i++)
19
+ await Promise.resolve();
20
+ }
21
+ beforeEach(() => {
22
+ destroyRouter();
23
+ globalThis.__KRATE_CFG__ = { viewTransitions: false };
24
+ history.replaceState(null, '', '/');
25
+ routes = {};
26
+ // happy-dom tries to fetch the stylesheets; the tests settle them by hand.
27
+ vi.spyOn(console, 'error').mockImplementation(() => { });
28
+ vi.stubGlobal('fetch', vi.fn(async (input) => {
29
+ const u = new URL(input, location.href);
30
+ const body = routes[u.pathname] ?? '';
31
+ return {
32
+ ok: true,
33
+ status: 200,
34
+ url: u.href,
35
+ redirected: false,
36
+ headers: new Headers({ 'content-type': 'text/html; charset=utf-8' }),
37
+ text: async () => body,
38
+ };
39
+ }));
40
+ document.head.innerHTML = '<title>Home</title>' + sheet('page-a') + sheet('tw');
41
+ document.body.innerHTML = '<div id="root"><p>home</p></div>';
42
+ initRouter();
43
+ });
44
+ afterEach(() => {
45
+ destroyRouter();
46
+ vi.unstubAllGlobals();
47
+ vi.restoreAllMocks();
48
+ vi.useRealTimers();
49
+ });
50
+ describe('router stylesheets', () => {
51
+ it('keeps the incoming document order and removes stale sheets after the swap', async () => {
52
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
53
+ const nav = navigate('/b');
54
+ await tick();
55
+ // Still on the old page: the old sheet stays until the new one loaded.
56
+ expect(document.querySelector('#root').textContent).toBe('home');
57
+ expect(linkFor('page-a')).not.toBeNull();
58
+ const added = linkFor('page-b');
59
+ expect(added.getAttribute('media')).toBe('not all');
60
+ added.dispatchEvent(new Event('load'));
61
+ await nav;
62
+ await tick();
63
+ expect(document.querySelector('#root').textContent).toBe('b');
64
+ expect(hrefs()).toEqual(['/page-b.css', '/tw.css']);
65
+ expect(linkFor('page-b').hasAttribute('media')).toBe(false);
66
+ });
67
+ it('waits for the new sheet to load before swapping', async () => {
68
+ routes['/b'] = page('B', sheet('tw') + sheet('page-b'), '<p>b</p>');
69
+ const nav = navigate('/b');
70
+ await tick();
71
+ expect(document.querySelector('#root').textContent).toBe('home');
72
+ expect(hrefs()).toEqual(['/page-a.css', '/tw.css', '/page-b.css']);
73
+ linkFor('page-b').dispatchEvent(new Event('load'));
74
+ await nav;
75
+ await tick();
76
+ expect(document.querySelector('#root').textContent).toBe('b');
77
+ expect(hrefs()).toEqual(['/tw.css', '/page-b.css']);
78
+ });
79
+ it('proceeds when a stylesheet fails to load', async () => {
80
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
81
+ const nav = navigate('/b');
82
+ await tick();
83
+ linkFor('page-b').dispatchEvent(new Event('error'));
84
+ await nav;
85
+ await tick();
86
+ expect(document.querySelector('#root').textContent).toBe('b');
87
+ });
88
+ it('proceeds after the timeout when a stylesheet never settles', async () => {
89
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
90
+ vi.useFakeTimers();
91
+ const nav = navigate('/b');
92
+ await vi.advanceTimersByTimeAsync(3100);
93
+ await nav;
94
+ await vi.advanceTimersByTimeAsync(10);
95
+ expect(document.querySelector('#root').textContent).toBe('b');
96
+ expect(hrefs()).toEqual(['/page-b.css', '/tw.css']);
97
+ });
98
+ });
package/dist/router.js CHANGED
@@ -428,6 +428,11 @@ function setupSpeculationRules() {
428
428
  const supports = typeof HTMLScriptElement !== 'undefined' ? HTMLScriptElement.supports : undefined;
429
429
  if (typeof supports !== 'function' || !supports('speculationrules'))
430
430
  return;
431
+ // An inline speculation-rules script needs a CSP hash or keyword that is not
432
+ // honoured next to script hashes, so under a CSP meta the JS prefetch path
433
+ // is used instead of emitting a blocked script.
434
+ if (document.querySelector('meta[http-equiv="Content-Security-Policy" i]'))
435
+ return;
431
436
  try {
432
437
  const script = document.createElement('script');
433
438
  script.type = 'speculationrules';
@@ -452,19 +457,24 @@ function setupSpeculationRules() {
452
457
  }
453
458
  }
454
459
  // Visual transition
455
- /** Whether native View Transitions should wrap the SPA mutation. */
456
- function supportsViewTransitions() {
457
- if (runtimeConfig().viewTransitions === false)
458
- return false;
460
+ /** Whether the user asked the OS/browser for reduced motion. */
461
+ function prefersReducedMotion() {
459
462
  if (typeof window !== 'undefined' && window.matchMedia) {
460
463
  try {
461
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches)
462
- return false;
464
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
463
465
  }
464
466
  catch {
465
467
  /* ignore */
466
468
  }
467
469
  }
470
+ return false;
471
+ }
472
+ /** Whether native View Transitions should wrap the SPA mutation. */
473
+ function supportsViewTransitions() {
474
+ if (runtimeConfig().viewTransitions === false)
475
+ return false;
476
+ if (prefersReducedMotion())
477
+ return false;
468
478
  return typeof document.startViewTransition === 'function';
469
479
  }
470
480
  function appRoot(doc) {
@@ -481,7 +491,8 @@ function beginTransition() {
481
491
  loadingOverlay = Array.from(frag.childNodes);
482
492
  document.body.appendChild(frag);
483
493
  }
484
- if (!supportsViewTransitions()) {
494
+ // Reduced motion: no fade at all (the overlay above is static).
495
+ if (!supportsViewTransitions() && !prefersReducedMotion()) {
485
496
  const el = appRoot(document);
486
497
  el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
487
498
  el.style.opacity = '0';
@@ -510,34 +521,94 @@ function applyViewTransitionNames(root) {
510
521
  });
511
522
  }
512
523
  // Document reconciliation
513
- /** Diff stylesheet <link>s by absolute URL (base-path and format safe). */
514
- function reconcileStylesheets(doc, baseUrl) {
515
- const newStyles = doc.querySelectorAll('link[rel="stylesheet"]');
516
- const newHrefs = new Set();
517
- newStyles.forEach((s) => {
518
- const href = s.getAttribute('href');
519
- if (href)
520
- newHrefs.add(new URL(href, baseUrl).href);
521
- });
522
- document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
523
- const abs = l.href;
524
- if (abs && !newHrefs.has(abs))
525
- l.remove();
526
- });
527
- const existing = new Set();
528
- document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
529
- newStyles.forEach((s) => {
524
+ /** How long a navigation waits for new stylesheets before swapping anyway. */
525
+ const STYLESHEET_TIMEOUT_MS = 3000;
526
+ /**
527
+ * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
528
+ * links are inserted at the position they have in the incoming document (before
529
+ * the next kept link), so the cascade order matches a hard load. They load with
530
+ * media="not all" so they do not affect the outgoing page; stale links stay
531
+ * until commit() so the old page keeps its styles while the new ones load.
532
+ */
533
+ function prepareStylesheets(doc, baseUrl) {
534
+ const incoming = [];
535
+ doc.querySelectorAll('link[rel="stylesheet"]').forEach((s) => {
530
536
  const href = s.getAttribute('href');
531
537
  if (!href)
532
538
  return;
533
539
  const abs = new URL(href, baseUrl).href;
534
- if (!existing.has(abs)) {
540
+ if (!incoming.includes(abs))
541
+ incoming.push(abs);
542
+ });
543
+ const live = new Map();
544
+ const stale = [];
545
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
546
+ const el = l;
547
+ if (!el.href)
548
+ return;
549
+ if (incoming.includes(el.href) && !live.has(el.href))
550
+ live.set(el.href, el);
551
+ else
552
+ stale.push(el);
553
+ });
554
+ const added = [];
555
+ const pending = [];
556
+ let prev = null;
557
+ incoming.forEach((abs, i) => {
558
+ let el = live.get(abs) || null;
559
+ if (!el) {
535
560
  const link = document.createElement('link');
536
561
  link.rel = 'stylesheet';
537
562
  link.href = abs;
538
- document.head.appendChild(link);
563
+ // Listen before insertion so a synchronous settle is not missed.
564
+ pending.push(new Promise((resolve) => {
565
+ const done = () => {
566
+ link.removeEventListener('load', done);
567
+ link.removeEventListener('error', done);
568
+ resolve();
569
+ };
570
+ link.addEventListener('load', done);
571
+ link.addEventListener('error', done);
572
+ }));
573
+ added.push({ link, media: link.getAttribute('media') });
574
+ link.media = 'not all';
575
+ if (prev) {
576
+ prev.after(link);
577
+ }
578
+ else {
579
+ const nextKept = incoming.slice(i + 1).map((h) => live.get(h)).find((l) => !!l);
580
+ if (nextKept)
581
+ nextKept.before(link);
582
+ else
583
+ document.head.appendChild(link);
584
+ }
585
+ el = link;
539
586
  }
587
+ prev = el;
540
588
  });
589
+ let ready = Promise.resolve();
590
+ if (pending.length > 0) {
591
+ let timer;
592
+ const timeout = new Promise((resolve) => {
593
+ timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
594
+ });
595
+ ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
596
+ }
597
+ return {
598
+ ready,
599
+ commit() {
600
+ for (const { link, media } of added) {
601
+ if (media === null)
602
+ link.removeAttribute('media');
603
+ else
604
+ link.setAttribute('media', media);
605
+ }
606
+ stale.forEach((l) => l.remove());
607
+ },
608
+ abort() {
609
+ added.forEach(({ link }) => link.remove());
610
+ },
611
+ };
541
612
  }
542
613
  // Document-level <head> tags that change per page and must follow a swap.
543
614
  const HEAD_SYNC_SEL = 'meta[name="description"], meta[name="robots"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], script[type="application/ld+json"]';
@@ -551,6 +622,7 @@ function scriptsToLoad(doc, baseUrl) {
551
622
  const keep = new Set();
552
623
  document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
553
624
  const out = [];
625
+ const seen = new Set();
554
626
  doc.querySelectorAll('script[src]').forEach((s) => {
555
627
  const src = s.getAttribute('src');
556
628
  if (!src)
@@ -559,18 +631,22 @@ function scriptsToLoad(doc, baseUrl) {
559
631
  if (t && t !== 'module' && t !== 'text/javascript' && t !== 'application/javascript')
560
632
  return;
561
633
  const abs = resolveSrc(src, baseUrl);
562
- if (!keep.has(abs) && !out.includes(abs))
563
- out.push(abs);
634
+ if (!keep.has(abs) && !seen.has(abs)) {
635
+ seen.add(abs);
636
+ out.push({ src: abs, module: t === 'module' });
637
+ }
564
638
  });
565
639
  return out;
566
640
  }
567
- function loadScript(src) {
641
+ function loadScript(script) {
568
642
  return new Promise((resolve) => {
569
643
  const s = document.createElement('script');
570
- s.src = src;
644
+ s.src = script.src;
645
+ if (script.module)
646
+ s.type = 'module';
571
647
  // Only page scripts are disposable across navigations; the shared runtime
572
648
  // chunk stays in place.
573
- if (!RUNTIME_CHUNK_RE.test(src))
649
+ if (!RUNTIME_CHUNK_RE.test(script.src))
574
650
  s.setAttribute('data-krate-spa', '');
575
651
  s.onload = () => resolve(true);
576
652
  s.onerror = () => resolve(false);
@@ -825,6 +901,14 @@ async function commitDocument(loaded, req, seq) {
825
901
  saveScroll(currentKey);
826
902
  const newChain = readRouteChain(doc);
827
903
  const plan = planSwap(currentChain, newChain, location.href, url, doc);
904
+ // Load the incoming stylesheets before swapping so the new page (and kept
905
+ // layouts whose rules live in the per-page sheet) never renders unstyled.
906
+ const sheets = prepareStylesheets(doc, url);
907
+ await sheets.ready;
908
+ if (seq !== navSeq) {
909
+ sheets.abort();
910
+ return;
911
+ }
828
912
  const mutate = () => {
829
913
  const title = doc.querySelector('title');
830
914
  if (title)
@@ -856,7 +940,7 @@ async function commitDocument(loaded, req, seq) {
856
940
  currentChain = plan.chain;
857
941
  // Detached slot content of earlier intercepts belonged to the old page.
858
942
  interceptSnapshots.clear();
859
- reconcileStylesheets(doc, url);
943
+ sheets.commit();
860
944
  reconcileHeadMeta(doc);
861
945
  applyViewTransitionNames(document);
862
946
  };