@sigil-dev/grimoire 0.9.32 → 0.9.33
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/package.json +4 -4
- package/src/client/router.ts +935 -927
- package/src/dev/hmr-client.ts +8 -0
- package/test/client-router.test.ts +904 -854
package/src/client/router.ts
CHANGED
|
@@ -1,927 +1,935 @@
|
|
|
1
|
-
import {
|
|
2
|
-
__component,
|
|
3
|
-
collectEffects,
|
|
4
|
-
popHydrationNodes,
|
|
5
|
-
pushHydrationNodes,
|
|
6
|
-
} from "@sigil-dev/runtime";
|
|
7
|
-
import { base, stripBase } from "../base";
|
|
8
|
-
import { onSubmitEnsureCsrf } from "./csrf.ts";
|
|
9
|
-
import {
|
|
10
|
-
clearDeps,
|
|
11
|
-
depends,
|
|
12
|
-
getDeps,
|
|
13
|
-
setDeps,
|
|
14
|
-
startCollecting,
|
|
15
|
-
stopCollecting,
|
|
16
|
-
} from "./deps";
|
|
17
|
-
import { withEffectScope } from "./scope";
|
|
18
|
-
|
|
19
|
-
// re-exported for app code that imports depends() from the router module
|
|
20
|
-
export { depends };
|
|
21
|
-
|
|
22
|
-
async function refetchCurrent(): Promise<void> {
|
|
23
|
-
if (!lastState) return;
|
|
24
|
-
// a refetch exists because the data changed; never serve it from a prefetch
|
|
25
|
-
prefetched.clear();
|
|
26
|
-
// keep the query string: a filtered or paginated page reloads as it is
|
|
27
|
-
await navigate(location.pathname + location.search, { history: "replace" });
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function invalidate(...keys: string[]): Promise<void> {
|
|
31
|
-
const current = lastState?.pattern;
|
|
32
|
-
if (!current) return;
|
|
33
|
-
const deps = getDeps(current);
|
|
34
|
-
// no recorded deps → conservative refetch; otherwise only on intersection
|
|
35
|
-
if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
|
|
36
|
-
await refetchCurrent();
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export async function invalidateAll(): Promise<void> {
|
|
41
|
-
await refetchCurrent();
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
type PageComponent = ((props: any) => any) & {
|
|
45
|
-
load?: (ctx: any) => Promise<any>;
|
|
46
|
-
loading?: () => any;
|
|
47
|
-
error?: (props: { error: unknown }) => any;
|
|
48
|
-
};
|
|
49
|
-
/** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
|
|
50
|
-
* component functions are also accepted (tests, HMR replacements). */
|
|
51
|
-
type RouteEntry =
|
|
52
|
-
| PageComponent
|
|
53
|
-
| { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
|
|
54
|
-
|
|
55
|
-
let routeMap: Record<string, RouteEntry> = {};
|
|
56
|
-
const resolvedRoutes: Record<string, PageComponent> = {};
|
|
57
|
-
|
|
58
|
-
async function resolveRoute(pattern: string): Promise<PageComponent | null> {
|
|
59
|
-
const entry = routeMap[pattern];
|
|
60
|
-
if (!entry) return null;
|
|
61
|
-
// plain function: eager component or an HMR hot-swap — always wins over cache
|
|
62
|
-
if (typeof entry === "function") return entry;
|
|
63
|
-
if (!resolvedRoutes[pattern]) {
|
|
64
|
-
let mod: { default: PageComponent; loading?: PageComponent["loading"] };
|
|
65
|
-
try {
|
|
66
|
-
mod = await entry.__lazy();
|
|
67
|
-
} catch (e) {
|
|
68
|
-
// The chunk is gone: a rebuild (dev) or a deploy (prod) replaced it
|
|
69
|
-
// while this tab kept the old bundle, which still names it. null
|
|
70
|
-
// sends every caller down its full-page-load path, which fetches
|
|
71
|
-
// fresh HTML that names the current chunks. Not cached, so a later
|
|
72
|
-
// navigation retries the import.
|
|
73
|
-
console.warn(
|
|
74
|
-
`[grimoire] could not load the page for ${pattern}; loading it from the server`,
|
|
75
|
-
e,
|
|
76
|
-
);
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
// `loading` is a named export of the page module; navigation looks
|
|
80
|
-
// for it on the component, and never saw it before
|
|
81
|
-
if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
|
|
82
|
-
resolvedRoutes[pattern] = mod.default;
|
|
83
|
-
}
|
|
84
|
-
return resolvedRoutes[pattern];
|
|
85
|
-
}
|
|
86
|
-
let layoutList: { path: string; component: (props: any) => any }[] = [];
|
|
87
|
-
let disposeCurrentPage: (() => void) | null = null;
|
|
88
|
-
// Scroll keys and same-page refetch detection are pathname-only on purpose.
|
|
89
|
-
// currentSearch is tracked alongside so popstate can tell "?page=2" apart
|
|
90
|
-
// from "?page=1" without polluting either of those.
|
|
91
|
-
let currentPath = location.pathname;
|
|
92
|
-
let currentSearch = location.search;
|
|
93
|
-
|
|
94
|
-
// C1: Navigation hooks
|
|
95
|
-
let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
|
|
96
|
-
let onNavigateCb: ((url: URL) => void) | null = null;
|
|
97
|
-
let afterNavigateCb: ((url: URL) => void) | null = null;
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Shows the page again with an enhanced form's failure as its `form` prop,
|
|
101
|
-
* which is what a submission without JavaScript gets from the server. The
|
|
102
|
-
* same page code then works either way.
|
|
103
|
-
*/
|
|
104
|
-
export function showActionFailure(form: unknown): Promise<void> {
|
|
105
|
-
if (!lastState) return Promise.resolve();
|
|
106
|
-
lastState = { ...lastState, form };
|
|
107
|
-
return hmrRerender();
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
export async function hmrRerender(): Promise<void> {
|
|
111
|
-
if (!lastState) {
|
|
112
|
-
location.reload();
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
const Page = await resolveRoute(lastState.pattern);
|
|
116
|
-
if (!Page) {
|
|
117
|
-
location.reload();
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
disposeCurrentPage?.();
|
|
121
|
-
pushHydrationNodes([]);
|
|
122
|
-
let rootNode: any;
|
|
123
|
-
let flush = () => {};
|
|
124
|
-
disposeCurrentPage = withEffectScope(() => {
|
|
125
|
-
({ value: rootNode, flush } = collectEffects(() =>
|
|
126
|
-
buildRouteTree(lastState!, Page),
|
|
127
|
-
));
|
|
128
|
-
});
|
|
129
|
-
popHydrationNodes();
|
|
130
|
-
const preserved = capturePreservedScroll();
|
|
131
|
-
// swapping the root can shrink the document for a moment, and the browser
|
|
132
|
-
// clamps scrollY to the shorter height; put the page back where it was
|
|
133
|
-
const y = window.scrollY;
|
|
134
|
-
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
135
|
-
flush();
|
|
136
|
-
restorePreservedScroll(preserved);
|
|
137
|
-
window.scrollTo(0, y);
|
|
138
|
-
requestAnimationFrame(() => window.scrollTo(0, y));
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Dev-only surface the HMR client drives. Route entries are replaced rather
|
|
143
|
-
* than mutated in place so a swapped module also wins for later navigations,
|
|
144
|
-
* and the resolved-module cache is dropped with them.
|
|
145
|
-
*/
|
|
146
|
-
export interface HmrControl {
|
|
147
|
-
setRoute(pattern: string, entry: RouteEntry): void;
|
|
148
|
-
setLayout(path: string, component: (props: any) => any): void;
|
|
149
|
-
rerender(): Promise<void>;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const hmrControl: HmrControl = {
|
|
153
|
-
setRoute(pattern, entry) {
|
|
154
|
-
routeMap[pattern] = entry;
|
|
155
|
-
delete resolvedRoutes[pattern];
|
|
156
|
-
},
|
|
157
|
-
setLayout(path: string, component: (props: any) => any) {
|
|
158
|
-
const existing = layoutList.find((l) => l.path === path);
|
|
159
|
-
if (existing) existing.component = component;
|
|
160
|
-
else layoutList.push({ path, component });
|
|
161
|
-
},
|
|
162
|
-
rerender: hmrRerender,
|
|
163
|
-
};
|
|
164
|
-
|
|
165
|
-
export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
|
|
166
|
-
beforeNavigateCb = cb;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
export function onNavigate(cb: (url: URL) => void): void {
|
|
170
|
-
onNavigateCb = cb;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
export function afterNavigate(cb: (url: URL) => void): void {
|
|
174
|
-
afterNavigateCb = cb;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// C2: Scroll restoration
|
|
178
|
-
const scrollPositions = new Map<string, number>();
|
|
179
|
-
|
|
180
|
-
function saveScrollPosition(): void {
|
|
181
|
-
scrollPositions.set(currentPath, window.scrollY);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function restoreScrollPosition(path: string): void {
|
|
185
|
-
const y = scrollPositions.get(path) ?? 0;
|
|
186
|
-
window.scrollTo(0, y);
|
|
187
|
-
// re-assert after layout settles (late effects/images can shift content)
|
|
188
|
-
requestAnimationFrame(() => window.scrollTo(0, y));
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function scrollToTop(): void {
|
|
192
|
-
window.scrollTo(0, 0);
|
|
193
|
-
requestAnimationFrame(() => window.scrollTo(0, 0));
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
|
|
197
|
-
// across the root swap: the router rebuilds the whole tree on navigation, so a
|
|
198
|
-
// long independently-scrollable sidebar would otherwise snap back to the top.
|
|
199
|
-
// The attribute value is the matching key; elements without one fall back to
|
|
200
|
-
// their id, then to their ordinal position.
|
|
201
|
-
const PRESERVE_ATTR = "data-sigil-scroll-preserve";
|
|
202
|
-
|
|
203
|
-
function preserveKey(el: Element, ordinal: number): string {
|
|
204
|
-
return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
function capturePreservedScroll(): Map<string, number> {
|
|
208
|
-
const positions = new Map<string, number>();
|
|
209
|
-
let ordinal = 0;
|
|
210
|
-
for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
|
|
211
|
-
positions.set(preserveKey(el, ordinal), el.scrollTop);
|
|
212
|
-
ordinal++;
|
|
213
|
-
}
|
|
214
|
-
return positions;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function restorePreservedScroll(positions: Map<string, number>): void {
|
|
218
|
-
if (positions.size === 0) return;
|
|
219
|
-
let ordinal = 0;
|
|
220
|
-
for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
|
|
221
|
-
const top = positions.get(preserveKey(el, ordinal));
|
|
222
|
-
if (top !== undefined) el.scrollTop = top;
|
|
223
|
-
ordinal++;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const TRANSITION_ATTR = "data-sigil-transition";
|
|
228
|
-
|
|
229
|
-
/** key → the one element carrying it; keys that appear twice are dropped,
|
|
230
|
-
* because a duplicate view-transition-name cancels the whole transition. */
|
|
231
|
-
function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
|
|
232
|
-
const seen = new Map<string, Element>();
|
|
233
|
-
const dup = new Set<string>();
|
|
234
|
-
for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
|
|
235
|
-
const key = el.getAttribute(TRANSITION_ATTR);
|
|
236
|
-
if (!key) continue;
|
|
237
|
-
if (seen.has(key)) dup.add(key);
|
|
238
|
-
else seen.set(key, el);
|
|
239
|
-
}
|
|
240
|
-
for (const key of dup) seen.delete(key);
|
|
241
|
-
return seen;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/** [key, element on the current page, element on the incoming page] */
|
|
245
|
-
function sharedTransitionKeys(
|
|
246
|
-
incoming: unknown,
|
|
247
|
-
): Array<[string, Element, Element]> {
|
|
248
|
-
const root = incoming as Partial<ParentNode> | null;
|
|
249
|
-
if (!root || typeof root.querySelectorAll !== "function") return [];
|
|
250
|
-
const next = uniqueTransitionEls(root as ParentNode);
|
|
251
|
-
if (next.size === 0) return [];
|
|
252
|
-
const prev = uniqueTransitionEls(document);
|
|
253
|
-
const both: Array<[string, Element, Element]> = [];
|
|
254
|
-
for (const [key, el] of next) {
|
|
255
|
-
const old = prev.get(key);
|
|
256
|
-
if (old) both.push([key, old, el]);
|
|
257
|
-
}
|
|
258
|
-
return both;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// C3: Preloading
|
|
262
|
-
//
|
|
263
|
-
// A prefetch keeps its in-flight Response here and navigate() consumes it.
|
|
264
|
-
// The HTTP cache cannot do this job: the navigate JSON carries no freshness
|
|
265
|
-
// headers and pages are commonly served `no-cache`, so a plain prefetch
|
|
266
|
-
// warmed nothing the click could reuse.
|
|
267
|
-
let preloadTimer: Timer | null = null;
|
|
268
|
-
const PREFETCH_TTL_MS = 15_000;
|
|
269
|
-
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
270
|
-
|
|
271
|
-
/**
|
|
272
|
-
* A held response is only valid for the cookies it was requested with: apps
|
|
273
|
-
* keep preferences (a language, a region, a theme) in cookies the server reads
|
|
274
|
-
* per request, so a page fetched before the visitor changed one is wrong
|
|
275
|
-
* after. Cookies the script can read are part of the key.
|
|
276
|
-
*/
|
|
277
|
-
function prefetchKey(url: URL): string {
|
|
278
|
-
return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* A prerendered site has no server to answer `x-grimoire-navigate`, so
|
|
283
|
-
* `adapterStatic` marks its pages and writes the same payload to
|
|
284
|
-
* `<page>/__data.json`, which any static host serves. The path must match
|
|
285
|
-
* `dataFileFor` in server/prerender.ts.
|
|
286
|
-
*/
|
|
287
|
-
function navigateTarget(path: string): string {
|
|
288
|
-
if (
|
|
289
|
-
(globalThis as { __grimoire_static__?: unknown }).__grimoire_static__ !== 1
|
|
290
|
-
) {
|
|
291
|
-
return path;
|
|
292
|
-
}
|
|
293
|
-
const { pathname } = new URL(path, location.origin);
|
|
294
|
-
return `${pathname.replace(/\/+$/, "")}/__data.json`;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function navigateFetch(path: string, priority?: "low"): Promise<Response> {
|
|
298
|
-
const target = navigateTarget(path);
|
|
299
|
-
return fetch(target, {
|
|
300
|
-
...(target === path ? { headers: { "x-grimoire-navigate": "1" } } : {}),
|
|
301
|
-
redirect: "manual",
|
|
302
|
-
...(priority ? { priority } : {}),
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/** The route-local href of an anchor worth prefetching, or null. */
|
|
307
|
-
function prefetchHref(a: Element | null): string | null {
|
|
308
|
-
if (!a) return null;
|
|
309
|
-
const href = a.getAttribute("href");
|
|
310
|
-
if (!href) return null;
|
|
311
|
-
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
|
|
312
|
-
if (a.getAttribute("data-sigil-preload") === "off") return null;
|
|
313
|
-
//
|
|
314
|
-
//
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
});
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
.
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
)
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
if (Page
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
disposeCurrentPage
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
//
|
|
694
|
-
//
|
|
695
|
-
const
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
//
|
|
710
|
-
|
|
711
|
-
return;
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
return;
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
const
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
const
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
for (const [key,
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
// browser
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
//
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
1
|
+
import {
|
|
2
|
+
__component,
|
|
3
|
+
collectEffects,
|
|
4
|
+
popHydrationNodes,
|
|
5
|
+
pushHydrationNodes,
|
|
6
|
+
} from "@sigil-dev/runtime";
|
|
7
|
+
import { base, stripBase } from "../base";
|
|
8
|
+
import { onSubmitEnsureCsrf } from "./csrf.ts";
|
|
9
|
+
import {
|
|
10
|
+
clearDeps,
|
|
11
|
+
depends,
|
|
12
|
+
getDeps,
|
|
13
|
+
setDeps,
|
|
14
|
+
startCollecting,
|
|
15
|
+
stopCollecting,
|
|
16
|
+
} from "./deps";
|
|
17
|
+
import { withEffectScope } from "./scope";
|
|
18
|
+
|
|
19
|
+
// re-exported for app code that imports depends() from the router module
|
|
20
|
+
export { depends };
|
|
21
|
+
|
|
22
|
+
async function refetchCurrent(): Promise<void> {
|
|
23
|
+
if (!lastState) return;
|
|
24
|
+
// a refetch exists because the data changed; never serve it from a prefetch
|
|
25
|
+
prefetched.clear();
|
|
26
|
+
// keep the query string: a filtered or paginated page reloads as it is
|
|
27
|
+
await navigate(location.pathname + location.search, { history: "replace" });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function invalidate(...keys: string[]): Promise<void> {
|
|
31
|
+
const current = lastState?.pattern;
|
|
32
|
+
if (!current) return;
|
|
33
|
+
const deps = getDeps(current);
|
|
34
|
+
// no recorded deps → conservative refetch; otherwise only on intersection
|
|
35
|
+
if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
|
|
36
|
+
await refetchCurrent();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function invalidateAll(): Promise<void> {
|
|
41
|
+
await refetchCurrent();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type PageComponent = ((props: any) => any) & {
|
|
45
|
+
load?: (ctx: any) => Promise<any>;
|
|
46
|
+
loading?: () => any;
|
|
47
|
+
error?: (props: { error: unknown }) => any;
|
|
48
|
+
};
|
|
49
|
+
/** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
|
|
50
|
+
* component functions are also accepted (tests, HMR replacements). */
|
|
51
|
+
type RouteEntry =
|
|
52
|
+
| PageComponent
|
|
53
|
+
| { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
|
|
54
|
+
|
|
55
|
+
let routeMap: Record<string, RouteEntry> = {};
|
|
56
|
+
const resolvedRoutes: Record<string, PageComponent> = {};
|
|
57
|
+
|
|
58
|
+
async function resolveRoute(pattern: string): Promise<PageComponent | null> {
|
|
59
|
+
const entry = routeMap[pattern];
|
|
60
|
+
if (!entry) return null;
|
|
61
|
+
// plain function: eager component or an HMR hot-swap — always wins over cache
|
|
62
|
+
if (typeof entry === "function") return entry;
|
|
63
|
+
if (!resolvedRoutes[pattern]) {
|
|
64
|
+
let mod: { default: PageComponent; loading?: PageComponent["loading"] };
|
|
65
|
+
try {
|
|
66
|
+
mod = await entry.__lazy();
|
|
67
|
+
} catch (e) {
|
|
68
|
+
// The chunk is gone: a rebuild (dev) or a deploy (prod) replaced it
|
|
69
|
+
// while this tab kept the old bundle, which still names it. null
|
|
70
|
+
// sends every caller down its full-page-load path, which fetches
|
|
71
|
+
// fresh HTML that names the current chunks. Not cached, so a later
|
|
72
|
+
// navigation retries the import.
|
|
73
|
+
console.warn(
|
|
74
|
+
`[grimoire] could not load the page for ${pattern}; loading it from the server`,
|
|
75
|
+
e,
|
|
76
|
+
);
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
// `loading` is a named export of the page module; navigation looks
|
|
80
|
+
// for it on the component, and never saw it before
|
|
81
|
+
if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
|
|
82
|
+
resolvedRoutes[pattern] = mod.default;
|
|
83
|
+
}
|
|
84
|
+
return resolvedRoutes[pattern];
|
|
85
|
+
}
|
|
86
|
+
let layoutList: { path: string; component: (props: any) => any }[] = [];
|
|
87
|
+
let disposeCurrentPage: (() => void) | null = null;
|
|
88
|
+
// Scroll keys and same-page refetch detection are pathname-only on purpose.
|
|
89
|
+
// currentSearch is tracked alongside so popstate can tell "?page=2" apart
|
|
90
|
+
// from "?page=1" without polluting either of those.
|
|
91
|
+
let currentPath = location.pathname;
|
|
92
|
+
let currentSearch = location.search;
|
|
93
|
+
|
|
94
|
+
// C1: Navigation hooks
|
|
95
|
+
let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
|
|
96
|
+
let onNavigateCb: ((url: URL) => void) | null = null;
|
|
97
|
+
let afterNavigateCb: ((url: URL) => void) | null = null;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Shows the page again with an enhanced form's failure as its `form` prop,
|
|
101
|
+
* which is what a submission without JavaScript gets from the server. The
|
|
102
|
+
* same page code then works either way.
|
|
103
|
+
*/
|
|
104
|
+
export function showActionFailure(form: unknown): Promise<void> {
|
|
105
|
+
if (!lastState) return Promise.resolve();
|
|
106
|
+
lastState = { ...lastState, form };
|
|
107
|
+
return hmrRerender();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function hmrRerender(): Promise<void> {
|
|
111
|
+
if (!lastState) {
|
|
112
|
+
location.reload();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const Page = await resolveRoute(lastState.pattern);
|
|
116
|
+
if (!Page) {
|
|
117
|
+
location.reload();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
disposeCurrentPage?.();
|
|
121
|
+
pushHydrationNodes([]);
|
|
122
|
+
let rootNode: any;
|
|
123
|
+
let flush = () => {};
|
|
124
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
125
|
+
({ value: rootNode, flush } = collectEffects(() =>
|
|
126
|
+
buildRouteTree(lastState!, Page),
|
|
127
|
+
));
|
|
128
|
+
});
|
|
129
|
+
popHydrationNodes();
|
|
130
|
+
const preserved = capturePreservedScroll();
|
|
131
|
+
// swapping the root can shrink the document for a moment, and the browser
|
|
132
|
+
// clamps scrollY to the shorter height; put the page back where it was
|
|
133
|
+
const y = window.scrollY;
|
|
134
|
+
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
135
|
+
flush();
|
|
136
|
+
restorePreservedScroll(preserved);
|
|
137
|
+
window.scrollTo(0, y);
|
|
138
|
+
requestAnimationFrame(() => window.scrollTo(0, y));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Dev-only surface the HMR client drives. Route entries are replaced rather
|
|
143
|
+
* than mutated in place so a swapped module also wins for later navigations,
|
|
144
|
+
* and the resolved-module cache is dropped with them.
|
|
145
|
+
*/
|
|
146
|
+
export interface HmrControl {
|
|
147
|
+
setRoute(pattern: string, entry: RouteEntry): void;
|
|
148
|
+
setLayout(path: string, component: (props: any) => any): void;
|
|
149
|
+
rerender(): Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const hmrControl: HmrControl = {
|
|
153
|
+
setRoute(pattern, entry) {
|
|
154
|
+
routeMap[pattern] = entry;
|
|
155
|
+
delete resolvedRoutes[pattern];
|
|
156
|
+
},
|
|
157
|
+
setLayout(path: string, component: (props: any) => any) {
|
|
158
|
+
const existing = layoutList.find((l) => l.path === path);
|
|
159
|
+
if (existing) existing.component = component;
|
|
160
|
+
else layoutList.push({ path, component });
|
|
161
|
+
},
|
|
162
|
+
rerender: hmrRerender,
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
|
|
166
|
+
beforeNavigateCb = cb;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function onNavigate(cb: (url: URL) => void): void {
|
|
170
|
+
onNavigateCb = cb;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function afterNavigate(cb: (url: URL) => void): void {
|
|
174
|
+
afterNavigateCb = cb;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// C2: Scroll restoration
|
|
178
|
+
const scrollPositions = new Map<string, number>();
|
|
179
|
+
|
|
180
|
+
function saveScrollPosition(): void {
|
|
181
|
+
scrollPositions.set(currentPath, window.scrollY);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function restoreScrollPosition(path: string): void {
|
|
185
|
+
const y = scrollPositions.get(path) ?? 0;
|
|
186
|
+
window.scrollTo(0, y);
|
|
187
|
+
// re-assert after layout settles (late effects/images can shift content)
|
|
188
|
+
requestAnimationFrame(() => window.scrollTo(0, y));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function scrollToTop(): void {
|
|
192
|
+
window.scrollTo(0, 0);
|
|
193
|
+
requestAnimationFrame(() => window.scrollTo(0, 0));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
|
|
197
|
+
// across the root swap: the router rebuilds the whole tree on navigation, so a
|
|
198
|
+
// long independently-scrollable sidebar would otherwise snap back to the top.
|
|
199
|
+
// The attribute value is the matching key; elements without one fall back to
|
|
200
|
+
// their id, then to their ordinal position.
|
|
201
|
+
const PRESERVE_ATTR = "data-sigil-scroll-preserve";
|
|
202
|
+
|
|
203
|
+
function preserveKey(el: Element, ordinal: number): string {
|
|
204
|
+
return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function capturePreservedScroll(): Map<string, number> {
|
|
208
|
+
const positions = new Map<string, number>();
|
|
209
|
+
let ordinal = 0;
|
|
210
|
+
for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
|
|
211
|
+
positions.set(preserveKey(el, ordinal), el.scrollTop);
|
|
212
|
+
ordinal++;
|
|
213
|
+
}
|
|
214
|
+
return positions;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function restorePreservedScroll(positions: Map<string, number>): void {
|
|
218
|
+
if (positions.size === 0) return;
|
|
219
|
+
let ordinal = 0;
|
|
220
|
+
for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
|
|
221
|
+
const top = positions.get(preserveKey(el, ordinal));
|
|
222
|
+
if (top !== undefined) el.scrollTop = top;
|
|
223
|
+
ordinal++;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const TRANSITION_ATTR = "data-sigil-transition";
|
|
228
|
+
|
|
229
|
+
/** key → the one element carrying it; keys that appear twice are dropped,
|
|
230
|
+
* because a duplicate view-transition-name cancels the whole transition. */
|
|
231
|
+
function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
|
|
232
|
+
const seen = new Map<string, Element>();
|
|
233
|
+
const dup = new Set<string>();
|
|
234
|
+
for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
|
|
235
|
+
const key = el.getAttribute(TRANSITION_ATTR);
|
|
236
|
+
if (!key) continue;
|
|
237
|
+
if (seen.has(key)) dup.add(key);
|
|
238
|
+
else seen.set(key, el);
|
|
239
|
+
}
|
|
240
|
+
for (const key of dup) seen.delete(key);
|
|
241
|
+
return seen;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** [key, element on the current page, element on the incoming page] */
|
|
245
|
+
function sharedTransitionKeys(
|
|
246
|
+
incoming: unknown,
|
|
247
|
+
): Array<[string, Element, Element]> {
|
|
248
|
+
const root = incoming as Partial<ParentNode> | null;
|
|
249
|
+
if (!root || typeof root.querySelectorAll !== "function") return [];
|
|
250
|
+
const next = uniqueTransitionEls(root as ParentNode);
|
|
251
|
+
if (next.size === 0) return [];
|
|
252
|
+
const prev = uniqueTransitionEls(document);
|
|
253
|
+
const both: Array<[string, Element, Element]> = [];
|
|
254
|
+
for (const [key, el] of next) {
|
|
255
|
+
const old = prev.get(key);
|
|
256
|
+
if (old) both.push([key, old, el]);
|
|
257
|
+
}
|
|
258
|
+
return both;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// C3: Preloading
|
|
262
|
+
//
|
|
263
|
+
// A prefetch keeps its in-flight Response here and navigate() consumes it.
|
|
264
|
+
// The HTTP cache cannot do this job: the navigate JSON carries no freshness
|
|
265
|
+
// headers and pages are commonly served `no-cache`, so a plain prefetch
|
|
266
|
+
// warmed nothing the click could reuse.
|
|
267
|
+
let preloadTimer: Timer | null = null;
|
|
268
|
+
const PREFETCH_TTL_MS = 15_000;
|
|
269
|
+
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* A held response is only valid for the cookies it was requested with: apps
|
|
273
|
+
* keep preferences (a language, a region, a theme) in cookies the server reads
|
|
274
|
+
* per request, so a page fetched before the visitor changed one is wrong
|
|
275
|
+
* after. Cookies the script can read are part of the key.
|
|
276
|
+
*/
|
|
277
|
+
function prefetchKey(url: URL): string {
|
|
278
|
+
return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* A prerendered site has no server to answer `x-grimoire-navigate`, so
|
|
283
|
+
* `adapterStatic` marks its pages and writes the same payload to
|
|
284
|
+
* `<page>/__data.json`, which any static host serves. The path must match
|
|
285
|
+
* `dataFileFor` in server/prerender.ts.
|
|
286
|
+
*/
|
|
287
|
+
function navigateTarget(path: string): string {
|
|
288
|
+
if (
|
|
289
|
+
(globalThis as { __grimoire_static__?: unknown }).__grimoire_static__ !== 1
|
|
290
|
+
) {
|
|
291
|
+
return path;
|
|
292
|
+
}
|
|
293
|
+
const { pathname } = new URL(path, location.origin);
|
|
294
|
+
return `${pathname.replace(/\/+$/, "")}/__data.json`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function navigateFetch(path: string, priority?: "low"): Promise<Response> {
|
|
298
|
+
const target = navigateTarget(path);
|
|
299
|
+
return fetch(target, {
|
|
300
|
+
...(target === path ? { headers: { "x-grimoire-navigate": "1" } } : {}),
|
|
301
|
+
redirect: "manual",
|
|
302
|
+
...(priority ? { priority } : {}),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The route-local href of an anchor worth prefetching, or null. */
|
|
307
|
+
function prefetchHref(a: Element | null): string | null {
|
|
308
|
+
if (!a) return null;
|
|
309
|
+
const href = a.getAttribute("href");
|
|
310
|
+
if (!href) return null;
|
|
311
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
|
|
312
|
+
if (a.getAttribute("data-sigil-preload") === "off") return null;
|
|
313
|
+
// links the router won't take on a click aren't warmed either: their GET
|
|
314
|
+
// may do something (rel="external" is the way to mark a sign-in link)
|
|
315
|
+
if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return null;
|
|
316
|
+
if (a.hasAttribute("download")) return null;
|
|
317
|
+
const target = a.getAttribute("target");
|
|
318
|
+
if (target && target !== "_self") return null;
|
|
319
|
+
// Only links that resolve to a known client route — external pages and
|
|
320
|
+
// non-page endpoints (API routes, redirects) are skipped.
|
|
321
|
+
try {
|
|
322
|
+
const url = new URL(href, location.origin);
|
|
323
|
+
if (!findPattern(url.pathname)) return null;
|
|
324
|
+
} catch {
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
return href;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Warm a navigation: load the route's code and start its data request. The
|
|
332
|
+
* response is held for a short while so the click that follows reuses it.
|
|
333
|
+
*/
|
|
334
|
+
export function prefetch(href: string): void {
|
|
335
|
+
const conn = (navigator as { connection?: { saveData?: boolean } })
|
|
336
|
+
.connection;
|
|
337
|
+
if (conn?.saveData) return;
|
|
338
|
+
const url = new URL(href, location.origin);
|
|
339
|
+
// the page already on screen needs no warming
|
|
340
|
+
if (url.pathname === location.pathname && url.search === location.search)
|
|
341
|
+
return;
|
|
342
|
+
const key = prefetchKey(url);
|
|
343
|
+
const hit = prefetched.get(key);
|
|
344
|
+
if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
|
|
345
|
+
const pattern = findPattern(url.pathname);
|
|
346
|
+
if (pattern) void resolveRoute(pattern).catch(() => {});
|
|
347
|
+
const res = navigateFetch(url.pathname + url.search, "low");
|
|
348
|
+
res.catch(() => prefetched.delete(key));
|
|
349
|
+
prefetched.set(key, { res, at: Date.now() });
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** The held prefetch for `path` if it is still fresh; each is used once. */
|
|
353
|
+
function takePrefetched(path: string): Promise<Response> | null {
|
|
354
|
+
const key = prefetchKey(new URL(path, location.origin));
|
|
355
|
+
const hit = prefetched.get(key);
|
|
356
|
+
prefetched.delete(key);
|
|
357
|
+
if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
|
|
358
|
+
return hit.res;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* The server points `<link rel="stylesheet">` at `/style.<hash>.css`, but a
|
|
363
|
+
* link the router renders after a navigation is built from the component's own
|
|
364
|
+
* `/style.css`. Point it at the hashed URL too, so it hits the cached copy
|
|
365
|
+
* instead of revalidating the plain one.
|
|
366
|
+
*/
|
|
367
|
+
function setupStylesheetHashes(): void {
|
|
368
|
+
const map = (globalThis as { __grimoire_css__?: Record<string, string> })
|
|
369
|
+
.__grimoire_css__;
|
|
370
|
+
if (!map || typeof MutationObserver === "undefined") return;
|
|
371
|
+
const fix = (el: Element) => {
|
|
372
|
+
if (!(el instanceof HTMLLinkElement) || el.rel !== "stylesheet") return;
|
|
373
|
+
const hashed = map[el.getAttribute("href") ?? ""];
|
|
374
|
+
if (hashed) el.setAttribute("href", hashed);
|
|
375
|
+
};
|
|
376
|
+
new MutationObserver((records) => {
|
|
377
|
+
for (const r of records) {
|
|
378
|
+
for (const node of r.addedNodes) {
|
|
379
|
+
if (node.nodeType !== 1) continue;
|
|
380
|
+
fix(node as Element);
|
|
381
|
+
for (const l of (node as Element).querySelectorAll?.("link") ?? [])
|
|
382
|
+
fix(l);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}).observe(document.documentElement, { childList: true, subtree: true });
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function setupPreload(): void {
|
|
389
|
+
// Hover is a desktop signal; a short delay ignores cursors passing over.
|
|
390
|
+
document.addEventListener("mouseover", (e) => {
|
|
391
|
+
const a = (e.target as Element).closest("a");
|
|
392
|
+
const href = prefetchHref(a);
|
|
393
|
+
if (!a || !href) return;
|
|
394
|
+
clearTimeout(preloadTimer);
|
|
395
|
+
preloadTimer = setTimeout(() => {
|
|
396
|
+
if (a.hasAttribute("data-sigil-preload-code")) {
|
|
397
|
+
const link = document.createElement("link");
|
|
398
|
+
link.rel = "prefetch";
|
|
399
|
+
link.href = href;
|
|
400
|
+
document.head.appendChild(link);
|
|
401
|
+
}
|
|
402
|
+
prefetch(href);
|
|
403
|
+
}, 80);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
document.addEventListener("mouseout", (e) => {
|
|
407
|
+
const a = (e.target as Element).closest("a");
|
|
408
|
+
if (!a) return;
|
|
409
|
+
clearTimeout(preloadTimer);
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
// Touch has no hover, but a tap lands 100-300ms after the finger goes
|
|
413
|
+
// down; start the request then.
|
|
414
|
+
document.addEventListener(
|
|
415
|
+
"touchstart",
|
|
416
|
+
(e) => {
|
|
417
|
+
const href = prefetchHref((e.target as Element).closest("a"));
|
|
418
|
+
if (href) prefetch(href);
|
|
419
|
+
},
|
|
420
|
+
{ passive: true },
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
// Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
|
|
424
|
+
// into view, for navs whose next tap is predictable.
|
|
425
|
+
if (typeof IntersectionObserver !== "undefined") {
|
|
426
|
+
const io = new IntersectionObserver((entries) => {
|
|
427
|
+
for (const entry of entries) {
|
|
428
|
+
if (!entry.isIntersecting) continue;
|
|
429
|
+
io.unobserve(entry.target);
|
|
430
|
+
const href = prefetchHref(entry.target);
|
|
431
|
+
if (href) prefetch(href);
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
const observe = (root: ParentNode) => {
|
|
435
|
+
for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
|
|
436
|
+
io.observe(a);
|
|
437
|
+
};
|
|
438
|
+
observe(document);
|
|
439
|
+
new MutationObserver((muts) => {
|
|
440
|
+
for (const m of muts)
|
|
441
|
+
for (const n of m.addedNodes)
|
|
442
|
+
if (n instanceof Element) {
|
|
443
|
+
if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
|
|
444
|
+
observe(n);
|
|
445
|
+
}
|
|
446
|
+
}).observe(document.body, { childList: true, subtree: true });
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
let lastState: {
|
|
451
|
+
data: any;
|
|
452
|
+
layoutData: any[];
|
|
453
|
+
params: any;
|
|
454
|
+
pattern: string;
|
|
455
|
+
/** What the page's last failed action passed to fail(); cleared by navigation. */
|
|
456
|
+
form?: unknown;
|
|
457
|
+
} | null = null;
|
|
458
|
+
|
|
459
|
+
function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
|
|
460
|
+
const { data, layoutData, params, pattern, form } = state!;
|
|
461
|
+
if (!Page) throw new Error(`no component for pattern ${pattern}`);
|
|
462
|
+
|
|
463
|
+
const matchedLayouts = layoutList
|
|
464
|
+
.filter(
|
|
465
|
+
(l) =>
|
|
466
|
+
l.path === "/" ||
|
|
467
|
+
pattern === l.path ||
|
|
468
|
+
pattern.startsWith(`${l.path}/`),
|
|
469
|
+
)
|
|
470
|
+
.sort((a, b) => a.path.length - b.path.length);
|
|
471
|
+
|
|
472
|
+
let renderFn = () => {
|
|
473
|
+
const pageNode = __component(Page, { data, params, form });
|
|
474
|
+
const pageDiv = document.createElement("div");
|
|
475
|
+
pageDiv.id = "grimoire-page";
|
|
476
|
+
pageDiv.appendChild(pageNode);
|
|
477
|
+
return pageDiv;
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
for (let i = matchedLayouts.length - 1; i >= 0; i--) {
|
|
481
|
+
const LayoutComponent = matchedLayouts[i].component;
|
|
482
|
+
const innerRender = renderFn;
|
|
483
|
+
const currentLayoutData = layoutData?.[i];
|
|
484
|
+
renderFn = () => {
|
|
485
|
+
const childNode = innerRender();
|
|
486
|
+
return __component(LayoutComponent, {
|
|
487
|
+
data: currentLayoutData,
|
|
488
|
+
params,
|
|
489
|
+
path: pattern,
|
|
490
|
+
children: childNode,
|
|
491
|
+
});
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
return renderFn();
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function matchClientPattern(pattern: string, pathname: string): boolean {
|
|
499
|
+
// haha pp and ph
|
|
500
|
+
const pp = pattern.split("/").filter(Boolean);
|
|
501
|
+
const ph = pathname.split("/").filter(Boolean);
|
|
502
|
+
|
|
503
|
+
// Depth-first walk; optional segments (:x?) try consuming one segment
|
|
504
|
+
// before consuming zero, mirroring the server's matchPattern.
|
|
505
|
+
function walk(pi: number, pj: number): boolean {
|
|
506
|
+
if (pi === pp.length) return pj === ph.length;
|
|
507
|
+
const part = pp[pi]!;
|
|
508
|
+
if (part.startsWith("*")) return true;
|
|
509
|
+
const optional = part.startsWith(":") && part.endsWith("?");
|
|
510
|
+
if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
|
|
511
|
+
if (!optional) {
|
|
512
|
+
if (pj >= ph.length) return false;
|
|
513
|
+
if (!part.startsWith(":") && part !== ph[pj]) return false;
|
|
514
|
+
return walk(pi + 1, pj + 1);
|
|
515
|
+
}
|
|
516
|
+
return walk(pi + 1, pj);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
return walk(0, 0);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// The one place the base is stripped. Everything else in the router handles
|
|
523
|
+
// full browser paths (history, fetch, scroll keys, `__data.json`), and a path
|
|
524
|
+
// outside the base matches no route, so the browser loads it as a page.
|
|
525
|
+
function findPattern(pathname: string): string | null {
|
|
526
|
+
const route = stripBase(pathname);
|
|
527
|
+
if (route === null) return null;
|
|
528
|
+
for (const pattern of Object.keys(routeMap)) {
|
|
529
|
+
if (matchClientPattern(pattern, route)) return pattern;
|
|
530
|
+
}
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** The URL as routes and loads see it: the same on the server, which strips the base from the request. */
|
|
535
|
+
function routeUrl(url: URL): URL {
|
|
536
|
+
const route = new URL(url);
|
|
537
|
+
route.pathname = stripBase(url.pathname) ?? url.pathname;
|
|
538
|
+
return route;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export interface NavigateOptions {
|
|
542
|
+
/** "push" (default) adds a history entry, "replace" swaps the current one,
|
|
543
|
+
* "none" leaves history untouched (popstate — the browser already moved). */
|
|
544
|
+
history?: "push" | "replace" | "none";
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// monotonically increasing id — a navigation aborts silently the moment a
|
|
548
|
+
// newer one starts, so overlapping navigations can't commit stale responses
|
|
549
|
+
let navigationId = 0;
|
|
550
|
+
|
|
551
|
+
export async function navigate(
|
|
552
|
+
path: string,
|
|
553
|
+
opts: NavigateOptions | boolean = {},
|
|
554
|
+
) {
|
|
555
|
+
// boolean back-compat: navigate(path, true) meant "replace"
|
|
556
|
+
const historyMode =
|
|
557
|
+
typeof opts === "boolean"
|
|
558
|
+
? opts
|
|
559
|
+
? "replace"
|
|
560
|
+
: "push"
|
|
561
|
+
: (opts.history ?? "push");
|
|
562
|
+
const navId = ++navigationId;
|
|
563
|
+
const url = new URL(path, location.origin);
|
|
564
|
+
const seen = routeUrl(url);
|
|
565
|
+
if (
|
|
566
|
+
base &&
|
|
567
|
+
url.origin === location.origin &&
|
|
568
|
+
stripBase(url.pathname) === null
|
|
569
|
+
) {
|
|
570
|
+
console.warn(
|
|
571
|
+
`[grimoire] navigate("${path}") is outside the base "${base}", so it loads as a new page and the server will not find it. Write navigate(withBase("${url.pathname}")).`,
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (beforeNavigateCb) {
|
|
576
|
+
const shouldProceed = beforeNavigateCb(seen);
|
|
577
|
+
if (shouldProceed === false) return;
|
|
578
|
+
}
|
|
579
|
+
onNavigateCb?.(seen);
|
|
580
|
+
saveScrollPosition();
|
|
581
|
+
// read before the loading placeholder below collapses the page and the
|
|
582
|
+
// browser clamps scrollY; a same-path refetch restores this value
|
|
583
|
+
const startY = window.scrollY;
|
|
584
|
+
|
|
585
|
+
// load the loading immediately
|
|
586
|
+
const destPattern = findPattern(url.pathname);
|
|
587
|
+
const DestPage = destPattern ? await resolveRoute(destPattern) : null;
|
|
588
|
+
if (navId !== navigationId) return;
|
|
589
|
+
if (DestPage?.loading) {
|
|
590
|
+
disposeCurrentPage?.();
|
|
591
|
+
disposeCurrentPage = null;
|
|
592
|
+
pushHydrationNodes([]);
|
|
593
|
+
let loadingNode: any;
|
|
594
|
+
let flush = () => {};
|
|
595
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
596
|
+
({ value: loadingNode, flush } = collectEffects(() =>
|
|
597
|
+
(DestPage as any).loading(),
|
|
598
|
+
));
|
|
599
|
+
});
|
|
600
|
+
popHydrationNodes();
|
|
601
|
+
// replace only grimoire-page, keeps layout stable during transition
|
|
602
|
+
const pageEl = document.getElementById("grimoire-page");
|
|
603
|
+
if (pageEl) pageEl.replaceChildren(loadingNode);
|
|
604
|
+
else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
|
|
605
|
+
flush();
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
let res: Response;
|
|
609
|
+
try {
|
|
610
|
+
res = await (takePrefetched(path) ?? navigateFetch(path));
|
|
611
|
+
} catch {
|
|
612
|
+
// a failed prefetch must not fail the click
|
|
613
|
+
res = await navigateFetch(path);
|
|
614
|
+
}
|
|
615
|
+
if (navId !== navigationId) return;
|
|
616
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
617
|
+
if (!contentType.includes("application/json")) {
|
|
618
|
+
window.location.href = path;
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const json = await res.json();
|
|
622
|
+
if (navId !== navigationId) return;
|
|
623
|
+
const { data, layoutData, params, pattern, head, deps } = json;
|
|
624
|
+
const Page = await resolveRoute(pattern);
|
|
625
|
+
if (navId !== navigationId) return;
|
|
626
|
+
if (!Page) {
|
|
627
|
+
window.location.href = path;
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
let mergedData = data;
|
|
632
|
+
if (Page.load) {
|
|
633
|
+
try {
|
|
634
|
+
startCollecting();
|
|
635
|
+
const clientData = await Page.load({
|
|
636
|
+
params,
|
|
637
|
+
url: seen,
|
|
638
|
+
request: new Request(seen),
|
|
639
|
+
// layout loads run server-side; their data arrives in layoutData —
|
|
640
|
+
// parent() merges it outermost-first, mirroring the server context
|
|
641
|
+
parent: async () =>
|
|
642
|
+
Object.assign(
|
|
643
|
+
{},
|
|
644
|
+
...(Array.isArray(layoutData) ? layoutData : []).filter(
|
|
645
|
+
(d) => d && typeof d === "object",
|
|
646
|
+
),
|
|
647
|
+
),
|
|
648
|
+
});
|
|
649
|
+
// merge server-collected keys (page/layout server loads) with
|
|
650
|
+
// whatever this client-side load itself registered
|
|
651
|
+
setDeps(pattern, [
|
|
652
|
+
...(Array.isArray(deps) ? deps : []),
|
|
653
|
+
...stopCollecting(),
|
|
654
|
+
]);
|
|
655
|
+
mergedData = { ...clientData, ...data };
|
|
656
|
+
} catch (e: unknown) {
|
|
657
|
+
stopCollecting();
|
|
658
|
+
if (e && typeof e === "object" && "location" in e) {
|
|
659
|
+
window.location.href = String((e as { location: unknown }).location);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
console.error("[grimoire] universal load error:", e);
|
|
663
|
+
}
|
|
664
|
+
if (navId !== navigationId) return;
|
|
665
|
+
} else if (Array.isArray(deps)) {
|
|
666
|
+
// no client-side load to run — the server's collected depends() keys
|
|
667
|
+
// (from +page.server.ts / +layout.server.ts) are the whole story
|
|
668
|
+
setDeps(pattern, deps);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// track state for HMR rerender
|
|
672
|
+
lastState = { data: mergedData, layoutData, params, pattern };
|
|
673
|
+
(globalThis as any).__grimoire_current_pattern__ = pattern;
|
|
674
|
+
|
|
675
|
+
disposeCurrentPage?.();
|
|
676
|
+
disposeCurrentPage = null;
|
|
677
|
+
pushHydrationNodes([]);
|
|
678
|
+
let rootNode: any;
|
|
679
|
+
// the page's effects (and use: directives) run once it is in the document
|
|
680
|
+
let flushEffects = () => {};
|
|
681
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
682
|
+
try {
|
|
683
|
+
({ value: rootNode, flush: flushEffects } = collectEffects(() =>
|
|
684
|
+
buildRouteTree(lastState!, Page),
|
|
685
|
+
));
|
|
686
|
+
} catch (e) {
|
|
687
|
+
console.error(e);
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
popHydrationNodes();
|
|
691
|
+
|
|
692
|
+
updateHead(head);
|
|
693
|
+
// isRefetch is read before currentPath moves, and captured, because
|
|
694
|
+
// applyScroll may run after this function has returned.
|
|
695
|
+
const isRefetch = url.pathname === currentPath;
|
|
696
|
+
|
|
697
|
+
// Scroll has to be decided in the same frame the content lands. Running it
|
|
698
|
+
// here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
|
|
699
|
+
// same-page anchor was already present and worked, while an anchor on the
|
|
700
|
+
// incoming page did not exist yet and fell through to scrollToTop().
|
|
701
|
+
const applyScroll = () => {
|
|
702
|
+
if (url.hash) {
|
|
703
|
+
const target = document.getElementById(url.hash.slice(1));
|
|
704
|
+
if (!target) {
|
|
705
|
+
scrollToTop();
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
target.scrollIntoView();
|
|
709
|
+
// re-assert after layout settles (late effects/images can shift content)
|
|
710
|
+
requestAnimationFrame(() => target.scrollIntoView());
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (historyMode === "none") {
|
|
714
|
+
// popstate: the browser already moved through history — restore what
|
|
715
|
+
// we saved for this path (back/forward semantics)
|
|
716
|
+
restoreScrollPosition(url.pathname);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
// fresh navigation starts at the top; a same-path replace
|
|
720
|
+
// (invalidate/refetch) keeps the scroll it started with
|
|
721
|
+
if (!isRefetch) {
|
|
722
|
+
scrollToTop();
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
window.scrollTo(0, startY);
|
|
726
|
+
requestAnimationFrame(() => window.scrollTo(0, startY));
|
|
727
|
+
};
|
|
728
|
+
|
|
729
|
+
// View transitions: animate the swap when the browser supports it and the
|
|
730
|
+
// user hasn't asked for reduced motion. The callback must stay synchronous.
|
|
731
|
+
const preserved = capturePreservedScroll();
|
|
732
|
+
const doc = document as Document & {
|
|
733
|
+
startViewTransition?: (
|
|
734
|
+
cb: () => void,
|
|
735
|
+
) => { finished?: Promise<unknown>; ready?: Promise<unknown> } | undefined;
|
|
736
|
+
};
|
|
737
|
+
const animate =
|
|
738
|
+
typeof doc.startViewTransition === "function" &&
|
|
739
|
+
!window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
740
|
+
// elements the old and new page share by key morph into each other
|
|
741
|
+
const shared = animate ? sharedTransitionKeys(rootNode) : [];
|
|
742
|
+
const named: Element[] = [];
|
|
743
|
+
const name = (el: Element, key: string) => {
|
|
744
|
+
(el as HTMLElement).style.setProperty("view-transition-name", key);
|
|
745
|
+
named.push(el);
|
|
746
|
+
};
|
|
747
|
+
const doSwap = () => {
|
|
748
|
+
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
749
|
+
flushEffects();
|
|
750
|
+
for (const [key, , next] of shared) name(next, key);
|
|
751
|
+
restorePreservedScroll(preserved);
|
|
752
|
+
applyScroll();
|
|
753
|
+
};
|
|
754
|
+
if (animate) {
|
|
755
|
+
// the browser snapshots the old page as startViewTransition is called
|
|
756
|
+
for (const [key, prev] of shared) name(prev, key);
|
|
757
|
+
const transition = doc.startViewTransition?.(doSwap);
|
|
758
|
+
const clear = () => {
|
|
759
|
+
for (const el of named)
|
|
760
|
+
(el as HTMLElement).style.removeProperty("view-transition-name");
|
|
761
|
+
};
|
|
762
|
+
Promise.resolve(transition?.finished).then(clear, clear);
|
|
763
|
+
// a skipped transition (another navigation, a hidden tab) rejects
|
|
764
|
+
// ready; the swap still runs, so it is not an error worth reporting
|
|
765
|
+
transition?.ready?.catch(() => {});
|
|
766
|
+
} else {
|
|
767
|
+
doSwap();
|
|
768
|
+
}
|
|
769
|
+
currentPath = url.pathname;
|
|
770
|
+
currentSearch = url.search;
|
|
771
|
+
|
|
772
|
+
if (historyMode !== "none") {
|
|
773
|
+
history[historyMode === "replace" ? "replaceState" : "pushState"](
|
|
774
|
+
null,
|
|
775
|
+
"",
|
|
776
|
+
path,
|
|
777
|
+
);
|
|
778
|
+
}
|
|
779
|
+
afterNavigateCb?.(seen);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
export interface RouterExtensions {
|
|
783
|
+
/** [param=matcher] validators from src/params/*.ts (manifest-generated). */
|
|
784
|
+
matchers?: Record<string, (value: string) => boolean>;
|
|
785
|
+
/** Server-collected depends() keys per route pattern (from SSR state). */
|
|
786
|
+
deps?: Record<string, string[]>;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
let paramMatcherFns: Record<string, (value: string) => boolean> = {};
|
|
790
|
+
|
|
791
|
+
export function initRouter(
|
|
792
|
+
routes: Record<string, RouteEntry>,
|
|
793
|
+
layouts: any[] = [],
|
|
794
|
+
initialDispose?: () => void,
|
|
795
|
+
ext?: RouterExtensions,
|
|
796
|
+
) {
|
|
797
|
+
paramMatcherFns = ext?.matchers ?? {};
|
|
798
|
+
routeMap = routes;
|
|
799
|
+
layoutList = layouts;
|
|
800
|
+
prefetched.clear();
|
|
801
|
+
disposeCurrentPage = initialDispose ?? null;
|
|
802
|
+
currentPath = location.pathname;
|
|
803
|
+
currentSearch = location.search;
|
|
804
|
+
|
|
805
|
+
// the app owns scroll: the browser's automatic restoration fires after
|
|
806
|
+
// the router's own scroll and clobbers scroll-to-top / saved positions
|
|
807
|
+
if ("scrollRestoration" in history) history.scrollRestoration = "manual";
|
|
808
|
+
// dev HMR surface: available even without SSR state so the client can tell
|
|
809
|
+
// a missing router apart from a missing initial payload
|
|
810
|
+
const globals = globalThis as unknown as {
|
|
811
|
+
__grimoire_current_pattern__?: string;
|
|
812
|
+
__grimoire_routes__?: Record<string, RouteEntry>;
|
|
813
|
+
__grimoire_rerender__?: () => Promise<void>;
|
|
814
|
+
__grimoire_navigate__?: (path: string, replace?: boolean) => void;
|
|
815
|
+
__grimoire_form__?: (form: unknown) => Promise<void>;
|
|
816
|
+
__grimoire_hmr__?: HmrControl;
|
|
817
|
+
};
|
|
818
|
+
globals.__grimoire_routes__ = routeMap;
|
|
819
|
+
globals.__grimoire_rerender__ = hmrRerender;
|
|
820
|
+
globals.__grimoire_hmr__ = hmrControl;
|
|
821
|
+
globals.__grimoire_form__ = showActionFailure;
|
|
822
|
+
globals.__grimoire_navigate__ = (path, replace) =>
|
|
823
|
+
navigate(path, replace ?? false);
|
|
824
|
+
|
|
825
|
+
// initial HMR state from SSR
|
|
826
|
+
const stateEl = document.getElementById("__grimoire_state__");
|
|
827
|
+
if (stateEl) {
|
|
828
|
+
const state = JSON.parse(stateEl.textContent!);
|
|
829
|
+
lastState = {
|
|
830
|
+
data: state.data,
|
|
831
|
+
layoutData: state.layoutData,
|
|
832
|
+
params: state.params,
|
|
833
|
+
pattern: state.pattern,
|
|
834
|
+
form: state.form,
|
|
835
|
+
};
|
|
836
|
+
if (Array.isArray(state.deps)) {
|
|
837
|
+
setDeps(state.pattern, state.deps);
|
|
838
|
+
}
|
|
839
|
+
globals.__grimoire_current_pattern__ = state.pattern;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
saveScrollPosition();
|
|
843
|
+
document.addEventListener("click", handleClick);
|
|
844
|
+
// forms rendered client-side have no SSR-injected _csrf input
|
|
845
|
+
document.addEventListener("submit", onSubmitEnsureCsrf, true);
|
|
846
|
+
window.addEventListener("popstate", () => {
|
|
847
|
+
if (
|
|
848
|
+
location.pathname === currentPath &&
|
|
849
|
+
location.search === currentSearch
|
|
850
|
+
) {
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
// the browser already moved through history — render only, never
|
|
854
|
+
// push/replace here or the forward stack gets clobbered.
|
|
855
|
+
// The search has to come along: refetching the bare pathname served
|
|
856
|
+
// unfiltered data while the address bar still showed the query.
|
|
857
|
+
// The hash deliberately does not, so back/forward restores the saved
|
|
858
|
+
// scroll offset instead of re-jumping to the anchor, matching the
|
|
859
|
+
// browser's own behaviour for document history navigation.
|
|
860
|
+
navigate(location.pathname + location.search, { history: "none" });
|
|
861
|
+
});
|
|
862
|
+
setupPreload();
|
|
863
|
+
setupStylesheetHashes();
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/**
|
|
867
|
+
* Swap the page's <head> tags for the incoming page's. Server-rendered tags
|
|
868
|
+
* sit between `<!--grimoire-head-->` markers; tags added by an earlier
|
|
869
|
+
* navigation carry `data-grimoire-head`. Both are replaced, so the first
|
|
870
|
+
* navigation doesn't leave the server-rendered description or icon behind
|
|
871
|
+
* next to the new ones. With no incoming <title>, the current title stays.
|
|
872
|
+
*/
|
|
873
|
+
function updateHead(headHtml: string) {
|
|
874
|
+
const prevTitle = document.title;
|
|
875
|
+
const markers = Array.from(document.head.childNodes).filter(
|
|
876
|
+
(n): n is Comment => n.nodeType === Node.COMMENT_NODE,
|
|
877
|
+
);
|
|
878
|
+
const start = markers.find((c) => c.data === "grimoire-head");
|
|
879
|
+
const end = markers.find((c) => c.data === "/grimoire-head");
|
|
880
|
+
if (start && end) {
|
|
881
|
+
while (start.nextSibling && start.nextSibling !== end) {
|
|
882
|
+
start.nextSibling.remove();
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
document
|
|
886
|
+
.querySelectorAll("[data-grimoire-head]")
|
|
887
|
+
//biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
|
|
888
|
+
.forEach((el) => el.remove());
|
|
889
|
+
const parsed = headHtml
|
|
890
|
+
? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
|
|
891
|
+
: null;
|
|
892
|
+
const incomingTitle = parsed?.querySelector("title");
|
|
893
|
+
//biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
|
|
894
|
+
document.querySelectorAll("title").forEach((el) => el.remove());
|
|
895
|
+
document.title = incomingTitle?.textContent ?? prevTitle;
|
|
896
|
+
if (parsed) {
|
|
897
|
+
for (const el of Array.from(parsed.head.children)) {
|
|
898
|
+
if (el.tagName === "TITLE") continue;
|
|
899
|
+
(el as HTMLElement).dataset.grimoireHead = "1";
|
|
900
|
+
if (end) document.head.insertBefore(el, end);
|
|
901
|
+
else document.head.appendChild(el);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function handleClick(e: MouseEvent) {
|
|
907
|
+
// a hover prefetch still pending must not fire after a click, whoever
|
|
908
|
+
// handles it: it would re-request what the page is leaving for, and that
|
|
909
|
+
// GET may do something (a sign-in link sets its state cookie)
|
|
910
|
+
clearTimeout(preloadTimer);
|
|
911
|
+
// let the browser handle modified clicks (new tab/window/download)
|
|
912
|
+
if (e.defaultPrevented || e.button !== 0) return;
|
|
913
|
+
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
|
914
|
+
const a = (e.target as Element).closest("a");
|
|
915
|
+
if (!a) return;
|
|
916
|
+
if (a.target && a.target !== "_self") return;
|
|
917
|
+
if (a.hasAttribute("download")) return;
|
|
918
|
+
if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
|
|
919
|
+
const href = a.getAttribute("href");
|
|
920
|
+
if (!href) return;
|
|
921
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
|
|
922
|
+
// Only intercept clicks for known page routes — let server routes
|
|
923
|
+
// (redirects, API endpoints, etc.) navigate normally so the browser
|
|
924
|
+
// follows the response without the extra fetch-then-redirect dance.
|
|
925
|
+
try {
|
|
926
|
+
const url = new URL(href, location.origin);
|
|
927
|
+
if (!findPattern(url.pathname)) return;
|
|
928
|
+
// same-page anchor: native behavior scrolls to it, no re-render needed
|
|
929
|
+
if (url.pathname === location.pathname && url.hash) return;
|
|
930
|
+
} catch {
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
e.preventDefault();
|
|
934
|
+
navigate(href);
|
|
935
|
+
}
|