akanjs 3.3.0-rc.77 → 3.3.0-rc.78

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.
@@ -432,6 +432,8 @@ export const pageActivityContext = sharedContext<PageActivityState>("pageActivit
432
432
  export interface PathRoute {
433
433
  path: string;
434
434
  pathSegments: string[];
435
+ /** The not-found view a path no page matches draws, under the layouts it reached. */
436
+ notFound?: true;
435
437
  /** The pages matched ahead of this one that take some of its paths, as `/:lang/chat/new` does of `/:lang/chat/:id`. */
436
438
  shadowedBy?: string[];
437
439
  renderPage: RouteRender;
package/client/index.ts CHANGED
@@ -162,6 +162,8 @@ export {
162
162
  type NavigationKind,
163
163
  NavigationRefused,
164
164
  } from "./navigationGuards";
165
+ export { isNotFoundView } from "./notFoundView";
166
+ export { isRedirectMove } from "./redirectMove";
165
167
  export { resolveServerUrl } from "./resolveServerUrl";
166
168
  export {
167
169
  assertGuardOnChain,
@@ -0,0 +1,9 @@
1
+ declare global {
2
+ var __AKAN_NOT_FOUND_VIEW__: (() => boolean) | undefined;
3
+ }
4
+
5
+ /**
6
+ * Whether the page on screen is the app's not-found view, which a path no page matches, or a page's `notFound()`,
7
+ * draws at the address it was asked for. The web's RSC client and an app's CSR stack each answer it.
8
+ */
9
+ export const isNotFoundView = () => globalThis.__AKAN_NOT_FOUND_VIEW__?.() ?? false;
@@ -0,0 +1,13 @@
1
+ import type { RouteOptions } from "./router";
2
+
3
+ const redirectMoves = new WeakSet<RouteOptions>();
4
+
5
+ export const redirectMoveOptions = (): RouteOptions => {
6
+ const options: RouteOptions = {};
7
+ redirectMoves.add(options);
8
+ return options;
9
+ };
10
+
11
+ /** Whether a `RouterInstance` was handed the move by `router.redirect()` or `router.notFound()`: the page it was sent
12
+ * from draws nothing. */
13
+ export const isRedirectMove = (options: RouteOptions | undefined) => !!options && redirectMoves.has(options);
package/client/router.ts CHANGED
@@ -15,6 +15,7 @@ import { CsrRuntimeParams } from "./csrRuntimeParams";
15
15
  import { Href } from "./href";
16
16
  import { isMcpView } from "./mcpView";
17
17
  import { type NavigationAttempt, type NavigationGuard, NavigationGuards, NavigationRefused } from "./navigationGuards";
18
+ import { redirectMoveOptions } from "./redirectMove";
18
19
  import type { PrefetchPriority } from "./rscNavigation";
19
20
 
20
21
  export interface RouteOptions {
@@ -309,9 +310,9 @@ class Router {
309
310
  const { path, pathname, hash, href: fullHref } = this.#getPathInfo(href);
310
311
  this.postPathChange({ path, pathname, hash });
311
312
 
312
- setTimeout(() => {
313
- options.router.replace(CsrRuntimeParams.carry(fullHref), routeOptions);
314
- }, 0);
313
+ return new Promise<void>((made) => {
314
+ setTimeout(() => made(options.router.replace(CsrRuntimeParams.carry(fullHref), routeOptions)), 0);
315
+ });
315
316
  },
316
317
  back: (routeOptions) => {
317
318
  this.#postPathAfterBack();
@@ -723,7 +724,7 @@ class Router {
723
724
  } else {
724
725
  this.#redirects += 1;
725
726
  this.#navigations += 1;
726
- this.#instance[method](href);
727
+ this.#instance[method](href, redirectMoveOptions());
727
728
  }
728
729
  return undefined as never;
729
730
  }
@@ -735,7 +736,7 @@ class Router {
735
736
  this.#checkInitialized();
736
737
  this.#redirects += 1;
737
738
  this.#navigations += 1;
738
- this.#instance.replace("/404");
739
+ this.#instance.replace("/404", redirectMoveOptions());
739
740
  return undefined as never;
740
741
  }
741
742
  setLang(lang: string) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.77",
3
+ "version": "3.3.0-rc.78",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -57,6 +57,7 @@ import { resetAkanSegmentOutletPatches, whenAkanSegmentOutletDraws } from "./rsc
57
57
 
58
58
  declare global {
59
59
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
60
+ var __AKAN_RSC_INITIAL_NOT_FOUND__: boolean | undefined;
60
61
  var __AKAN_DICT_URL__: string | undefined;
61
62
  var __AKAN_IMPORT__: ((id: string) => Promise<unknown>) | undefined;
62
63
  var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
@@ -337,6 +338,7 @@ let shownNode: RscCacheNode | null = initialNode;
337
338
  const parkedRedirect = new RscParkedRedirect<RscCacheNode>();
338
339
  let currentCommitKind: "full" | "patch" = "full";
339
340
  let currentCommitFromCache = false;
341
+ let shownNotFound = globalThis.__AKAN_RSC_INITIAL_NOT_FOUND__ === true;
340
342
  let navigationSeq = 0;
341
343
  let pendingRequest: { navId: number; controller: AbortController; target: string } | null = null;
342
344
  let latestPageNavId = 0;
@@ -414,6 +416,7 @@ function loadDocumentForLazyChunkFailure(error: unknown, goneKey?: string): void
414
416
  }
415
417
 
416
418
  globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
419
+ globalThis.__AKAN_NOT_FOUND_VIEW__ = () => shownNotFound;
417
420
 
418
421
  function rememberCommittedRouteState(node: RscCacheNode): void {
419
422
  currentFullNode = node;
@@ -423,6 +426,7 @@ function rememberCommittedRouteState(node: RscCacheNode): void {
423
426
  currentRouterState = node.routerState;
424
427
  currentSegmentTree = createAkanSegmentCacheTree(node);
425
428
  currentCommitKind = "full";
429
+ shownNotFound = false;
426
430
  }
427
431
 
428
432
  function forgetCommittedRouteState(): void {
@@ -432,12 +436,14 @@ function forgetCommittedRouteState(): void {
432
436
  currentSegmentTree = null;
433
437
  currentFullNode = null;
434
438
  currentCommitKind = "full";
439
+ shownNotFound = true;
435
440
  }
436
441
 
437
442
  function rememberPatchedRouteState(tree: RscSegmentCacheNode, patchedNode: RscSegmentCacheNode): void {
438
443
  currentRouterState = patchedNode.routerState;
439
444
  currentSegmentTree = tree;
440
445
  currentCommitKind = "patch";
446
+ shownNotFound = false;
441
447
  }
442
448
 
443
449
  function forgetPagesOfAnotherAccount(): void {
@@ -10,6 +10,7 @@ export interface SsrBootstrapData {
10
10
  token: string;
11
11
  modules: string[];
12
12
  routeState?: string;
13
+ notFound?: boolean;
13
14
  /** The page dictionary file, or where the dictionary is cut by route the route's files, comma-separated. */
14
15
  dictionaryUrl?: string;
15
16
  importMapKey?: string;
@@ -90,6 +91,7 @@ export class SsrInlineScripts {
90
91
  self.__RSC_PUSH__ = function(type,data){ self.__RSC_CHUNKS__.push([type,data]); };
91
92
  self.__RSC_CLOSE__ = function(){ self.__RSC_CLOSED__ = true; };
92
93
  if (d.routeState) self.__AKAN_RSC_INITIAL_STATE__ = d.routeState;
94
+ if (d.notFound) self.__AKAN_RSC_INITIAL_NOT_FOUND__ = true;
93
95
  if (d.dictionaryUrl) self.__AKAN_DICT_URL__ = d.dictionaryUrl;
94
96
  if (d.importMapKey) self.__AKAN_IMPORT_MAP_KEY__ = d.importMapKey;
95
97
  if (d.prefix) self.__AKAN_PREFIX__ = d.prefix;
@@ -77,7 +77,7 @@ export interface SsrFromRscInput {
77
77
  modulePreloads?: string[];
78
78
  /** Preloads the chunks of each client reference the shell's flight names, with the runtime and their vendors. */
79
79
  modulePreloadPlan?: ModulePreloadPlan;
80
- bootstrapData?: Pick<SsrBootstrapData, "routeState" | "dictionaryUrl" | "importMapKey">;
80
+ bootstrapData?: Pick<SsrBootstrapData, "routeState" | "notFound" | "dictionaryUrl" | "importMapKey">;
81
81
  /** Dev only: script text that runs after the bootstrap, under the response's nonce. */
82
82
  devBootstrapInline?: string;
83
83
  /** The response's script nonce: React's own inline scripts carry it. */
@@ -190,6 +190,7 @@ export class WebDocumentRoute {
190
190
  modulePreloadPlan: this.#modulePreloadPlan,
191
191
  bootstrapData: {
192
192
  routeState: rscResult.trace?.routeState,
193
+ ...(rscResult.status === 404 ? { notFound: true } : {}),
193
194
  dictionaryUrl: dictionaryUrls.join(",") || undefined,
194
195
  importMapKey: this.#importMapKey,
195
196
  },
@@ -1,6 +1,7 @@
1
1
  import type { ToolActivity } from "../../vendor/use-agentic";
2
2
  import { AgentCursor } from "./AgentCursor";
3
3
  import { ScreenFlash } from "./ScreenFlash";
4
+ import { ScreenReader } from "./ScreenReader";
4
5
  import { ScreenTarget } from "./ScreenTarget";
5
6
 
6
7
  export interface AgentVisualOption {
@@ -109,9 +110,9 @@ export class AgentVisual {
109
110
  static #linkTo(path: unknown): HTMLElement[] {
110
111
  const wanted = ScreenTarget.routeOf(typeof path === "string" ? path : "");
111
112
  if (!wanted || !document.body) return [];
112
- const links = [...document.body.querySelectorAll<HTMLAnchorElement>("a[href]")].filter(
113
+ const links = [...document.body.querySelectorAll<HTMLAnchorElement>(ScreenReader.links)].filter(
113
114
  (link) =>
114
- ScreenTarget.routeOf(link.getAttribute("href") ?? "") === wanted &&
115
+ ScreenTarget.routeOf(ScreenReader.hrefOf(link)) === wanted &&
115
116
  ScreenTarget.visible(link) &&
116
117
  ScreenFlash.inView(link),
117
118
  );
@@ -67,6 +67,12 @@ export interface ScreenReadOptions {
67
67
  * reads a password, a one-time code or a card number. */
68
68
  export class ScreenReader {
69
69
  static readonly limit = 8000;
70
+
71
+ static readonly links = "a[href], a[data-href]";
72
+
73
+ static hrefOf(link: Element): string {
74
+ return link.getAttribute("href") ?? link.getAttribute("data-href") ?? "";
75
+ }
70
76
 
71
77
  static read(root?: HTMLElement | null, options: ScreenReadOptions = {}): string {
72
78
  if (typeof document === "undefined") return "No rendered document is available.";
@@ -278,7 +284,7 @@ export class ScreenReader {
278
284
  }
279
285
 
280
286
  #anchor(el: HTMLElement) {
281
- const href = el.getAttribute("href") ?? "";
287
+ const href = ScreenReader.hrefOf(el);
282
288
  const before = this.#buffer;
283
289
  this.#walkChildren(el);
284
290
  const text = this.#buffer.slice(before.length).replace(/\s+/g, " ").trim();
@@ -80,8 +80,8 @@ export class ScreenTarget {
80
80
  const scope = root ?? ScreenTarget.#body();
81
81
  if (!scope) return [];
82
82
  const routes = new Set<string>();
83
- for (const link of scope.querySelectorAll<HTMLAnchorElement>("a[href]")) {
84
- const route = ScreenTarget.visible(link) ? ScreenTarget.routeOf(link.getAttribute("href") ?? "") : "";
83
+ for (const link of scope.querySelectorAll<HTMLAnchorElement>(ScreenReader.links)) {
84
+ const route = ScreenTarget.visible(link) ? ScreenTarget.routeOf(ScreenReader.hrefOf(link)) : "";
85
85
  if (route) routes.add(route);
86
86
  if (routes.size >= nameCap) break;
87
87
  }
@@ -1,4 +1,4 @@
1
- import { csrLocation, router } from "akanjs/client";
1
+ import { csrLocation, isNotFoundView, router } from "akanjs/client";
2
2
  import { AgenticSurface, type SurfaceSource, type ToolEntry, ToolReturn } from "../../vendor/use-agentic";
3
3
  import { InlineToken } from "../../common/inlineToken";
4
4
  import { AgentBridge } from "./AgentBridge";
@@ -67,12 +67,29 @@ export class StoreSurfaceSource implements SurfaceSource {
67
67
  }
68
68
 
69
69
  await ScreenSettle.wait({ appearMs: 800, timeoutMs: 5000 });
70
+ if (isNotFoundView()) {
71
+ const left = await StoreSurfaceSource.#leaveNotFound();
72
+ throw new Error(
73
+ `There is no route at ${path}, so ${left ? "the page went back" : "the page shows the app's not-found page"}. ${StoreSurfaceSource.#linked()}`,
74
+ );
75
+ }
70
76
  const landed = StoreSurfaceSource.#redirected(path);
71
77
  return `${landed ? `Asked for ${path}, but the app sent the page to ${landed} instead.` : `Now on ${path}.`} ${StoreSurfaceSource.#arrived}`;
72
78
  },
73
79
  };
74
80
  }
75
81
 
82
+ static async #leaveNotFound(): Promise<boolean> {
83
+ if (!router.canGoBack()) return false;
84
+ router.back();
85
+ const left = await router.navigation().then(
86
+ () => true,
87
+ () => false,
88
+ );
89
+ await ScreenSettle.wait({ appearMs: 800, timeoutMs: 5000 });
90
+ return left;
91
+ }
92
+
76
93
  static readonly #arrived =
77
94
  "This screen's own tools and state replace the previous screen's and are listed on your next turn — call them then, by the names listed. Call readScreen to see the page.";
78
95
 
@@ -90,7 +107,7 @@ export class StoreSurfaceSource implements SurfaceSource {
90
107
  : "Call readScreen — it prints each link on this screen with its own path — and navigate to one of those.";
91
108
  }
92
109
 
93
- /** A redirect or the app's not-found page moves the page somewhere other than the path it was sent to. */
110
+ /** A redirect moves the page somewhere other than the path it was sent to. */
94
111
  static #redirected(path: string): string | null {
95
112
  const trimmed = (route: string) => (route.length > 1 ? route.replace(/\/+$/, "") : route);
96
113
  try {
@@ -419,6 +419,8 @@ export declare const pageActivityContext: import("react").Context<PageActivitySt
419
419
  export interface PathRoute {
420
420
  path: string;
421
421
  pathSegments: string[];
422
+ /** The not-found view a path no page matches draws, under the layouts it reached. */
423
+ notFound?: true;
422
424
  /** The pages matched ahead of this one that take some of its paths, as `/:lang/chat/new` does of `/:lang/chat/:id`. */
423
425
  shadowedBy?: string[];
424
426
  renderPage: RouteRender;
@@ -12,6 +12,8 @@ export { type ErrPayload, makePageProto, type PageErrConstructor, type PageErrIn
12
12
  export { isMcpView } from "./mcpView.d.ts";
13
13
  export { desktopPlatform, isNativeApp, isNativeShell, nativePlatform, openExternalUrl } from "./nativeHost.d.ts";
14
14
  export { type NavigationAttempt, type NavigationGuard, type NavigationKind, NavigationRefused, } from "./navigationGuards.d.ts";
15
+ export { isNotFoundView } from "./notFoundView.d.ts";
16
+ export { isRedirectMove } from "./redirectMove.d.ts";
15
17
  export { resolveServerUrl } from "./resolveServerUrl.d.ts";
16
18
  export { assertGuardOnChain, isRouteDefinition, LayoutDefinition, type LayoutExtra, layout, PageDefinition, page, type ResolvedRouteModule, type ResolveRouteModuleOption, RootLayoutDefinition, RouteArgError, type RouteArgInfo, type RouteArgInput, type RouteArgOption, RouteArgPending, type RouteArgResolveOption, type RouteArgsShape, type RouteArgType, type RouteArgValue, type RouteBaseArgs, RouteDefinition, type RouteGuardRequest, RouteGuards, RouteHead, type RouteKind, type RouteLoadingOption, type RouteModuleSource, type RoutePromptArgument, type RoutePromptMeta, type RouteSearchType, resolveRouteModule, rootLayout, routeArgsMarker, routeDefinitionMarker, routeLoadingAtPressMarker, } from "./route.d.ts";
17
19
  export { AkanNotFoundError, AkanRedirectError, type DeepLinkOptions, getPathInfo, isRouteControl, normalizeDeepLinkHref, type RedirectMethod, type RedirectOptions, type RedirectStatus, type RouteManifest, type RouteOptions, type RouterInstance, router, } from "./router.d.ts";
@@ -0,0 +1,8 @@
1
+ declare global {
2
+ var __AKAN_NOT_FOUND_VIEW__: (() => boolean) | undefined;
3
+ }
4
+ /**
5
+ * Whether the page on screen is the app's not-found view, which a path no page matches, or a page's `notFound()`,
6
+ * draws at the address it was asked for. The web's RSC client and an app's CSR stack each answer it.
7
+ */
8
+ export declare const isNotFoundView: () => boolean;
@@ -0,0 +1,5 @@
1
+ import type { RouteOptions } from "./router.d.ts";
2
+ export declare const redirectMoveOptions: () => RouteOptions;
3
+ /** Whether a `RouterInstance` was handed the move by `router.redirect()` or `router.notFound()`: the page it was sent
4
+ * from draws nothing. */
5
+ export declare const isRedirectMove: (options: RouteOptions | undefined) => boolean;
@@ -1,5 +1,6 @@
1
1
  declare global {
2
2
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
3
+ var __AKAN_RSC_INITIAL_NOT_FOUND__: boolean | undefined;
3
4
  var __AKAN_DICT_URL__: string | undefined;
4
5
  var __AKAN_IMPORT__: ((id: string) => Promise<unknown>) | undefined;
5
6
  var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
@@ -6,6 +6,7 @@ export interface SsrBootstrapData {
6
6
  token: string;
7
7
  modules: string[];
8
8
  routeState?: string;
9
+ notFound?: boolean;
9
10
  /** The page dictionary file, or where the dictionary is cut by route the route's files, comma-separated. */
10
11
  dictionaryUrl?: string;
11
12
  importMapKey?: string;
@@ -73,7 +73,7 @@ export interface SsrFromRscInput {
73
73
  modulePreloads?: string[];
74
74
  /** Preloads the chunks of each client reference the shell's flight names, with the runtime and their vendors. */
75
75
  modulePreloadPlan?: ModulePreloadPlan;
76
- bootstrapData?: Pick<SsrBootstrapData, "routeState" | "dictionaryUrl" | "importMapKey">;
76
+ bootstrapData?: Pick<SsrBootstrapData, "routeState" | "notFound" | "dictionaryUrl" | "importMapKey">;
77
77
  /** Dev only: script text that runs after the bootstrap, under the response's nonce. */
78
78
  devBootstrapInline?: string;
79
79
  /** The response's script nonce: React's own inline scripts carry it. */
@@ -7,6 +7,8 @@ export interface ScreenReadOptions {
7
7
  export declare class ScreenReader {
8
8
  #private;
9
9
  static readonly limit = 8000;
10
+ static readonly links = "a[href], a[data-href]";
11
+ static hrefOf(link: Element): string;
10
12
  static read(root?: HTMLElement | null, options?: ScreenReadOptions): string;
11
13
  /** One heading's section: its container when that holds no peer heading, else its following siblings. */
12
14
  static readFrom(heading: HTMLElement, root?: HTMLElement | null, options?: ScreenReadOptions): string;
@@ -0,0 +1,7 @@
1
+ export declare class CsrMoves {
2
+ #private;
3
+ static open(move: object): Promise<void>;
4
+ static of(move: object | null | undefined): Promise<void> | undefined;
5
+ static settle(move: object | null | undefined): void;
6
+ static follow(move: object | null | undefined, next: void | Promise<void>): void;
7
+ }
@@ -19,7 +19,7 @@ export declare const useCsrNavigation: (input: CsrNavigationInput) => {
19
19
  settle: (prev: LocationState["prevLocation"]) => void;
20
20
  cancelPendingNavigation: () => NavigationIntent | null;
21
21
  broadcastSyncNavigation: (kind: "replace" | "pop" | "push" | "back", href: string) => void;
22
- runForwardNavigation: (requested: "push" | "replace", href: string, { scrollToTop }?: RouteOptions) => void;
22
+ runForwardNavigation: (requested: "push" | "replace", href: string, { scrollToTop }?: RouteOptions) => Promise<void> | undefined;
23
23
  };
24
24
  export type CsrNavigation = ReturnType<typeof useCsrNavigation>;
25
25
  export {};
@@ -84,6 +84,7 @@ export declare function resolvePathRoutesWithFrameState(pathRoutes: PathRoute[],
84
84
  pageState: PageState;
85
85
  path: string;
86
86
  pathSegments: string[];
87
+ notFound?: true;
87
88
  shadowedBy?: string[];
88
89
  renderPage: import("akanjs/client").RouteRender;
89
90
  pageConfigChain?: import("akanjs/client").PageConfig[];
@@ -17,6 +17,7 @@ export declare const useResolvedFrame: ({ pathRoutes, slots: { frameSlots, pendi
17
17
  pageState: PageState;
18
18
  path: string;
19
19
  pathSegments: string[];
20
+ notFound?: true;
20
21
  shadowedBy?: string[];
21
22
  renderPage: import("akanjs/client").RouteRender;
22
23
  pageConfigChain?: import("akanjs/client").PageConfig[];
@@ -64,7 +64,7 @@ export const CsrLink = ({
64
64
  const { prefix } = usePathCtx();
65
65
  const pathname = ShellState.use("pathname");
66
66
  const { lang } = usePage();
67
- const { hash } = getPathInfo(href, lang, prefix ?? "");
67
+ const { hash, href: shownHref } = getPathInfo(href, lang, prefix ?? "");
68
68
  const active =
69
69
  !!activeClassName &&
70
70
  isActiveHref({ pathname, href, lang, prefix: prefix ?? "", exact: activeExact, match: activeMatch });
@@ -73,6 +73,7 @@ export const CsrLink = ({
73
73
  <a
74
74
  className={cn("cursor-pointer", className, active && activeClassName, pending && pendingClassName)}
75
75
  data-pending={pending ? "" : undefined}
76
+ data-href={Href.isExternal(href) || href.startsWith("#") ? href : shownHref}
76
77
  {...props}
77
78
  onClick={(event) => {
78
79
  props.onClick?.(event);
package/ui/System/CSR.tsx CHANGED
@@ -174,6 +174,7 @@ const CSRWrapper = ({
174
174
  routeManifest: pathRoutes.map((pathRoute) => pathRoute.path),
175
175
  indexPath: window.__AKAN_MOBILE_TARGET__?.indexPath,
176
176
  });
177
+ globalThis.__AKAN_NOT_FOUND_VIEW__ = () => !!history.current.locations[history.current.idx]?.pathRoute.notFound;
177
178
  st.do.setCsrLoaded(true);
178
179
  const onVisibilityChange = () => debugFrame("document.visibility", { visibilityState: document.visibilityState });
179
180
  const onPageHide = (event: PageTransitionEvent) => debugFrame("window.pagehide", { persisted: event.persisted });
@@ -0,0 +1,30 @@
1
+
2
+
3
+ export class CsrMoves {
4
+ static readonly #open = new WeakMap<object, { made: Promise<void>; settle: () => void }>();
5
+
6
+ static open(move: object): Promise<void> {
7
+ let settle: () => void = () => undefined;
8
+ const made = new Promise<void>((resolve) => {
9
+ settle = resolve;
10
+ });
11
+ CsrMoves.#open.set(move, { made, settle });
12
+ return made;
13
+ }
14
+
15
+ static of(move: object | null | undefined): Promise<void> | undefined {
16
+ return move ? CsrMoves.#open.get(move)?.made : undefined;
17
+ }
18
+
19
+ static settle(move: object | null | undefined) {
20
+ if (!move) return;
21
+ CsrMoves.#open.get(move)?.settle();
22
+ CsrMoves.#open.delete(move);
23
+ }
24
+
25
+ static follow(move: object | null | undefined, next: void | Promise<void>) {
26
+ if (!move) return;
27
+ const settle = () => CsrMoves.settle(move);
28
+ void Promise.resolve(next).then(settle, settle);
29
+ }
30
+ }
@@ -287,6 +287,7 @@ export class CsrRouteTable {
287
287
  routeOf: (pathname) => ({
288
288
  path,
289
289
  pathSegments,
290
+ notFound: true,
290
291
  renderRootLayouts: layer.renderRootLayouts,
291
292
  renderLayouts,
292
293
  pageState,
@@ -9,6 +9,7 @@ import {
9
9
  type RouteOptions,
10
10
  } from "akanjs/client";
11
11
  import { useCallback } from "react";
12
+ import { CsrMoves } from "./CsrMoves";
12
13
  import { CsrStack } from "./CsrStack";
13
14
  import { CsrPageReadiness } from "./csrPageReadiness";
14
15
  import { CsrPendingNavigation } from "./csrPendingNavigation";
@@ -112,6 +113,7 @@ const commitWhenFrameReady = ({
112
113
  });
113
114
  if (kind === "push") csrLocation.push({ akanEntryId: toLocation.entryId }, href);
114
115
  else csrLocation.replace({ akanEntryId: toLocation.entryId }, href);
116
+ CsrMoves.settle(intent);
115
117
  debugFrame("navigation.commit", { id: intent.id, kind, to: href });
116
118
  window.setTimeout(
117
119
  () => {
@@ -129,7 +131,11 @@ const commitWhenFrameReady = ({
129
131
  debugFrame("transition.actionEnd", { id: plan.id, phase: "idle" });
130
132
  const waiting = waitingNavigation.current;
131
133
  waitingNavigation.current = null;
132
- if (waiting) currentRouter(latestRouter)[waiting.kind](waiting.href, { scrollToTop: waiting.scrollToTop });
134
+ if (waiting)
135
+ CsrMoves.follow(
136
+ waiting,
137
+ currentRouter(latestRouter)[waiting.kind](waiting.href, { scrollToTop: waiting.scrollToTop }),
138
+ );
133
139
  },
134
140
  Math.max(360, plan.duration),
135
141
  );
@@ -171,6 +177,20 @@ const commitWhenDrawn = (
171
177
  window.setTimeout(waitUntilDrawn, 16);
172
178
  };
173
179
 
180
+ const queueAfterSlide = (
181
+ waitingNavigation: CsrRefs["waitingNavigation"],
182
+ move: { kind: "push" | "replace"; href: string; scrollToTop?: boolean },
183
+ from: string,
184
+ ) => {
185
+ const waiting = waitingNavigation.current;
186
+ const queued = { ...move, kind: waiting?.kind === "push" ? ("push" as const) : move.kind };
187
+ waitingNavigation.current = queued;
188
+ debugFrame("navigation.wait", { kind: move.kind, from, to: move.href });
189
+ const made = CsrMoves.open(queued);
190
+ CsrMoves.follow(waiting, made);
191
+ return made;
192
+ };
193
+
174
194
  interface CsrNavigationInput {
175
195
  viewport: ReturnType<typeof useFrameViewport>["viewport"];
176
196
  slots: ReturnType<typeof useFrameSlots>;
@@ -276,13 +296,8 @@ export const useCsrNavigation = (input: CsrNavigationInput) => {
276
296
  commitInPlace();
277
297
  return;
278
298
  }
279
- if (slides && navigationLocked.current) {
280
-
281
- const waiting = waitingNavigation.current;
282
- waitingNavigation.current = { kind: waiting?.kind === "push" ? "push" : kind, href, scrollToTop };
283
- debugFrame("navigation.wait", { kind, from: fromLocation.href, to: href });
284
- return;
285
- }
299
+ if (slides && navigationLocked.current)
300
+ return queueAfterSlide(waitingNavigation, { kind, href, scrollToTop }, fromLocation.href);
286
301
  if (slides) navigationLocked.current = true;
287
302
  const intent: NavigationIntent = {
288
303
  id: ++navigationIntentId.current,
@@ -294,6 +309,7 @@ export const useCsrNavigation = (input: CsrNavigationInput) => {
294
309
  createdAt: Date.now(),
295
310
  };
296
311
  pendingNavigation.current = intent;
312
+ const made = CsrMoves.open(intent);
297
313
  debugFrame(slides ? "navigation.intent" : "navigation.drawAhead", {
298
314
  id: intent.id,
299
315
  kind,
@@ -312,8 +328,9 @@ export const useCsrNavigation = (input: CsrNavigationInput) => {
312
328
  commitWhenDrawn(intent, pendingNavigation, () => {
313
329
  commitInPlace();
314
330
  promotePendingSlots();
331
+ CsrMoves.settle(intent);
315
332
  });
316
- return;
333
+ return made;
317
334
  }
318
335
  commitWhenFrameReady({
319
336
  kind,
@@ -330,6 +347,7 @@ export const useCsrNavigation = (input: CsrNavigationInput) => {
330
347
  nav,
331
348
  frame,
332
349
  });
350
+ return made;
333
351
  },
334
352
  [
335
353
  clearPendingSlots,
@@ -4,6 +4,7 @@ import {
4
4
  csrLocation,
5
5
  debugFrame,
6
6
  Href,
7
+ isRedirectMove,
7
8
  type Location,
8
9
  type NavigationIntent,
9
10
  type PageState,
@@ -17,6 +18,7 @@ import {
17
18
  } from "akanjs/client";
18
19
  import { isNativeApp, openExternalUrl } from "akanjs/client/native";
19
20
  import { useCallback, useLayoutEffect, useMemo, useState } from "react";
21
+ import { CsrMoves } from "./CsrMoves";
20
22
  import { CsrPendingNavigation } from "./csrPendingNavigation";
21
23
  import { CsrRefresh } from "./csrRefresh";
22
24
  import { CsrSlide } from "./csrSlide";
@@ -32,6 +34,8 @@ import { FRAME_Z_INDEX, useFrameSlots, useFrameViewport } from "./useFrameRuntim
32
34
  import { useResolvedFrame } from "./useResolvedFrame";
33
35
  import { getSyncRouteHref, useSyncNavigation } from "./useSyncNavigation";
34
36
 
37
+ const sentByRedirect = new WeakSet<NavigationIntent>();
38
+
35
39
  const useCsrRouter = ({
36
40
  refs: { pendingNavigation, pageContentRef, waitingNavigation, onBack, latestRouter },
37
41
  nav,
@@ -47,36 +51,42 @@ const useCsrRouter = ({
47
51
  const { shouldPrepareFrameTransition, startFrameTransition } = navigation;
48
52
  const getRouter = useCallback((): RouterInstance => {
49
53
  const playBack = (transition: TransitionType) => onBack.current[transition]?.();
50
- const forward =
51
- (kind: "push" | "replace") =>
52
- (href: string, { scrollToTop }: RouteOptions = {}) => {
53
- const location = getCurrentLocation();
54
- debugFrame(`router.${kind}`, { from: location.href, to: href, scrollToTop });
54
+ const forward = (kind: "push" | "replace") => (href: string, options?: RouteOptions) => {
55
+ const scrollToTop = options?.scrollToTop;
56
+ const location = getCurrentLocation();
57
+ debugFrame(`router.${kind}`, { from: location.href, to: href, scrollToTop });
55
58
 
56
- if (Href.hasWebScheme(href)) {
57
- const target = Href.toExternalUrl(href, document.baseURI);
58
-
59
- if (isNativeApp())
60
- void openExternalUrl(target).catch((error: unknown) => {
61
- if (!(error instanceof Error && "code" in error && error.code === "NOT_ALLOWED"))
62
- window.open(target, "_blank", "noopener,noreferrer");
63
- });
64
- else if (kind === "push") csrLocation.assign(target);
65
- else window.location.replace(target);
66
- return;
67
- }
68
- if (pendingNavigation.current?.to.href === href) return;
59
+ if (Href.hasWebScheme(href)) {
60
+ const target = Href.toExternalUrl(href, document.baseURI);
61
+
62
+ if (isNativeApp())
63
+ void openExternalUrl(target).catch((error: unknown) => {
64
+ if (!(error instanceof Error && "code" in error && error.code === "NOT_ALLOWED"))
65
+ window.open(target, "_blank", "noopener,noreferrer");
66
+ });
67
+ else if (kind === "push") csrLocation.assign(target);
68
+ else window.location.replace(target);
69
+ return;
70
+ }
71
+ const pending = pendingNavigation.current;
72
+ if (pending?.to.href === href || (pending && location.href === href && sentByRedirect.has(pending)))
73
+ return CsrMoves.of(pending);
69
74
 
70
- const cancelled: NavigationIntent | null = cancelPendingNavigation();
71
- if (location.href === href) {
72
- CsrPendingNavigation.end();
73
- if (cancelled) NativeNavigation.turnedBack();
74
- if (!pageContentRef.current) return;
75
- pageContentRef.current.scrollTop = getScrollTop(location);
76
- return;
77
- }
78
- runForwardNavigation(cancelled?.kind === "push" ? "push" : kind, href, { scrollToTop });
79
- };
75
+ const cancelled: NavigationIntent | null = cancelPendingNavigation();
76
+ if (location.href === href) {
77
+ CsrMoves.settle(cancelled);
78
+ CsrPendingNavigation.end();
79
+ if (cancelled) NativeNavigation.turnedBack();
80
+ if (!pageContentRef.current) return;
81
+ pageContentRef.current.scrollTop = getScrollTop(location);
82
+ return;
83
+ }
84
+ const made = runForwardNavigation(cancelled?.kind === "push" ? "push" : kind, href, { scrollToTop });
85
+ if (!cancelled && pendingNavigation.current && isRedirectMove(options))
86
+ sentByRedirect.add(pendingNavigation.current);
87
+ CsrMoves.follow(cancelled, made);
88
+ return made;
89
+ };
80
90
  const router: RouterInstance = {
81
91
  push: forward("push"),
82
92
  replace: forward("replace"),
@@ -86,10 +96,13 @@ const useCsrRouter = ({
86
96
  CsrRefresh.request(location);
87
97
  },
88
98
  back: async ({ scrollToTop }: RouteOptions = {}) => {
99
+ CsrMoves.settle(waitingNavigation.current);
89
100
  waitingNavigation.current = null;
90
101
  CsrPendingNavigation.end();
91
102
 
92
- if (cancelPendingNavigation()) return;
103
+ const cancelled = cancelPendingNavigation();
104
+ CsrMoves.settle(cancelled);
105
+ if (cancelled) return;
93
106
  const targetLocation = getPrevLocation();
94
107
  if (!targetLocation) return;
95
108
  const location = getCurrentLocation();
@@ -118,9 +131,10 @@ const useCsrRouter = ({
118
131
  const target = routeType ? null : history.current.locations.findIndex((candidate) => isAt(candidate));
119
132
  if (target === history.current.idx) return;
120
133
 
134
+ CsrMoves.settle(waitingNavigation.current);
121
135
  waitingNavigation.current = null;
122
136
  CsrPendingNavigation.end();
123
- cancelPendingNavigation();
137
+ CsrMoves.settle(cancelPendingNavigation());
124
138
  if (target !== null) {
125
139
  if (target >= 0) setHistoryJump(target, scrollTop);
126
140
  else {