@sigil-dev/grimoire 0.9.20 → 0.9.22
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/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -114
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -745
- package/src/rendering/preload.ts +101 -95
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -194
- package/src/server/asset-cache.ts +57 -55
- package/src/server/build.ts +262 -249
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -0
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1022
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -0
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -113
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -69
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
|
@@ -1,734 +1,789 @@
|
|
|
1
|
-
import { beforeEach, describe, expect, test, vi } from "bun:test";
|
|
2
|
-
import type { Document, History, Location, Window } from "happy-dom";
|
|
3
|
-
import {
|
|
4
|
-
clearDeps,
|
|
5
|
-
depends,
|
|
6
|
-
hasDep,
|
|
7
|
-
setDeps,
|
|
8
|
-
startCollecting,
|
|
9
|
-
stopCollecting,
|
|
10
|
-
} from "../src/client/deps.ts";
|
|
11
|
-
|
|
12
|
-
// test/preload.ts installs happy-dom globals at runtime; this package's
|
|
13
|
-
// compiler options have no DOM lib, so declare the shapes we rely on.
|
|
14
|
-
declare global {
|
|
15
|
-
// biome-ignore-all lint/style/noVar: ambient global declarations require var
|
|
16
|
-
var window: Window;
|
|
17
|
-
var document: Document;
|
|
18
|
-
var location: Location;
|
|
19
|
-
var history: History;
|
|
20
|
-
var MouseEvent: Window["MouseEvent"];
|
|
21
|
-
var Event: Window["Event"];
|
|
22
|
-
var requestAnimationFrame: Window["requestAnimationFrame"];
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// router.ts reads `location` at module load — DOM globals must exist first.
|
|
26
|
-
// Dynamic import is required because the module under test captures location
|
|
27
|
-
// during evaluation, which static-hoisted imports would race. The default
|
|
28
|
-
// about:blank URL has origin "null", which breaks new URL(href, origin) —
|
|
29
|
-
// point the window at a real origin first.
|
|
30
|
-
window.location.href = "http://localhost/";
|
|
31
|
-
const globalEnv = globalThis as typeof globalThis & {
|
|
32
|
-
location: Location;
|
|
33
|
-
history: History;
|
|
34
|
-
requestAnimationFrame: Window["requestAnimationFrame"];
|
|
35
|
-
};
|
|
36
|
-
globalEnv.location = window.location;
|
|
37
|
-
globalEnv.history = window.history;
|
|
38
|
-
globalEnv.requestAnimationFrame = window.requestAnimationFrame.bind(window);
|
|
39
|
-
const router = await import("../src/client/router.ts");
|
|
40
|
-
|
|
41
|
-
function jsonResponse(pattern: string): Response {
|
|
42
|
-
return new Response(
|
|
43
|
-
JSON.stringify({
|
|
44
|
-
data: {},
|
|
45
|
-
layoutData: [],
|
|
46
|
-
params: {},
|
|
47
|
-
pattern,
|
|
48
|
-
head: "",
|
|
49
|
-
}),
|
|
50
|
-
{ headers: { "content-type": "application/json" } },
|
|
51
|
-
);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function captureFetch(): {
|
|
55
|
-
calls: Array<{ input: string; init?: RequestInit }>;
|
|
56
|
-
restore: () => void;
|
|
57
|
-
} {
|
|
58
|
-
const calls: Array<{ input: string; init?: RequestInit }> = [];
|
|
59
|
-
const original = globalThis.fetch;
|
|
60
|
-
// test shim over the global — precise fetch typing is impossible here.
|
|
61
|
-
// Echoes the requested pathname as the route pattern, mirroring renderRoute.
|
|
62
|
-
globalThis.fetch = (async (
|
|
63
|
-
input: string,
|
|
64
|
-
init?: RequestInit,
|
|
65
|
-
): Promise<Response> => {
|
|
66
|
-
calls.push({ input, init });
|
|
67
|
-
const pattern = new URL(input, "http://localhost").pathname;
|
|
68
|
-
return jsonResponse(pattern);
|
|
69
|
-
}) as unknown as typeof fetch;
|
|
70
|
-
return {
|
|
71
|
-
calls,
|
|
72
|
-
restore: () => {
|
|
73
|
-
globalThis.fetch = original;
|
|
74
|
-
},
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
describe("depends", () => {
|
|
79
|
-
test("no-op outside collection", () => {
|
|
80
|
-
depends("posts");
|
|
81
|
-
expect(hasDep("/", "posts")).toBe(false);
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
test("registers key during collection", () => {
|
|
85
|
-
startCollecting();
|
|
86
|
-
depends("posts");
|
|
87
|
-
stopCollecting("/");
|
|
88
|
-
expect(hasDep("/", "posts")).toBe(true);
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
test("multiple keys", () => {
|
|
92
|
-
startCollecting();
|
|
93
|
-
depends("posts");
|
|
94
|
-
depends("tags");
|
|
95
|
-
stopCollecting("/");
|
|
96
|
-
expect(hasDep("/", "posts")).toBe(true);
|
|
97
|
-
expect(hasDep("/", "tags")).toBe(true);
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
test("cleared on next collection", () => {
|
|
101
|
-
startCollecting();
|
|
102
|
-
depends("posts");
|
|
103
|
-
stopCollecting("/");
|
|
104
|
-
startCollecting();
|
|
105
|
-
depends("comments");
|
|
106
|
-
stopCollecting("/");
|
|
107
|
-
expect(hasDep("/", "posts")).toBe(false);
|
|
108
|
-
expect(hasDep("/", "comments")).toBe(true);
|
|
109
|
-
});
|
|
110
|
-
});
|
|
111
|
-
describe("navigate — head", () => {
|
|
112
|
-
test("server-rendered head tags are replaced, not kept beside the new ones", async () => {
|
|
113
|
-
const root = document.createElement("div");
|
|
114
|
-
root.id = "grimoire-root";
|
|
115
|
-
document.body.appendChild(root);
|
|
116
|
-
document.head.innerHTML =
|
|
117
|
-
'<meta charset="UTF-8"><!--grimoire-head--><title>Old</title><meta name="description" content="old"><!--/grimoire-head-->';
|
|
118
|
-
const g = globalThis as { DOMParser?: unknown };
|
|
119
|
-
g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
|
|
120
|
-
const original = globalThis.fetch;
|
|
121
|
-
globalThis.fetch = (async () =>
|
|
122
|
-
new Response(
|
|
123
|
-
JSON.stringify({
|
|
124
|
-
data: {},
|
|
125
|
-
layoutData: [],
|
|
126
|
-
params: {},
|
|
127
|
-
pattern: "/",
|
|
128
|
-
head: '<title>New</title><meta name="description" content="new">',
|
|
129
|
-
}),
|
|
130
|
-
{ headers: { "content-type": "application/json" } },
|
|
131
|
-
)) as unknown as typeof fetch;
|
|
132
|
-
try {
|
|
133
|
-
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
134
|
-
await router.navigate("/");
|
|
135
|
-
const descriptions = [
|
|
136
|
-
...document.head.querySelectorAll('meta[name="description"]'),
|
|
137
|
-
].map((m) => m.getAttribute("content"));
|
|
138
|
-
expect(descriptions).toEqual(["new"]);
|
|
139
|
-
expect(document.title).toBe("New");
|
|
140
|
-
expect(document.head.querySelectorAll("meta[charset]").length).toBe(1);
|
|
141
|
-
// a second navigation replaces the tags the first one added
|
|
142
|
-
await router.navigate("/");
|
|
143
|
-
expect(
|
|
144
|
-
document.head.querySelectorAll('meta[name="description"]').length,
|
|
145
|
-
).toBe(1);
|
|
146
|
-
} finally {
|
|
147
|
-
globalThis.fetch = original;
|
|
148
|
-
root.remove();
|
|
149
|
-
document.head.innerHTML = "";
|
|
150
|
-
}
|
|
151
|
-
});
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
describe("navigate — loading export", () => {
|
|
155
|
-
test("a lazy page module's loading export shows while data loads", async () => {
|
|
156
|
-
// other files' tests may leave a page host behind
|
|
157
|
-
for (const id of ["grimoire-root", "grimoire-page"])
|
|
158
|
-
document.getElementById(id)?.remove();
|
|
159
|
-
const root = document.createElement("div");
|
|
160
|
-
root.id = "grimoire-root";
|
|
161
|
-
const page = document.createElement("div");
|
|
162
|
-
page.id = "grimoire-page";
|
|
163
|
-
root.appendChild(page);
|
|
164
|
-
document.body.appendChild(root);
|
|
165
|
-
let release!: () => void;
|
|
166
|
-
const gate = new Promise<void>((r) => (release = r));
|
|
167
|
-
const original = globalThis.fetch;
|
|
168
|
-
globalThis.fetch = (async () => {
|
|
169
|
-
await gate;
|
|
170
|
-
return jsonResponse("/slow");
|
|
171
|
-
}) as unknown as typeof fetch;
|
|
172
|
-
try {
|
|
173
|
-
const Page = () => {
|
|
174
|
-
const el = document.createElement("p");
|
|
175
|
-
el.textContent = "page";
|
|
176
|
-
return el;
|
|
177
|
-
};
|
|
178
|
-
const loading = () => {
|
|
179
|
-
const el = document.createElement("p");
|
|
180
|
-
el.textContent = "loading";
|
|
181
|
-
return el;
|
|
182
|
-
};
|
|
183
|
-
router.initRouter(
|
|
184
|
-
{ "/slow": { __lazy: async () => ({ default: Page, loading }) } },
|
|
185
|
-
[],
|
|
186
|
-
);
|
|
187
|
-
const done = router.navigate("/slow");
|
|
188
|
-
for (let i = 0; i < 20 && !root.textContent?.includes("loading"); i++)
|
|
189
|
-
await new Promise((r) => setTimeout(r, 5));
|
|
190
|
-
expect(root.textContent).toContain("loading");
|
|
191
|
-
release();
|
|
192
|
-
await done;
|
|
193
|
-
expect(root.textContent).toContain("page");
|
|
194
|
-
} finally {
|
|
195
|
-
globalThis.fetch = original;
|
|
196
|
-
root.remove();
|
|
197
|
-
}
|
|
198
|
-
});
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
describe("navigate — view transitions", () => {
|
|
202
|
-
test("falls back to direct swap when startViewTransition is missing", async () => {
|
|
203
|
-
const root = document.createElement("div");
|
|
204
|
-
root.id = "grimoire-root";
|
|
205
|
-
document.body.appendChild(root);
|
|
206
|
-
const fetchShim = captureFetch();
|
|
207
|
-
try {
|
|
208
|
-
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
209
|
-
await router.navigate("/");
|
|
210
|
-
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
211
|
-
} finally {
|
|
212
|
-
fetchShim.restore();
|
|
213
|
-
root.remove();
|
|
214
|
-
}
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
test("routes the swap through startViewTransition when available", async () => {
|
|
218
|
-
const root = document.createElement("div");
|
|
219
|
-
root.id = "grimoire-root";
|
|
220
|
-
document.body.appendChild(root);
|
|
221
|
-
let vtCalled = false;
|
|
222
|
-
const docEnv = document as Document & {
|
|
223
|
-
startViewTransition?: (cb: () => void) => unknown;
|
|
224
|
-
};
|
|
225
|
-
docEnv.startViewTransition = (cb: () => void) => {
|
|
226
|
-
vtCalled = true;
|
|
227
|
-
cb();
|
|
228
|
-
return undefined;
|
|
229
|
-
};
|
|
230
|
-
const fetchShim = captureFetch();
|
|
231
|
-
try {
|
|
232
|
-
router.initRouter({ "/vt": () => document.createElement("main") }, []);
|
|
233
|
-
await router.navigate("/vt");
|
|
234
|
-
expect(vtCalled).toBe(true);
|
|
235
|
-
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
236
|
-
} finally {
|
|
237
|
-
delete docEnv.startViewTransition;
|
|
238
|
-
fetchShim.restore();
|
|
239
|
-
root.remove();
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
describe("shared-element view transitions", () => {
|
|
245
|
-
const nameOf = (el: Element) =>
|
|
246
|
-
(el as HTMLElement).style.getPropertyValue("view-transition-name");
|
|
247
|
-
|
|
248
|
-
test("elements sharing data-sigil-transition are named on both pages", async () => {
|
|
249
|
-
const root = document.createElement("div");
|
|
250
|
-
root.id = "grimoire-root";
|
|
251
|
-
const oldHero = document.createElement("img");
|
|
252
|
-
oldHero.setAttribute("data-sigil-transition", "hero-7");
|
|
253
|
-
const other = document.createElement("img");
|
|
254
|
-
other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
|
|
255
|
-
root.append(oldHero, other);
|
|
256
|
-
document.body.appendChild(root);
|
|
257
|
-
|
|
258
|
-
let newHero: Element | undefined;
|
|
259
|
-
const page = () => {
|
|
260
|
-
const main = document.createElement("main");
|
|
261
|
-
newHero = document.createElement("img");
|
|
262
|
-
newHero.setAttribute("data-sigil-transition", "hero-7");
|
|
263
|
-
main.appendChild(newHero);
|
|
264
|
-
return main;
|
|
265
|
-
};
|
|
266
|
-
const docEnv = document as unknown as {
|
|
267
|
-
startViewTransition?: (cb: () => void) => unknown;
|
|
268
|
-
};
|
|
269
|
-
const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] = [];
|
|
270
|
-
docEnv.startViewTransition = (cb: () => void) => {
|
|
271
|
-
const before = { oldNamed: nameOf(oldHero), otherNamed: nameOf(other), newNamed: "" };
|
|
272
|
-
cb();
|
|
273
|
-
before.newNamed = nameOf(newHero!);
|
|
274
|
-
seen.push(before);
|
|
275
|
-
return { finished: Promise.resolve() };
|
|
276
|
-
};
|
|
277
|
-
const shim = captureFetch();
|
|
278
|
-
try {
|
|
279
|
-
router.initRouter({ "/shared": page }, []);
|
|
280
|
-
await router.navigate("/shared");
|
|
281
|
-
// the old element is named when the browser snapshots, the new one
|
|
282
|
-
// once the swap ran; an element with no partner is left alone
|
|
283
|
-
expect(seen).toEqual([{ oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" }]);
|
|
284
|
-
await Promise.resolve();
|
|
285
|
-
await Promise.resolve();
|
|
286
|
-
expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
|
|
287
|
-
} finally {
|
|
288
|
-
delete docEnv.startViewTransition;
|
|
289
|
-
shim.restore();
|
|
290
|
-
root.remove();
|
|
291
|
-
}
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
test("a key used twice on a page is skipped", async () => {
|
|
295
|
-
const root = document.createElement("div");
|
|
296
|
-
root.id = "grimoire-root";
|
|
297
|
-
for (let i = 0; i < 2; i++) {
|
|
298
|
-
const el = document.createElement("div");
|
|
299
|
-
el.setAttribute("data-sigil-transition", "dup");
|
|
300
|
-
root.appendChild(el);
|
|
301
|
-
}
|
|
302
|
-
document.body.appendChild(root);
|
|
303
|
-
const docEnv = document as unknown as {
|
|
304
|
-
startViewTransition?: (cb: () => void) => unknown;
|
|
305
|
-
};
|
|
306
|
-
let named = 0;
|
|
307
|
-
docEnv.startViewTransition = (cb: () => void) => {
|
|
308
|
-
named = document.querySelectorAll('[style*="view-transition-name"]').length;
|
|
309
|
-
cb();
|
|
310
|
-
return undefined;
|
|
311
|
-
};
|
|
312
|
-
const shim = captureFetch();
|
|
313
|
-
try {
|
|
314
|
-
router.initRouter(
|
|
315
|
-
{
|
|
316
|
-
"/dup": () => {
|
|
317
|
-
const el = document.createElement("div");
|
|
318
|
-
el.setAttribute("data-sigil-transition", "dup");
|
|
319
|
-
return el;
|
|
320
|
-
},
|
|
321
|
-
},
|
|
322
|
-
[],
|
|
323
|
-
);
|
|
324
|
-
await router.navigate("/dup");
|
|
325
|
-
expect(named).toBe(0);
|
|
326
|
-
} finally {
|
|
327
|
-
delete docEnv.startViewTransition;
|
|
328
|
-
shim.restore();
|
|
329
|
-
root.remove();
|
|
330
|
-
}
|
|
331
|
-
});
|
|
332
|
-
});
|
|
333
|
-
|
|
334
|
-
describe("hover prefetch", () => {
|
|
335
|
-
// The 80ms debounce is real timer logic under test — fake timers advance
|
|
336
|
-
// it deterministically instead of sleeping past it.
|
|
337
|
-
test("plain internal link prefetches route data; preload=off skips", () => {
|
|
338
|
-
vi.useFakeTimers();
|
|
339
|
-
router.initRouter(
|
|
340
|
-
{
|
|
341
|
-
"/": () => document.createElement("div"),
|
|
342
|
-
"/off": () => document.createElement("div"),
|
|
343
|
-
},
|
|
344
|
-
[],
|
|
345
|
-
);
|
|
346
|
-
const fetchShim = captureFetch();
|
|
347
|
-
try {
|
|
348
|
-
const plain = document.createElement("a");
|
|
349
|
-
plain.setAttribute("href", "/");
|
|
350
|
-
document.body.appendChild(plain);
|
|
351
|
-
plain.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
352
|
-
vi.advanceTimersByTime(80);
|
|
353
|
-
expect(fetchShim.calls.length).toBe(1);
|
|
354
|
-
expect(fetchShim.calls[0]?.init?.headers).toEqual({
|
|
355
|
-
"x-grimoire-navigate": "1",
|
|
356
|
-
});
|
|
357
|
-
|
|
358
|
-
const optedOut = document.createElement("a");
|
|
359
|
-
optedOut.setAttribute("href", "/off");
|
|
360
|
-
optedOut.setAttribute("data-sigil-preload", "off");
|
|
361
|
-
document.body.appendChild(optedOut);
|
|
362
|
-
optedOut.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
363
|
-
vi.advanceTimersByTime(80);
|
|
364
|
-
expect(fetchShim.calls.length).toBe(1); // unchanged
|
|
365
|
-
} finally {
|
|
366
|
-
vi.useRealTimers();
|
|
367
|
-
fetchShim.restore();
|
|
368
|
-
}
|
|
369
|
-
});
|
|
370
|
-
|
|
371
|
-
test("external links are never prefetched", () => {
|
|
372
|
-
vi.useFakeTimers();
|
|
373
|
-
const fetchShim = captureFetch();
|
|
374
|
-
try {
|
|
375
|
-
const ext = document.createElement("a");
|
|
376
|
-
ext.setAttribute("href", "https://example.com/page");
|
|
377
|
-
document.body.appendChild(ext);
|
|
378
|
-
ext.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
379
|
-
vi.advanceTimersByTime(80);
|
|
380
|
-
expect(fetchShim.calls.length).toBe(0);
|
|
381
|
-
} finally {
|
|
382
|
-
vi.useRealTimers();
|
|
383
|
-
fetchShim.restore();
|
|
384
|
-
}
|
|
385
|
-
});
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
describe("prefetch reuse", () => {
|
|
389
|
-
test("a tap reuses the request started on touchstart", async () => {
|
|
390
|
-
const root = document.createElement("div");
|
|
391
|
-
root.id = "grimoire-root";
|
|
392
|
-
document.body.appendChild(root);
|
|
393
|
-
router.initRouter({ "/tap": () => document.createElement("main") }, []);
|
|
394
|
-
const shim = captureFetch();
|
|
395
|
-
try {
|
|
396
|
-
const a = document.createElement("a");
|
|
397
|
-
a.setAttribute("href", "/tap");
|
|
398
|
-
document.body.appendChild(a);
|
|
399
|
-
a.dispatchEvent(new Event("touchstart", { bubbles: true }));
|
|
400
|
-
expect(shim.calls.length).toBe(1);
|
|
401
|
-
|
|
402
|
-
await router.navigate("/tap");
|
|
403
|
-
// the click did not issue a second request
|
|
404
|
-
expect(shim.calls.length).toBe(1);
|
|
405
|
-
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
406
|
-
|
|
407
|
-
// and a prefetch is single-use: the next visit fetches fresh data
|
|
408
|
-
await router.navigate("/tap");
|
|
409
|
-
expect(shim.calls.length).toBe(2);
|
|
410
|
-
} finally {
|
|
411
|
-
shim.restore();
|
|
412
|
-
root.remove();
|
|
413
|
-
}
|
|
414
|
-
});
|
|
415
|
-
|
|
416
|
-
test("a click cancels the hover prefetch it just consumed", async () => {
|
|
417
|
-
const root = document.createElement("div");
|
|
418
|
-
root.id = "grimoire-root";
|
|
419
|
-
document.body.appendChild(root);
|
|
420
|
-
router.initRouter({ "/hov": () => document.createElement("main") }, []);
|
|
421
|
-
const shim = captureFetch();
|
|
422
|
-
try {
|
|
423
|
-
const a = document.createElement("a");
|
|
424
|
-
a.setAttribute("href", "/hov");
|
|
425
|
-
document.body.appendChild(a);
|
|
426
|
-
a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
427
|
-
a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
428
|
-
await Bun.sleep(200); // past the 80ms hover delay
|
|
429
|
-
expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
|
|
430
|
-
expect(shim.calls.length).toBe(1); // its own request, not a second
|
|
431
|
-
} finally {
|
|
432
|
-
shim.restore();
|
|
433
|
-
root.remove();
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
test("a prefetch made before a cookie changed is not reused", async () => {
|
|
438
|
-
const root = document.createElement("div");
|
|
439
|
-
root.id = "grimoire-root";
|
|
440
|
-
document.body.appendChild(root);
|
|
441
|
-
router.initRouter({ "/pref": () => document.createElement("main") }, []);
|
|
442
|
-
const shim = captureFetch();
|
|
443
|
-
try {
|
|
444
|
-
document.cookie = "region=jp";
|
|
445
|
-
router.prefetch("/pref");
|
|
446
|
-
expect(shim.calls.length).toBe(1);
|
|
447
|
-
document.cookie = "region=en"; // the visitor switched server
|
|
448
|
-
await router.navigate("/pref");
|
|
449
|
-
// the held response was fetched as jp, so the click asks again
|
|
450
|
-
expect(shim.calls.length).toBe(2);
|
|
451
|
-
} finally {
|
|
452
|
-
document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
|
453
|
-
shim.restore();
|
|
454
|
-
root.remove();
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
|
|
458
|
-
test("invalidateAll never serves a prefetched response", async () => {
|
|
459
|
-
const root = document.createElement("div");
|
|
460
|
-
root.id = "grimoire-root";
|
|
461
|
-
document.body.appendChild(root);
|
|
462
|
-
window.history.pushState(null, "", "/inv");
|
|
463
|
-
router.initRouter({ "/inv": () => document.createElement("main") }, []);
|
|
464
|
-
const shim = captureFetch();
|
|
465
|
-
try {
|
|
466
|
-
await router.navigate("/inv");
|
|
467
|
-
router.prefetch("/inv");
|
|
468
|
-
const before = shim.calls.length;
|
|
469
|
-
await router.invalidateAll();
|
|
470
|
-
expect(shim.calls.length).toBe(before + 1);
|
|
471
|
-
} finally {
|
|
472
|
-
shim.restore();
|
|
473
|
-
root.remove();
|
|
474
|
-
}
|
|
475
|
-
});
|
|
476
|
-
});
|
|
477
|
-
|
|
478
|
-
describe("popstate — query string", () => {
|
|
479
|
-
// popstate fires navigate() from an event listener, so there is no promise
|
|
480
|
-
// to await at the call site. afterNavigate is the router's own completion
|
|
481
|
-
// signal; a fixed sleep would be both slower and racy.
|
|
482
|
-
function onNavigated(): Promise<void> {
|
|
483
|
-
const { promise, resolve } = Promise.withResolvers<void>();
|
|
484
|
-
router.afterNavigate(() => resolve());
|
|
485
|
-
return promise;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
// Back used to refetch the bare pathname, so a query-driven page rendered
|
|
489
|
-
// unfiltered data while the address bar still showed the query.
|
|
490
|
-
test("back to a query URL refetches with the query intact", async () => {
|
|
491
|
-
const root = document.createElement("div");
|
|
492
|
-
root.id = "grimoire-root";
|
|
493
|
-
document.body.appendChild(root);
|
|
494
|
-
window.history.pushState(null, "", "/");
|
|
495
|
-
router.initRouter(
|
|
496
|
-
{
|
|
497
|
-
"/list": () => document.createElement("div"),
|
|
498
|
-
"/other": () => document.createElement("div"),
|
|
499
|
-
},
|
|
500
|
-
[],
|
|
501
|
-
);
|
|
502
|
-
const shim = captureFetch();
|
|
503
|
-
try {
|
|
504
|
-
await router.navigate("/list?q=fireball&page=2");
|
|
505
|
-
await router.navigate("/other");
|
|
506
|
-
shim.calls.length = 0;
|
|
507
|
-
|
|
508
|
-
// the browser moves history itself, then fires popstate
|
|
509
|
-
const navigated = onNavigated();
|
|
510
|
-
window.history.pushState(null, "", "/list?q=fireball&page=2");
|
|
511
|
-
window.dispatchEvent(new Event("popstate"));
|
|
512
|
-
await navigated;
|
|
513
|
-
|
|
514
|
-
expect(shim.calls.map((c) => c.input)).toEqual([
|
|
515
|
-
"/list?q=fireball&page=2",
|
|
516
|
-
]);
|
|
517
|
-
} finally {
|
|
518
|
-
router.afterNavigate(() => {});
|
|
519
|
-
shim.restore();
|
|
520
|
-
root.remove();
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
|
|
524
|
-
test("a popstate that only changes the query still refetches", async () => {
|
|
525
|
-
const root = document.createElement("div");
|
|
526
|
-
root.id = "grimoire-root";
|
|
527
|
-
document.body.appendChild(root);
|
|
528
|
-
window.history.pushState(null, "", "/");
|
|
529
|
-
router.initRouter({ "/list": () => document.createElement("div") }, []);
|
|
530
|
-
const shim = captureFetch();
|
|
531
|
-
try {
|
|
532
|
-
await router.navigate("/list?page=2");
|
|
533
|
-
shim.calls.length = 0;
|
|
534
|
-
|
|
535
|
-
const navigated = onNavigated();
|
|
536
|
-
window.history.pushState(null, "", "/list?page=1");
|
|
537
|
-
window.dispatchEvent(new Event("popstate"));
|
|
538
|
-
await navigated;
|
|
539
|
-
|
|
540
|
-
expect(shim.calls.map((c) => c.input)).toEqual(["/list?page=1"]);
|
|
541
|
-
} finally {
|
|
542
|
-
router.afterNavigate(() => {});
|
|
543
|
-
shim.restore();
|
|
544
|
-
root.remove();
|
|
545
|
-
}
|
|
546
|
-
});
|
|
547
|
-
});
|
|
548
|
-
|
|
549
|
-
describe("enhance — named action URLs", () => {
|
|
550
|
-
test("action starting with ?/ submits to the current pathname", async () => {
|
|
551
|
-
// earlier navigate() tests moved history — reset to a clean path
|
|
552
|
-
window.history.pushState(null, "", "/");
|
|
553
|
-
const { enhance } = await import("../src/client/enhance.ts");
|
|
554
|
-
const calls: string[] = [];
|
|
555
|
-
const original = globalThis.fetch;
|
|
556
|
-
globalThis.fetch = (async (input: string) => {
|
|
557
|
-
calls.push(input);
|
|
558
|
-
return new Response(null, { status: 303, headers: { location: "/" } });
|
|
559
|
-
}) as unknown as typeof fetch;
|
|
560
|
-
|
|
561
|
-
const form = document.createElement("form");
|
|
562
|
-
document.body.appendChild(form);
|
|
563
|
-
const cleanup = enhance(form, { action: "?/create" });
|
|
564
|
-
try {
|
|
565
|
-
form.dispatchEvent(
|
|
566
|
-
new Event("submit", { bubbles: true, cancelable: true }),
|
|
567
|
-
);
|
|
568
|
-
await new Promise((r) => setTimeout(r, 0));
|
|
569
|
-
expect(calls).toEqual([`${window.location.pathname}?/create`]);
|
|
570
|
-
} finally {
|
|
571
|
-
cleanup();
|
|
572
|
-
form.remove();
|
|
573
|
-
globalThis.fetch = original;
|
|
574
|
-
}
|
|
575
|
-
});
|
|
576
|
-
});
|
|
577
|
-
|
|
578
|
-
describe("enhance — outcomes", () => {
|
|
579
|
-
async function submit(
|
|
580
|
-
reply: Response,
|
|
581
|
-
options: Record<string, unknown> = {},
|
|
582
|
-
submitter?: HTMLButtonElement,
|
|
583
|
-
) {
|
|
584
|
-
window.history.pushState(null, "", "/books");
|
|
585
|
-
const { enhance } = await import("../src/client/enhance.ts");
|
|
586
|
-
const sent: { headers: Headers; body: FormData }[] = [];
|
|
587
|
-
const navigations: [string, boolean | undefined][] = [];
|
|
588
|
-
const g = globalThis as Record<string, unknown>;
|
|
589
|
-
const originalFetch = globalThis.fetch;
|
|
590
|
-
const originalNavigate = g.__grimoire_navigate__;
|
|
591
|
-
globalThis.fetch = (async (_input: string, init: RequestInit) => {
|
|
592
|
-
sent.push({
|
|
593
|
-
headers: new Headers(init.headers),
|
|
594
|
-
body: init.body as FormData,
|
|
595
|
-
});
|
|
596
|
-
return reply;
|
|
597
|
-
}) as unknown as typeof fetch;
|
|
598
|
-
g.__grimoire_navigate__ = (path: string, replace?: boolean) =>
|
|
599
|
-
navigations.push([path, replace]);
|
|
600
|
-
|
|
601
|
-
const form = document.createElement("form");
|
|
602
|
-
form.setAttribute("action", "?/toggle");
|
|
603
|
-
const input = document.createElement("input");
|
|
604
|
-
input.setAttribute("name", "id");
|
|
605
|
-
input.setAttribute("value", "7");
|
|
606
|
-
form.appendChild(input);
|
|
607
|
-
if (submitter) form.appendChild(submitter);
|
|
608
|
-
document.body.appendChild(form);
|
|
609
|
-
const cleanup = enhance(form, options);
|
|
610
|
-
try {
|
|
611
|
-
const event = new Event("submit", { bubbles: true, cancelable: true });
|
|
612
|
-
if (submitter)
|
|
613
|
-
Object.defineProperty(event, "submitter", { value: submitter });
|
|
614
|
-
form.dispatchEvent(event);
|
|
615
|
-
await new Promise((r) => setTimeout(r, 0));
|
|
616
|
-
return { sent, navigations };
|
|
617
|
-
} finally {
|
|
618
|
-
cleanup();
|
|
619
|
-
form.remove();
|
|
620
|
-
globalThis.fetch = originalFetch;
|
|
621
|
-
g.__grimoire_navigate__ = originalNavigate;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
test("success on the same page re-runs its loads in place", async () => {
|
|
626
|
-
const seen: unknown[] = [];
|
|
627
|
-
const { sent, navigations } = await submit(
|
|
628
|
-
Response.json({
|
|
629
|
-
type: "success",
|
|
630
|
-
location: "http://localhost/books",
|
|
631
|
-
data: { ok: 1 },
|
|
632
|
-
}),
|
|
633
|
-
{ onSuccess: (r: unknown) => seen.push(r) },
|
|
634
|
-
);
|
|
635
|
-
expect(sent[0]!.headers.get("x-grimoire-form")).toBe("1");
|
|
636
|
-
expect(seen).toEqual([
|
|
637
|
-
{ redirect: "http://localhost/books", data: { ok: 1 } },
|
|
638
|
-
]);
|
|
639
|
-
// replace: no new history entry for the same page
|
|
640
|
-
expect(navigations).toEqual([["/books", true]]);
|
|
641
|
-
});
|
|
642
|
-
|
|
643
|
-
test("a redirect elsewhere pushes a new entry", async () => {
|
|
644
|
-
const { navigations } = await submit(
|
|
645
|
-
Response.json({ type: "redirect", status: 303, location: "/books/7" }),
|
|
646
|
-
);
|
|
647
|
-
expect(navigations).toEqual([["/books/7", false]]);
|
|
648
|
-
});
|
|
649
|
-
|
|
650
|
-
test("fail() data goes to onFail, and nothing navigates", async () => {
|
|
651
|
-
const failed: unknown[] = [];
|
|
652
|
-
const { navigations } = await submit(
|
|
653
|
-
Response.json(
|
|
654
|
-
{ fail: true, status: 400, data: { problem: "x" } },
|
|
655
|
-
{ status: 400 },
|
|
656
|
-
),
|
|
657
|
-
{ onFail: (d: unknown) => failed.push(d) },
|
|
658
|
-
);
|
|
659
|
-
expect(failed).toEqual([{ problem: "x" }]);
|
|
660
|
-
expect(navigations).toEqual([]);
|
|
661
|
-
});
|
|
662
|
-
|
|
663
|
-
test("the submitting button's name=value is sent", async () => {
|
|
664
|
-
const button = document.createElement("button");
|
|
665
|
-
button.name = "read";
|
|
666
|
-
button.value = "1";
|
|
667
|
-
const { sent } = await submit(
|
|
668
|
-
Response.json({ type: "success", location: "/books", data: null }),
|
|
669
|
-
{},
|
|
670
|
-
button,
|
|
671
|
-
);
|
|
672
|
-
expect(sent[0]!.body.get("read")).toBe("1");
|
|
673
|
-
});
|
|
674
|
-
});
|
|
675
|
-
|
|
676
|
-
describe("Page.load — parent()", () => {
|
|
677
|
-
test("parent() merges layoutData entries outermost-first", async () => {
|
|
678
|
-
let seenParent: Record<string, unknown> | undefined;
|
|
679
|
-
const PageWithLoad = Object.assign(() => document.createElement("div"), {
|
|
680
|
-
load: async (ctx: { parent: () => Promise<Record<string, unknown>> }) => {
|
|
681
|
-
seenParent = await ctx.parent();
|
|
682
|
-
return {};
|
|
683
|
-
},
|
|
684
|
-
});
|
|
685
|
-
|
|
686
|
-
const original = globalThis.fetch;
|
|
687
|
-
globalThis.fetch = (async (input: string) => {
|
|
688
|
-
const pattern = new URL(input, "http://localhost").pathname;
|
|
689
|
-
return new Response(
|
|
690
|
-
JSON.stringify({
|
|
691
|
-
data: {},
|
|
692
|
-
layoutData: [{ a: 1 }, { b: 2 }],
|
|
693
|
-
params: {},
|
|
694
|
-
pattern,
|
|
695
|
-
head: "",
|
|
696
|
-
}),
|
|
697
|
-
{ headers: { "content-type": "application/json" } },
|
|
698
|
-
);
|
|
699
|
-
}) as unknown as typeof fetch;
|
|
700
|
-
|
|
701
|
-
try {
|
|
702
|
-
router.initRouter({ "/pl": PageWithLoad }, []);
|
|
703
|
-
await router.navigate("/pl");
|
|
704
|
-
expect(seenParent).toEqual({ a: 1, b: 2 });
|
|
705
|
-
} finally {
|
|
706
|
-
globalThis.fetch = original;
|
|
707
|
-
}
|
|
708
|
-
});
|
|
709
|
-
});
|
|
710
|
-
|
|
711
|
-
describe("invalidate", () => {
|
|
712
|
-
test("refetches only on key intersection; empty deps always refetch", async () => {
|
|
713
|
-
router.initRouter({ "/": () => document.createElement("div") }, []);
|
|
714
|
-
const shim = captureFetch();
|
|
715
|
-
try {
|
|
716
|
-
await router.navigate("/"); // establishes lastState.pattern = "/"
|
|
717
|
-
|
|
718
|
-
setDeps("/", ["user:1"]);
|
|
719
|
-
shim.calls.length = 0;
|
|
720
|
-
await router.invalidate("other");
|
|
721
|
-
expect(shim.calls.length).toBe(0); // no intersection → skip
|
|
722
|
-
|
|
723
|
-
await router.invalidate("user:1");
|
|
724
|
-
expect(shim.calls.length).toBe(1); // intersect → refetch
|
|
725
|
-
|
|
726
|
-
clearDeps("/");
|
|
727
|
-
await router.invalidate("anything");
|
|
728
|
-
expect(shim.calls.length).toBe(2); // no deps → conservative refetch
|
|
729
|
-
} finally {
|
|
730
|
-
shim.restore();
|
|
731
|
-
clearDeps("/");
|
|
732
|
-
}
|
|
733
|
-
});
|
|
734
|
-
});
|
|
1
|
+
import { beforeEach, describe, expect, test, vi } from "bun:test";
|
|
2
|
+
import type { Document, History, Location, Window } from "happy-dom";
|
|
3
|
+
import {
|
|
4
|
+
clearDeps,
|
|
5
|
+
depends,
|
|
6
|
+
hasDep,
|
|
7
|
+
setDeps,
|
|
8
|
+
startCollecting,
|
|
9
|
+
stopCollecting,
|
|
10
|
+
} from "../src/client/deps.ts";
|
|
11
|
+
|
|
12
|
+
// test/preload.ts installs happy-dom globals at runtime; this package's
|
|
13
|
+
// compiler options have no DOM lib, so declare the shapes we rely on.
|
|
14
|
+
declare global {
|
|
15
|
+
// biome-ignore-all lint/style/noVar: ambient global declarations require var
|
|
16
|
+
var window: Window;
|
|
17
|
+
var document: Document;
|
|
18
|
+
var location: Location;
|
|
19
|
+
var history: History;
|
|
20
|
+
var MouseEvent: Window["MouseEvent"];
|
|
21
|
+
var Event: Window["Event"];
|
|
22
|
+
var requestAnimationFrame: Window["requestAnimationFrame"];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// router.ts reads `location` at module load — DOM globals must exist first.
|
|
26
|
+
// Dynamic import is required because the module under test captures location
|
|
27
|
+
// during evaluation, which static-hoisted imports would race. The default
|
|
28
|
+
// about:blank URL has origin "null", which breaks new URL(href, origin) —
|
|
29
|
+
// point the window at a real origin first.
|
|
30
|
+
window.location.href = "http://localhost/";
|
|
31
|
+
const globalEnv = globalThis as typeof globalThis & {
|
|
32
|
+
location: Location;
|
|
33
|
+
history: History;
|
|
34
|
+
requestAnimationFrame: Window["requestAnimationFrame"];
|
|
35
|
+
};
|
|
36
|
+
globalEnv.location = window.location;
|
|
37
|
+
globalEnv.history = window.history;
|
|
38
|
+
globalEnv.requestAnimationFrame = window.requestAnimationFrame.bind(window);
|
|
39
|
+
const router = await import("../src/client/router.ts");
|
|
40
|
+
|
|
41
|
+
function jsonResponse(pattern: string): Response {
|
|
42
|
+
return new Response(
|
|
43
|
+
JSON.stringify({
|
|
44
|
+
data: {},
|
|
45
|
+
layoutData: [],
|
|
46
|
+
params: {},
|
|
47
|
+
pattern,
|
|
48
|
+
head: "",
|
|
49
|
+
}),
|
|
50
|
+
{ headers: { "content-type": "application/json" } },
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function captureFetch(): {
|
|
55
|
+
calls: Array<{ input: string; init?: RequestInit }>;
|
|
56
|
+
restore: () => void;
|
|
57
|
+
} {
|
|
58
|
+
const calls: Array<{ input: string; init?: RequestInit }> = [];
|
|
59
|
+
const original = globalThis.fetch;
|
|
60
|
+
// test shim over the global — precise fetch typing is impossible here.
|
|
61
|
+
// Echoes the requested pathname as the route pattern, mirroring renderRoute.
|
|
62
|
+
globalThis.fetch = (async (
|
|
63
|
+
input: string,
|
|
64
|
+
init?: RequestInit,
|
|
65
|
+
): Promise<Response> => {
|
|
66
|
+
calls.push({ input, init });
|
|
67
|
+
const pattern = new URL(input, "http://localhost").pathname;
|
|
68
|
+
return jsonResponse(pattern);
|
|
69
|
+
}) as unknown as typeof fetch;
|
|
70
|
+
return {
|
|
71
|
+
calls,
|
|
72
|
+
restore: () => {
|
|
73
|
+
globalThis.fetch = original;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
describe("depends", () => {
|
|
79
|
+
test("no-op outside collection", () => {
|
|
80
|
+
depends("posts");
|
|
81
|
+
expect(hasDep("/", "posts")).toBe(false);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("registers key during collection", () => {
|
|
85
|
+
startCollecting();
|
|
86
|
+
depends("posts");
|
|
87
|
+
stopCollecting("/");
|
|
88
|
+
expect(hasDep("/", "posts")).toBe(true);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("multiple keys", () => {
|
|
92
|
+
startCollecting();
|
|
93
|
+
depends("posts");
|
|
94
|
+
depends("tags");
|
|
95
|
+
stopCollecting("/");
|
|
96
|
+
expect(hasDep("/", "posts")).toBe(true);
|
|
97
|
+
expect(hasDep("/", "tags")).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("cleared on next collection", () => {
|
|
101
|
+
startCollecting();
|
|
102
|
+
depends("posts");
|
|
103
|
+
stopCollecting("/");
|
|
104
|
+
startCollecting();
|
|
105
|
+
depends("comments");
|
|
106
|
+
stopCollecting("/");
|
|
107
|
+
expect(hasDep("/", "posts")).toBe(false);
|
|
108
|
+
expect(hasDep("/", "comments")).toBe(true);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
describe("navigate — head", () => {
|
|
112
|
+
test("server-rendered head tags are replaced, not kept beside the new ones", async () => {
|
|
113
|
+
const root = document.createElement("div");
|
|
114
|
+
root.id = "grimoire-root";
|
|
115
|
+
document.body.appendChild(root);
|
|
116
|
+
document.head.innerHTML =
|
|
117
|
+
'<meta charset="UTF-8"><!--grimoire-head--><title>Old</title><meta name="description" content="old"><!--/grimoire-head-->';
|
|
118
|
+
const g = globalThis as { DOMParser?: unknown };
|
|
119
|
+
g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
|
|
120
|
+
const original = globalThis.fetch;
|
|
121
|
+
globalThis.fetch = (async () =>
|
|
122
|
+
new Response(
|
|
123
|
+
JSON.stringify({
|
|
124
|
+
data: {},
|
|
125
|
+
layoutData: [],
|
|
126
|
+
params: {},
|
|
127
|
+
pattern: "/",
|
|
128
|
+
head: '<title>New</title><meta name="description" content="new">',
|
|
129
|
+
}),
|
|
130
|
+
{ headers: { "content-type": "application/json" } },
|
|
131
|
+
)) as unknown as typeof fetch;
|
|
132
|
+
try {
|
|
133
|
+
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
134
|
+
await router.navigate("/");
|
|
135
|
+
const descriptions = [
|
|
136
|
+
...document.head.querySelectorAll('meta[name="description"]'),
|
|
137
|
+
].map((m) => m.getAttribute("content"));
|
|
138
|
+
expect(descriptions).toEqual(["new"]);
|
|
139
|
+
expect(document.title).toBe("New");
|
|
140
|
+
expect(document.head.querySelectorAll("meta[charset]").length).toBe(1);
|
|
141
|
+
// a second navigation replaces the tags the first one added
|
|
142
|
+
await router.navigate("/");
|
|
143
|
+
expect(
|
|
144
|
+
document.head.querySelectorAll('meta[name="description"]').length,
|
|
145
|
+
).toBe(1);
|
|
146
|
+
} finally {
|
|
147
|
+
globalThis.fetch = original;
|
|
148
|
+
root.remove();
|
|
149
|
+
document.head.innerHTML = "";
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
describe("navigate — loading export", () => {
|
|
155
|
+
test("a lazy page module's loading export shows while data loads", async () => {
|
|
156
|
+
// other files' tests may leave a page host behind
|
|
157
|
+
for (const id of ["grimoire-root", "grimoire-page"])
|
|
158
|
+
document.getElementById(id)?.remove();
|
|
159
|
+
const root = document.createElement("div");
|
|
160
|
+
root.id = "grimoire-root";
|
|
161
|
+
const page = document.createElement("div");
|
|
162
|
+
page.id = "grimoire-page";
|
|
163
|
+
root.appendChild(page);
|
|
164
|
+
document.body.appendChild(root);
|
|
165
|
+
let release!: () => void;
|
|
166
|
+
const gate = new Promise<void>((r) => (release = r));
|
|
167
|
+
const original = globalThis.fetch;
|
|
168
|
+
globalThis.fetch = (async () => {
|
|
169
|
+
await gate;
|
|
170
|
+
return jsonResponse("/slow");
|
|
171
|
+
}) as unknown as typeof fetch;
|
|
172
|
+
try {
|
|
173
|
+
const Page = () => {
|
|
174
|
+
const el = document.createElement("p");
|
|
175
|
+
el.textContent = "page";
|
|
176
|
+
return el;
|
|
177
|
+
};
|
|
178
|
+
const loading = () => {
|
|
179
|
+
const el = document.createElement("p");
|
|
180
|
+
el.textContent = "loading";
|
|
181
|
+
return el;
|
|
182
|
+
};
|
|
183
|
+
router.initRouter(
|
|
184
|
+
{ "/slow": { __lazy: async () => ({ default: Page, loading }) } },
|
|
185
|
+
[],
|
|
186
|
+
);
|
|
187
|
+
const done = router.navigate("/slow");
|
|
188
|
+
for (let i = 0; i < 20 && !root.textContent?.includes("loading"); i++)
|
|
189
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
190
|
+
expect(root.textContent).toContain("loading");
|
|
191
|
+
release();
|
|
192
|
+
await done;
|
|
193
|
+
expect(root.textContent).toContain("page");
|
|
194
|
+
} finally {
|
|
195
|
+
globalThis.fetch = original;
|
|
196
|
+
root.remove();
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
describe("navigate — view transitions", () => {
|
|
202
|
+
test("falls back to direct swap when startViewTransition is missing", async () => {
|
|
203
|
+
const root = document.createElement("div");
|
|
204
|
+
root.id = "grimoire-root";
|
|
205
|
+
document.body.appendChild(root);
|
|
206
|
+
const fetchShim = captureFetch();
|
|
207
|
+
try {
|
|
208
|
+
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
209
|
+
await router.navigate("/");
|
|
210
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
211
|
+
} finally {
|
|
212
|
+
fetchShim.restore();
|
|
213
|
+
root.remove();
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("routes the swap through startViewTransition when available", async () => {
|
|
218
|
+
const root = document.createElement("div");
|
|
219
|
+
root.id = "grimoire-root";
|
|
220
|
+
document.body.appendChild(root);
|
|
221
|
+
let vtCalled = false;
|
|
222
|
+
const docEnv = document as Document & {
|
|
223
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
224
|
+
};
|
|
225
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
226
|
+
vtCalled = true;
|
|
227
|
+
cb();
|
|
228
|
+
return undefined;
|
|
229
|
+
};
|
|
230
|
+
const fetchShim = captureFetch();
|
|
231
|
+
try {
|
|
232
|
+
router.initRouter({ "/vt": () => document.createElement("main") }, []);
|
|
233
|
+
await router.navigate("/vt");
|
|
234
|
+
expect(vtCalled).toBe(true);
|
|
235
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
236
|
+
} finally {
|
|
237
|
+
delete docEnv.startViewTransition;
|
|
238
|
+
fetchShim.restore();
|
|
239
|
+
root.remove();
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe("shared-element view transitions", () => {
|
|
245
|
+
const nameOf = (el: Element) =>
|
|
246
|
+
(el as HTMLElement).style.getPropertyValue("view-transition-name");
|
|
247
|
+
|
|
248
|
+
test("elements sharing data-sigil-transition are named on both pages", async () => {
|
|
249
|
+
const root = document.createElement("div");
|
|
250
|
+
root.id = "grimoire-root";
|
|
251
|
+
const oldHero = document.createElement("img");
|
|
252
|
+
oldHero.setAttribute("data-sigil-transition", "hero-7");
|
|
253
|
+
const other = document.createElement("img");
|
|
254
|
+
other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
|
|
255
|
+
root.append(oldHero, other);
|
|
256
|
+
document.body.appendChild(root);
|
|
257
|
+
|
|
258
|
+
let newHero: Element | undefined;
|
|
259
|
+
const page = () => {
|
|
260
|
+
const main = document.createElement("main");
|
|
261
|
+
newHero = document.createElement("img");
|
|
262
|
+
newHero.setAttribute("data-sigil-transition", "hero-7");
|
|
263
|
+
main.appendChild(newHero);
|
|
264
|
+
return main;
|
|
265
|
+
};
|
|
266
|
+
const docEnv = document as unknown as {
|
|
267
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
268
|
+
};
|
|
269
|
+
const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] = [];
|
|
270
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
271
|
+
const before = { oldNamed: nameOf(oldHero), otherNamed: nameOf(other), newNamed: "" };
|
|
272
|
+
cb();
|
|
273
|
+
before.newNamed = nameOf(newHero!);
|
|
274
|
+
seen.push(before);
|
|
275
|
+
return { finished: Promise.resolve() };
|
|
276
|
+
};
|
|
277
|
+
const shim = captureFetch();
|
|
278
|
+
try {
|
|
279
|
+
router.initRouter({ "/shared": page }, []);
|
|
280
|
+
await router.navigate("/shared");
|
|
281
|
+
// the old element is named when the browser snapshots, the new one
|
|
282
|
+
// once the swap ran; an element with no partner is left alone
|
|
283
|
+
expect(seen).toEqual([{ oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" }]);
|
|
284
|
+
await Promise.resolve();
|
|
285
|
+
await Promise.resolve();
|
|
286
|
+
expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
|
|
287
|
+
} finally {
|
|
288
|
+
delete docEnv.startViewTransition;
|
|
289
|
+
shim.restore();
|
|
290
|
+
root.remove();
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test("a key used twice on a page is skipped", async () => {
|
|
295
|
+
const root = document.createElement("div");
|
|
296
|
+
root.id = "grimoire-root";
|
|
297
|
+
for (let i = 0; i < 2; i++) {
|
|
298
|
+
const el = document.createElement("div");
|
|
299
|
+
el.setAttribute("data-sigil-transition", "dup");
|
|
300
|
+
root.appendChild(el);
|
|
301
|
+
}
|
|
302
|
+
document.body.appendChild(root);
|
|
303
|
+
const docEnv = document as unknown as {
|
|
304
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
305
|
+
};
|
|
306
|
+
let named = 0;
|
|
307
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
308
|
+
named = document.querySelectorAll('[style*="view-transition-name"]').length;
|
|
309
|
+
cb();
|
|
310
|
+
return undefined;
|
|
311
|
+
};
|
|
312
|
+
const shim = captureFetch();
|
|
313
|
+
try {
|
|
314
|
+
router.initRouter(
|
|
315
|
+
{
|
|
316
|
+
"/dup": () => {
|
|
317
|
+
const el = document.createElement("div");
|
|
318
|
+
el.setAttribute("data-sigil-transition", "dup");
|
|
319
|
+
return el;
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
[],
|
|
323
|
+
);
|
|
324
|
+
await router.navigate("/dup");
|
|
325
|
+
expect(named).toBe(0);
|
|
326
|
+
} finally {
|
|
327
|
+
delete docEnv.startViewTransition;
|
|
328
|
+
shim.restore();
|
|
329
|
+
root.remove();
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
describe("hover prefetch", () => {
|
|
335
|
+
// The 80ms debounce is real timer logic under test — fake timers advance
|
|
336
|
+
// it deterministically instead of sleeping past it.
|
|
337
|
+
test("plain internal link prefetches route data; preload=off skips", () => {
|
|
338
|
+
vi.useFakeTimers();
|
|
339
|
+
router.initRouter(
|
|
340
|
+
{
|
|
341
|
+
"/": () => document.createElement("div"),
|
|
342
|
+
"/off": () => document.createElement("div"),
|
|
343
|
+
},
|
|
344
|
+
[],
|
|
345
|
+
);
|
|
346
|
+
const fetchShim = captureFetch();
|
|
347
|
+
try {
|
|
348
|
+
const plain = document.createElement("a");
|
|
349
|
+
plain.setAttribute("href", "/");
|
|
350
|
+
document.body.appendChild(plain);
|
|
351
|
+
plain.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
352
|
+
vi.advanceTimersByTime(80);
|
|
353
|
+
expect(fetchShim.calls.length).toBe(1);
|
|
354
|
+
expect(fetchShim.calls[0]?.init?.headers).toEqual({
|
|
355
|
+
"x-grimoire-navigate": "1",
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
const optedOut = document.createElement("a");
|
|
359
|
+
optedOut.setAttribute("href", "/off");
|
|
360
|
+
optedOut.setAttribute("data-sigil-preload", "off");
|
|
361
|
+
document.body.appendChild(optedOut);
|
|
362
|
+
optedOut.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
363
|
+
vi.advanceTimersByTime(80);
|
|
364
|
+
expect(fetchShim.calls.length).toBe(1); // unchanged
|
|
365
|
+
} finally {
|
|
366
|
+
vi.useRealTimers();
|
|
367
|
+
fetchShim.restore();
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
test("external links are never prefetched", () => {
|
|
372
|
+
vi.useFakeTimers();
|
|
373
|
+
const fetchShim = captureFetch();
|
|
374
|
+
try {
|
|
375
|
+
const ext = document.createElement("a");
|
|
376
|
+
ext.setAttribute("href", "https://example.com/page");
|
|
377
|
+
document.body.appendChild(ext);
|
|
378
|
+
ext.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
379
|
+
vi.advanceTimersByTime(80);
|
|
380
|
+
expect(fetchShim.calls.length).toBe(0);
|
|
381
|
+
} finally {
|
|
382
|
+
vi.useRealTimers();
|
|
383
|
+
fetchShim.restore();
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
describe("prefetch reuse", () => {
|
|
389
|
+
test("a tap reuses the request started on touchstart", async () => {
|
|
390
|
+
const root = document.createElement("div");
|
|
391
|
+
root.id = "grimoire-root";
|
|
392
|
+
document.body.appendChild(root);
|
|
393
|
+
router.initRouter({ "/tap": () => document.createElement("main") }, []);
|
|
394
|
+
const shim = captureFetch();
|
|
395
|
+
try {
|
|
396
|
+
const a = document.createElement("a");
|
|
397
|
+
a.setAttribute("href", "/tap");
|
|
398
|
+
document.body.appendChild(a);
|
|
399
|
+
a.dispatchEvent(new Event("touchstart", { bubbles: true }));
|
|
400
|
+
expect(shim.calls.length).toBe(1);
|
|
401
|
+
|
|
402
|
+
await router.navigate("/tap");
|
|
403
|
+
// the click did not issue a second request
|
|
404
|
+
expect(shim.calls.length).toBe(1);
|
|
405
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
406
|
+
|
|
407
|
+
// and a prefetch is single-use: the next visit fetches fresh data
|
|
408
|
+
await router.navigate("/tap");
|
|
409
|
+
expect(shim.calls.length).toBe(2);
|
|
410
|
+
} finally {
|
|
411
|
+
shim.restore();
|
|
412
|
+
root.remove();
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
test("a click cancels the hover prefetch it just consumed", async () => {
|
|
417
|
+
const root = document.createElement("div");
|
|
418
|
+
root.id = "grimoire-root";
|
|
419
|
+
document.body.appendChild(root);
|
|
420
|
+
router.initRouter({ "/hov": () => document.createElement("main") }, []);
|
|
421
|
+
const shim = captureFetch();
|
|
422
|
+
try {
|
|
423
|
+
const a = document.createElement("a");
|
|
424
|
+
a.setAttribute("href", "/hov");
|
|
425
|
+
document.body.appendChild(a);
|
|
426
|
+
a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
427
|
+
a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
428
|
+
await Bun.sleep(200); // past the 80ms hover delay
|
|
429
|
+
expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
|
|
430
|
+
expect(shim.calls.length).toBe(1); // its own request, not a second
|
|
431
|
+
} finally {
|
|
432
|
+
shim.restore();
|
|
433
|
+
root.remove();
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
test("a prefetch made before a cookie changed is not reused", async () => {
|
|
438
|
+
const root = document.createElement("div");
|
|
439
|
+
root.id = "grimoire-root";
|
|
440
|
+
document.body.appendChild(root);
|
|
441
|
+
router.initRouter({ "/pref": () => document.createElement("main") }, []);
|
|
442
|
+
const shim = captureFetch();
|
|
443
|
+
try {
|
|
444
|
+
document.cookie = "region=jp";
|
|
445
|
+
router.prefetch("/pref");
|
|
446
|
+
expect(shim.calls.length).toBe(1);
|
|
447
|
+
document.cookie = "region=en"; // the visitor switched server
|
|
448
|
+
await router.navigate("/pref");
|
|
449
|
+
// the held response was fetched as jp, so the click asks again
|
|
450
|
+
expect(shim.calls.length).toBe(2);
|
|
451
|
+
} finally {
|
|
452
|
+
document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
|
453
|
+
shim.restore();
|
|
454
|
+
root.remove();
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
test("invalidateAll never serves a prefetched response", async () => {
|
|
459
|
+
const root = document.createElement("div");
|
|
460
|
+
root.id = "grimoire-root";
|
|
461
|
+
document.body.appendChild(root);
|
|
462
|
+
window.history.pushState(null, "", "/inv");
|
|
463
|
+
router.initRouter({ "/inv": () => document.createElement("main") }, []);
|
|
464
|
+
const shim = captureFetch();
|
|
465
|
+
try {
|
|
466
|
+
await router.navigate("/inv");
|
|
467
|
+
router.prefetch("/inv");
|
|
468
|
+
const before = shim.calls.length;
|
|
469
|
+
await router.invalidateAll();
|
|
470
|
+
expect(shim.calls.length).toBe(before + 1);
|
|
471
|
+
} finally {
|
|
472
|
+
shim.restore();
|
|
473
|
+
root.remove();
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
describe("popstate — query string", () => {
|
|
479
|
+
// popstate fires navigate() from an event listener, so there is no promise
|
|
480
|
+
// to await at the call site. afterNavigate is the router's own completion
|
|
481
|
+
// signal; a fixed sleep would be both slower and racy.
|
|
482
|
+
function onNavigated(): Promise<void> {
|
|
483
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
484
|
+
router.afterNavigate(() => resolve());
|
|
485
|
+
return promise;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Back used to refetch the bare pathname, so a query-driven page rendered
|
|
489
|
+
// unfiltered data while the address bar still showed the query.
|
|
490
|
+
test("back to a query URL refetches with the query intact", async () => {
|
|
491
|
+
const root = document.createElement("div");
|
|
492
|
+
root.id = "grimoire-root";
|
|
493
|
+
document.body.appendChild(root);
|
|
494
|
+
window.history.pushState(null, "", "/");
|
|
495
|
+
router.initRouter(
|
|
496
|
+
{
|
|
497
|
+
"/list": () => document.createElement("div"),
|
|
498
|
+
"/other": () => document.createElement("div"),
|
|
499
|
+
},
|
|
500
|
+
[],
|
|
501
|
+
);
|
|
502
|
+
const shim = captureFetch();
|
|
503
|
+
try {
|
|
504
|
+
await router.navigate("/list?q=fireball&page=2");
|
|
505
|
+
await router.navigate("/other");
|
|
506
|
+
shim.calls.length = 0;
|
|
507
|
+
|
|
508
|
+
// the browser moves history itself, then fires popstate
|
|
509
|
+
const navigated = onNavigated();
|
|
510
|
+
window.history.pushState(null, "", "/list?q=fireball&page=2");
|
|
511
|
+
window.dispatchEvent(new Event("popstate"));
|
|
512
|
+
await navigated;
|
|
513
|
+
|
|
514
|
+
expect(shim.calls.map((c) => c.input)).toEqual([
|
|
515
|
+
"/list?q=fireball&page=2",
|
|
516
|
+
]);
|
|
517
|
+
} finally {
|
|
518
|
+
router.afterNavigate(() => {});
|
|
519
|
+
shim.restore();
|
|
520
|
+
root.remove();
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
test("a popstate that only changes the query still refetches", async () => {
|
|
525
|
+
const root = document.createElement("div");
|
|
526
|
+
root.id = "grimoire-root";
|
|
527
|
+
document.body.appendChild(root);
|
|
528
|
+
window.history.pushState(null, "", "/");
|
|
529
|
+
router.initRouter({ "/list": () => document.createElement("div") }, []);
|
|
530
|
+
const shim = captureFetch();
|
|
531
|
+
try {
|
|
532
|
+
await router.navigate("/list?page=2");
|
|
533
|
+
shim.calls.length = 0;
|
|
534
|
+
|
|
535
|
+
const navigated = onNavigated();
|
|
536
|
+
window.history.pushState(null, "", "/list?page=1");
|
|
537
|
+
window.dispatchEvent(new Event("popstate"));
|
|
538
|
+
await navigated;
|
|
539
|
+
|
|
540
|
+
expect(shim.calls.map((c) => c.input)).toEqual(["/list?page=1"]);
|
|
541
|
+
} finally {
|
|
542
|
+
router.afterNavigate(() => {});
|
|
543
|
+
shim.restore();
|
|
544
|
+
root.remove();
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
describe("enhance — named action URLs", () => {
|
|
550
|
+
test("action starting with ?/ submits to the current pathname", async () => {
|
|
551
|
+
// earlier navigate() tests moved history — reset to a clean path
|
|
552
|
+
window.history.pushState(null, "", "/");
|
|
553
|
+
const { enhance } = await import("../src/client/enhance.ts");
|
|
554
|
+
const calls: string[] = [];
|
|
555
|
+
const original = globalThis.fetch;
|
|
556
|
+
globalThis.fetch = (async (input: string) => {
|
|
557
|
+
calls.push(input);
|
|
558
|
+
return new Response(null, { status: 303, headers: { location: "/" } });
|
|
559
|
+
}) as unknown as typeof fetch;
|
|
560
|
+
|
|
561
|
+
const form = document.createElement("form");
|
|
562
|
+
document.body.appendChild(form);
|
|
563
|
+
const cleanup = enhance(form, { action: "?/create" });
|
|
564
|
+
try {
|
|
565
|
+
form.dispatchEvent(
|
|
566
|
+
new Event("submit", { bubbles: true, cancelable: true }),
|
|
567
|
+
);
|
|
568
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
569
|
+
expect(calls).toEqual([`${window.location.pathname}?/create`]);
|
|
570
|
+
} finally {
|
|
571
|
+
cleanup();
|
|
572
|
+
form.remove();
|
|
573
|
+
globalThis.fetch = original;
|
|
574
|
+
}
|
|
575
|
+
});
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
describe("enhance — outcomes", () => {
|
|
579
|
+
async function submit(
|
|
580
|
+
reply: Response,
|
|
581
|
+
options: Record<string, unknown> = {},
|
|
582
|
+
submitter?: HTMLButtonElement,
|
|
583
|
+
) {
|
|
584
|
+
window.history.pushState(null, "", "/books");
|
|
585
|
+
const { enhance } = await import("../src/client/enhance.ts");
|
|
586
|
+
const sent: { headers: Headers; body: FormData }[] = [];
|
|
587
|
+
const navigations: [string, boolean | undefined][] = [];
|
|
588
|
+
const g = globalThis as Record<string, unknown>;
|
|
589
|
+
const originalFetch = globalThis.fetch;
|
|
590
|
+
const originalNavigate = g.__grimoire_navigate__;
|
|
591
|
+
globalThis.fetch = (async (_input: string, init: RequestInit) => {
|
|
592
|
+
sent.push({
|
|
593
|
+
headers: new Headers(init.headers),
|
|
594
|
+
body: init.body as FormData,
|
|
595
|
+
});
|
|
596
|
+
return reply;
|
|
597
|
+
}) as unknown as typeof fetch;
|
|
598
|
+
g.__grimoire_navigate__ = (path: string, replace?: boolean) =>
|
|
599
|
+
navigations.push([path, replace]);
|
|
600
|
+
|
|
601
|
+
const form = document.createElement("form");
|
|
602
|
+
form.setAttribute("action", "?/toggle");
|
|
603
|
+
const input = document.createElement("input");
|
|
604
|
+
input.setAttribute("name", "id");
|
|
605
|
+
input.setAttribute("value", "7");
|
|
606
|
+
form.appendChild(input);
|
|
607
|
+
if (submitter) form.appendChild(submitter);
|
|
608
|
+
document.body.appendChild(form);
|
|
609
|
+
const cleanup = enhance(form, options);
|
|
610
|
+
try {
|
|
611
|
+
const event = new Event("submit", { bubbles: true, cancelable: true });
|
|
612
|
+
if (submitter)
|
|
613
|
+
Object.defineProperty(event, "submitter", { value: submitter });
|
|
614
|
+
form.dispatchEvent(event);
|
|
615
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
616
|
+
return { sent, navigations };
|
|
617
|
+
} finally {
|
|
618
|
+
cleanup();
|
|
619
|
+
form.remove();
|
|
620
|
+
globalThis.fetch = originalFetch;
|
|
621
|
+
g.__grimoire_navigate__ = originalNavigate;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
test("success on the same page re-runs its loads in place", async () => {
|
|
626
|
+
const seen: unknown[] = [];
|
|
627
|
+
const { sent, navigations } = await submit(
|
|
628
|
+
Response.json({
|
|
629
|
+
type: "success",
|
|
630
|
+
location: "http://localhost/books",
|
|
631
|
+
data: { ok: 1 },
|
|
632
|
+
}),
|
|
633
|
+
{ onSuccess: (r: unknown) => seen.push(r) },
|
|
634
|
+
);
|
|
635
|
+
expect(sent[0]!.headers.get("x-grimoire-form")).toBe("1");
|
|
636
|
+
expect(seen).toEqual([
|
|
637
|
+
{ redirect: "http://localhost/books", data: { ok: 1 } },
|
|
638
|
+
]);
|
|
639
|
+
// replace: no new history entry for the same page
|
|
640
|
+
expect(navigations).toEqual([["/books", true]]);
|
|
641
|
+
});
|
|
642
|
+
|
|
643
|
+
test("a redirect elsewhere pushes a new entry", async () => {
|
|
644
|
+
const { navigations } = await submit(
|
|
645
|
+
Response.json({ type: "redirect", status: 303, location: "/books/7" }),
|
|
646
|
+
);
|
|
647
|
+
expect(navigations).toEqual([["/books/7", false]]);
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
test("fail() data goes to onFail, and nothing navigates", async () => {
|
|
651
|
+
const failed: unknown[] = [];
|
|
652
|
+
const { navigations } = await submit(
|
|
653
|
+
Response.json(
|
|
654
|
+
{ fail: true, status: 400, data: { problem: "x" } },
|
|
655
|
+
{ status: 400 },
|
|
656
|
+
),
|
|
657
|
+
{ onFail: (d: unknown) => failed.push(d) },
|
|
658
|
+
);
|
|
659
|
+
expect(failed).toEqual([{ problem: "x" }]);
|
|
660
|
+
expect(navigations).toEqual([]);
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
test("the submitting button's name=value is sent", async () => {
|
|
664
|
+
const button = document.createElement("button");
|
|
665
|
+
button.name = "read";
|
|
666
|
+
button.value = "1";
|
|
667
|
+
const { sent } = await submit(
|
|
668
|
+
Response.json({ type: "success", location: "/books", data: null }),
|
|
669
|
+
{},
|
|
670
|
+
button,
|
|
671
|
+
);
|
|
672
|
+
expect(sent[0]!.body.get("read")).toBe("1");
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
describe("Page.load — parent()", () => {
|
|
677
|
+
test("parent() merges layoutData entries outermost-first", async () => {
|
|
678
|
+
let seenParent: Record<string, unknown> | undefined;
|
|
679
|
+
const PageWithLoad = Object.assign(() => document.createElement("div"), {
|
|
680
|
+
load: async (ctx: { parent: () => Promise<Record<string, unknown>> }) => {
|
|
681
|
+
seenParent = await ctx.parent();
|
|
682
|
+
return {};
|
|
683
|
+
},
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
const original = globalThis.fetch;
|
|
687
|
+
globalThis.fetch = (async (input: string) => {
|
|
688
|
+
const pattern = new URL(input, "http://localhost").pathname;
|
|
689
|
+
return new Response(
|
|
690
|
+
JSON.stringify({
|
|
691
|
+
data: {},
|
|
692
|
+
layoutData: [{ a: 1 }, { b: 2 }],
|
|
693
|
+
params: {},
|
|
694
|
+
pattern,
|
|
695
|
+
head: "",
|
|
696
|
+
}),
|
|
697
|
+
{ headers: { "content-type": "application/json" } },
|
|
698
|
+
);
|
|
699
|
+
}) as unknown as typeof fetch;
|
|
700
|
+
|
|
701
|
+
try {
|
|
702
|
+
router.initRouter({ "/pl": PageWithLoad }, []);
|
|
703
|
+
await router.navigate("/pl");
|
|
704
|
+
expect(seenParent).toEqual({ a: 1, b: 2 });
|
|
705
|
+
} finally {
|
|
706
|
+
globalThis.fetch = original;
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
describe("invalidate", () => {
|
|
712
|
+
test("refetches only on key intersection; empty deps always refetch", async () => {
|
|
713
|
+
router.initRouter({ "/": () => document.createElement("div") }, []);
|
|
714
|
+
const shim = captureFetch();
|
|
715
|
+
try {
|
|
716
|
+
await router.navigate("/"); // establishes lastState.pattern = "/"
|
|
717
|
+
|
|
718
|
+
setDeps("/", ["user:1"]);
|
|
719
|
+
shim.calls.length = 0;
|
|
720
|
+
await router.invalidate("other");
|
|
721
|
+
expect(shim.calls.length).toBe(0); // no intersection → skip
|
|
722
|
+
|
|
723
|
+
await router.invalidate("user:1");
|
|
724
|
+
expect(shim.calls.length).toBe(1); // intersect → refetch
|
|
725
|
+
|
|
726
|
+
clearDeps("/");
|
|
727
|
+
await router.invalidate("anything");
|
|
728
|
+
expect(shim.calls.length).toBe(2); // no deps → conservative refetch
|
|
729
|
+
} finally {
|
|
730
|
+
shim.restore();
|
|
731
|
+
clearDeps("/");
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
describe("navigate — under a base", () => {
|
|
737
|
+
test("fetches and records the full path, but routes and loads see the route path", async () => {
|
|
738
|
+
const { setBase } = await import("../src/base.ts");
|
|
739
|
+
const root = document.createElement("div");
|
|
740
|
+
root.id = "grimoire-root";
|
|
741
|
+
document.body.appendChild(root);
|
|
742
|
+
const g = globalThis as { DOMParser?: unknown };
|
|
743
|
+
g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
|
|
744
|
+
const original = globalThis.fetch;
|
|
745
|
+
const requested: string[] = [];
|
|
746
|
+
globalThis.fetch = (async (input: string) => {
|
|
747
|
+
requested.push(input);
|
|
748
|
+
return jsonResponse("/about");
|
|
749
|
+
}) as unknown as typeof fetch;
|
|
750
|
+
const seen: string[] = [];
|
|
751
|
+
const warn = console.warn;
|
|
752
|
+
const warned: string[] = [];
|
|
753
|
+
console.warn = (m: string) => warned.push(m);
|
|
754
|
+
setBase("/repo");
|
|
755
|
+
try {
|
|
756
|
+
const About = Object.assign(() => document.createElement("main"), {
|
|
757
|
+
load: async ({ url }: { url: URL }) => {
|
|
758
|
+
seen.push(url.pathname);
|
|
759
|
+
return {};
|
|
760
|
+
},
|
|
761
|
+
});
|
|
762
|
+
router.initRouter({ "/about": About }, []);
|
|
763
|
+
router.onNavigate((url) => seen.push(`cb:${url.pathname}`));
|
|
764
|
+
await router.navigate("/repo/about?x=1");
|
|
765
|
+
expect(requested).toEqual(["/repo/about?x=1"]);
|
|
766
|
+
expect(location.pathname).toBe("/repo/about");
|
|
767
|
+
expect(seen).toContain("/about");
|
|
768
|
+
expect(seen).toContain("cb:/about");
|
|
769
|
+
expect(warned).toEqual([]);
|
|
770
|
+
|
|
771
|
+
// the base alone is the root route, with or without the slash
|
|
772
|
+
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
773
|
+
await router.navigate("/repo");
|
|
774
|
+
expect(requested.at(-1)).toBe("/repo");
|
|
775
|
+
|
|
776
|
+
// outside the base: not a route, and the mistake is named
|
|
777
|
+
requested.length = 0;
|
|
778
|
+
const href = location.href;
|
|
779
|
+
await router.navigate("/about").catch(() => {});
|
|
780
|
+
expect(warned.join("\n")).toContain('withBase("/about")');
|
|
781
|
+
location.href = href;
|
|
782
|
+
} finally {
|
|
783
|
+
setBase("");
|
|
784
|
+
console.warn = warn;
|
|
785
|
+
globalThis.fetch = original;
|
|
786
|
+
root.remove();
|
|
787
|
+
}
|
|
788
|
+
});
|
|
789
|
+
});
|