@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2
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.
- package/dist/action-context.d.ts +5 -1
- package/dist/action-context.js +33 -3
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +84 -4
- package/dist/actions.test.js +61 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +64 -13
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/cache.test.js +16 -0
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +357 -32
- package/dist/class-helpers.test.d.ts +1 -0
- package/dist/class-helpers.test.js +169 -0
- package/dist/context.d.ts +16 -2
- package/dist/context.js +44 -3
- package/dist/dev-overlay.js +85 -12
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +15 -0
- package/dist/dom.js +97 -3
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +7 -7
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/hook-args.d.ts +7 -0
- package/dist/hook-args.js +10 -0
- package/dist/htmlspec-attributes.d.ts +1 -0
- package/dist/htmlspec-attributes.js +159 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +75 -12
- package/dist/krate-f-actions.js +2 -0
- package/dist/krate-f-classes.js +8 -0
- package/dist/krate-f-helpers.js +2 -0
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +2 -0
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router-lite.js +2 -0
- package/dist/krate-f-router.js +2 -0
- package/dist/krate-features.json +493 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/reactivity-core.test.d.ts +1 -0
- package/dist/reactivity-core.test.js +152 -0
- package/dist/reconcile.js +4 -2
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +65 -0
- package/dist/router-speculation.test.d.ts +1 -0
- package/dist/router-speculation.test.js +25 -0
- package/dist/router-styles.test.d.ts +1 -0
- package/dist/router-styles.test.js +98 -0
- package/dist/router.js +175 -36
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +43 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +165 -720
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +13 -1
- package/dist/server.js +131 -16
- package/dist/server.test.js +20 -0
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.d.ts +3 -2
- package/dist/signal.js +163 -23
- package/dist/slots.js +12 -1
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +30 -2
package/dist/router-nav.test.js
CHANGED
|
@@ -183,6 +183,17 @@ describe('view transitions', () => {
|
|
|
183
183
|
expect(order).toEqual(['mutate', 'push:About']);
|
|
184
184
|
});
|
|
185
185
|
});
|
|
186
|
+
describe('view transition names', () => {
|
|
187
|
+
it('names elements and applies their transition class after a swap', async () => {
|
|
188
|
+
routes['/vt'] = {
|
|
189
|
+
body: page('VT', '<h1 id="hero" data-view-transition="hero" data-view-transition-class="slow-fade">x</h1>'),
|
|
190
|
+
};
|
|
191
|
+
await krateRouter.push('/vt');
|
|
192
|
+
const hero = document.getElementById('hero');
|
|
193
|
+
expect(hero.style.viewTransitionName).toBe('hero');
|
|
194
|
+
expect(hero.style.getPropertyValue('view-transition-class')).toBe('slow-fade');
|
|
195
|
+
});
|
|
196
|
+
});
|
|
186
197
|
describe('hash navigation', () => {
|
|
187
198
|
it('handles hash-only links in place without fetching', async () => {
|
|
188
199
|
document.getElementById('root').innerHTML = `${link('#sec', 'Sec')}<div id="sec">x</div>`;
|
|
@@ -312,6 +323,22 @@ describe('prefetch cache', () => {
|
|
|
312
323
|
// The cache hit was consumed: revisiting fetches fresh HTML.
|
|
313
324
|
expect(fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/about')).length).toBe(2);
|
|
314
325
|
});
|
|
326
|
+
it('keeps the fragment of the link when the document was prefetched', async () => {
|
|
327
|
+
routes['/about'] = { body: page('About', '<h1>About</h1><h2 id="team">Team</h2>') };
|
|
328
|
+
const original = Element.prototype.scrollIntoView;
|
|
329
|
+
const scrolled = vi.fn();
|
|
330
|
+
Element.prototype.scrollIntoView = scrolled;
|
|
331
|
+
try {
|
|
332
|
+
await krateRouter.prefetch('/about#team');
|
|
333
|
+
await krateRouter.push('/about#team');
|
|
334
|
+
await settle();
|
|
335
|
+
expect(location.pathname + location.hash).toBe('/about#team');
|
|
336
|
+
expect(scrolled).toHaveBeenCalled();
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
Element.prototype.scrollIntoView = original;
|
|
340
|
+
}
|
|
341
|
+
});
|
|
315
342
|
it('expires entries after the TTL', async () => {
|
|
316
343
|
globalThis.__KRATE_CFG__ = { viewTransitions: false, prefetchTTL: 0 };
|
|
317
344
|
await krateRouter.prefetch('/about');
|
|
@@ -397,3 +424,41 @@ describe('focus', () => {
|
|
|
397
424
|
expect(root.hasAttribute('tabindex')).toBe(false);
|
|
398
425
|
});
|
|
399
426
|
});
|
|
427
|
+
describe('fallback fade and reduced motion', () => {
|
|
428
|
+
function stubReducedMotion(reduce) {
|
|
429
|
+
vi.stubGlobal('matchMedia', (q) => ({
|
|
430
|
+
matches: reduce && q.includes('prefers-reduced-motion'),
|
|
431
|
+
media: q,
|
|
432
|
+
addEventListener() { },
|
|
433
|
+
removeEventListener() { },
|
|
434
|
+
addListener() { },
|
|
435
|
+
removeListener() { },
|
|
436
|
+
}));
|
|
437
|
+
window.matchMedia = globalThis.matchMedia;
|
|
438
|
+
}
|
|
439
|
+
async function rootStyleDuringFetch() {
|
|
440
|
+
let release;
|
|
441
|
+
routes['/about'].gate = new Promise((r) => (release = r));
|
|
442
|
+
const p = krateRouter.push('/about');
|
|
443
|
+
await settle();
|
|
444
|
+
const el = document.getElementById('root');
|
|
445
|
+
const seen = { transition: el.style.transition, opacity: el.style.opacity };
|
|
446
|
+
release();
|
|
447
|
+
await p;
|
|
448
|
+
await settle();
|
|
449
|
+
return seen;
|
|
450
|
+
}
|
|
451
|
+
it('applies the opacity fade without View Transitions', async () => {
|
|
452
|
+
stubReducedMotion(false);
|
|
453
|
+
const seen = await rootStyleDuringFetch();
|
|
454
|
+
expect(seen.opacity).toBe('0');
|
|
455
|
+
expect(seen.transition).toContain('opacity');
|
|
456
|
+
});
|
|
457
|
+
it('applies no fade under prefers-reduced-motion', async () => {
|
|
458
|
+
stubReducedMotion(true);
|
|
459
|
+
const seen = await rootStyleDuringFetch();
|
|
460
|
+
expect(seen.opacity).toBe('');
|
|
461
|
+
expect(seen.transition).toBe('');
|
|
462
|
+
expect(document.querySelector('#root h1').textContent).toBe('About');
|
|
463
|
+
});
|
|
464
|
+
});
|
|
@@ -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
|
|
456
|
-
function
|
|
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
|
-
|
|
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
|
-
|
|
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';
|
|
@@ -498,7 +509,8 @@ function endTransition() {
|
|
|
498
509
|
el.style.opacity = '';
|
|
499
510
|
}
|
|
500
511
|
/**
|
|
501
|
-
* Apply `data-view-transition="name"` to `view-transition-name
|
|
512
|
+
* Apply `data-view-transition="name"` to `view-transition-name` (and
|
|
513
|
+
* `data-view-transition-class` to `view-transition-class`). Persistent
|
|
502
514
|
* chrome (navbar/sidebar) keeps its name across mutations so it morphs
|
|
503
515
|
* instead of cross-fading.
|
|
504
516
|
*/
|
|
@@ -507,37 +519,101 @@ function applyViewTransitionNames(root) {
|
|
|
507
519
|
const name = el.getAttribute('data-view-transition');
|
|
508
520
|
if (name)
|
|
509
521
|
el.style.viewTransitionName = name;
|
|
522
|
+
// `<ViewTransition default="slow-fade">` selects ::view-transition-*(*.slow-fade).
|
|
523
|
+
const cls = el.getAttribute('data-view-transition-class');
|
|
524
|
+
if (cls)
|
|
525
|
+
el.style.setProperty('view-transition-class', cls);
|
|
510
526
|
});
|
|
511
527
|
}
|
|
512
528
|
// Document reconciliation
|
|
513
|
-
/**
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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) => {
|
|
529
|
+
/** How long a navigation waits for new stylesheets before swapping anyway. */
|
|
530
|
+
const STYLESHEET_TIMEOUT_MS = 3000;
|
|
531
|
+
/**
|
|
532
|
+
* Diff stylesheet <link>s by absolute URL (base-path and format safe). New
|
|
533
|
+
* links are inserted at the position they have in the incoming document (before
|
|
534
|
+
* the next kept link), so the cascade order matches a hard load. They load with
|
|
535
|
+
* media="not all" so they do not affect the outgoing page; stale links stay
|
|
536
|
+
* until commit() so the old page keeps its styles while the new ones load.
|
|
537
|
+
*/
|
|
538
|
+
function prepareStylesheets(doc, baseUrl) {
|
|
539
|
+
const incoming = [];
|
|
540
|
+
doc.querySelectorAll('link[rel="stylesheet"]').forEach((s) => {
|
|
530
541
|
const href = s.getAttribute('href');
|
|
531
542
|
if (!href)
|
|
532
543
|
return;
|
|
533
544
|
const abs = new URL(href, baseUrl).href;
|
|
534
|
-
if (!
|
|
545
|
+
if (!incoming.includes(abs))
|
|
546
|
+
incoming.push(abs);
|
|
547
|
+
});
|
|
548
|
+
const live = new Map();
|
|
549
|
+
const stale = [];
|
|
550
|
+
document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
|
|
551
|
+
const el = l;
|
|
552
|
+
if (!el.href)
|
|
553
|
+
return;
|
|
554
|
+
if (incoming.includes(el.href) && !live.has(el.href))
|
|
555
|
+
live.set(el.href, el);
|
|
556
|
+
else
|
|
557
|
+
stale.push(el);
|
|
558
|
+
});
|
|
559
|
+
const added = [];
|
|
560
|
+
const pending = [];
|
|
561
|
+
let prev = null;
|
|
562
|
+
incoming.forEach((abs, i) => {
|
|
563
|
+
let el = live.get(abs) || null;
|
|
564
|
+
if (!el) {
|
|
535
565
|
const link = document.createElement('link');
|
|
536
566
|
link.rel = 'stylesheet';
|
|
537
567
|
link.href = abs;
|
|
538
|
-
|
|
568
|
+
// Listen before insertion so a synchronous settle is not missed.
|
|
569
|
+
pending.push(new Promise((resolve) => {
|
|
570
|
+
const done = () => {
|
|
571
|
+
link.removeEventListener('load', done);
|
|
572
|
+
link.removeEventListener('error', done);
|
|
573
|
+
resolve();
|
|
574
|
+
};
|
|
575
|
+
link.addEventListener('load', done);
|
|
576
|
+
link.addEventListener('error', done);
|
|
577
|
+
}));
|
|
578
|
+
added.push({ link, media: link.getAttribute('media') });
|
|
579
|
+
link.media = 'not all';
|
|
580
|
+
if (prev) {
|
|
581
|
+
prev.after(link);
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
const nextKept = incoming.slice(i + 1).map((h) => live.get(h)).find((l) => !!l);
|
|
585
|
+
if (nextKept)
|
|
586
|
+
nextKept.before(link);
|
|
587
|
+
else
|
|
588
|
+
document.head.appendChild(link);
|
|
589
|
+
}
|
|
590
|
+
el = link;
|
|
539
591
|
}
|
|
592
|
+
prev = el;
|
|
540
593
|
});
|
|
594
|
+
let ready = Promise.resolve();
|
|
595
|
+
if (pending.length > 0) {
|
|
596
|
+
let timer;
|
|
597
|
+
const timeout = new Promise((resolve) => {
|
|
598
|
+
timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
|
|
599
|
+
});
|
|
600
|
+
ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
ready,
|
|
604
|
+
commit() {
|
|
605
|
+
for (const { link, media } of added) {
|
|
606
|
+
if (media === null)
|
|
607
|
+
link.removeAttribute('media');
|
|
608
|
+
else
|
|
609
|
+
link.setAttribute('media', media);
|
|
610
|
+
}
|
|
611
|
+
stale.forEach((l) => l.remove());
|
|
612
|
+
},
|
|
613
|
+
abort() {
|
|
614
|
+
added.forEach(({ link }) => link.remove());
|
|
615
|
+
},
|
|
616
|
+
};
|
|
541
617
|
}
|
|
542
618
|
// Document-level <head> tags that change per page and must follow a swap.
|
|
543
619
|
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 +627,7 @@ function scriptsToLoad(doc, baseUrl) {
|
|
|
551
627
|
const keep = new Set();
|
|
552
628
|
document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
|
|
553
629
|
const out = [];
|
|
630
|
+
const seen = new Set();
|
|
554
631
|
doc.querySelectorAll('script[src]').forEach((s) => {
|
|
555
632
|
const src = s.getAttribute('src');
|
|
556
633
|
if (!src)
|
|
@@ -559,18 +636,22 @@ function scriptsToLoad(doc, baseUrl) {
|
|
|
559
636
|
if (t && t !== 'module' && t !== 'text/javascript' && t !== 'application/javascript')
|
|
560
637
|
return;
|
|
561
638
|
const abs = resolveSrc(src, baseUrl);
|
|
562
|
-
if (!keep.has(abs) && !
|
|
563
|
-
|
|
639
|
+
if (!keep.has(abs) && !seen.has(abs)) {
|
|
640
|
+
seen.add(abs);
|
|
641
|
+
out.push({ src: abs, module: t === 'module' });
|
|
642
|
+
}
|
|
564
643
|
});
|
|
565
644
|
return out;
|
|
566
645
|
}
|
|
567
|
-
function loadScript(
|
|
646
|
+
function loadScript(script) {
|
|
568
647
|
return new Promise((resolve) => {
|
|
569
648
|
const s = document.createElement('script');
|
|
570
|
-
s.src = src;
|
|
649
|
+
s.src = script.src;
|
|
650
|
+
if (script.module)
|
|
651
|
+
s.type = 'module';
|
|
571
652
|
// Only page scripts are disposable across navigations; the shared runtime
|
|
572
653
|
// chunk stays in place.
|
|
573
|
-
if (!RUNTIME_CHUNK_RE.test(src))
|
|
654
|
+
if (!RUNTIME_CHUNK_RE.test(script.src))
|
|
574
655
|
s.setAttribute('data-krate-spa', '');
|
|
575
656
|
s.onload = () => resolve(true);
|
|
576
657
|
s.onerror = () => resolve(false);
|
|
@@ -711,8 +792,13 @@ async function loadDocument(req, signal) {
|
|
|
711
792
|
if (signal.aborted)
|
|
712
793
|
return { ok: false, aborted: true };
|
|
713
794
|
const hit = cacheTake(key);
|
|
714
|
-
if (hit)
|
|
715
|
-
|
|
795
|
+
if (hit) {
|
|
796
|
+
// The prefetch fetched the URL without its fragment: keep the one the
|
|
797
|
+
// link asked for, so `/docs/page#section` still scrolls to the section.
|
|
798
|
+
const hash = new URL(req.url, location.href).hash;
|
|
799
|
+
const target = hash && !new URL(hit.url, location.href).hash ? hit.url + hash : hit.url;
|
|
800
|
+
return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
|
|
801
|
+
}
|
|
716
802
|
}
|
|
717
803
|
let res;
|
|
718
804
|
try {
|
|
@@ -825,6 +911,14 @@ async function commitDocument(loaded, req, seq) {
|
|
|
825
911
|
saveScroll(currentKey);
|
|
826
912
|
const newChain = readRouteChain(doc);
|
|
827
913
|
const plan = planSwap(currentChain, newChain, location.href, url, doc);
|
|
914
|
+
// Load the incoming stylesheets before swapping so the new page (and kept
|
|
915
|
+
// layouts whose rules live in the per-page sheet) never renders unstyled.
|
|
916
|
+
const sheets = prepareStylesheets(doc, url);
|
|
917
|
+
await sheets.ready;
|
|
918
|
+
if (seq !== navSeq) {
|
|
919
|
+
sheets.abort();
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
828
922
|
const mutate = () => {
|
|
829
923
|
const title = doc.querySelector('title');
|
|
830
924
|
if (title)
|
|
@@ -856,7 +950,7 @@ async function commitDocument(loaded, req, seq) {
|
|
|
856
950
|
currentChain = plan.chain;
|
|
857
951
|
// Detached slot content of earlier intercepts belonged to the old page.
|
|
858
952
|
interceptSnapshots.clear();
|
|
859
|
-
|
|
953
|
+
sheets.commit();
|
|
860
954
|
reconcileHeadMeta(doc);
|
|
861
955
|
applyViewTransitionNames(document);
|
|
862
956
|
};
|
|
@@ -885,6 +979,7 @@ async function commitDocument(loaded, req, seq) {
|
|
|
885
979
|
renderedPath = pathOf(location.href);
|
|
886
980
|
docPath = renderedPath;
|
|
887
981
|
syncParams(doc);
|
|
982
|
+
syncErrorData(doc);
|
|
888
983
|
applyScroll(url, req);
|
|
889
984
|
if (req.kind !== 'pop' && req.kind !== 'refresh')
|
|
890
985
|
focusContent();
|
|
@@ -1015,16 +1110,24 @@ function keepScopes(ids) {
|
|
|
1015
1110
|
* route has a matching slot page and otherwise keep their content (a soft
|
|
1016
1111
|
* navigation never resets a slot to its default).
|
|
1017
1112
|
*/
|
|
1113
|
+
function boundaryFailed(scope) {
|
|
1114
|
+
const fn = globalThis.krateScopeFailed;
|
|
1115
|
+
return typeof fn === 'function' && !!fn(scope);
|
|
1116
|
+
}
|
|
1018
1117
|
function planSwap(oldChain, newChain, fromUrl, toUrl, doc) {
|
|
1019
1118
|
const full = { keep: [], skip: [], region: null, slots: [], chain: newChain };
|
|
1020
1119
|
let k = 0;
|
|
1021
1120
|
while (k < oldChain.length && k < newChain.length) {
|
|
1022
1121
|
const a = oldChain[k];
|
|
1023
1122
|
const b = newChain[k];
|
|
1024
|
-
if (a.id !== b.id || a.k !== 'layout'
|
|
1123
|
+
if (a.id !== b.id || a.k !== b.k || (a.k !== 'layout' && a.k !== 'error'))
|
|
1025
1124
|
break;
|
|
1026
1125
|
if (segmentKey(fromUrl, a.d) !== segmentKey(toUrl, b.d))
|
|
1027
1126
|
break;
|
|
1127
|
+
// A segment's error boundary stays mounted while it shows the page, so the
|
|
1128
|
+
// layouts below it keep their state; one that caught an error is replaced.
|
|
1129
|
+
if (a.k === 'error' && boundaryFailed(a.id))
|
|
1130
|
+
break;
|
|
1028
1131
|
if (!a.p || !b.p) {
|
|
1029
1132
|
devWarn(`layout ${b.f || b.id} is remounted on this navigation: ${b.why || a.why || 'not persistable'}`);
|
|
1030
1133
|
break;
|
|
@@ -1167,6 +1270,22 @@ function setSlotInfo(key, next) {
|
|
|
1167
1270
|
currentChain = currentChain.map((e) => e.s && e.s.some((x) => x.key === key) ? { ...e, s: e.s.map((x) => (x.key === key ? next : x)) } : e);
|
|
1168
1271
|
}
|
|
1169
1272
|
function syncParams(doc) {
|
|
1273
|
+
// The route pattern of a dynamic page, for useParams(). A static page has
|
|
1274
|
+
// none; the empty string says so (the first page's block is not in the DOM
|
|
1275
|
+
// any more once the router swapped it out).
|
|
1276
|
+
let route = '';
|
|
1277
|
+
const routeEl = doc.getElementById('__krate_page');
|
|
1278
|
+
if (routeEl) {
|
|
1279
|
+
try {
|
|
1280
|
+
const data = JSON.parse(routeEl.textContent || '{}');
|
|
1281
|
+
if (typeof data.r === 'string')
|
|
1282
|
+
route = data.r;
|
|
1283
|
+
}
|
|
1284
|
+
catch {
|
|
1285
|
+
/* ignore */
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
globalThis.__KRATE_ROUTE__ = route;
|
|
1170
1289
|
for (const script of Array.from(doc.querySelectorAll('script:not([src])'))) {
|
|
1171
1290
|
const m = /window\.__KRATE_PARAMS__\s*=\s*(\{[\s\S]*?\})\s*;?\s*$/.exec(script.textContent || '');
|
|
1172
1291
|
if (!m)
|
|
@@ -1181,6 +1300,26 @@ function syncParams(doc) {
|
|
|
1181
1300
|
}
|
|
1182
1301
|
delete globalThis.__KRATE_PARAMS__;
|
|
1183
1302
|
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Moves the server-rendered error (a JSON data block the Go server injects into
|
|
1305
|
+
* a 500 page, read by error components while they hydrate) from the incoming
|
|
1306
|
+
* document to the live one, so an error page shown by soft navigation sees the
|
|
1307
|
+
* error of its own response. The block is removed when the new page has none.
|
|
1308
|
+
*/
|
|
1309
|
+
function syncErrorData(doc) {
|
|
1310
|
+
const next = doc.getElementById('__krate_error');
|
|
1311
|
+
const live = document.getElementById('__krate_error');
|
|
1312
|
+
if (!next) {
|
|
1313
|
+
if (live)
|
|
1314
|
+
live.remove();
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
const copy = document.importNode(next, true);
|
|
1318
|
+
if (live)
|
|
1319
|
+
live.replaceWith(copy);
|
|
1320
|
+
else
|
|
1321
|
+
document.head.appendChild(copy);
|
|
1322
|
+
}
|
|
1184
1323
|
function disposeScopes(ids) {
|
|
1185
1324
|
const fn = globalThis.krateDisposeScopes;
|
|
1186
1325
|
if (typeof fn === 'function')
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare class SegmentedLRU<V> {
|
|
2
|
+
private probation;
|
|
3
|
+
private protectedSeg;
|
|
4
|
+
private readonly max;
|
|
5
|
+
private readonly protectedMax;
|
|
6
|
+
constructor(maxSize: number);
|
|
7
|
+
get size(): number;
|
|
8
|
+
has(key: string): boolean;
|
|
9
|
+
/** Reads an entry without counting as a use. */
|
|
10
|
+
peek(key: string): V | undefined;
|
|
11
|
+
/** Reads an entry and counts the use: probation entries are promoted. */
|
|
12
|
+
get(key: string): V | undefined;
|
|
13
|
+
/** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
|
|
14
|
+
set(key: string, value: V): Array<[string, V]>;
|
|
15
|
+
delete(key: string): boolean;
|
|
16
|
+
clear(): void;
|
|
17
|
+
keys(): string[];
|
|
18
|
+
entries(): Array<[string, V]>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// A bounded cache that one client cannot flush. A plain LRU drops the hot
|
|
2
|
+
// entries as soon as enough new keys arrive between two hits, and on an open
|
|
3
|
+
// dynamic route ("/blog/[slug]") any slug renders, so a client can mint new
|
|
4
|
+
// keys at will. This is a segmented LRU: a new entry starts in a small
|
|
5
|
+
// probation segment and moves to the protected segment on its first hit, so a
|
|
6
|
+
// flood of one-off keys only churns probation and never reaches the entries
|
|
7
|
+
// that were requested twice.
|
|
8
|
+
export class SegmentedLRU {
|
|
9
|
+
constructor(maxSize) {
|
|
10
|
+
this.probation = new Map();
|
|
11
|
+
this.protectedSeg = new Map();
|
|
12
|
+
this.max = Math.max(1, Math.floor(maxSize));
|
|
13
|
+
// At least one probation slot, so a new entry can always be admitted.
|
|
14
|
+
this.protectedMax = Math.min(this.max - 1, Math.max(1, Math.floor(this.max * 0.8)));
|
|
15
|
+
}
|
|
16
|
+
get size() {
|
|
17
|
+
return this.probation.size + this.protectedSeg.size;
|
|
18
|
+
}
|
|
19
|
+
has(key) {
|
|
20
|
+
return this.protectedSeg.has(key) || this.probation.has(key);
|
|
21
|
+
}
|
|
22
|
+
/** Reads an entry without counting as a use. */
|
|
23
|
+
peek(key) {
|
|
24
|
+
return this.protectedSeg.get(key) ?? this.probation.get(key);
|
|
25
|
+
}
|
|
26
|
+
/** Reads an entry and counts the use: probation entries are promoted. */
|
|
27
|
+
get(key) {
|
|
28
|
+
const hot = this.protectedSeg.get(key);
|
|
29
|
+
if (hot !== undefined) {
|
|
30
|
+
this.protectedSeg.delete(key);
|
|
31
|
+
this.protectedSeg.set(key, hot);
|
|
32
|
+
return hot;
|
|
33
|
+
}
|
|
34
|
+
const cold = this.probation.get(key);
|
|
35
|
+
if (cold === undefined)
|
|
36
|
+
return undefined;
|
|
37
|
+
this.probation.delete(key);
|
|
38
|
+
if (this.protectedMax <= 0) {
|
|
39
|
+
this.probation.set(key, cold);
|
|
40
|
+
return cold;
|
|
41
|
+
}
|
|
42
|
+
this.protectedSeg.set(key, cold);
|
|
43
|
+
if (this.protectedSeg.size > this.protectedMax) {
|
|
44
|
+
// The coldest protected entry goes back to probation's newest slot.
|
|
45
|
+
const demoted = this.protectedSeg.keys().next().value;
|
|
46
|
+
const v = this.protectedSeg.get(demoted);
|
|
47
|
+
this.protectedSeg.delete(demoted);
|
|
48
|
+
this.probation.set(demoted, v);
|
|
49
|
+
}
|
|
50
|
+
return cold;
|
|
51
|
+
}
|
|
52
|
+
/** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
|
|
53
|
+
set(key, value) {
|
|
54
|
+
if (this.protectedSeg.has(key)) {
|
|
55
|
+
this.protectedSeg.delete(key);
|
|
56
|
+
this.protectedSeg.set(key, value);
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
if (this.probation.has(key)) {
|
|
60
|
+
this.probation.delete(key);
|
|
61
|
+
this.probation.set(key, value);
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
const evicted = [];
|
|
65
|
+
while (this.size >= this.max) {
|
|
66
|
+
const seg = this.probation.size > 0 ? this.probation : this.protectedSeg;
|
|
67
|
+
const oldest = seg.keys().next().value;
|
|
68
|
+
evicted.push([oldest, seg.get(oldest)]);
|
|
69
|
+
seg.delete(oldest);
|
|
70
|
+
}
|
|
71
|
+
this.probation.set(key, value);
|
|
72
|
+
return evicted;
|
|
73
|
+
}
|
|
74
|
+
delete(key) {
|
|
75
|
+
return this.protectedSeg.delete(key) || this.probation.delete(key);
|
|
76
|
+
}
|
|
77
|
+
clear() {
|
|
78
|
+
this.probation.clear();
|
|
79
|
+
this.protectedSeg.clear();
|
|
80
|
+
}
|
|
81
|
+
keys() {
|
|
82
|
+
return [...this.probation.keys(), ...this.protectedSeg.keys()];
|
|
83
|
+
}
|
|
84
|
+
entries() {
|
|
85
|
+
return [...this.probation.entries(), ...this.protectedSeg.entries()];
|
|
86
|
+
}
|
|
87
|
+
}
|