@opentf/afw 0.37.0 → 0.38.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.
package/runtime/router.js CHANGED
@@ -22,9 +22,12 @@ import { prepareRouteHead, updateRouteHead } from "./head.js";
22
22
  import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
23
23
  import { collectHotState, withHotCarry } from "./hot-carry.js";
24
24
  import { buildScopedView, runCleanup, runMount } from "./mount.js";
25
- import { RouteRedirect, fetchRouteData, readInlineRouteData } from "./route-data.js";
25
+ import { RouteRedirect, fetchRouteData, readInlineRouteData, routeErrorFrom } from "./route-data.js";
26
+ import { enterPending, exitPending } from "./pending-scope.js";
27
+ import { setRouteErrorHandler } from "./route-errors.js";
28
+ import { enterEntry, manageScroll, rememberScroll, restoreScroll } from "./scroll.js";
26
29
  import { setRouteDataRefresher } from "./invalidate.js";
27
- import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
30
+ import { compareRoutes, compileRoute, decodeParams, urlCollisions } from "./route-match.js";
28
31
 
29
32
  const isBrowser = typeof window !== "undefined";
30
33
 
@@ -46,7 +49,7 @@ const state = {
46
49
  toc: signal([]),
47
50
  };
48
51
 
49
- export const routes = { pages: {}, layouts: {}, notFound: null, loaderRoutes: new Set() };
52
+ export const routes = { pages: {}, layouts: {}, loading: {}, errors: {}, notFound: null, loaderRoutes: new Set() };
50
53
  let guard = null;
51
54
  let rootEl = null;
52
55
 
@@ -132,6 +135,69 @@ export function setLocale(locale) {
132
135
  state.locale.value = locale;
133
136
  }
134
137
  let currentNodes = [];
138
+ // The page's part of `currentNodes` — the page node, or the route <Pending> around it —
139
+ // and the matched route pattern: where an error no <ErrorBoundary> caught may be
140
+ // replaced by the route's `error.jsx` (see `showRouteError`).
141
+ let currentRegion = null;
142
+ let currentRoute = null;
143
+
144
+ /** Opt-in `document.startViewTransition()` around client navigations (`mountApp`). */
145
+ let viewTransitions = false;
146
+ /** Has this app committed a page yet (the first paint is never a transition)? */
147
+ let committed = false;
148
+
149
+ /**
150
+ * Run `update` (a synchronous DOM swap) inside a view transition when they are on,
151
+ * supported, `animate` allows it (never the first paint) and the user hasn't asked
152
+ * for reduced motion; otherwise run it directly. An error thrown by `update` is
153
+ * rethrown either way.
154
+ */
155
+ async function swapView(update, animate = true) {
156
+ const supported = isBrowser && typeof document.startViewTransition === "function";
157
+ const reduced = isBrowser && typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
158
+ if (!viewTransitions || !animate || !supported || reduced) {
159
+ update();
160
+ return;
161
+ }
162
+ let failure = null;
163
+ const transition = document.startViewTransition(() => {
164
+ try {
165
+ update();
166
+ } catch (error) {
167
+ failure = error;
168
+ }
169
+ });
170
+ // A navigation during a running transition skips it: `ready` and `finished` then
171
+ // reject (AbortError), which is expected, not an app error.
172
+ transition.ready?.catch(() => {});
173
+ transition.finished?.catch(() => {});
174
+ await transition.updateCallbackDone.catch(() => {});
175
+ if (failure) throw failure;
176
+ }
177
+
178
+ /** Scroll a forward navigation: to its `#anchor`, or the top. */
179
+ function scrollToTarget(url) {
180
+ const anchor = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
181
+ if (anchor) anchor.scrollIntoView();
182
+ else window.scrollTo(0, 0);
183
+ }
184
+
185
+ /**
186
+ * Where a committed navigation leaves the scroll: back/forward and a reload restore
187
+ * the position saved for the entry (falling back to its `#anchor`, else unchanged);
188
+ * a forward navigation goes to its anchor or the top.
189
+ */
190
+ function landScroll(url, isPop, entry) {
191
+ if (!isPop) return scrollToTarget(url);
192
+ if (restoreScroll(entry)) return;
193
+ if (url.hash) scrollToTarget(url);
194
+ }
195
+
196
+ /** How long a navigation waits before showing `loading.jsx`: a fast one never flashes it. */
197
+ export const LOADING_DELAY = 150;
198
+
199
+ const factoryOf = (module) => module?.default ?? module;
200
+ const currentLocation = () => window.location.pathname + window.location.search + window.location.hash;
135
201
 
136
202
  function routeValue(key) {
137
203
  const route = getRenderContext()?.route;
@@ -172,7 +238,7 @@ export const router = {
172
238
  function routeFromPath(filePath) {
173
239
  const r = filePath
174
240
  .replace(/^.*\/app(?=\/)/, "")
175
- .replace(/\/(page|layout|404)\.(jsx|tsx|mdx|md)$/, "");
241
+ .replace(/\/(page|layout|404|loading|error)\.(jsx|tsx|mdx|md)$/, "");
176
242
  return r === "" ? "/" : r;
177
243
  }
178
244
 
@@ -180,7 +246,9 @@ function routeFromPath(filePath) {
180
246
  * Register routes from a `{ path: entry }` map. Each `entry` is either a module
181
247
  * namespace (eager) or a `() => import(...)` loader (lazy, code-split) — both
182
248
  * resolve to a default-export factory at navigation time. `layout.jsx` files
183
- * register as layouts (wrapping nested pages), `404.jsx` as the fallback.
249
+ * register as layouts (wrapping nested pages), `404.jsx` as the fallback, and
250
+ * `loading.jsx` / `error.jsx` as the loading and error views of the pages beneath
251
+ * their folder.
184
252
  */
185
253
  export function registerRoutes(modules) {
186
254
  // Validate before changing the table: an unsupported fallback otherwise
@@ -189,13 +257,22 @@ export function registerRoutes(modules) {
189
257
  if (/\/404\.(mdx|md)$/.test(file)) {
190
258
  throw new Error(`Unsupported Markdown 404 route: ${file}. Use 404.jsx or 404.tsx instead.`);
191
259
  }
260
+ const special = /\/(loading|error)\.(mdx|md)$/.exec(file);
261
+ if (special) {
262
+ throw new Error(`Unsupported Markdown ${special[1]} file: ${file}. Use ${special[1]}.jsx or ${special[1]}.tsx instead.`);
263
+ }
192
264
  }
193
265
  for (const file in modules) {
194
266
  const entry = modules[file];
195
267
  if (/\/404\.(jsx|tsx)$/.test(file)) routes.notFound = entry;
196
268
  else if (/\/layout\.(jsx|tsx)$/.test(file)) routes.layouts[routeFromPath(file)] = entry;
269
+ else if (/\/loading\.(jsx|tsx)$/.test(file)) routes.loading[routeFromPath(file)] = entry;
270
+ else if (/\/error\.(jsx|tsx)$/.test(file)) routes.errors[routeFromPath(file)] = entry;
197
271
  else routes.pages[routeFromPath(file)] = entry;
198
272
  }
273
+ // Route groups drop out of the URL, so two of them can hold the same page path.
274
+ const [clash] = urlCollisions(Object.keys(routes.pages));
275
+ if (clash) throw new Error(`Two pages answer ${clash[0]}: app${clash[1]} and app${clash[2]}. Move one to another path.`);
199
276
  }
200
277
 
201
278
  /**
@@ -230,6 +307,50 @@ export function layoutChain(route) {
230
307
  return chain;
231
308
  }
232
309
 
310
+ /**
311
+ * The nearest `loading.jsx` / `error.jsx` entry for `route` (`table` is
312
+ * `routes.loading` or `routes.errors`): the route's own folder first, then each
313
+ * parent up to the app root. The 404 fallback (`route` null) uses the root's.
314
+ */
315
+ export function nearestRouteFile(table, route) {
316
+ let p = route || "/";
317
+ while (true) {
318
+ if (table[p]) return table[p];
319
+ if (p === "/") return null;
320
+ p = p.slice(0, p.lastIndexOf("/")) || "/";
321
+ }
322
+ }
323
+
324
+ /** The folders of the layouts that wrap `route`, outermost (root) first — aligned with `layoutChain`. */
325
+ export function layoutFolders(route) {
326
+ const folders = [];
327
+ if (!route) return routes.layouts["/"] ? ["/"] : folders;
328
+ let p = route;
329
+ while (true) {
330
+ if (routes.layouts[p]) folders.unshift(p);
331
+ if (p === "/") break;
332
+ p = p.slice(0, p.lastIndexOf("/")) || "/";
333
+ }
334
+ return folders;
335
+ }
336
+
337
+ /** Does the layout at `folder` wrap `route` (the folder itself, or anything beneath it)? */
338
+ export const layoutWraps = (folder, route) =>
339
+ folder === "/" || route === folder || (route ?? "").startsWith(`${folder}/`);
340
+
341
+ /**
342
+ * Where an error shows: the `error.jsx` entry for it (or null). A page's errors use the
343
+ * nearest one from the page's folder; a broken layout's (`brokenLayout`, its folder) the
344
+ * nearest one *above* that layout, since the layout itself is what failed. The root
345
+ * layout has nothing above it.
346
+ */
347
+ export function routeErrorSite(route, brokenLayout = null) {
348
+ if (!brokenLayout) return { entry: nearestRouteFile(routes.errors, route) };
349
+ if (brokenLayout === "/") return { entry: null };
350
+ const parent = brokenLayout.slice(0, brokenLayout.lastIndexOf("/")) || "/";
351
+ return { entry: nearestRouteFile(routes.errors, parent) };
352
+ }
353
+
233
354
  /** Resolve a route entry (module namespace or lazy loader) to its factory. */
234
355
  export async function resolveFactory(entry) {
235
356
  const mod = await resolveModule(entry);
@@ -264,30 +385,204 @@ async function resolveAll(entries, resolve) {
264
385
  * the ordered `nodes` list (page → … → root) so callers can run lifecycle on each.
265
386
  * Each factory owns a reactive scope, disposed with its node on navigation.
266
387
  */
267
- export async function buildRouteNode(match, query = {}) {
388
+ export async function buildRouteNode(match, query = {}, { error = null, loadingShown = false } = {}) {
268
389
  const props = { params: match.params, query };
269
- const chain = layoutChain(match.route);
270
- const [pageModule, ...layoutModules] = await resolveAll(
271
- [match.entry, ...chain],
390
+ const folders = layoutFolders(match.route);
391
+ // A failed loader replaces the page (its own loader) or a layout and everything in it
392
+ // (a layout loader: `afwLayoutRoute`) with the error view at that site.
393
+ const broken = error?.afwLayoutRoute ?? null;
394
+ const keep = broken ? folders.filter((f) => f !== broken && layoutWraps(f, broken)) : folders;
395
+ const chain = keep.map((f) => routes.layouts[f]);
396
+ // The nearest `loading.jsx` wraps the page in a <Pending>. The error views that could be
397
+ // needed — the page's, and the one above each layout — load up front with the rest.
398
+ const loadingEntry = error ? null : nearestRouteFile(routes.loading, match.route);
399
+ const pageError = error ? routeErrorSite(match.route, broken).entry : nearestRouteFile(routes.errors, match.route);
400
+ const layoutErrors = keep.map((f) => routeErrorSite(match.route, f).entry);
401
+ const errorEntries = [...new Set([pageError, ...layoutErrors].filter(Boolean))];
402
+ const [pageModule, ...rest] = await resolveAll(
403
+ [error ? null : match.entry, ...chain, loadingEntry, ...errorEntries],
272
404
  resolveModule,
273
405
  );
406
+ const layoutModules = rest.slice(0, chain.length);
407
+ const loadingModule = rest[chain.length];
408
+ const errorModules = new Map(errorEntries.map((entry, i) => [entry, rest[chain.length + 1 + i]]));
274
409
  const namespace = module => typeof module === "function" ? { default: module } : module;
275
- const modules = [...layoutModules, pageModule].map(namespace);
276
- const pageFactory = pageModule?.default ?? pageModule;
410
+ const modules = [...layoutModules, pageModule].filter(Boolean).map(namespace);
277
411
  const layoutFactories = layoutModules.map(module => module?.default ?? module);
278
- setRouteToc(pageModule);
279
- let node = buildScopedView(() => pageFactory(props));
280
- const nodes = [node];
412
+ if (!error) setRouteToc(pageModule);
413
+ const errorView = (entry, e) => {
414
+ const view = factoryOf(errorModules.get(entry));
415
+ return buildScopedView(() => view({ ...props, error: e, retry: () => navigate(currentLocation(), true) }));
416
+ };
417
+ let node;
418
+ const nodes = [];
419
+ if (error) {
420
+ if (!pageError) throw error;
421
+ node = errorView(pageError, error);
422
+ nodes.push(node);
423
+ } else {
424
+ const pageFactory = pageModule?.default ?? pageModule;
425
+ const loading = factoryOf(loadingModule);
426
+ let pending = loading ? routePending(loading, props, loadingShown) : null;
427
+ let page;
428
+ try {
429
+ if (pending) enterPending(pending);
430
+ try {
431
+ page = buildScopedView(() => pageFactory(props));
432
+ } finally {
433
+ if (pending) exitPending();
434
+ }
435
+ } catch (e) {
436
+ if (!pageError) throw e;
437
+ reportError(e, { phase: "render" });
438
+ if (pending) runCleanup(pending);
439
+ pending = null;
440
+ page = errorView(pageError, e);
441
+ }
442
+ nodes.push(page);
443
+ node = page;
444
+ if (pending) {
445
+ pending.append(page);
446
+ nodes.push(pending);
447
+ node = pending;
448
+ }
449
+ }
450
+ let region = node;
281
451
  try {
282
452
  for (let i = chain.length - 1; i >= 0; i--) {
283
- node = buildScopedView(() => layoutFactories[i]({ ...props, children: node }));
453
+ const inner = node;
454
+ try {
455
+ node = buildScopedView(() => layoutFactories[i]({ ...props, children: inner }));
456
+ } catch (e) {
457
+ // A layout that throws is replaced, with everything inside it, by the error view
458
+ // above it; the layouts above it still wrap that view.
459
+ const site = layoutErrors[i];
460
+ if (!site) throw e;
461
+ reportError(e, { phase: "render" });
462
+ for (const n of nodes.splice(0)) runCleanup(n);
463
+ node = errorView(site, e);
464
+ nodes.push(node);
465
+ region = null; // the page is gone; the error view is not re-handled
466
+ continue;
467
+ }
468
+ node.__afwLayoutRoute = keep[i];
284
469
  nodes.push(node);
285
470
  }
286
- } catch (error) {
471
+ } catch (e) {
287
472
  for (const n of nodes) runCleanup(n);
288
- throw error;
473
+ throw e;
474
+ }
475
+ return { node, nodes, modules, region };
476
+ }
477
+
478
+ /**
479
+ * The route-level <Pending> a page with a `loading.jsx` is built inside: the loading
480
+ * view is its fallback, held back by {@link LOADING_DELAY} unless the navigation is
481
+ * already showing it (`immediate`).
482
+ */
483
+ function routePending(loading, props, immediate) {
484
+ const pending = document.createElement("afw-internal-pending");
485
+ const view = buildScopedView(() => loading(props));
486
+ pending.fallback = view;
487
+ pending.delay = immediate ? 0 : LOADING_DELAY;
488
+ pending.__lifecycle = { mounts: [() => runMount(view)], cleanups: [() => runCleanup(view)] };
489
+ return pending;
490
+ }
491
+
492
+ /**
493
+ * Show the route's `loading.jsx` inside its layouts if the navigation is still waiting
494
+ * (on loader data or route chunks) after {@link LOADING_DELAY}. Returns
495
+ * `{ cancel, shown }`; the navigation's own commit replaces the loading view.
496
+ */
497
+ function scheduleRouteLoading(match, query, seq, entry) {
498
+ const status = { shown: false, cancelled: false, timer: null };
499
+ status.timer = setTimeout(async () => {
500
+ try {
501
+ const chain = layoutChain(match.route);
502
+ const [loadingModule, ...layoutModules] = await resolveAll([entry, ...chain], resolveModule);
503
+ if (status.cancelled || seq !== navSeq) return;
504
+ const props = { params: match.params, query };
505
+ let node = buildScopedView(() => factoryOf(loadingModule)(props));
506
+ const nodes = [node];
507
+ for (let i = chain.length - 1; i >= 0; i--) {
508
+ const inner = node;
509
+ node = buildScopedView(() => factoryOf(layoutModules[i])({ ...props, children: inner }));
510
+ nodes.push(node);
511
+ }
512
+ await swapView(() => {
513
+ // A transition runs this later: the page may have committed meanwhile.
514
+ if (status.cancelled || seq !== navSeq) {
515
+ for (const n of nodes) runCleanup(n);
516
+ return;
517
+ }
518
+ for (const n of currentNodes) runCleanup(n);
519
+ currentRegion = null;
520
+ rootEl.replaceChildren(node);
521
+ for (const n of nodes) runMount(n);
522
+ currentNodes = nodes;
523
+ status.shown = true;
524
+ });
525
+ } catch (e) {
526
+ reportError(e, { phase: "route" });
527
+ }
528
+ }, LOADING_DELAY);
529
+ return {
530
+ cancel() {
531
+ status.cancelled = true;
532
+ clearTimeout(status.timer);
533
+ },
534
+ get shown() {
535
+ return status.shown;
536
+ },
537
+ };
538
+ }
539
+
540
+ /**
541
+ * An error no <ErrorBoundary> caught (a component throwing, a resource's first load
542
+ * failing). Inside the page, the page's nearest `error.jsx` replaces it; inside a layout,
543
+ * the `error.jsx` above that layout replaces the layout (and everything in it). The
544
+ * layouts above stay. Retry navigates to the page again. First error per view wins.
545
+ */
546
+ const handledViews = new WeakSet();
547
+ function showRouteError(el, error) {
548
+ if (!el) return;
549
+ const holds = (node) => viewNodes(node).some((n) => n === el || (n.contains && n.contains(el)));
550
+ let target = null;
551
+ let entry = null;
552
+ if (currentRegion && holds(currentRegion)) {
553
+ target = currentRegion;
554
+ entry = nearestRouteFile(routes.errors, currentRoute);
555
+ } else {
556
+ // The innermost layout around the element (currentNodes runs inner → outer).
557
+ target = currentNodes.find((n) => n.__afwLayoutRoute && holds(n)) ?? null;
558
+ if (target) entry = routeErrorSite(currentRoute, target.__afwLayoutRoute).entry;
289
559
  }
290
- return { node, nodes, modules };
560
+ if (!target || !entry || handledViews.has(target)) return;
561
+ handledViews.add(target);
562
+ if (target === currentRegion) currentRegion = null; // the error view itself is not re-handled
563
+ const seq = navSeq;
564
+ // Deferred: never swap the tree in the middle of the connectedCallback that threw.
565
+ queueMicrotask(async () => {
566
+ try {
567
+ const module = await resolveModule(entry);
568
+ if (seq !== navSeq) return;
569
+ const index = currentNodes.indexOf(target);
570
+ const old = viewNodes(target);
571
+ const parent = old[0]?.parentNode;
572
+ if (index < 0 || !parent) return;
573
+ const props = { params: state.params.value, query: Object.fromEntries(state.searchParams.value) };
574
+ const view = buildScopedView(() =>
575
+ factoryOf(module)({ ...props, error, retry: () => navigate(currentLocation(), true) }));
576
+ parent.insertBefore(view, old[0]);
577
+ for (const n of old) n.remove();
578
+ for (let i = 0; i <= index; i++) runCleanup(currentNodes[i]);
579
+ if (index >= currentNodes.indexOf(currentRegion)) currentRegion = null;
580
+ currentNodes = [view, ...currentNodes.slice(index + 1)];
581
+ runMount(view);
582
+ } catch (e) {
583
+ reportError(e, { phase: "fallback" });
584
+ }
585
+ });
291
586
  }
292
587
 
293
588
  /**
@@ -300,14 +595,22 @@ export async function buildRouteNode(match, query = {}) {
300
595
  * caller then falls back to a clean CSR build. A thrown `HydrationMismatch` propagates up,
301
596
  * disposing each layer's partial wiring on the way (each `hydrateAt` has its own guard).
302
597
  */
303
- export async function hydrateRouteNode(match, query, rootEl) {
304
- const props = { params: match.params, query };
305
- const chain = layoutChain(match.route);
598
+ export async function hydrateRouteNode(match, query, rootEl, { error = null } = {}) {
599
+ // A page the server rendered with an `error.jsx` (a failed loader) adopts that view, at
600
+ // the same site: the page's, or above the layout whose loader failed.
601
+ const broken = error?.afwLayoutRoute ?? null;
602
+ const errorEntry = error ? routeErrorSite(match.route, broken).entry : null;
603
+ if (error && !errorEntry) return null;
604
+ const props = error
605
+ ? { params: match.params, query, error, retry: () => navigate(currentLocation(), true) }
606
+ : { params: match.params, query };
607
+ const folders = layoutFolders(match.route).filter((f) => !broken || (f !== broken && layoutWraps(f, broken)));
608
+ const chain = folders.map((f) => routes.layouts[f]);
306
609
  // Page + layout chunks download concurrently (see `resolveAll`). Adoptability is
307
610
  // checked after they all land rather than short-circuiting on the page: bailing
308
611
  // early would only skip imports the CSR fallback below is about to need anyway.
309
- const [pageMod, ...layoutMods] = await resolveAll([match.entry, ...chain], resolveModule);
310
- setRouteToc(pageMod);
612
+ const [pageMod, ...layoutMods] = await resolveAll([errorEntry ?? match.entry, ...chain], resolveModule);
613
+ if (!error) setRouteToc(pageMod);
311
614
  if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
312
615
  // The whole chain must be adoptable — one non-adoptable layout means a clean CSR build.
313
616
  if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) return null;
@@ -324,8 +627,10 @@ export async function hydrateRouteNode(match, query, rootEl) {
324
627
  for (let i = chain.length - 1; i >= 0; i--) {
325
628
  const layout = layoutMods[i];
326
629
  const inner = thunk;
630
+ const folder = folders[i];
327
631
  thunk = (c) => {
328
632
  const n = buildScopedView(() => layout.hydrateAt(c, { ...props, children: inner }));
633
+ n.__afwLayoutRoute = folder;
329
634
  nodes.push(n);
330
635
  return n;
331
636
  };
@@ -571,6 +876,10 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
571
876
  if (!path || !rootEl) return;
572
877
  const seq = ++navSeq;
573
878
  const url = new URL(path, window.location.origin);
879
+ // SPA mode restores scroll itself (scroll.js): save where the page being left was,
880
+ // before anything (a loading view, the new page) replaces it.
881
+ const spa = isBrowser && navMode === "spa";
882
+ if (spa) rememberScroll();
574
883
 
575
884
  if (guard) {
576
885
  let redirected = false;
@@ -626,17 +935,31 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
626
935
  // DOM swap, mirroring the guard's "settle before commit" flow. First paint over
627
936
  // server HTML reads the inlined payload; every other navigation (SPA nav, dev/CSR
628
937
  // first load, popstate) fetches the `<path>/__data.json` endpoint. A failed fetch
629
- // is reported and the navigation commits with `data === undefined`.
938
+ // is reported; with an `error.jsx` the page shows it, otherwise the navigation
939
+ // commits with `data === undefined`.
940
+ //
941
+ // A route with a `loading.jsx` shows it inside its layouts when the navigation is
942
+ // still waiting (data, route chunks) after LOADING_DELAY.
943
+ const loadingEntry = !hydrate && match?.route ? nearestRouteFile(routes.loading, match.route) : null;
944
+ const loading = loadingEntry && isBrowser
945
+ ? scheduleRouteLoading(match, Object.fromEntries(url.searchParams), seq, loadingEntry)
946
+ : null;
947
+ try {
630
948
  let data;
949
+ let dataError = null;
631
950
  if (match && match.route && routes.loaderRoutes.has(match.route)) {
632
951
  if (hydrate) {
633
952
  data = readInlineRouteData();
953
+ // The server rendered this page's `error.jsx` (its loader failed).
954
+ dataError = routeErrorFrom(data);
955
+ if (dataError) data = undefined;
634
956
  } else {
635
957
  try {
636
958
  const warmed = takePrefetched(url.pathname + url.search);
637
959
  data = warmed ? await warmed.catch(() => fetchRouteData(url.pathname, url.search)) : await fetchRouteData(url.pathname, url.search);
638
960
  } catch (e) {
639
961
  reportError(e, { phase: "data", path: url.pathname });
962
+ if (routeErrorSite(match.route, e?.afwLayoutRoute ?? null).entry) dataError = e;
640
963
  }
641
964
  if (seq !== navSeq) return; // a newer navigation superseded this one
642
965
  if (data instanceof RouteRedirect) return followRedirect(data);
@@ -649,7 +972,11 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
649
972
  state.locale.value = resolveLocale(url.pathname).locale;
650
973
  state.data.value = data;
651
974
 
652
- if (!isPop) {
975
+ // The history entry this navigation lands on; back/forward and the first load keep
976
+ // the one already there. Its key finds the scroll position saved for it.
977
+ let entry = null;
978
+ if (spa) entry = enterEntry(path, isPop ? "pop" : replace ? "replace" : "push");
979
+ else if (!isPop) {
653
980
  if (replace) window.history.replaceState({}, "", path);
654
981
  else window.history.pushState({}, "", path);
655
982
  }
@@ -671,9 +998,13 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
671
998
  beginHydration();
672
999
  try {
673
1000
  const query = Object.fromEntries(url.searchParams);
674
- const adopted = await hydrateRouteNode(match, query, rootEl);
1001
+ const adopted = await hydrateRouteNode(match, query, rootEl, { error: dataError });
675
1002
  if (adopted) {
676
1003
  currentNodes = adopted.nodes;
1004
+ currentRegion = dataError ? null : adopted.nodes[0];
1005
+ currentRoute = match.route;
1006
+ if (spa) landScroll(url, true, entry); // a reload of a server-rendered page
1007
+ committed = true;
677
1008
  for (const n of adopted.nodes) runMount(n); // onMount for page + every layout
678
1009
  clearError({ phase: "route" });
679
1010
  clearChunkReloadFlag();
@@ -690,17 +1021,22 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
690
1021
  // Resolve (and lazily load) the page + its layout chain before tearing down the
691
1022
  // current view, so a slow/failed import doesn't leave a blank page.
692
1023
  let nodes = null;
1024
+ let region = null;
693
1025
  let metadata = {};
694
1026
  if (match) {
695
1027
  let built;
696
1028
  try {
697
- built = await buildRouteNode(match, Object.fromEntries(url.searchParams));
1029
+ built = await buildRouteNode(match, Object.fromEntries(url.searchParams), {
1030
+ error: dataError,
1031
+ loadingShown: loading?.shown ?? false,
1032
+ });
698
1033
  metadata = await resolveMetadataModules(built.modules, { params: match.params, query: Object.fromEntries(url.searchParams) });
699
1034
  if (seq !== navSeq) {
700
1035
  for (const node of built.nodes) runCleanup(node);
701
1036
  return;
702
1037
  }
703
1038
  nodes = built.nodes;
1039
+ region = built.region;
704
1040
  } catch (e) {
705
1041
  if (built) for (const node of built.nodes) runCleanup(node);
706
1042
  if (seq !== navSeq) return;
@@ -717,27 +1053,36 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
717
1053
  }
718
1054
  }
719
1055
 
720
- for (const n of currentNodes) runCleanup(n);
721
- rootEl.replaceChildren();
722
- updateRouteHead(metadata, url.pathname);
723
-
724
- if (nodes) {
725
- rootEl.appendChild(nodes[nodes.length - 1]); // outermost node
726
- for (const n of nodes) runMount(n); // run onMount for page + every layout
727
- currentNodes = nodes;
728
- clearError({ phase: "route" }); // a good render dismisses a prior error overlay
729
- clearChunkReloadFlag(); // a successful render means the reload (if any) recovered
730
- // A forward navigation lands at the top of the new page (or at the targeted
731
- // anchor); back/forward (`isPop`) keeps the browser's restored scroll position.
732
- if (!isPop && isBrowser) {
733
- const anchor = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
734
- if (anchor) anchor.scrollIntoView();
735
- else window.scrollTo(0, 0);
1056
+ loading?.cancel();
1057
+ // The swap itself: one synchronous update, so a view transition (when enabled)
1058
+ // snapshots the old page before it and animates to the new one after it.
1059
+ const commit = () => {
1060
+ for (const n of currentNodes) runCleanup(n);
1061
+ rootEl.replaceChildren();
1062
+ updateRouteHead(metadata, url.pathname);
1063
+ if (nodes) {
1064
+ // Set before inserting: a component that throws as it connects reports into it.
1065
+ currentRegion = region;
1066
+ currentRoute = match.route;
1067
+ rootEl.appendChild(nodes[nodes.length - 1]); // outermost node
1068
+ for (const n of nodes) runMount(n); // run onMount for page + every layout
1069
+ currentNodes = nodes;
1070
+ clearError({ phase: "route" }); // a good render dismisses a prior error overlay
1071
+ clearChunkReloadFlag(); // a successful render means the reload (if any) recovered
1072
+ if (spa) landScroll(url, isPop, entry);
1073
+ else if (!isPop && isBrowser) scrollToTarget(url);
1074
+ if (isBrowser) focusRouteContent(rootEl);
1075
+ } else {
1076
+ rootEl.innerHTML = "<h1>404 — Not Found</h1>";
1077
+ currentNodes = [];
1078
+ currentRegion = null;
736
1079
  }
737
- if (isBrowser) focusRouteContent(rootEl);
738
- } else {
739
- rootEl.innerHTML = "<h1>404 — Not Found</h1>";
740
- currentNodes = [];
1080
+ };
1081
+ // Never on the first paint: there is no previous page to transition from.
1082
+ await swapView(commit, committed);
1083
+ committed = true;
1084
+ } finally {
1085
+ loading?.cancel();
741
1086
  }
742
1087
  }
743
1088
 
@@ -847,14 +1192,18 @@ function focusRouteContent(container) {
847
1192
  * @param {string[]} [opts.loaders] route patterns that have a server loader
848
1193
  * (docs/DATA.md) — navigation fetches `<path>/__data.json` for these.
849
1194
  */
850
- export function mountApp({ pages, target, guard: g, i18n, nav, loaders } = {}) {
1195
+ export function mountApp({ pages, target, guard: g, i18n, nav, loaders, viewTransitions: vt = false } = {}) {
851
1196
  rootEl = target || (isBrowser ? document.getElementById("app") : null);
852
1197
  navMode = nav === "mpa" ? "mpa" : "spa";
1198
+ viewTransitions = Boolean(vt) && navMode === "spa";
1199
+ committed = false;
1200
+ if (isBrowser && navMode === "spa") manageScroll();
853
1201
  if (i18n) configureI18n(i18n);
854
1202
  if (pages) registerRoutes(pages);
855
1203
  if (loaders) registerLoaderRoutes(loaders);
856
1204
  guard = g || null;
857
1205
  setRouteDataRefresher(refreshRouteData);
1206
+ setRouteErrorHandler(showRouteError);
858
1207
  prefetched.clear(); // a fresh app starts with nothing warmed
859
1208
  // In MPA mode the browser owns navigation (full loads push real history entries),
860
1209
  // so there is no client-side history to react to — only wire popstate for SPA.