@opentf/afw 0.37.0 → 0.39.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
@@ -14,17 +14,22 @@
14
14
  // emit yet — for now pages read params via the reactive `router.params`, and a
15
15
  // route loader's data via the reactive `router.data` (docs/DATA.md).
16
16
 
17
+ import { DEV } from "../core/dev.js";
17
18
  import { clearError, reportError } from "../core/errors.js";
18
19
  import { signal } from "../core/signals.js";
19
20
  import { getRenderContext } from "../core/render-context.js";
20
21
  import { resolveMetadataModules } from "../core/metadata.js";
21
22
  import { prepareRouteHead, updateRouteHead } from "./head.js";
22
- import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
23
+ import { beginHydration, cursor, endHydration, renderedForPath, runBuild } from "./hydrate.js";
23
24
  import { collectHotState, withHotCarry } from "./hot-carry.js";
24
25
  import { buildScopedView, runCleanup, runMount } from "./mount.js";
25
- import { RouteRedirect, fetchRouteData, readInlineRouteData } from "./route-data.js";
26
+ import { RouteRedirect, fetchRouteData, readInlineRouteData, routeErrorFrom } from "./route-data.js";
27
+ import { enterPending, exitPending } from "./pending-scope.js";
28
+ import { setRouteErrorHandler } from "./route-errors.js";
29
+ import { enterEntry, manageScroll, rememberScroll, restoreScroll } from "./scroll.js";
26
30
  import { setRouteDataRefresher } from "./invalidate.js";
27
- import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
31
+ import { compareRoutes, compileRoute, decodeParams, isClientRoute, urlCollisions } from "./route-match.js";
32
+ export { clientRoute, isClientRoute } from "./route-match.js";
28
33
 
29
34
  const isBrowser = typeof window !== "undefined";
30
35
 
@@ -46,7 +51,7 @@ const state = {
46
51
  toc: signal([]),
47
52
  };
48
53
 
49
- export const routes = { pages: {}, layouts: {}, notFound: null, loaderRoutes: new Set() };
54
+ export const routes = { pages: {}, layouts: {}, loading: {}, errors: {}, notFound: null, loaderRoutes: new Set() };
50
55
  let guard = null;
51
56
  let rootEl = null;
52
57
 
@@ -132,6 +137,69 @@ export function setLocale(locale) {
132
137
  state.locale.value = locale;
133
138
  }
134
139
  let currentNodes = [];
140
+ // The page's part of `currentNodes` — the page node, or the route <Pending> around it —
141
+ // and the matched route pattern: where an error no <ErrorBoundary> caught may be
142
+ // replaced by the route's `error.jsx` (see `showRouteError`).
143
+ let currentRegion = null;
144
+ let currentRoute = null;
145
+
146
+ /** Opt-in `document.startViewTransition()` around client navigations (`mountApp`). */
147
+ let viewTransitions = false;
148
+ /** Has this app committed a page yet (the first paint is never a transition)? */
149
+ let committed = false;
150
+
151
+ /**
152
+ * Run `update` (a synchronous DOM swap) inside a view transition when they are on,
153
+ * supported, `animate` allows it (never the first paint) and the user hasn't asked
154
+ * for reduced motion; otherwise run it directly. An error thrown by `update` is
155
+ * rethrown either way.
156
+ */
157
+ async function swapView(update, animate = true) {
158
+ const supported = isBrowser && typeof document.startViewTransition === "function";
159
+ const reduced = isBrowser && typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
160
+ if (!viewTransitions || !animate || !supported || reduced) {
161
+ update();
162
+ return;
163
+ }
164
+ let failure = null;
165
+ const transition = document.startViewTransition(() => {
166
+ try {
167
+ update();
168
+ } catch (error) {
169
+ failure = error;
170
+ }
171
+ });
172
+ // A navigation during a running transition skips it: `ready` and `finished` then
173
+ // reject (AbortError), which is expected, not an app error.
174
+ transition.ready?.catch(() => {});
175
+ transition.finished?.catch(() => {});
176
+ await transition.updateCallbackDone.catch(() => {});
177
+ if (failure) throw failure;
178
+ }
179
+
180
+ /** Scroll a forward navigation: to its `#anchor`, or the top. */
181
+ function scrollToTarget(url) {
182
+ const anchor = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
183
+ if (anchor) anchor.scrollIntoView();
184
+ else window.scrollTo(0, 0);
185
+ }
186
+
187
+ /**
188
+ * Where a committed navigation leaves the scroll: back/forward and a reload restore
189
+ * the position saved for the entry (falling back to its `#anchor`, else unchanged);
190
+ * a forward navigation goes to its anchor or the top.
191
+ */
192
+ function landScroll(url, isPop, entry) {
193
+ if (!isPop) return scrollToTarget(url);
194
+ if (restoreScroll(entry)) return;
195
+ if (url.hash) scrollToTarget(url);
196
+ }
197
+
198
+ /** How long a navigation waits before showing `loading.jsx`: a fast one never flashes it. */
199
+ export const LOADING_DELAY = 150;
200
+
201
+ const factoryOf = (module) => module?.default ?? module;
202
+ const currentLocation = () => window.location.pathname + window.location.search + window.location.hash;
135
203
 
136
204
  function routeValue(key) {
137
205
  const route = getRenderContext()?.route;
@@ -172,7 +240,7 @@ export const router = {
172
240
  function routeFromPath(filePath) {
173
241
  const r = filePath
174
242
  .replace(/^.*\/app(?=\/)/, "")
175
- .replace(/\/(page|layout|404)\.(jsx|tsx|mdx|md)$/, "");
243
+ .replace(/\/(page|layout|404|loading|error)\.(jsx|tsx|mdx|md)$/, "");
176
244
  return r === "" ? "/" : r;
177
245
  }
178
246
 
@@ -180,7 +248,9 @@ function routeFromPath(filePath) {
180
248
  * Register routes from a `{ path: entry }` map. Each `entry` is either a module
181
249
  * namespace (eager) or a `() => import(...)` loader (lazy, code-split) — both
182
250
  * resolve to a default-export factory at navigation time. `layout.jsx` files
183
- * register as layouts (wrapping nested pages), `404.jsx` as the fallback.
251
+ * register as layouts (wrapping nested pages), `404.jsx` as the fallback, and
252
+ * `loading.jsx` / `error.jsx` as the loading and error views of the pages beneath
253
+ * their folder.
184
254
  */
185
255
  export function registerRoutes(modules) {
186
256
  // Validate before changing the table: an unsupported fallback otherwise
@@ -189,13 +259,22 @@ export function registerRoutes(modules) {
189
259
  if (/\/404\.(mdx|md)$/.test(file)) {
190
260
  throw new Error(`Unsupported Markdown 404 route: ${file}. Use 404.jsx or 404.tsx instead.`);
191
261
  }
262
+ const special = /\/(loading|error)\.(mdx|md)$/.exec(file);
263
+ if (special) {
264
+ throw new Error(`Unsupported Markdown ${special[1]} file: ${file}. Use ${special[1]}.jsx or ${special[1]}.tsx instead.`);
265
+ }
192
266
  }
193
267
  for (const file in modules) {
194
268
  const entry = modules[file];
195
269
  if (/\/404\.(jsx|tsx)$/.test(file)) routes.notFound = entry;
196
270
  else if (/\/layout\.(jsx|tsx)$/.test(file)) routes.layouts[routeFromPath(file)] = entry;
271
+ else if (/\/loading\.(jsx|tsx)$/.test(file)) routes.loading[routeFromPath(file)] = entry;
272
+ else if (/\/error\.(jsx|tsx)$/.test(file)) routes.errors[routeFromPath(file)] = entry;
197
273
  else routes.pages[routeFromPath(file)] = entry;
198
274
  }
275
+ // Route groups drop out of the URL, so two of them can hold the same page path.
276
+ const [clash] = urlCollisions(Object.keys(routes.pages));
277
+ if (clash) throw new Error(`Two pages answer ${clash[0]}: app${clash[1]} and app${clash[2]}. Move one to another path.`);
199
278
  }
200
279
 
201
280
  /**
@@ -230,6 +309,50 @@ export function layoutChain(route) {
230
309
  return chain;
231
310
  }
232
311
 
312
+ /**
313
+ * The nearest `loading.jsx` / `error.jsx` entry for `route` (`table` is
314
+ * `routes.loading` or `routes.errors`): the route's own folder first, then each
315
+ * parent up to the app root. The 404 fallback (`route` null) uses the root's.
316
+ */
317
+ export function nearestRouteFile(table, route) {
318
+ let p = route || "/";
319
+ while (true) {
320
+ if (table[p]) return table[p];
321
+ if (p === "/") return null;
322
+ p = p.slice(0, p.lastIndexOf("/")) || "/";
323
+ }
324
+ }
325
+
326
+ /** The folders of the layouts that wrap `route`, outermost (root) first — aligned with `layoutChain`. */
327
+ export function layoutFolders(route) {
328
+ const folders = [];
329
+ if (!route) return routes.layouts["/"] ? ["/"] : folders;
330
+ let p = route;
331
+ while (true) {
332
+ if (routes.layouts[p]) folders.unshift(p);
333
+ if (p === "/") break;
334
+ p = p.slice(0, p.lastIndexOf("/")) || "/";
335
+ }
336
+ return folders;
337
+ }
338
+
339
+ /** Does the layout at `folder` wrap `route` (the folder itself, or anything beneath it)? */
340
+ export const layoutWraps = (folder, route) =>
341
+ folder === "/" || route === folder || (route ?? "").startsWith(`${folder}/`);
342
+
343
+ /**
344
+ * Where an error shows: the `error.jsx` entry for it (or null). A page's errors use the
345
+ * nearest one from the page's folder; a broken layout's (`brokenLayout`, its folder) the
346
+ * nearest one *above* that layout, since the layout itself is what failed. The root
347
+ * layout has nothing above it.
348
+ */
349
+ export function routeErrorSite(route, brokenLayout = null) {
350
+ if (!brokenLayout) return { entry: nearestRouteFile(routes.errors, route) };
351
+ if (brokenLayout === "/") return { entry: null };
352
+ const parent = brokenLayout.slice(0, brokenLayout.lastIndexOf("/")) || "/";
353
+ return { entry: nearestRouteFile(routes.errors, parent) };
354
+ }
355
+
233
356
  /** Resolve a route entry (module namespace or lazy loader) to its factory. */
234
357
  export async function resolveFactory(entry) {
235
358
  const mod = await resolveModule(entry);
@@ -264,30 +387,206 @@ async function resolveAll(entries, resolve) {
264
387
  * the ordered `nodes` list (page → … → root) so callers can run lifecycle on each.
265
388
  * Each factory owns a reactive scope, disposed with its node on navigation.
266
389
  */
267
- export async function buildRouteNode(match, query = {}) {
390
+ export async function buildRouteNode(match, query = {}, { error = null, loadingShown = false, outer = 0 } = {}) {
268
391
  const props = { params: match.params, query };
269
- const chain = layoutChain(match.route);
270
- const [pageModule, ...layoutModules] = await resolveAll(
271
- [match.entry, ...chain],
392
+ // `outer` leaves out that many outermost layouts: the server rendered them and the
393
+ // client adopts them, building only what is inside (a client route's part).
394
+ const folders = layoutFolders(match.route).slice(outer);
395
+ // A failed loader replaces the page (its own loader) or a layout and everything in it
396
+ // (a layout loader: `afwLayoutRoute`) with the error view at that site.
397
+ const broken = error?.afwLayoutRoute ?? null;
398
+ const keep = broken ? folders.filter((f) => f !== broken && layoutWraps(f, broken)) : folders;
399
+ const chain = keep.map((f) => routes.layouts[f]);
400
+ // The nearest `loading.jsx` wraps the page in a <Pending>. The error views that could be
401
+ // needed — the page's, and the one above each layout — load up front with the rest.
402
+ const loadingEntry = error ? null : nearestRouteFile(routes.loading, match.route);
403
+ const pageError = error ? routeErrorSite(match.route, broken).entry : nearestRouteFile(routes.errors, match.route);
404
+ const layoutErrors = keep.map((f) => routeErrorSite(match.route, f).entry);
405
+ const errorEntries = [...new Set([pageError, ...layoutErrors].filter(Boolean))];
406
+ const [pageModule, ...rest] = await resolveAll(
407
+ [error ? null : match.entry, ...chain, loadingEntry, ...errorEntries],
272
408
  resolveModule,
273
409
  );
410
+ const layoutModules = rest.slice(0, chain.length);
411
+ const loadingModule = rest[chain.length];
412
+ const errorModules = new Map(errorEntries.map((entry, i) => [entry, rest[chain.length + 1 + i]]));
274
413
  const namespace = module => typeof module === "function" ? { default: module } : module;
275
- const modules = [...layoutModules, pageModule].map(namespace);
276
- const pageFactory = pageModule?.default ?? pageModule;
414
+ const modules = [...layoutModules, pageModule].filter(Boolean).map(namespace);
277
415
  const layoutFactories = layoutModules.map(module => module?.default ?? module);
278
- setRouteToc(pageModule);
279
- let node = buildScopedView(() => pageFactory(props));
280
- const nodes = [node];
416
+ if (!error) setRouteToc(pageModule);
417
+ const errorView = (entry, e) => {
418
+ const view = factoryOf(errorModules.get(entry));
419
+ return buildScopedView(() => view({ ...props, error: e, retry: () => navigate(currentLocation(), true) }));
420
+ };
421
+ let node;
422
+ const nodes = [];
423
+ if (error) {
424
+ if (!pageError) throw error;
425
+ node = errorView(pageError, error);
426
+ nodes.push(node);
427
+ } else {
428
+ const pageFactory = pageModule?.default ?? pageModule;
429
+ const loading = factoryOf(loadingModule);
430
+ let pending = loading ? routePending(loading, props, loadingShown) : null;
431
+ let page;
432
+ try {
433
+ if (pending) enterPending(pending);
434
+ try {
435
+ page = buildScopedView(() => pageFactory(props));
436
+ } finally {
437
+ if (pending) exitPending();
438
+ }
439
+ } catch (e) {
440
+ if (!pageError) throw e;
441
+ reportError(e, { phase: "render" });
442
+ if (pending) runCleanup(pending);
443
+ pending = null;
444
+ page = errorView(pageError, e);
445
+ }
446
+ nodes.push(page);
447
+ node = page;
448
+ if (pending) {
449
+ pending.append(page);
450
+ nodes.push(pending);
451
+ node = pending;
452
+ }
453
+ }
454
+ let region = node;
281
455
  try {
282
456
  for (let i = chain.length - 1; i >= 0; i--) {
283
- node = buildScopedView(() => layoutFactories[i]({ ...props, children: node }));
457
+ const inner = node;
458
+ try {
459
+ node = buildScopedView(() => layoutFactories[i]({ ...props, children: inner }));
460
+ } catch (e) {
461
+ // A layout that throws is replaced, with everything inside it, by the error view
462
+ // above it; the layouts above it still wrap that view.
463
+ const site = layoutErrors[i];
464
+ if (!site) throw e;
465
+ reportError(e, { phase: "render" });
466
+ for (const n of nodes.splice(0)) runCleanup(n);
467
+ node = errorView(site, e);
468
+ nodes.push(node);
469
+ region = null; // the page is gone; the error view is not re-handled
470
+ continue;
471
+ }
472
+ node.__afwLayoutRoute = keep[i];
284
473
  nodes.push(node);
285
474
  }
286
- } catch (error) {
475
+ } catch (e) {
287
476
  for (const n of nodes) runCleanup(n);
288
- throw error;
477
+ throw e;
289
478
  }
290
- return { node, nodes, modules };
479
+ return { node, nodes, modules, region };
480
+ }
481
+
482
+ /**
483
+ * The route-level <Pending> a page with a `loading.jsx` is built inside: the loading
484
+ * view is its fallback, held back by {@link LOADING_DELAY} unless the navigation is
485
+ * already showing it (`immediate`).
486
+ */
487
+ function routePending(loading, props, immediate) {
488
+ const pending = document.createElement("afw-internal-pending");
489
+ const view = buildScopedView(() => loading(props));
490
+ pending.fallback = view;
491
+ pending.delay = immediate ? 0 : LOADING_DELAY;
492
+ pending.__lifecycle = { mounts: [() => runMount(view)], cleanups: [() => runCleanup(view)] };
493
+ return pending;
494
+ }
495
+
496
+ /**
497
+ * Show the route's `loading.jsx` inside its layouts if the navigation is still waiting
498
+ * (on loader data or route chunks) after {@link LOADING_DELAY}. Returns
499
+ * `{ cancel, shown }`; the navigation's own commit replaces the loading view.
500
+ */
501
+ function scheduleRouteLoading(match, query, seq, entry) {
502
+ const status = { shown: false, cancelled: false, timer: null };
503
+ status.timer = setTimeout(async () => {
504
+ try {
505
+ const chain = layoutChain(match.route);
506
+ const [loadingModule, ...layoutModules] = await resolveAll([entry, ...chain], resolveModule);
507
+ if (status.cancelled || seq !== navSeq) return;
508
+ const props = { params: match.params, query };
509
+ let node = buildScopedView(() => factoryOf(loadingModule)(props));
510
+ const nodes = [node];
511
+ for (let i = chain.length - 1; i >= 0; i--) {
512
+ const inner = node;
513
+ node = buildScopedView(() => factoryOf(layoutModules[i])({ ...props, children: inner }));
514
+ nodes.push(node);
515
+ }
516
+ await swapView(() => {
517
+ // A transition runs this later: the page may have committed meanwhile.
518
+ if (status.cancelled || seq !== navSeq) {
519
+ for (const n of nodes) runCleanup(n);
520
+ return;
521
+ }
522
+ for (const n of currentNodes) runCleanup(n);
523
+ currentRegion = null;
524
+ rootEl.replaceChildren(node);
525
+ for (const n of nodes) runMount(n);
526
+ currentNodes = nodes;
527
+ status.shown = true;
528
+ });
529
+ } catch (e) {
530
+ reportError(e, { phase: "route" });
531
+ }
532
+ }, LOADING_DELAY);
533
+ return {
534
+ cancel() {
535
+ status.cancelled = true;
536
+ clearTimeout(status.timer);
537
+ },
538
+ get shown() {
539
+ return status.shown;
540
+ },
541
+ };
542
+ }
543
+
544
+ /**
545
+ * An error no <ErrorBoundary> caught (a component throwing, a resource's first load
546
+ * failing). Inside the page, the page's nearest `error.jsx` replaces it; inside a layout,
547
+ * the `error.jsx` above that layout replaces the layout (and everything in it). The
548
+ * layouts above stay. Retry navigates to the page again. First error per view wins.
549
+ */
550
+ const handledViews = new WeakSet();
551
+ function showRouteError(el, error) {
552
+ if (!el) return;
553
+ const holds = (node) => viewNodes(node).some((n) => n === el || (n.contains && n.contains(el)));
554
+ let target = null;
555
+ let entry = null;
556
+ if (currentRegion && holds(currentRegion)) {
557
+ target = currentRegion;
558
+ entry = nearestRouteFile(routes.errors, currentRoute);
559
+ } else {
560
+ // The innermost layout around the element (currentNodes runs inner → outer).
561
+ target = currentNodes.find((n) => n.__afwLayoutRoute && holds(n)) ?? null;
562
+ if (target) entry = routeErrorSite(currentRoute, target.__afwLayoutRoute).entry;
563
+ }
564
+ if (!target || !entry || handledViews.has(target)) return;
565
+ handledViews.add(target);
566
+ if (target === currentRegion) currentRegion = null; // the error view itself is not re-handled
567
+ const seq = navSeq;
568
+ // Deferred: never swap the tree in the middle of the connectedCallback that threw.
569
+ queueMicrotask(async () => {
570
+ try {
571
+ const module = await resolveModule(entry);
572
+ if (seq !== navSeq) return;
573
+ const index = currentNodes.indexOf(target);
574
+ const old = viewNodes(target);
575
+ const parent = old[0]?.parentNode;
576
+ if (index < 0 || !parent) return;
577
+ const props = { params: state.params.value, query: Object.fromEntries(state.searchParams.value) };
578
+ const view = buildScopedView(() =>
579
+ factoryOf(module)({ ...props, error, retry: () => navigate(currentLocation(), true) }));
580
+ parent.insertBefore(view, old[0]);
581
+ for (const n of old) n.remove();
582
+ for (let i = 0; i <= index; i++) runCleanup(currentNodes[i]);
583
+ if (index >= currentNodes.indexOf(currentRegion)) currentRegion = null;
584
+ currentNodes = [view, ...currentNodes.slice(index + 1)];
585
+ runMount(view);
586
+ } catch (e) {
587
+ reportError(e, { phase: "fallback" });
588
+ }
589
+ });
291
590
  }
292
591
 
293
592
  /**
@@ -300,14 +599,26 @@ export async function buildRouteNode(match, query = {}) {
300
599
  * caller then falls back to a clean CSR build. A thrown `HydrationMismatch` propagates up,
301
600
  * disposing each layer's partial wiring on the way (each `hydrateAt` has its own guard).
302
601
  */
303
- export async function hydrateRouteNode(match, query, rootEl) {
304
- const props = { params: match.params, query };
305
- const chain = layoutChain(match.route);
602
+ export async function hydrateRouteNode(match, query, rootEl, { error = null } = {}) {
603
+ // A page the server rendered with an `error.jsx` (a failed loader) adopts that view, at
604
+ // the same site: the page's, or above the layout whose loader failed.
605
+ const broken = error?.afwLayoutRoute ?? null;
606
+ const errorEntry = error ? routeErrorSite(match.route, broken).entry : null;
607
+ if (error && !errorEntry) return null;
608
+ const props = error
609
+ ? { params: match.params, query, error, retry: () => navigate(currentLocation(), true) }
610
+ : { params: match.params, query };
611
+ const folders = layoutFolders(match.route).filter((f) => !broken || (f !== broken && layoutWraps(f, broken)));
612
+ const chain = folders.map((f) => routes.layouts[f]);
306
613
  // Page + layout chunks download concurrently (see `resolveAll`). Adoptability is
307
614
  // checked after they all land rather than short-circuiting on the page: bailing
308
615
  // 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);
616
+ // A client route: the server rendered the layouts above its first client entry and left
617
+ // that region empty. Adopt those layouts and build the rest into the region.
618
+ const split = error ? -1 : clientSplit(match.entry, chain);
619
+ if (split >= 0) return hydrateClientRoute(match, query, rootEl, props, folders.slice(0, split), chain.slice(0, split));
620
+ const [pageMod, ...layoutMods] = await resolveAll([errorEntry ?? match.entry, ...chain], resolveModule);
621
+ if (!error) setRouteToc(pageMod);
311
622
  if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
312
623
  // The whole chain must be adoptable — one non-adoptable layout means a clean CSR build.
313
624
  if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) return null;
@@ -324,8 +635,10 @@ export async function hydrateRouteNode(match, query, rootEl) {
324
635
  for (let i = chain.length - 1; i >= 0; i--) {
325
636
  const layout = layoutMods[i];
326
637
  const inner = thunk;
638
+ const folder = folders[i];
327
639
  thunk = (c) => {
328
640
  const n = buildScopedView(() => layout.hydrateAt(c, { ...props, children: inner }));
641
+ n.__afwLayoutRoute = folder;
329
642
  nodes.push(n);
330
643
  return n;
331
644
  };
@@ -339,6 +652,66 @@ export async function hydrateRouteNode(match, query, rootEl) {
339
652
  return { nodes };
340
653
  }
341
654
 
655
+ /**
656
+ * Where a route's client part starts: the index of its first client layout (outermost
657
+ * first), the chain's length when only the page renders in the browser, or -1 when the
658
+ * whole route renders on the server.
659
+ */
660
+ export function clientSplit(pageEntry, chain) {
661
+ const layout = chain.findIndex(isClientRoute);
662
+ if (layout >= 0) return layout;
663
+ return isClientRoute(pageEntry) ? chain.length : -1;
664
+ }
665
+
666
+ /**
667
+ * First paint of a client route: adopt the server-rendered layouts (`outerFolders`,
668
+ * outermost first) and build the client part — the first client layout or the page, and
669
+ * everything inside it — into the innermost adopted layout's empty `{children}` region.
670
+ * The build is inserted inside `runBuild`, so its components build rather than adopt.
671
+ */
672
+ async function hydrateClientRoute(match, query, rootEl, props, outerFolders, outerEntries) {
673
+ const [layoutMods, inner] = await Promise.all([
674
+ resolveAll(outerEntries, resolveModule),
675
+ buildRouteNode(match, query, { outer: outerEntries.length }),
676
+ ]);
677
+ if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) {
678
+ for (const n of inner.nodes) runCleanup(n);
679
+ return null;
680
+ }
681
+ const place = (parent, before) => runBuild(() => parent.insertBefore(inner.node, before));
682
+ const nodes = [...inner.nodes];
683
+ if (outerEntries.length === 0) {
684
+ // The page or the root layout is the client part: the server left `#app` empty.
685
+ place(rootEl, null);
686
+ return { nodes, region: inner.region };
687
+ }
688
+ // The innermost adopted layout's children thunk: the cursor stands on its region's end
689
+ // marker, so the built part goes right before it.
690
+ let thunk = (c) => {
691
+ if (!c.node?.parentNode) throw new Error("hydrate: no region for the client part of this route");
692
+ place(c.node.parentNode, c.node);
693
+ return inner.node;
694
+ };
695
+ for (let i = outerEntries.length - 1; i >= 0; i--) {
696
+ const layout = layoutMods[i];
697
+ const innerThunk = thunk;
698
+ const folder = outerFolders[i];
699
+ thunk = (c) => {
700
+ const n = buildScopedView(() => layout.hydrateAt(c, { ...props, children: innerThunk }));
701
+ n.__afwLayoutRoute = folder;
702
+ nodes.push(n);
703
+ return n;
704
+ };
705
+ }
706
+ try {
707
+ thunk(cursor(rootEl));
708
+ } catch (error) {
709
+ for (const node of nodes) runCleanup(node);
710
+ throw error;
711
+ }
712
+ return { nodes, region: inner.region };
713
+ }
714
+
342
715
  /** Resolve a route entry (lazy loader or module namespace) to its module. */
343
716
  export async function resolveModule(entry) {
344
717
  return typeof entry === "function" ? await entry() : entry;
@@ -571,6 +944,10 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
571
944
  if (!path || !rootEl) return;
572
945
  const seq = ++navSeq;
573
946
  const url = new URL(path, window.location.origin);
947
+ // SPA mode restores scroll itself (scroll.js): save where the page being left was,
948
+ // before anything (a loading view, the new page) replaces it.
949
+ const spa = isBrowser && navMode === "spa";
950
+ if (spa) rememberScroll();
574
951
 
575
952
  if (guard) {
576
953
  let redirected = false;
@@ -626,17 +1003,31 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
626
1003
  // DOM swap, mirroring the guard's "settle before commit" flow. First paint over
627
1004
  // server HTML reads the inlined payload; every other navigation (SPA nav, dev/CSR
628
1005
  // first load, popstate) fetches the `<path>/__data.json` endpoint. A failed fetch
629
- // is reported and the navigation commits with `data === undefined`.
1006
+ // is reported; with an `error.jsx` the page shows it, otherwise the navigation
1007
+ // commits with `data === undefined`.
1008
+ //
1009
+ // A route with a `loading.jsx` shows it inside its layouts when the navigation is
1010
+ // still waiting (data, route chunks) after LOADING_DELAY.
1011
+ const loadingEntry = !hydrate && match?.route ? nearestRouteFile(routes.loading, match.route) : null;
1012
+ const loading = loadingEntry && isBrowser
1013
+ ? scheduleRouteLoading(match, Object.fromEntries(url.searchParams), seq, loadingEntry)
1014
+ : null;
1015
+ try {
630
1016
  let data;
1017
+ let dataError = null;
631
1018
  if (match && match.route && routes.loaderRoutes.has(match.route)) {
632
1019
  if (hydrate) {
633
1020
  data = readInlineRouteData();
1021
+ // The server rendered this page's `error.jsx` (its loader failed).
1022
+ dataError = routeErrorFrom(data);
1023
+ if (dataError) data = undefined;
634
1024
  } else {
635
1025
  try {
636
1026
  const warmed = takePrefetched(url.pathname + url.search);
637
1027
  data = warmed ? await warmed.catch(() => fetchRouteData(url.pathname, url.search)) : await fetchRouteData(url.pathname, url.search);
638
1028
  } catch (e) {
639
1029
  reportError(e, { phase: "data", path: url.pathname });
1030
+ if (routeErrorSite(match.route, e?.afwLayoutRoute ?? null).entry) dataError = e;
640
1031
  }
641
1032
  if (seq !== navSeq) return; // a newer navigation superseded this one
642
1033
  if (data instanceof RouteRedirect) return followRedirect(data);
@@ -649,7 +1040,11 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
649
1040
  state.locale.value = resolveLocale(url.pathname).locale;
650
1041
  state.data.value = data;
651
1042
 
652
- if (!isPop) {
1043
+ // The history entry this navigation lands on; back/forward and the first load keep
1044
+ // the one already there. Its key finds the scroll position saved for it.
1045
+ let entry = null;
1046
+ if (spa) entry = enterEntry(path, isPop ? "pop" : replace ? "replace" : "push");
1047
+ else if (!isPop) {
653
1048
  if (replace) window.history.replaceState({}, "", path);
654
1049
  else window.history.pushState({}, "", path);
655
1050
  }
@@ -671,14 +1066,22 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
671
1066
  beginHydration();
672
1067
  try {
673
1068
  const query = Object.fromEntries(url.searchParams);
674
- const adopted = await hydrateRouteNode(match, query, rootEl);
1069
+ const adopted = await hydrateRouteNode(match, query, rootEl, { error: dataError });
675
1070
  if (adopted) {
676
1071
  currentNodes = adopted.nodes;
1072
+ currentRegion = dataError ? null : adopted.nodes[0];
1073
+ currentRoute = match.route;
1074
+ if (spa) landScroll(url, true, entry); // a reload of a server-rendered page
1075
+ committed = true;
677
1076
  for (const n of adopted.nodes) runMount(n); // onMount for page + every layout
678
1077
  clearError({ phase: "route" });
679
1078
  clearChunkReloadFlag();
680
1079
  return;
681
1080
  }
1081
+ // Not a mismatch: the page or a layout has no adopt factory (the compiler could
1082
+ // not emit one), so the server HTML is rebuilt. Say so in development, where the
1083
+ // compiler's warning may have scrolled away.
1084
+ if (DEV && !dataError) console.warn(`[afw:hydrate] ${url.pathname}: the page or one of its layouts cannot adopt the server-rendered HTML, so it is rebuilt on the client. See the compiler's warning for that file.`);
682
1085
  } catch (e) {
683
1086
  reportError(e, { phase: "hydrate", path: url.pathname });
684
1087
  // fall through to a clean CSR build below
@@ -690,17 +1093,22 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
690
1093
  // Resolve (and lazily load) the page + its layout chain before tearing down the
691
1094
  // current view, so a slow/failed import doesn't leave a blank page.
692
1095
  let nodes = null;
1096
+ let region = null;
693
1097
  let metadata = {};
694
1098
  if (match) {
695
1099
  let built;
696
1100
  try {
697
- built = await buildRouteNode(match, Object.fromEntries(url.searchParams));
1101
+ built = await buildRouteNode(match, Object.fromEntries(url.searchParams), {
1102
+ error: dataError,
1103
+ loadingShown: loading?.shown ?? false,
1104
+ });
698
1105
  metadata = await resolveMetadataModules(built.modules, { params: match.params, query: Object.fromEntries(url.searchParams) });
699
1106
  if (seq !== navSeq) {
700
1107
  for (const node of built.nodes) runCleanup(node);
701
1108
  return;
702
1109
  }
703
1110
  nodes = built.nodes;
1111
+ region = built.region;
704
1112
  } catch (e) {
705
1113
  if (built) for (const node of built.nodes) runCleanup(node);
706
1114
  if (seq !== navSeq) return;
@@ -717,27 +1125,36 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
717
1125
  }
718
1126
  }
719
1127
 
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);
1128
+ loading?.cancel();
1129
+ // The swap itself: one synchronous update, so a view transition (when enabled)
1130
+ // snapshots the old page before it and animates to the new one after it.
1131
+ const commit = () => {
1132
+ for (const n of currentNodes) runCleanup(n);
1133
+ rootEl.replaceChildren();
1134
+ updateRouteHead(metadata, url.pathname);
1135
+ if (nodes) {
1136
+ // Set before inserting: a component that throws as it connects reports into it.
1137
+ currentRegion = region;
1138
+ currentRoute = match.route;
1139
+ rootEl.appendChild(nodes[nodes.length - 1]); // outermost node
1140
+ for (const n of nodes) runMount(n); // run onMount for page + every layout
1141
+ currentNodes = nodes;
1142
+ clearError({ phase: "route" }); // a good render dismisses a prior error overlay
1143
+ clearChunkReloadFlag(); // a successful render means the reload (if any) recovered
1144
+ if (spa) landScroll(url, isPop, entry);
1145
+ else if (!isPop && isBrowser) scrollToTarget(url);
1146
+ if (isBrowser) focusRouteContent(rootEl);
1147
+ } else {
1148
+ rootEl.innerHTML = "<h1>404 — Not Found</h1>";
1149
+ currentNodes = [];
1150
+ currentRegion = null;
736
1151
  }
737
- if (isBrowser) focusRouteContent(rootEl);
738
- } else {
739
- rootEl.innerHTML = "<h1>404 — Not Found</h1>";
740
- currentNodes = [];
1152
+ };
1153
+ // Never on the first paint: there is no previous page to transition from.
1154
+ await swapView(commit, committed);
1155
+ committed = true;
1156
+ } finally {
1157
+ loading?.cancel();
741
1158
  }
742
1159
  }
743
1160
 
@@ -847,14 +1264,18 @@ function focusRouteContent(container) {
847
1264
  * @param {string[]} [opts.loaders] route patterns that have a server loader
848
1265
  * (docs/DATA.md) — navigation fetches `<path>/__data.json` for these.
849
1266
  */
850
- export function mountApp({ pages, target, guard: g, i18n, nav, loaders } = {}) {
1267
+ export function mountApp({ pages, target, guard: g, i18n, nav, loaders, viewTransitions: vt = false } = {}) {
851
1268
  rootEl = target || (isBrowser ? document.getElementById("app") : null);
852
1269
  navMode = nav === "mpa" ? "mpa" : "spa";
1270
+ viewTransitions = Boolean(vt) && navMode === "spa";
1271
+ committed = false;
1272
+ if (isBrowser && navMode === "spa") manageScroll();
853
1273
  if (i18n) configureI18n(i18n);
854
1274
  if (pages) registerRoutes(pages);
855
1275
  if (loaders) registerLoaderRoutes(loaders);
856
1276
  guard = g || null;
857
1277
  setRouteDataRefresher(refreshRouteData);
1278
+ setRouteErrorHandler(showRouteError);
858
1279
  prefetched.clear(); // a fresh app starts with nothing warmed
859
1280
  // In MPA mode the browser owns navigation (full loads push real history entries),
860
1281
  // so there is no client-side history to react to — only wire popstate for SPA.