@krate/runtime 0.5.0-alpha.3 → 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.
- package/dist/action-context.d.ts +14 -3
- package/dist/action-context.js +70 -4
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +101 -5
- package/dist/actions.test.js +87 -1
- package/dist/cache-scope.d.ts +118 -0
- package/dist/cache-scope.js +314 -0
- package/dist/cache.d.ts +55 -0
- package/dist/cache.js +155 -0
- package/dist/cache.test.d.ts +1 -0
- package/dist/cache.test.js +233 -0
- 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 +75 -2
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +7 -0
- package/dist/dom.js +69 -3
- package/dist/effects.js +74 -3
- package/dist/error-overlay.js +4 -4
- 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 +3 -2
- package/dist/index.js +2 -1
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +65 -2
- 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-list.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 +239 -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/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/portal.d.ts +5 -1
- package/dist/portal.js +15 -4
- 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 +62 -0
- package/dist/request-context.js +107 -0
- package/dist/router-layout.test.d.ts +1 -0
- package/dist/router-layout.test.js +179 -0
- package/dist/router-lite.d.ts +25 -0
- package/dist/router-lite.js +73 -0
- package/dist/router-nav.test.d.ts +1 -0
- package/dist/router-nav.test.js +437 -0
- package/dist/router-slots.test.d.ts +1 -0
- package/dist/router-slots.test.js +144 -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.d.ts +66 -2
- package/dist/router.js +1617 -648
- package/dist/server-async.test.d.ts +1 -0
- package/dist/server-async.test.js +194 -0
- package/dist/server-renderer.js +556 -132
- package/dist/server.d.ts +24 -0
- package/dist/server.js +247 -11
- package/dist/server.test.js +20 -0
- package/dist/signal.d.ts +41 -4
- package/dist/signal.js +254 -24
- package/dist/slots.d.ts +5 -1
- package/dist/slots.js +40 -3
- package/package.json +6 -2
package/dist/router-lite.d.ts
CHANGED
|
@@ -3,6 +3,31 @@ export interface NavigateOptions {
|
|
|
3
3
|
scroll?: boolean;
|
|
4
4
|
state?: unknown;
|
|
5
5
|
}
|
|
6
|
+
export interface NavigationState {
|
|
7
|
+
url: string;
|
|
8
|
+
pathname: string;
|
|
9
|
+
search: string;
|
|
10
|
+
hash: string;
|
|
11
|
+
status: 'idle' | 'loading';
|
|
12
|
+
}
|
|
13
|
+
export declare function getNavigationState(): NavigationState;
|
|
14
|
+
/** Without the SPA router the URL only changes in-document on hash changes. */
|
|
15
|
+
export declare function subscribeNavigation(fn: (s: NavigationState) => void): () => void;
|
|
16
|
+
export declare function getHistoryState(): unknown;
|
|
17
|
+
/** No prefetch cache exists without the SPA router. */
|
|
18
|
+
export declare function invalidatePrefetchCache(_url?: string): void;
|
|
6
19
|
export declare function initRouter(): void;
|
|
7
20
|
export declare function reinitRouter(): void;
|
|
21
|
+
export declare function destroyRouter(): void;
|
|
8
22
|
export declare function navigate(url: string, opts?: NavigateOptions): boolean;
|
|
23
|
+
export declare const krateRouter: {
|
|
24
|
+
push(url: string, opts?: NavigateOptions): Promise<void>;
|
|
25
|
+
replace(url: string, opts?: NavigateOptions): Promise<void>;
|
|
26
|
+
back(): void;
|
|
27
|
+
forward(): void;
|
|
28
|
+
refresh(): Promise<void>;
|
|
29
|
+
prefetch(_url: string): Promise<void>;
|
|
30
|
+
subscribe: typeof subscribeNavigation;
|
|
31
|
+
getState: typeof getNavigationState;
|
|
32
|
+
invalidate: typeof invalidatePrefetchCache;
|
|
33
|
+
};
|
package/dist/router-lite.js
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
|
+
// Router API for sites with the SPA router disabled (`spa: false`). Every
|
|
2
|
+
// navigation is a full document load; the API surface matches router.ts so
|
|
3
|
+
// application code (and the Next.js migration shim) works unchanged.
|
|
4
|
+
function basePath() {
|
|
5
|
+
const cfg = globalThis.__KRATE_CFG__;
|
|
6
|
+
const bp = (cfg && cfg.basePath) || '';
|
|
7
|
+
if (!bp || bp === '/')
|
|
8
|
+
return '';
|
|
9
|
+
return '/' + bp.replace(/^\/+|\/+$/g, '');
|
|
10
|
+
}
|
|
11
|
+
export function getNavigationState() {
|
|
12
|
+
if (typeof location === 'undefined')
|
|
13
|
+
return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
|
|
14
|
+
const bp = basePath();
|
|
15
|
+
let pathname = location.pathname;
|
|
16
|
+
if (bp && (pathname === bp || pathname.startsWith(bp + '/')))
|
|
17
|
+
pathname = pathname.slice(bp.length) || '/';
|
|
18
|
+
return { url: location.href, pathname, search: location.search, hash: location.hash, status: 'idle' };
|
|
19
|
+
}
|
|
20
|
+
/** Without the SPA router the URL only changes in-document on hash changes. */
|
|
21
|
+
export function subscribeNavigation(fn) {
|
|
22
|
+
if (typeof window === 'undefined')
|
|
23
|
+
return () => { };
|
|
24
|
+
const handler = () => fn(getNavigationState());
|
|
25
|
+
window.addEventListener('hashchange', handler);
|
|
26
|
+
return () => {
|
|
27
|
+
window.removeEventListener('hashchange', handler);
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function getHistoryState() {
|
|
31
|
+
return typeof history === 'undefined' ? null : history.state;
|
|
32
|
+
}
|
|
33
|
+
/** No prefetch cache exists without the SPA router. */
|
|
34
|
+
export function invalidatePrefetchCache(_url) { }
|
|
1
35
|
export function initRouter() { }
|
|
2
36
|
export function reinitRouter() { }
|
|
37
|
+
export function destroyRouter() { }
|
|
3
38
|
export function navigate(url, opts = {}) {
|
|
4
39
|
if (typeof location === 'undefined')
|
|
5
40
|
return true;
|
|
@@ -9,3 +44,41 @@ export function navigate(url, opts = {}) {
|
|
|
9
44
|
location.assign(url);
|
|
10
45
|
return true;
|
|
11
46
|
}
|
|
47
|
+
export const krateRouter = {
|
|
48
|
+
push(url, opts = {}) {
|
|
49
|
+
navigate(url, { ...opts, replace: false });
|
|
50
|
+
return Promise.resolve();
|
|
51
|
+
},
|
|
52
|
+
replace(url, opts = {}) {
|
|
53
|
+
navigate(url, { ...opts, replace: true });
|
|
54
|
+
return Promise.resolve();
|
|
55
|
+
},
|
|
56
|
+
back() {
|
|
57
|
+
if (typeof history !== 'undefined')
|
|
58
|
+
history.back();
|
|
59
|
+
},
|
|
60
|
+
forward() {
|
|
61
|
+
if (typeof history !== 'undefined')
|
|
62
|
+
history.forward();
|
|
63
|
+
},
|
|
64
|
+
refresh() {
|
|
65
|
+
if (typeof location !== 'undefined')
|
|
66
|
+
location.reload();
|
|
67
|
+
return Promise.resolve();
|
|
68
|
+
},
|
|
69
|
+
// Full-page navigations go through the browser's HTTP cache; there is no
|
|
70
|
+
// client document cache to warm.
|
|
71
|
+
prefetch(_url) {
|
|
72
|
+
return Promise.resolve();
|
|
73
|
+
},
|
|
74
|
+
subscribe: subscribeNavigation,
|
|
75
|
+
getState: getNavigationState,
|
|
76
|
+
invalidate: invalidatePrefetchCache,
|
|
77
|
+
};
|
|
78
|
+
if (typeof window !== 'undefined') {
|
|
79
|
+
// Revalidated server data is only visible after a reload without the SPA router.
|
|
80
|
+
window.addEventListener('krate:revalidate', () => {
|
|
81
|
+
if (typeof location !== 'undefined')
|
|
82
|
+
location.reload();
|
|
83
|
+
});
|
|
84
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
2
|
+
import { initRouter, destroyRouter, krateRouter, navigate, getHistoryState, subscribeNavigation, invalidatePrefetchCache, } from './router';
|
|
3
|
+
function page(title, body, head = '') {
|
|
4
|
+
return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
|
|
5
|
+
}
|
|
6
|
+
let routes;
|
|
7
|
+
let fetchMock;
|
|
8
|
+
let hardNavs;
|
|
9
|
+
function installFetch() {
|
|
10
|
+
fetchMock = vi.fn(async (input, init) => {
|
|
11
|
+
const u = new URL(input, location.href);
|
|
12
|
+
const r = routes[u.pathname + u.search] ?? routes[u.pathname];
|
|
13
|
+
if (!r) {
|
|
14
|
+
return mockResponse({ status: 404, body: 'nope', type: 'text/plain' }, u.href);
|
|
15
|
+
}
|
|
16
|
+
if (r.gate)
|
|
17
|
+
await r.gate;
|
|
18
|
+
if (init?.signal?.aborted) {
|
|
19
|
+
const e = new Error('aborted');
|
|
20
|
+
e.name = 'AbortError';
|
|
21
|
+
throw e;
|
|
22
|
+
}
|
|
23
|
+
if (r.fail)
|
|
24
|
+
throw r.fail;
|
|
25
|
+
return mockResponse(r, r.redirect ? new URL(r.redirect, location.href).href : u.href);
|
|
26
|
+
});
|
|
27
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
28
|
+
}
|
|
29
|
+
function mockResponse(r, url) {
|
|
30
|
+
const status = r.status ?? 200;
|
|
31
|
+
return {
|
|
32
|
+
ok: status >= 200 && status < 300,
|
|
33
|
+
status,
|
|
34
|
+
url,
|
|
35
|
+
redirected: !!r.redirect,
|
|
36
|
+
headers: new Headers({ 'content-type': r.type ?? 'text/html; charset=utf-8' }),
|
|
37
|
+
text: async () => r.body ?? '',
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function link(href, text, attrs = '') {
|
|
41
|
+
return `<a data-krate-link href="${href}" ${attrs}>${text}</a>`;
|
|
42
|
+
}
|
|
43
|
+
function click(el) {
|
|
44
|
+
el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }));
|
|
45
|
+
}
|
|
46
|
+
async function settle() {
|
|
47
|
+
for (let i = 0; i < 10; i++)
|
|
48
|
+
await Promise.resolve();
|
|
49
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
50
|
+
for (let i = 0; i < 10; i++)
|
|
51
|
+
await Promise.resolve();
|
|
52
|
+
}
|
|
53
|
+
function events(name) {
|
|
54
|
+
const got = [];
|
|
55
|
+
window.addEventListener(name, (e) => got.push(e.detail));
|
|
56
|
+
return got;
|
|
57
|
+
}
|
|
58
|
+
beforeEach(() => {
|
|
59
|
+
destroyRouter();
|
|
60
|
+
globalThis.__KRATE_CFG__ = { viewTransitions: false };
|
|
61
|
+
history.replaceState(null, '', '/');
|
|
62
|
+
document.title = 'Home';
|
|
63
|
+
document.head.innerHTML = '<title>Home</title>';
|
|
64
|
+
document.body.innerHTML = `<div id="root"><h1>Home</h1>${link('/about', 'About')}${link('/docs', 'Docs')}${link('/docs-old', 'Old')}</div>`;
|
|
65
|
+
routes = {
|
|
66
|
+
'/about': { body: page('About', `<h1>About</h1>${link('/', 'Home')}`) },
|
|
67
|
+
'/docs': { body: page('Docs', `<h1>Docs</h1>${link('/docs', 'Docs')}${link('/docs/intro', 'Intro')}`) },
|
|
68
|
+
'/docs/intro': { body: page('Intro', `<h1>Intro</h1>${link('/docs', 'Docs')}${link('/docs-old', 'Old')}`) },
|
|
69
|
+
};
|
|
70
|
+
installFetch();
|
|
71
|
+
hardNavs = [];
|
|
72
|
+
globalThis.__krateHardNavigate = (url, replace) => hardNavs.push([url, replace]);
|
|
73
|
+
initRouter();
|
|
74
|
+
});
|
|
75
|
+
afterEach(() => {
|
|
76
|
+
destroyRouter();
|
|
77
|
+
vi.unstubAllGlobals();
|
|
78
|
+
delete globalThis.__krateHardNavigate;
|
|
79
|
+
delete globalThis.__KRATE_CFG__;
|
|
80
|
+
delete document.startViewTransition;
|
|
81
|
+
});
|
|
82
|
+
describe('SPA navigation', () => {
|
|
83
|
+
it('swaps the app root, title, history and announces the route', async () => {
|
|
84
|
+
const nav = events('krate:navigate');
|
|
85
|
+
click(document.querySelector('a[href="/about"]'));
|
|
86
|
+
await settle();
|
|
87
|
+
expect(location.pathname).toBe('/about');
|
|
88
|
+
expect(document.querySelector('#root h1').textContent).toBe('About');
|
|
89
|
+
expect(document.title).toBe('About');
|
|
90
|
+
expect(nav.length).toBe(1);
|
|
91
|
+
expect(document.getElementById('__krate-route-announcer').textContent).toBe('About');
|
|
92
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
93
|
+
});
|
|
94
|
+
it('ignores modified clicks and target=_blank links', async () => {
|
|
95
|
+
// Keep happy-dom from performing the default (real) navigation.
|
|
96
|
+
const stop = (e) => e.preventDefault();
|
|
97
|
+
window.addEventListener('click', stop);
|
|
98
|
+
document.getElementById('root').innerHTML = link('/about', 'x', 'target="_blank"');
|
|
99
|
+
click(document.querySelector('a'));
|
|
100
|
+
const a = document.createElement('a');
|
|
101
|
+
a.setAttribute('data-krate-link', '');
|
|
102
|
+
a.href = '/about';
|
|
103
|
+
document.body.appendChild(a);
|
|
104
|
+
a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0, metaKey: true }));
|
|
105
|
+
await settle();
|
|
106
|
+
window.removeEventListener('click', stop);
|
|
107
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
108
|
+
});
|
|
109
|
+
it('stores NavigateOptions.state on the history entry', async () => {
|
|
110
|
+
await krateRouter.push('/about', { state: { from: 'test' } });
|
|
111
|
+
expect(getHistoryState()).toEqual({ from: 'test' });
|
|
112
|
+
expect(location.pathname).toBe('/about');
|
|
113
|
+
});
|
|
114
|
+
it('replace() does not add a history entry', async () => {
|
|
115
|
+
const before = history.length;
|
|
116
|
+
await krateRouter.replace('/about');
|
|
117
|
+
expect(history.length).toBe(before);
|
|
118
|
+
expect(location.pathname).toBe('/about');
|
|
119
|
+
});
|
|
120
|
+
it('navigate() drives the SPA router and returns false', async () => {
|
|
121
|
+
expect(navigate('/about')).toBe(false);
|
|
122
|
+
await settle();
|
|
123
|
+
expect(document.title).toBe('About');
|
|
124
|
+
});
|
|
125
|
+
it('follows the final URL after a redirect', async () => {
|
|
126
|
+
routes['/old'] = { body: page('About', '<h1>About</h1>'), redirect: '/about?moved=1' };
|
|
127
|
+
await krateRouter.push('/old');
|
|
128
|
+
expect(location.pathname + location.search).toBe('/about?moved=1');
|
|
129
|
+
});
|
|
130
|
+
it('hard-navigates for non-HTML responses', async () => {
|
|
131
|
+
routes['/file.json'] = { body: '{}', type: 'application/json' };
|
|
132
|
+
await krateRouter.push('/file.json');
|
|
133
|
+
expect(hardNavs).toEqual([['http://localhost:3000/file.json', false]]);
|
|
134
|
+
expect(location.pathname).toBe('/');
|
|
135
|
+
});
|
|
136
|
+
it('hard-navigates when a redirect leaves the origin', async () => {
|
|
137
|
+
routes['/out'] = { body: page('x', ''), redirect: 'https://example.com/elsewhere' };
|
|
138
|
+
await krateRouter.push('/out');
|
|
139
|
+
expect(hardNavs[0][0]).toBe('https://example.com/elsewhere');
|
|
140
|
+
});
|
|
141
|
+
it('cancels a navigation when krate:navigate-start is prevented', async () => {
|
|
142
|
+
const stop = (e) => e.preventDefault();
|
|
143
|
+
window.addEventListener('krate:navigate-start', stop);
|
|
144
|
+
await krateRouter.push('/about');
|
|
145
|
+
window.removeEventListener('krate:navigate-start', stop);
|
|
146
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
147
|
+
expect(location.pathname).toBe('/');
|
|
148
|
+
});
|
|
149
|
+
it('notifies subscribers with pathname, search and status', async () => {
|
|
150
|
+
const seen = [];
|
|
151
|
+
const off = subscribeNavigation((s) => seen.push(`${s.status}:${s.pathname}${s.search}`));
|
|
152
|
+
await krateRouter.push('/docs?x=1');
|
|
153
|
+
off();
|
|
154
|
+
expect(seen).toContain('loading:/');
|
|
155
|
+
expect(seen[seen.length - 1]).toBe('idle:/docs?x=1');
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
describe('view transitions', () => {
|
|
159
|
+
it('updates history and focus only after the transition callback ran', async () => {
|
|
160
|
+
globalThis.__KRATE_CFG__ = { viewTransitions: 'auto' };
|
|
161
|
+
const order = [];
|
|
162
|
+
let release;
|
|
163
|
+
const gate = new Promise((r) => (release = r));
|
|
164
|
+
document.startViewTransition = (cb) => {
|
|
165
|
+
// The browser runs the update callback asynchronously.
|
|
166
|
+
const updateCallbackDone = gate.then(() => {
|
|
167
|
+
order.push('mutate');
|
|
168
|
+
cb();
|
|
169
|
+
});
|
|
170
|
+
return { updateCallbackDone, finished: updateCallbackDone };
|
|
171
|
+
};
|
|
172
|
+
const origPush = history.pushState.bind(history);
|
|
173
|
+
const spy = vi.spyOn(history, 'pushState').mockImplementation((...args) => {
|
|
174
|
+
order.push('push:' + document.title);
|
|
175
|
+
origPush(...args);
|
|
176
|
+
});
|
|
177
|
+
const p = krateRouter.push('/about');
|
|
178
|
+
await settle();
|
|
179
|
+
expect(order).toEqual([]);
|
|
180
|
+
release();
|
|
181
|
+
await p;
|
|
182
|
+
spy.mockRestore();
|
|
183
|
+
expect(order).toEqual(['mutate', 'push:About']);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
describe('hash navigation', () => {
|
|
187
|
+
it('handles hash-only links in place without fetching', async () => {
|
|
188
|
+
document.getElementById('root').innerHTML = `${link('#sec', 'Sec')}<div id="sec">x</div>`;
|
|
189
|
+
const scrolled = vi.fn();
|
|
190
|
+
document.getElementById('sec').scrollIntoView = scrolled;
|
|
191
|
+
click(document.querySelector('a'));
|
|
192
|
+
await settle();
|
|
193
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
194
|
+
expect(location.hash).toBe('#sec');
|
|
195
|
+
expect(scrolled).toHaveBeenCalled();
|
|
196
|
+
});
|
|
197
|
+
it('does not refetch on a hash-only popstate', async () => {
|
|
198
|
+
history.pushState(history.state, '', '/#a');
|
|
199
|
+
window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
|
|
200
|
+
await settle();
|
|
201
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
202
|
+
});
|
|
203
|
+
it('a same-page link with a hash scrolls instead of fetching', async () => {
|
|
204
|
+
await krateRouter.push('/docs');
|
|
205
|
+
fetchMock.mockClear();
|
|
206
|
+
await krateRouter.push('/docs#part');
|
|
207
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
208
|
+
expect(location.href).toBe('http://localhost:3000/docs#part');
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
describe('scroll restoration', () => {
|
|
212
|
+
it('restores the scroll position of the entry being returned to', async () => {
|
|
213
|
+
routes['/'] = { body: page('Home', '<h1>Home</h1>') };
|
|
214
|
+
const homeState = history.state;
|
|
215
|
+
window.scrollTo(0, 420);
|
|
216
|
+
await krateRouter.push('/about');
|
|
217
|
+
expect(window.scrollY).toBe(0);
|
|
218
|
+
const aboutState = history.state;
|
|
219
|
+
window.scrollTo(0, 77);
|
|
220
|
+
// Simulate the browser's history step back to "/": the URL and state
|
|
221
|
+
// change first, then popstate fires.
|
|
222
|
+
history.replaceState(homeState, '', '/');
|
|
223
|
+
window.dispatchEvent(new PopStateEvent('popstate', { state: homeState }));
|
|
224
|
+
await settle();
|
|
225
|
+
expect(document.title).toBe('Home');
|
|
226
|
+
expect(window.scrollY).toBe(420);
|
|
227
|
+
history.replaceState(aboutState, '', '/about');
|
|
228
|
+
window.dispatchEvent(new PopStateEvent('popstate', { state: aboutState }));
|
|
229
|
+
await settle();
|
|
230
|
+
expect(document.title).toBe('About');
|
|
231
|
+
expect(window.scrollY).toBe(77);
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
describe('error handling', () => {
|
|
235
|
+
it('shows a server-rendered 404 document in place and reports the status', async () => {
|
|
236
|
+
const errs = events('krate:navigate-error');
|
|
237
|
+
routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
|
|
238
|
+
await krateRouter.push('/missing');
|
|
239
|
+
expect(document.title).toBe('Not found');
|
|
240
|
+
expect(location.pathname).toBe('/missing');
|
|
241
|
+
expect(errs).toEqual([{ url: 'http://localhost:3000/missing', status: 404 }]);
|
|
242
|
+
expect(hardNavs).toEqual([]);
|
|
243
|
+
});
|
|
244
|
+
it('falls back to <basePath>/404.html when the 404 response is not HTML', async () => {
|
|
245
|
+
globalThis.__KRATE_CFG__ = { viewTransitions: false, basePath: '/app' };
|
|
246
|
+
routes['/app/gone'] = { status: 404, body: 'nope', type: 'text/plain' };
|
|
247
|
+
routes['/app/404.html'] = { body: page('404', '<h1>Lost</h1>') };
|
|
248
|
+
await krateRouter.push('/app/gone');
|
|
249
|
+
expect(document.querySelector('#root h1').textContent).toBe('Lost');
|
|
250
|
+
expect(fetchMock.mock.calls.map((c) => new URL(c[0], location.href).pathname)).toContain('/app/404.html');
|
|
251
|
+
});
|
|
252
|
+
it('uses /500.html for server errors without an HTML body', async () => {
|
|
253
|
+
routes['/boom'] = { status: 503, body: '', type: 'text/plain' };
|
|
254
|
+
routes['/500.html'] = { body: page('Error', '<h1>Broken</h1>') };
|
|
255
|
+
await krateRouter.push('/boom');
|
|
256
|
+
expect(document.querySelector('#root h1').textContent).toBe('Broken');
|
|
257
|
+
});
|
|
258
|
+
it('does not show the 404 page for 403 responses', async () => {
|
|
259
|
+
routes['/secret'] = { status: 403, body: 'forbidden', type: 'text/plain' };
|
|
260
|
+
routes['/404.html'] = { body: page('404', '<h1>Lost</h1>') };
|
|
261
|
+
await krateRouter.push('/secret');
|
|
262
|
+
expect(hardNavs).toEqual([['http://localhost:3000/secret', false]]);
|
|
263
|
+
expect(document.querySelector('#root h1').textContent).toBe('Home');
|
|
264
|
+
});
|
|
265
|
+
it('emits krate:navigate-error on network failure, then hard-navigates', async () => {
|
|
266
|
+
const errs = events('krate:navigate-error');
|
|
267
|
+
routes['/net'] = { fail: new TypeError('Failed to fetch') };
|
|
268
|
+
await krateRouter.push('/net');
|
|
269
|
+
expect(errs.length).toBe(1);
|
|
270
|
+
expect(errs[0].status).toBe(0);
|
|
271
|
+
expect(hardNavs).toEqual([['http://localhost:3000/net', false]]);
|
|
272
|
+
});
|
|
273
|
+
it('lets the app cancel the hard-reload fallback', async () => {
|
|
274
|
+
const stop = (e) => e.preventDefault();
|
|
275
|
+
window.addEventListener('krate:navigate-error', stop);
|
|
276
|
+
routes['/net'] = { fail: new TypeError('Failed to fetch') };
|
|
277
|
+
await krateRouter.push('/net');
|
|
278
|
+
window.removeEventListener('krate:navigate-error', stop);
|
|
279
|
+
expect(hardNavs).toEqual([]);
|
|
280
|
+
expect(location.pathname).toBe('/');
|
|
281
|
+
});
|
|
282
|
+
it('never uses document.write', async () => {
|
|
283
|
+
const spy = vi.spyOn(document, 'write');
|
|
284
|
+
routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
|
|
285
|
+
await krateRouter.push('/missing');
|
|
286
|
+
expect(spy).not.toHaveBeenCalled();
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
describe('races', () => {
|
|
290
|
+
it('a slower superseded navigation never overwrites a newer one', async () => {
|
|
291
|
+
let open;
|
|
292
|
+
routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
|
|
293
|
+
const first = krateRouter.push('/slow');
|
|
294
|
+
const second = krateRouter.push('/about');
|
|
295
|
+
await second;
|
|
296
|
+
open();
|
|
297
|
+
await first;
|
|
298
|
+
await settle();
|
|
299
|
+
expect(document.title).toBe('About');
|
|
300
|
+
expect(location.pathname).toBe('/about');
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
describe('prefetch cache', () => {
|
|
304
|
+
it('serves a prefetched document once, then refetches', async () => {
|
|
305
|
+
await krateRouter.prefetch('/about');
|
|
306
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
307
|
+
await krateRouter.push('/about');
|
|
308
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
309
|
+
routes['/'] = { body: page('Home', '<h1>Home</h1>') };
|
|
310
|
+
await krateRouter.push('/');
|
|
311
|
+
await krateRouter.push('/about');
|
|
312
|
+
// The cache hit was consumed: revisiting fetches fresh HTML.
|
|
313
|
+
expect(fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/about')).length).toBe(2);
|
|
314
|
+
});
|
|
315
|
+
it('expires entries after the TTL', async () => {
|
|
316
|
+
globalThis.__KRATE_CFG__ = { viewTransitions: false, prefetchTTL: 0 };
|
|
317
|
+
await krateRouter.prefetch('/about');
|
|
318
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
319
|
+
await krateRouter.push('/about');
|
|
320
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
321
|
+
});
|
|
322
|
+
it('invalidatePrefetchCache drops entries', async () => {
|
|
323
|
+
await krateRouter.prefetch('/about');
|
|
324
|
+
invalidatePrefetchCache('/about');
|
|
325
|
+
await krateRouter.push('/about');
|
|
326
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
327
|
+
});
|
|
328
|
+
it('does not cache error responses', async () => {
|
|
329
|
+
routes['/missing'] = { status: 404, body: page('Not found', '') };
|
|
330
|
+
await krateRouter.prefetch('/missing');
|
|
331
|
+
await krateRouter.push('/missing');
|
|
332
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
describe('refresh and revalidation', () => {
|
|
336
|
+
it('refresh() refetches the current route bypassing the cache and keeps history', async () => {
|
|
337
|
+
await krateRouter.push('/about');
|
|
338
|
+
routes['/about'] = { body: page('About v2', '<h1>About v2</h1>') };
|
|
339
|
+
await krateRouter.prefetch('/about');
|
|
340
|
+
const len = history.length;
|
|
341
|
+
window.scrollTo(0, 33);
|
|
342
|
+
await krateRouter.refresh();
|
|
343
|
+
expect(document.title).toBe('About v2');
|
|
344
|
+
expect(history.length).toBe(len);
|
|
345
|
+
expect(window.scrollY).toBe(33);
|
|
346
|
+
const last = fetchMock.mock.calls[fetchMock.mock.calls.length - 1];
|
|
347
|
+
expect(last[1].cache).toBe('no-cache');
|
|
348
|
+
});
|
|
349
|
+
it('krate:revalidate refreshes the current route', async () => {
|
|
350
|
+
await krateRouter.push('/about');
|
|
351
|
+
routes['/about'] = { body: page('Fresh', '<h1>Fresh</h1>') };
|
|
352
|
+
window.dispatchEvent(new CustomEvent('krate:revalidate', { detail: { paths: ['/about'] } }));
|
|
353
|
+
await settle();
|
|
354
|
+
expect(document.title).toBe('Fresh');
|
|
355
|
+
});
|
|
356
|
+
});
|
|
357
|
+
describe('active links', () => {
|
|
358
|
+
it('marks exact matches with aria-current and segments separately', async () => {
|
|
359
|
+
await krateRouter.push('/docs/intro');
|
|
360
|
+
const docs = document.querySelector('a[href="/docs"]');
|
|
361
|
+
const old = document.querySelector('a[href="/docs-old"]');
|
|
362
|
+
expect(docs.getAttribute('aria-current')).toBeNull();
|
|
363
|
+
expect(docs.getAttribute('data-krate-active')).toBe('segment');
|
|
364
|
+
expect(old.hasAttribute('data-krate-active')).toBe(false);
|
|
365
|
+
await krateRouter.push('/docs');
|
|
366
|
+
expect(document.querySelector('a[href="/docs"]').getAttribute('aria-current')).toBe('page');
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
describe('forms', () => {
|
|
370
|
+
it('intercepts GET form submissions', async () => {
|
|
371
|
+
routes['/search'] = { body: page('Search', '<h1>Results</h1>') };
|
|
372
|
+
document.getElementById('root').innerHTML =
|
|
373
|
+
'<form action="/search"><input name="q" value="krate"><button name="go" value="1">Go</button></form>';
|
|
374
|
+
const form = document.querySelector('form');
|
|
375
|
+
const ev = new Event('submit', { bubbles: true, cancelable: true });
|
|
376
|
+
ev.submitter = form.querySelector('button');
|
|
377
|
+
form.dispatchEvent(ev);
|
|
378
|
+
expect(ev.defaultPrevented).toBe(true);
|
|
379
|
+
await settle();
|
|
380
|
+
expect(location.pathname + location.search).toBe('/search?q=krate&go=1');
|
|
381
|
+
expect(document.title).toBe('Search');
|
|
382
|
+
});
|
|
383
|
+
it('leaves POST forms alone', async () => {
|
|
384
|
+
document.getElementById('root').innerHTML = '<form method="post" action="/search"><input name="q"></form>';
|
|
385
|
+
const ev = new Event('submit', { bubbles: true, cancelable: true });
|
|
386
|
+
document.querySelector('form').dispatchEvent(ev);
|
|
387
|
+
expect(ev.defaultPrevented).toBe(false);
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
describe('focus', () => {
|
|
391
|
+
it('focuses the root temporarily and removes tabindex on blur', async () => {
|
|
392
|
+
await krateRouter.push('/about');
|
|
393
|
+
const root = document.getElementById('root');
|
|
394
|
+
expect(document.activeElement).toBe(root);
|
|
395
|
+
expect(root.getAttribute('tabindex')).toBe('-1');
|
|
396
|
+
root.blur();
|
|
397
|
+
expect(root.hasAttribute('tabindex')).toBe(false);
|
|
398
|
+
});
|
|
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 {};
|