@sigil-dev/grimoire 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "private": false,
7
- "version": "0.9.5",
7
+ "version": "0.9.6",
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./server": "./server.ts",
@@ -23,8 +23,8 @@
23
23
  "test": "bun test"
24
24
  },
25
25
  "dependencies": {
26
- "@sigil-dev/compiler": "0.9.5",
27
- "@sigil-dev/runtime": "0.9.5",
26
+ "@sigil-dev/compiler": "0.9.6",
27
+ "@sigil-dev/runtime": "0.9.6",
28
28
  "vite": "^8.0.16"
29
29
  },
30
30
  "peerDependencies": {
@@ -54,7 +54,11 @@ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
54
54
  }
55
55
  let layoutList: { path: string; component: (props: any) => any }[] = [];
56
56
  let disposeCurrentPage: (() => void) | null = null;
57
+ // Scroll keys and same-page refetch detection are pathname-only on purpose.
58
+ // currentSearch is tracked alongside so popstate can tell "?page=2" apart
59
+ // from "?page=1" without polluting either of those.
57
60
  let currentPath = location.pathname;
61
+ let currentSearch = location.search;
58
62
 
59
63
  // C1: Navigation hooks
60
64
  let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
@@ -78,7 +82,9 @@ export async function hmrRerender(): Promise<void> {
78
82
  rootNode = buildRouteTree(lastState!, Page);
79
83
  });
80
84
  popHydrationNodes();
85
+ const preserved = capturePreservedScroll();
81
86
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
87
+ restorePreservedScroll(preserved);
82
88
  }
83
89
 
84
90
  /**
@@ -97,7 +103,7 @@ const hmrControl: HmrControl = {
97
103
  routeMap[pattern] = entry;
98
104
  delete resolvedRoutes[pattern];
99
105
  },
100
- setLayout(path, component) {
106
+ setLayout(path: string, component: (props: any) => any) {
101
107
  const existing = layoutList.find((l) => l.path === path);
102
108
  if (existing) existing.component = component;
103
109
  else layoutList.push({ path, component });
@@ -136,6 +142,37 @@ function scrollToTop(): void {
136
142
  requestAnimationFrame(() => window.scrollTo(0, 0));
137
143
  }
138
144
 
145
+ // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
146
+ // across the root swap: the router rebuilds the whole tree on navigation, so a
147
+ // long independently-scrollable sidebar would otherwise snap back to the top.
148
+ // The attribute value is the matching key; elements without one fall back to
149
+ // their id, then to their ordinal position.
150
+ const PRESERVE_ATTR = "data-sigil-scroll-preserve";
151
+
152
+ function preserveKey(el: Element, ordinal: number): string {
153
+ return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
154
+ }
155
+
156
+ function capturePreservedScroll(): Map<string, number> {
157
+ const positions = new Map<string, number>();
158
+ let ordinal = 0;
159
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
160
+ positions.set(preserveKey(el, ordinal), el.scrollTop);
161
+ ordinal++;
162
+ }
163
+ return positions;
164
+ }
165
+
166
+ function restorePreservedScroll(positions: Map<string, number>): void {
167
+ if (positions.size === 0) return;
168
+ let ordinal = 0;
169
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
170
+ const top = positions.get(preserveKey(el, ordinal));
171
+ if (top !== undefined) el.scrollTop = top;
172
+ ordinal++;
173
+ }
174
+ }
175
+
139
176
  // C3: Preloading
140
177
  let preloadTimer: Timer | null = null;
141
178
 
@@ -388,10 +425,44 @@ export async function navigate(
388
425
  popHydrationNodes();
389
426
 
390
427
  updateHead(head);
428
+ // isRefetch is read before currentPath moves, and captured, because
429
+ // applyScroll may run after this function has returned.
430
+ const isRefetch = url.pathname === currentPath;
431
+
432
+ // Scroll has to be decided in the same frame the content lands. Running it
433
+ // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
434
+ // same-page anchor was already present and worked, while an anchor on the
435
+ // incoming page did not exist yet and fell through to scrollToTop().
436
+ const applyScroll = () => {
437
+ if (url.hash) {
438
+ const target = document.getElementById(url.hash.slice(1));
439
+ if (!target) {
440
+ scrollToTop();
441
+ return;
442
+ }
443
+ target.scrollIntoView();
444
+ // re-assert after layout settles (late effects/images can shift content)
445
+ requestAnimationFrame(() => target.scrollIntoView());
446
+ return;
447
+ }
448
+ if (historyMode === "none") {
449
+ // popstate: the browser already moved through history — restore what
450
+ // we saved for this path (back/forward semantics)
451
+ restoreScrollPosition(url.pathname);
452
+ return;
453
+ }
454
+ // fresh navigation starts at the top; a same-path replace
455
+ // (invalidate/refetch) keeps the current scroll
456
+ if (!isRefetch) scrollToTop();
457
+ };
458
+
391
459
  // View transitions: animate the swap when the browser supports it and the
392
460
  // user hasn't asked for reduced motion. The callback must stay synchronous.
461
+ const preserved = capturePreservedScroll();
393
462
  const doSwap = () => {
394
463
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
464
+ restorePreservedScroll(preserved);
465
+ applyScroll();
395
466
  };
396
467
  const doc = document as Document & {
397
468
  startViewTransition?: (cb: () => void) => unknown;
@@ -404,8 +475,8 @@ export async function navigate(
404
475
  } else {
405
476
  doSwap();
406
477
  }
407
- const isRefetch = url.pathname === currentPath;
408
478
  currentPath = url.pathname;
479
+ currentSearch = url.search;
409
480
 
410
481
  if (historyMode !== "none") {
411
482
  history[historyMode === "replace" ? "replaceState" : "pushState"](
@@ -414,19 +485,6 @@ export async function navigate(
414
485
  path,
415
486
  );
416
487
  }
417
- if (url.hash) {
418
- const target = document.getElementById(url.hash.slice(1));
419
- if (target) requestAnimationFrame(() => target.scrollIntoView());
420
- else scrollToTop();
421
- } else if (historyMode === "none") {
422
- // popstate: the browser already moved through history — restore what
423
- // we saved for this path (back/forward semantics)
424
- restoreScrollPosition(url.pathname);
425
- } else if (!isRefetch) {
426
- // fresh navigation: the new page starts at the top
427
- scrollToTop();
428
- }
429
- // same-path replace (invalidate/refetch): keep the current scroll
430
488
  afterNavigateCb?.(url);
431
489
  }
432
490
 
@@ -450,6 +508,7 @@ export function initRouter(
450
508
  layoutList = layouts;
451
509
  disposeCurrentPage = initialDispose ?? null;
452
510
  currentPath = location.pathname;
511
+ currentSearch = location.search;
453
512
 
454
513
  // the app owns scroll: the browser's automatic restoration fires after
455
514
  // the router's own scroll and clobbers scroll-to-top / saved positions
@@ -488,11 +547,20 @@ export function initRouter(
488
547
  saveScrollPosition();
489
548
  document.addEventListener("click", handleClick);
490
549
  window.addEventListener("popstate", () => {
491
- if (location.pathname !== currentPath) {
492
- // the browser already moved through history — render only, never
493
- // push/replace here or the forward stack gets clobbered
494
- navigate(location.pathname, { history: "none" });
550
+ if (
551
+ location.pathname === currentPath &&
552
+ location.search === currentSearch
553
+ ) {
554
+ return;
495
555
  }
556
+ // the browser already moved through history — render only, never
557
+ // push/replace here or the forward stack gets clobbered.
558
+ // The search has to come along: refetching the bare pathname served
559
+ // unfiltered data while the address bar still showed the query.
560
+ // The hash deliberately does not, so back/forward restores the saved
561
+ // scroll offset instead of re-jumping to the anchor, matching the
562
+ // browser's own behaviour for document history navigation.
563
+ navigate(location.pathname + location.search, { history: "none" });
496
564
  });
497
565
  setupPreload();
498
566
  }
@@ -28,6 +28,13 @@ class DeferredMarker {
28
28
 
29
29
  type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
30
30
 
31
+ /**
32
+ * Request header the client router sets to ask for the JSON navigate payload
33
+ * instead of an HTML document. Both representations live at the same URL, so
34
+ * every response that depends on it MUST also send it in `Vary`.
35
+ */
36
+ export const NAVIGATE_HEADER = "x-grimoire-navigate";
37
+
31
38
  /**
32
39
  * Serialize the hydration state payload for embedding inside a
33
40
  * `<script type="application/json">` tag. Escapes every `<` so a data value
@@ -169,7 +176,7 @@ export async function renderErrorPage(
169
176
 
170
177
  return new Response(html, {
171
178
  status,
172
- headers: { "Content-Type": "text/html" },
179
+ headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
173
180
  });
174
181
  });
175
182
  }
@@ -375,12 +382,17 @@ export async function renderRoute(
375
382
  }
376
383
  }
377
384
 
378
- const isNavigate = req.headers.get("x-grimoire-navigate") === "1";
385
+ const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
379
386
  const hasLoading = typeof pageMod.loading === "function";
380
387
 
381
388
  // helper: wrap page html in layout tree
382
389
  function applyLayouts(pageHtml: string): string {
383
- return applyLayoutTree(pageHtml, layoutPairs, matched.params, matched.route.path);
390
+ return applyLayoutTree(
391
+ pageHtml,
392
+ layoutPairs,
393
+ matched.params,
394
+ matched.route.path,
395
+ );
384
396
  }
385
397
 
386
398
  // ── two-pass streaming (loading export present) ─────────────────────────
@@ -466,7 +478,7 @@ export async function renderRoute(
466
478
  });
467
479
 
468
480
  return new Response(stream, {
469
- headers: { "Content-Type": "text/html" },
481
+ headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
470
482
  });
471
483
  }
472
484
 
@@ -507,14 +519,23 @@ export async function renderRoute(
507
519
  (mergedData as Record<string, unknown>)[d.key] = null;
508
520
  }
509
521
  }
510
- return Response.json({
511
- data: mergedData ?? {},
512
- layoutData: layoutPairs.map((l) => l.data),
513
- params: matched.params,
514
- pattern: matched.route.path,
515
- head: headHtml,
516
- deps: [...collectedDeps],
517
- });
522
+ // Vary is mandatory here: this JSON and the HTML document share one
523
+ // URL and are chosen by a request header, so without it any cache may
524
+ // hand the JSON to a plain document request. That is what surfaced as
525
+ // raw state payloads rendering as the page after a back navigation.
526
+ // Deliberately still cacheable: hover-prefetch exists to warm this
527
+ // entry, and Vary already keeps document requests from matching it.
528
+ return Response.json(
529
+ {
530
+ data: mergedData ?? {},
531
+ layoutData: layoutPairs.map((l) => l.data),
532
+ params: matched.params,
533
+ pattern: matched.route.path,
534
+ head: headHtml,
535
+ deps: [...collectedDeps],
536
+ },
537
+ { headers: { Vary: NAVIGATE_HEADER } },
538
+ );
518
539
  }
519
540
 
520
541
  // ── single-pass SSR stream ──────────────────────────────────────────────
@@ -571,6 +592,7 @@ export async function renderRoute(
571
592
  headers: {
572
593
  "Content-Type": "text/html",
573
594
  "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
595
+ Vary: NAVIGATE_HEADER,
574
596
  },
575
597
  });
576
598
  });