@sigil-dev/grimoire 0.9.32 → 0.10.0

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