akanjs 3.3.0-rc.77 → 3.3.0-rc.79

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.
Files changed (45) hide show
  1. package/client/csrLocation.ts +19 -2
  2. package/client/csrTypes.ts +2 -0
  3. package/client/index.ts +2 -0
  4. package/client/notFoundView.ts +9 -0
  5. package/client/redirectMove.ts +13 -0
  6. package/client/router.ts +11 -7
  7. package/package.json +1 -1
  8. package/server/rscClient.tsx +6 -0
  9. package/server/ssrInlineScripts.ts +2 -0
  10. package/server/ssrTypes.ts +1 -1
  11. package/server/webDocumentRoute.ts +1 -0
  12. package/store/agent/AgentVisual.ts +3 -2
  13. package/store/agent/ScreenReader.ts +7 -1
  14. package/store/agent/ScreenSettle.ts +27 -0
  15. package/store/agent/ScreenTarget.ts +2 -2
  16. package/store/agent/StoreSurfaceSource.ts +26 -4
  17. package/types/client/csrLocation.d.ts +2 -1
  18. package/types/client/csrTypes.d.ts +2 -0
  19. package/types/client/index.d.ts +2 -0
  20. package/types/client/notFoundView.d.ts +8 -0
  21. package/types/client/redirectMove.d.ts +5 -0
  22. package/types/client/router.d.ts +2 -1
  23. package/types/server/rscClient.d.ts +1 -0
  24. package/types/server/ssrInlineScripts.d.ts +1 -0
  25. package/types/server/ssrTypes.d.ts +1 -1
  26. package/types/store/agent/ScreenReader.d.ts +2 -0
  27. package/types/store/agent/ScreenSettle.d.ts +5 -0
  28. package/types/ui/Load/LoadingMark.d.ts +4 -0
  29. package/types/ui/Load/Stream.d.ts +1 -1
  30. package/types/webkit/CsrMoves.d.ts +7 -0
  31. package/types/webkit/useCsrNavigation.d.ts +1 -1
  32. package/types/webkit/useFrameRuntime.d.ts +1 -0
  33. package/types/webkit/useResolvedFrame.d.ts +1 -0
  34. package/ui/Link/Anchor.tsx +2 -1
  35. package/ui/Load/LoadingMark.tsx +8 -0
  36. package/ui/Load/PageCSR.tsx +3 -1
  37. package/ui/Load/Stream.tsx +3 -1
  38. package/ui/Load/Units.tsx +3 -2
  39. package/ui/System/CSR.tsx +1 -0
  40. package/ui/System/Client.tsx +1 -3
  41. package/webkit/CsrMoves.ts +30 -0
  42. package/webkit/CsrRouteTable.ts +1 -0
  43. package/webkit/RenderLayer.tsx +7 -1
  44. package/webkit/useCsrNavigation.ts +27 -9
  45. package/webkit/useCsrValues.ts +45 -31
@@ -4,6 +4,8 @@ declare global {
4
4
  var __AKAN_EMBED__: { kind: "mcp-app"; origin?: string; account?: Record<string, unknown> | null } | undefined;
5
5
  }
6
6
 
7
+ const popWaitMs = 1000;
8
+
7
9
  /** The document's location and history, as the routers read and move them. */
8
10
  export class CsrLocation {
9
11
 
@@ -117,12 +119,27 @@ export class CsrLocation {
117
119
  return entry === this.#backAsked || entry === this.#backSent;
118
120
  }
119
121
 
120
- back() {
122
+ /** Settles once the back's pop has moved the address, or at once when no entry of this document is under it. */
123
+ back(): Promise<void> {
121
124
  const entry = this.entry();
122
125
  if (entry.idx !== undefined) this.#onBack?.(entry.idx - 1);
123
126
 
124
- if (entry.idx !== undefined && entry.idx > 0) this.#backSent = entry;
127
+ const pops = entry.idx !== undefined && entry.idx > 0;
128
+ if (pops) this.#backSent = entry;
129
+ const landed = pops ? CsrLocation.#nextPop() : Promise.resolve();
125
130
  window.history.back();
131
+ return landed;
132
+ }
133
+
134
+ static #nextPop() {
135
+ return new Promise<void>((resolve) => {
136
+ const land = () => {
137
+ clearTimeout(cap);
138
+ resolve();
139
+ };
140
+ const cap = setTimeout(land, popWaitMs);
141
+ window.addEventListener("popstate", land, { once: true });
142
+ });
126
143
  }
127
144
 
128
145
  assign(href: string) {
@@ -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 {
@@ -42,7 +43,8 @@ export interface RouterInstance {
42
43
  /** May answer a promise that rejects when the route refused to move — see `Router.navigation`. */
43
44
  push: (href: string, routeOptions?: RouteOptions) => void | Promise<void>;
44
45
  replace: (href: string, routeOptions?: RouteOptions) => void | Promise<void>;
45
- back: (routeOptions?: RouteOptions) => void;
46
+ /** May answer a promise that settles once the back has landed. */
47
+ back: (routeOptions?: RouteOptions) => void | Promise<void>;
46
48
  refresh: () => void;
47
49
  /** Whether `back` has a page to return to; left out, the router reads the index stamped on the history entry. */
48
50
  canGoBack?: () => boolean;
@@ -309,9 +311,9 @@ class Router {
309
311
  const { path, pathname, hash, href: fullHref } = this.#getPathInfo(href);
310
312
  this.postPathChange({ path, pathname, hash });
311
313
 
312
- setTimeout(() => {
313
- options.router.replace(CsrRuntimeParams.carry(fullHref), routeOptions);
314
- }, 0);
314
+ return new Promise<void>((made) => {
315
+ setTimeout(() => made(options.router.replace(CsrRuntimeParams.carry(fullHref), routeOptions)), 0);
316
+ });
315
317
  },
316
318
  back: (routeOptions) => {
317
319
  this.#postPathAfterBack();
@@ -674,7 +676,9 @@ class Router {
674
676
  this.#checkInitialized();
675
677
  this.#guarded("back", null, () => {
676
678
  this.#navigations += 1;
677
- csrLocation.leaving(this.#instance.back(routeOptions));
679
+ const moving = this.#instance.back(routeOptions);
680
+ csrLocation.leaving(moving);
681
+ return moving;
678
682
  });
679
683
  return undefined as never;
680
684
  }
@@ -723,7 +727,7 @@ class Router {
723
727
  } else {
724
728
  this.#redirects += 1;
725
729
  this.#navigations += 1;
726
- this.#instance[method](href);
730
+ this.#instance[method](href, redirectMoveOptions());
727
731
  }
728
732
  return undefined as never;
729
733
  }
@@ -735,7 +739,7 @@ class Router {
735
739
  this.#checkInitialized();
736
740
  this.#redirects += 1;
737
741
  this.#navigations += 1;
738
- this.#instance.replace("/404");
742
+ this.#instance.replace("/404", redirectMoveOptions());
739
743
  return undefined as never;
740
744
  }
741
745
  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.79",
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();
@@ -30,4 +30,31 @@ export class ScreenSettle {
30
30
  else rearm();
31
31
  });
32
32
  }
33
+
34
+ /** Resolves once no load on a page in view is pending, each `Load.*` fallback marking itself; `false` when none was. */
35
+ static loaded({ timeoutMs = 5000 }: { timeoutMs?: number } = {}): Promise<boolean> {
36
+ const body = typeof document === "undefined" ? null : (document.body ?? document.documentElement);
37
+ if (!body || typeof MutationObserver === "undefined" || !ScreenSettle.#loading(body)) return Promise.resolve(false);
38
+ return new Promise((resolve) => {
39
+ const done = () => {
40
+ clearTimeout(deadline);
41
+ observer.disconnect();
42
+ resolve(true);
43
+ };
44
+ const observer = new MutationObserver(() => {
45
+ if (!ScreenSettle.#loading(body)) done();
46
+ });
47
+ const deadline = setTimeout(done, timeoutMs);
48
+ observer.observe(body, { attributes: true, childList: true, subtree: true });
49
+ });
50
+ }
51
+
52
+ static #loading(body: HTMLElement) {
53
+ for (const mark of body.querySelectorAll("template[data-akan-loading]")) {
54
+ const holder = mark.parentElement;
55
+ if (!holder || holder.closest('[hidden], [aria-hidden="true"], [inert]')) continue;
56
+ if (typeof holder.checkVisibility !== "function" || holder.checkVisibility()) return true;
57
+ }
58
+ return false;
59
+ }
33
60
  }
@@ -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";
@@ -66,13 +66,35 @@ export class StoreSurfaceSource implements SurfaceSource {
66
66
  throw new Error(`There is no route at ${path}, so the page did not move. ${StoreSurfaceSource.#linked()}`);
67
67
  }
68
68
 
69
- await ScreenSettle.wait({ appearMs: 800, timeoutMs: 5000 });
69
+ await StoreSurfaceSource.#settled();
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 #settled() {
83
+ await ScreenSettle.wait({ appearMs: 800, timeoutMs: 5000 });
84
+ if (await ScreenSettle.loaded({ timeoutMs: 5000 })) await ScreenSettle.wait({ timeoutMs: 2000 });
85
+ }
86
+
87
+ static async #leaveNotFound(): Promise<boolean> {
88
+ if (!router.canGoBack()) return false;
89
+ router.back();
90
+ const left = await router.navigation().then(
91
+ () => true,
92
+ () => false,
93
+ );
94
+ await StoreSurfaceSource.#settled();
95
+ return left;
96
+ }
97
+
76
98
  static readonly #arrived =
77
99
  "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
100
 
@@ -90,7 +112,7 @@ export class StoreSurfaceSource implements SurfaceSource {
90
112
  : "Call readScreen — it prints each link on this screen with its own path — and navigate to one of those.";
91
113
  }
92
114
 
93
- /** A redirect or the app's not-found page moves the page somewhere other than the path it was sent to. */
115
+ /** A redirect moves the page somewhere other than the path it was sent to. */
94
116
  static #redirected(path: string): string | null {
95
117
  const trimmed = (route: string) => (route.length > 1 ? route.replace(/\/+$/, "") : route);
96
118
  try {
@@ -115,7 +137,7 @@ export class StoreSurfaceSource implements SurfaceSource {
115
137
  await router.navigation().catch((error: unknown) => {
116
138
  if (StoreSurfaceSource.#isKept(error)) throw new Error(StoreSurfaceSource.#kept);
117
139
  });
118
- await ScreenSettle.wait({ appearMs: 800, timeoutMs: 5000 });
140
+ await StoreSurfaceSource.#settled();
119
141
  return `Back on ${router.getPath()}. ${StoreSurfaceSource.#arrived}`;
120
142
  },
121
143
  };
@@ -43,7 +43,8 @@ export declare class CsrLocation {
43
43
  leaving(moving: unknown): void;
44
44
  /** Whether a back has left the entry on screen and not landed yet. */
45
45
  isLeaving(): boolean;
46
- back(): void;
46
+ /** Settles once the back's pop has moved the address, or at once when no entry of this document is under it. */
47
+ back(): Promise<void>;
47
48
  assign(href: string): void;
48
49
  reload(): void;
49
50
  }
@@ -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;
@@ -23,7 +23,8 @@ export interface RouterInstance {
23
23
  /** May answer a promise that rejects when the route refused to move — see `Router.navigation`. */
24
24
  push: (href: string, routeOptions?: RouteOptions) => void | Promise<void>;
25
25
  replace: (href: string, routeOptions?: RouteOptions) => void | Promise<void>;
26
- back: (routeOptions?: RouteOptions) => void;
26
+ /** May answer a promise that settles once the back has landed. */
27
+ back: (routeOptions?: RouteOptions) => void | Promise<void>;
27
28
  refresh: () => void;
28
29
  /** Whether `back` has a page to return to; left out, the router reads the index stamped on the history entry. */
29
30
  canGoBack?: () => 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;
@@ -7,5 +7,10 @@ export interface ScreenSettleOptions {
7
7
  }
8
8
  /** Resolves once the DOM stops mutating, always bounded; no single router or store signal says "settled". */
9
9
  export declare class ScreenSettle {
10
+ #private;
10
11
  static wait({ quietMs, appearMs, timeoutMs }?: ScreenSettleOptions): Promise<void>;
12
+ /** Resolves once no load on a page in view is pending, each `Load.*` fallback marking itself; `false` when none was. */
13
+ static loaded({ timeoutMs }?: {
14
+ timeoutMs?: number;
15
+ }): Promise<boolean>;
11
16
  }
@@ -0,0 +1,4 @@
1
+ import type { ReactNode } from "react";
2
+ export declare const LoadingMark: ({ children }: {
3
+ children?: ReactNode;
4
+ }) => import("react").JSX.Element;
@@ -12,5 +12,5 @@ interface StreamProps<Value> {
12
12
  error?: StreamError;
13
13
  children: (value: Value) => ReactNode;
14
14
  }
15
- export default function Stream<Value>({ of, fallback, error, children }: StreamProps<Value>): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | import("react").JSX.Element | null | undefined;
15
+ export default function Stream<Value>({ of, fallback: shown, error, children }: StreamProps<Value>): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | import("react").JSX.Element | null | undefined;
16
16
  export {};
@@ -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);
@@ -0,0 +1,8 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ export const LoadingMark = ({ children }: { children?: ReactNode }) => (
4
+ <>
5
+ {children}
6
+ <template data-akan-loading="" />
7
+ </>
8
+ );
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { type ReactNode, useEffect, useMemo, useState } from "react";
3
3
 
4
+ import { LoadingMark } from "./LoadingMark";
4
5
  import type { PageProps } from "./Page";
5
6
 
6
7
  const CacheMap = new WeakMap<object, Record<string, unknown>>();
@@ -34,6 +35,7 @@ export const PageCSR = <Return,>({ of, loader, render, loading, noCache = false
34
35
  }
35
36
  })();
36
37
  }, []);
37
- if (!fetchState.fulfilled || !fetchState.value) return loading ? loading() : null;
38
+ if (!fetchState.fulfilled) return <LoadingMark>{loading?.()}</LoadingMark>;
39
+ if (!fetchState.value) return loading ? loading() : null;
38
40
  else return <>{render(fetchState.value)}</>;
39
41
  };
@@ -1,6 +1,7 @@
1
1
  import type { PromiseOrObject } from "akanjs/base";
2
2
  import { isThenable } from "akanjs/common";
3
3
  import { type ReactNode, Suspense, type Usable, use } from "react";
4
+ import { LoadingMark } from "./LoadingMark";
4
5
  import { StreamBoundary, type StreamError } from "./StreamBoundary";
5
6
  import { StreamDeferred } from "./StreamDeferred";
6
7
 
@@ -28,7 +29,8 @@ const resetKeyOf = (thenable: object) => {
28
29
  return key;
29
30
  };
30
31
 
31
- export default function Stream<Value>({ of, fallback = null, error, children }: StreamProps<Value>) {
32
+ export default function Stream<Value>({ of, fallback: shown = null, error, children }: StreamProps<Value>) {
33
+ const fallback = <LoadingMark>{shown}</LoadingMark>;
32
34
 
33
35
  if (isThenable(of) && process.env.AKAN_PUBLIC_RENDER_ENV === "csr")
34
36
  return (
package/ui/Load/Units.tsx CHANGED
@@ -13,6 +13,7 @@ import { Empty } from "../Empty";
13
13
  import { Loading } from "../Loading";
14
14
  import { More } from "../More";
15
15
  import { sliceNamesOf } from "../sliceNamesOf";
16
+ import { LoadingMark } from "./LoadingMark";
16
17
  import Stream from "./Stream";
17
18
  import type { StreamError } from "./StreamBoundary";
18
19
  import { SliceClaim } from "./sliceClaim";
@@ -229,7 +230,7 @@ function Render<RefName extends string, Light extends { id: string }>({
229
230
  ) : typeof renderEmpty === "function" ? (
230
231
  renderEmpty()
231
232
  ) : null}
232
- {showLoading ? loading : null}
233
+ {showLoading ? <LoadingMark>{loading}</LoadingMark> : null}
233
234
  </>
234
235
  );
235
236
  else if (!renderItem) throw new Error("renderItem is required");
@@ -256,7 +257,7 @@ function Render<RefName extends string, Light extends { id: string }>({
256
257
  ? renderEmpty()
257
258
  : null}
258
259
  </ContainerWrapper>
259
- {showLoading ? loading : null}
260
+ {showLoading ? <LoadingMark>{loading}</LoadingMark> : null}
260
261
  </>
261
262
  );
262
263
  }
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 });
@@ -457,9 +457,7 @@ export const ClientSsrBridge = ({ lang, prefix = "", initialPageState }: ClientS
457
457
  syncHref(href);
458
458
  return navigateRscWithFallback(href, { ...routeOptions, replace: true }, () => window.location.replace(href));
459
459
  },
460
- back: () => {
461
- csrLocation.back();
462
- },
460
+ back: () => csrLocation.back(),
463
461
  refresh: () => {
464
462
  syncHref(window.location.href);
465
463
  void refreshRsc();
@@ -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,
@@ -184,7 +184,13 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
184
184
  );
185
185
  if (drawn) return createElement(routeRender.render as never, { children, ...drawn } as never);
186
186
  if (!value || !isAsyncRender || isRefused)
187
- return <>{Translator.renderAt(renderPath, () => composeLoadingFallback(renders.slice(index), params))}</>;
187
+ return (
188
+ <>
189
+ {Translator.renderAt(renderPath, () => composeLoadingFallback(renders.slice(index), params))}
190
+ {/* The mark a `Load.*` fallback draws too, which the in-page agent's navigate waits out. */}
191
+ {isLoading ? <template data-akan-loading="" /> : null}
192
+ </>
193
+ );
188
194
  return <layerChildContext.Provider value={children}>{value}</layerChildContext.Provider>;
189
195
  });
190
196
 
@@ -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();
@@ -101,7 +114,7 @@ const useCsrRouter = ({
101
114
  const scrollTop = pageContentRef.current?.scrollTop ?? 0;
102
115
  setHistoryBack({ type: "back", location, scrollTop, scrollToTop });
103
116
  settle(getPrevLocation());
104
- csrLocation.back();
117
+ await csrLocation.back();
105
118
  },
106
119
  };
107
120
  window.onpopstate = async (event) => {
@@ -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 {