@sigil-dev/grimoire 0.9.25 → 0.9.27

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