akanjs 3.3.0-rc.61 → 3.3.0-rc.63

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.
@@ -428,6 +428,8 @@ export const pageActivityContext = sharedContext<PageActivityState>("pageActivit
428
428
  export interface PathRoute {
429
429
  path: string;
430
430
  pathSegments: string[];
431
+ /** The pages matched ahead of this one that take some of its paths, as `/:lang/chat/new` does of `/:lang/chat/:id`. */
432
+ shadowedBy?: string[];
431
433
  renderPage: RouteRender;
432
434
  pageState: PageState;
433
435
  pageConfigChain?: PageConfig[];
package/client/index.ts CHANGED
@@ -189,6 +189,7 @@ export {
189
189
  RouteGuards,
190
190
  RouteHead,
191
191
  type RouteKind,
192
+ type RouteLoadingOption,
192
193
  type RouteModuleSource,
193
194
  type RoutePromptArgument,
194
195
  type RoutePromptMeta,
@@ -197,6 +198,7 @@ export {
197
198
  rootLayout,
198
199
  routeArgsMarker,
199
200
  routeDefinitionMarker,
201
+ routeLoadingAtPressMarker,
200
202
  } from "./route";
201
203
  export {
202
204
  AkanNotFoundError,
@@ -3,6 +3,13 @@ import { useSyncExternalStore } from "react";
3
3
 
4
4
  export interface PendingNavigationEntry {
5
5
  href: string;
6
+
7
+ from: string | null;
8
+
9
+ traversal: boolean;
10
+
11
+ waits: boolean;
12
+ left?: { promise: Promise<void>; resolve: () => void };
6
13
  }
7
14
 
8
15
  interface PendingNavigationStore {
@@ -23,16 +30,27 @@ export class PendingNavigation {
23
30
 
24
31
  static #set(entry: PendingNavigationEntry | null) {
25
32
  const store = PendingNavigation.#store();
33
+ const previous = store.entry;
26
34
  store.entry = entry;
35
+ if (previous !== entry) previous?.left?.resolve();
27
36
  for (const listener of [...store.listeners]) listener();
28
37
  }
29
38
 
30
- static begin(href: string): PendingNavigationEntry {
31
- const entry = { href };
39
+ static begin(
40
+ href: string,
41
+ { from = null, traversal = false }: { from?: string | null; traversal?: boolean } = {},
42
+ ): PendingNavigationEntry {
43
+ const entry: PendingNavigationEntry = { href, from, traversal, waits: false };
32
44
  PendingNavigation.#set(entry);
33
45
  return entry;
34
46
  }
35
47
 
48
+ static wait(entry: PendingNavigationEntry) {
49
+ if (entry.waits || PendingNavigation.#store().entry !== entry) return;
50
+ entry.waits = true;
51
+ PendingNavigation.#set(entry);
52
+ }
53
+
36
54
  static end(entry: PendingNavigationEntry) {
37
55
  if (PendingNavigation.#store().entry === entry) PendingNavigation.#set(null);
38
56
  }
@@ -42,9 +60,31 @@ export class PendingNavigation {
42
60
  }
43
61
 
44
62
  static get(): string | null {
63
+ const { entry } = PendingNavigation.#store();
64
+ return entry?.waits ? entry.href : null;
65
+ }
66
+
67
+ static target(): string | null {
45
68
  return PendingNavigation.#store().entry?.href ?? null;
46
69
  }
47
70
 
71
+ static entry(): PendingNavigationEntry | null {
72
+ return PendingNavigation.#store().entry;
73
+ }
74
+
75
+ /** Settles once `entry` is no longer the navigation in flight: it was drawn, it failed, or another began. */
76
+ static left(entry: PendingNavigationEntry): Promise<void> {
77
+ if (!entry.left) {
78
+ let resolve = () => {};
79
+ const promise = new Promise<void>((done) => {
80
+ resolve = done;
81
+ });
82
+ entry.left = { promise, resolve };
83
+ if (PendingNavigation.#store().entry !== entry) resolve();
84
+ }
85
+ return entry.left.promise;
86
+ }
87
+
48
88
  static subscribe(listener: () => void) {
49
89
  const { listeners } = PendingNavigation.#store();
50
90
  listeners.add(listener);
@@ -0,0 +1,29 @@
1
+ const partsOf = (path: string) => path.split("/").filter(Boolean);
2
+
3
+ export class PressLoading {
4
+
5
+ static readonly defaultDelayMs = 150;
6
+
7
+ static staysOnPage(pattern: string, shadowedBy: string[], from: string, to: string): boolean {
8
+ const fromParts = partsOf(new URL(from).pathname);
9
+ const toParts = partsOf(new URL(to).pathname);
10
+ if (fromParts.length !== toParts.length) return false;
11
+ const patternParts = partsOf(pattern);
12
+ const offset = patternParts.length - toParts.length;
13
+ let moved = false;
14
+ for (let index = 0; index < toParts.length; index++) {
15
+ if (fromParts[index] === toParts[index]) continue;
16
+ const part = patternParts[index + offset];
17
+ if (!part?.startsWith(":") || part === ":lang") return false;
18
+ moved = true;
19
+ }
20
+ if (!moved) return false;
21
+ return !shadowedBy.some((shadow) => {
22
+ const shadowParts = partsOf(shadow);
23
+ return toParts.every((value, index) => {
24
+ const part = shadowParts[index + offset];
25
+ return part === undefined || part.startsWith(":") || part === value;
26
+ });
27
+ });
28
+ }
29
+ }
@@ -11,6 +11,7 @@ import { deserialize } from "akanjs/constant";
11
11
  import { RenderScope } from "akanjs/fetch";
12
12
  import type { ReactNode } from "react";
13
13
  import type { Head, LayoutModule, PageConfig, PageModule, RouteGuardProps } from "../csrTypes";
14
+ import { PressLoading } from "../pressLoading";
14
15
  import { AkanNotFoundError, getRequestRoutePath } from "../router";
15
16
  import { Translator } from "../translator";
16
17
  import {
@@ -28,6 +29,16 @@ export type RouteKind = "page" | "layout" | "rootLayout";
28
29
  export const routeDefinitionMarker = Symbol.for("akan.routeDefinition");
29
30
  /** Interned like the marker: the declared args ride on the module's render function, read by the CSR render cache. */
30
31
  export const routeArgsMarker = Symbol.for("akan.routeArgs");
32
+ /** Interned like the marker: the delay of `.loading(…, { atPress })` rides on the module's `Loading`. */
33
+ export const routeLoadingAtPressMarker = Symbol.for("akan.routeLoadingAtPress");
34
+
35
+ export interface RouteLoadingOption {
36
+ /**
37
+ * Shows the fallback once a press to another path of this page (`/chat/a` to `/chat/b`) waits on the server, in
38
+ * place of the page being left. `true` waits 150 ms first. The fallback drawn is the one of the path being left.
39
+ */
40
+ atPress?: boolean | { delayMs: number };
41
+ }
31
42
 
32
43
  type HeadStage<Args> = Head | ((args: Args) => PromiseOrObject<Head | null | undefined>);
33
44
  type GuardStage<Args> = (args: Args, request: RouteGuardRequest) => void | Promise<void>;
@@ -56,6 +67,7 @@ export abstract class RouteDefinition<
56
67
  #head?: HeadStage<never>;
57
68
  #guard?: GuardStage<never>;
58
69
  #loading?: (args: never) => PromiseOrObject<ReactNode>;
70
+ #loadingAtPressMs?: number;
59
71
  #render?: (args: never) => PromiseOrObject<ReactNode>;
60
72
  #renderRoute?: {
61
73
  render: (args: never) => PromiseOrObject<ReactNode>;
@@ -78,8 +90,19 @@ export abstract class RouteDefinition<
78
90
  this.#guard = guard as GuardStage<never>;
79
91
  return this;
80
92
  }
81
- loading(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>) {
93
+ loading(
94
+ render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>,
95
+ { atPress = false }: RouteLoadingOption = {},
96
+ ) {
97
+ const delayMs = atPress === true ? PressLoading.defaultDelayMs : atPress ? atPress.delayMs : undefined;
98
+ if (delayMs !== undefined && this.kind !== "page")
99
+ throw new Error(
100
+ `[route-convention] ${this.kind}() takes no .loading(…, { atPress }); a press replaces the page under its layouts`,
101
+ );
102
+ if (delayMs !== undefined && !(Number.isFinite(delayMs) && delayMs >= 0))
103
+ throw new Error(`[route-convention] .loading(…, { atPress }) takes a delayMs of 0 or more, not ${delayMs}`);
82
104
  this.#loading = render as (args: never) => PromiseOrObject<ReactNode>;
105
+ this.#loadingAtPressMs = delayMs;
83
106
  return this;
84
107
  }
85
108
  render(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>) {
@@ -159,12 +182,7 @@ export abstract class RouteDefinition<
159
182
  await RenderScope.run(() => head(this.#argsOf(props) as never)),
160
183
  }
161
184
  : { head }),
162
- ...(loading
163
- ? {
164
- Loading: ((props: RouteRenderProps) =>
165
- RenderScope.run(() => loading(this.#argsOf({ ...props, searchParams: {} }) as never))) as never,
166
- }
167
- : {}),
185
+ ...(loading ? { Loading: this.#loadingRouteOf(loading) as never } : {}),
168
186
  };
169
187
  return this.extendModule(module);
170
188
  }
@@ -178,6 +196,14 @@ export abstract class RouteDefinition<
178
196
  return args;
179
197
  }
180
198
 
199
+ #loadingRouteOf(loading: (args: never) => PromiseOrObject<ReactNode>) {
200
+ const route = (props: RouteRenderProps) =>
201
+ RenderScope.run(() => loading(this.#argsOf({ ...props, searchParams: {} }) as never));
202
+ if (this.#loadingAtPressMs !== undefined)
203
+ Object.defineProperty(route, routeLoadingAtPressMarker, { value: this.#loadingAtPressMs });
204
+ return route;
205
+ }
206
+
181
207
  #guardRouteOf(guard: GuardStage<never>) {
182
208
  const route = async (props: RouteGuardProps) =>
183
209
  await RenderScope.run(() => {
@@ -9,7 +9,14 @@ declare global {
9
9
  var __AKAN_RSC_NAVIGATE__:
10
10
  | ((
11
11
  href: string,
12
- options?: { replace?: boolean; scrollToTop?: boolean; scrollY?: number; shallow?: boolean },
12
+ options?: {
13
+ replace?: boolean;
14
+ scrollToTop?: boolean;
15
+ scrollY?: number;
16
+ shallow?: boolean;
17
+ /** Back or Forward: the history entry is already the target's. */
18
+ traversal?: boolean;
19
+ },
13
20
  ) => Promise<void>)
14
21
  | undefined;
15
22
  var __AKAN_DEV_SYNC_NAVIGATION__: ((href: string, kind: "push" | "replace" | "back" | "pop") => void) | undefined;
@@ -16,7 +16,7 @@ export interface PendingLocation {
16
16
  searchParams: Record<string, string | string[]>;
17
17
  }
18
18
 
19
- /** The location a navigation is loading, from the press until its page is drawn; `null` with none in flight. */
19
+ /** The location a navigation is loading from the server, from the press until its page is drawn; else `null`. */
20
20
  export const usePendingNavigation = (): PendingLocation | null => {
21
21
  const pending = PendingNavigation.use((href) => href);
22
22
  const { lang } = usePage();
package/index.ts CHANGED
@@ -23,6 +23,11 @@ export interface DockerImageConfig {
23
23
  * for another architecture then never runs Bun emulated. A dependency's lifecycle script runs on the build machine.
24
24
  */
25
25
  crossBuild: boolean;
26
+ /**
27
+ * False when `image` was built with the base step already run (`DOCKER_BASE_RUNS` in `@akanjs/devkit/akanConfig`),
28
+ * so a builder with no layer cache does not repeat `apt-get` on every build.
29
+ */
30
+ baseSetup: boolean;
26
31
  /**
27
32
  * `ENV` lines laid over the build's own, as the image's defaults. The config is tracked and the image shows them,
28
33
  * so never a secret.
@@ -460,6 +465,24 @@ export interface AkanPlugin {
460
465
  syncAssets?: (ctx: AkanSyncContext) => Promise<void>;
461
466
  }
462
467
 
468
+ export interface AkanPreviewSignIn {
469
+ /** The dev server the preview opens its pages on. */
470
+ origin: string;
471
+ /** What `akan preview --as <name>` named, for an app with more than one kind of account. */
472
+ as: string | null;
473
+ }
474
+
475
+ /** Read live by `akan preview`; it carries a function, so it stays out of the serializable config results. */
476
+ export interface AkanPreviewConfig {
477
+ /**
478
+ * Signs in the pages a preview opens: the sign-in answer, whose `Set-Cookie` pairs become their cookies, or the
479
+ * cookies by name. Credentials are read from the environment here, never written in this file.
480
+ */
481
+ signIn?: (signIn: AkanPreviewSignIn) => Promise<Response | Record<string, string>>;
482
+ /** One concrete path per `[param]` route, without the locale, for `akan preview --changed` to open. */
483
+ examples?: string[];
484
+ }
485
+
463
486
  export interface AkanApiConfig {
464
487
  /** Where signal endpoints are mounted. Defaults to `/api`. */
465
488
  prefix: string;
@@ -544,6 +567,7 @@ export type AppConfigInput = Omit<DeepPartial<AppConfigResult>, "docker" | "web"
544
567
  native?: AkanNativeAppConfig;
545
568
  plugins?: AkanPlugin[];
546
569
  pipeline?: AppPipelineConfig;
570
+ preview?: AkanPreviewConfig;
547
571
  };
548
572
  export type LibConfigInput = Omit<DeepPartial<LibConfigResult>, "bin"> & {
549
573
  bin?: AkanBinConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.61",
3
+ "version": "3.3.0-rc.63",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -20,6 +20,7 @@ import {
20
20
  Suspense,
21
21
  } from "react";
22
22
  import { getExplicitPageConfigKeys, mergePageConfigs, resolvePageState } from "../client/frameConfig";
23
+ import { routeLoadingAtPressMarker } from "../client/route/RouteDefinition";
23
24
  import { RouteGuards } from "../client/route/RouteGuards";
24
25
  import { RouteHead } from "../client/route/RouteHead";
25
26
  import type { FallbackHead } from "./fallbackHead";
@@ -33,7 +34,7 @@ import {
33
34
  isAkanRscPartialCommitEnabled,
34
35
  } from "./routeState";
35
36
  import { RscRenderLevels } from "./rscRenderLevels";
36
- import { AkanSegmentOutletReference } from "./rscSegmentOutletReference";
37
+ import { AkanPressLoadingReference, AkanSegmentOutletReference } from "./rscSegmentOutletReference";
37
38
 
38
39
  /** How a render reached after the layouts streamed answers `router.notFound()` — in place, since its parents are out. */
39
40
  export interface RouteNotFoundInPlace {
@@ -140,6 +141,7 @@ export class RouteElementComposer {
140
141
  renders: RouteElementComposer.#getRenderStack(pathRoute),
141
142
  segments: isAkanRscPartialCommitEnabled() ? createAkanRouteSegments(pathRoute) : undefined,
142
143
  levelBoundary: pathRoute.levelBoundary,
144
+ page: pathRoute,
143
145
  params,
144
146
  searchParams,
145
147
  navKey,
@@ -262,6 +264,7 @@ export class RouteElementComposer {
262
264
  renders: renders.slice(patchStartIndex),
263
265
  owners: renders.slice(0, patchStartIndex),
264
266
  levelBoundary: pathRoute.levelBoundary,
267
+ page: pathRoute,
265
268
  params,
266
269
  searchParams,
267
270
  navKey,
@@ -370,6 +373,7 @@ export class RouteElementComposer {
370
373
  owners = [],
371
374
  segments,
372
375
  levelBoundary,
376
+ page,
373
377
  params,
374
378
  searchParams,
375
379
  navKey,
@@ -383,6 +387,8 @@ export class RouteElementComposer {
383
387
  /** Around each level below its owner: the Flight server only references it and React's server renderer runs no
384
388
  * error boundary, so a level failing before the first byte still takes its `.error()`. */
385
389
  levelBoundary?: OwnedLevelBoundary;
390
+ /** The route whose page is the last of `renders`, named so `.loading(…, { atPress })` knows its other paths. */
391
+ page?: Pick<PathRoute, "path" | "shadowedBy">;
386
392
  params: Record<string, string>;
387
393
  searchParams: Record<string, string | string[]>;
388
394
  navKey?: string;
@@ -399,6 +405,7 @@ export class RouteElementComposer {
399
405
  const loadingFallback = RouteElementComposer.#composeLoadingFallback(renders.slice(i), params);
400
406
  const suspenseKey =
401
407
  navKey && loadingFallback != null && i === renders.length - 1 ? `akan-loading:${navKey}` : undefined;
408
+ const pressDelayMs = suspenseKey && page ? RouteElementComposer.#loadingAtPressMsOf(routeRender) : undefined;
402
409
  const levelGate = levelGates[i];
403
410
 
404
411
  const Boundary = i > ownerIndex ? levelBoundary?.Boundary : undefined;
@@ -417,6 +424,9 @@ export class RouteElementComposer {
417
424
  element = (
418
425
  <Suspense key={suspenseKey} fallback={loadingFallback}>
419
426
  {Boundary ? <Boundary>{level}</Boundary> : level}
427
+ {page && pressDelayMs !== undefined ? (
428
+ <AkanPressLoadingReference pattern={page.path} shadowedBy={page.shadowedBy ?? []} delayMs={pressDelayMs} />
429
+ ) : null}
420
430
  {routeRender.Loading && levelGate ? <RouteShellGate.Wait until={levelGate.opened} /> : null}
421
431
  </Suspense>
422
432
  );
@@ -571,6 +581,10 @@ export class RouteElementComposer {
571
581
  return gates;
572
582
  }
573
583
 
584
+ static #loadingAtPressMsOf(routeRender: RouteRender): number | undefined {
585
+ return (routeRender.Loading as { [routeLoadingAtPressMarker]?: number } | undefined)?.[routeLoadingAtPressMarker];
586
+ }
587
+
574
588
  static #composeLoadingFallback(renders: RouteRender[], params: Record<string, string>): ReactNode {
575
589
  let element: ReactNode = null;
576
590
  for (let i = renders.length - 1; i >= 0; i--) {
@@ -77,7 +77,30 @@ export class RouteTreeBuilder {
77
77
 
78
78
  const rootRoute = this.#routeMap.get("/");
79
79
  if (!rootRoute) throw new AkanError("invalidRoute", "No root route");
80
- return this.#getPathRoutes(rootRoute).sort((a, b) => compareRouteSpecificity(a.path, b.path));
80
+ return RouteTreeBuilder.#withShadows(
81
+ this.#getPathRoutes(rootRoute).sort((a, b) => compareRouteSpecificity(a.path, b.path)),
82
+ );
83
+ }
84
+
85
+ static #withShadows(sorted: PathRoute[]): PathRoute[] {
86
+ const parts = sorted.map((pathRoute) => pathRoute.path.split("/").filter(Boolean));
87
+ const isParam = (part: string | undefined) => part?.startsWith(":") === true;
88
+ sorted.forEach((pathRoute, index) => {
89
+ const own = parts[index] ?? [];
90
+ if (!own.some((part) => isParam(part) && part !== ":lang")) return;
91
+ const shadowedBy = sorted
92
+ .slice(0, index)
93
+ .filter((_, ahead) => {
94
+ const other = parts[ahead] ?? [];
95
+ return (
96
+ other.length === own.length &&
97
+ other.every((part, at) => part === own[at] || isParam(part) || isParam(own[at]))
98
+ );
99
+ })
100
+ .map((ahead) => ahead.path);
101
+ if (shadowedBy.length) pathRoute.shadowedBy = shadowedBy;
102
+ });
103
+ return sorted;
81
104
  }
82
105
 
83
106
  getFallbackRoutes(): LayoutFallbackRoute[] {
@@ -573,7 +573,7 @@ function installNavigate(
573
573
  const navId = supersedeForPageNavigation();
574
574
  const target = normalizeHref(href);
575
575
  const signal = requestSignalOf(navId, target);
576
- const pending = PendingNavigation.begin(target);
576
+ const pending = PendingNavigation.begin(target, { from: renderedHref, traversal: options.traversal });
577
577
 
578
578
  let endsPending = true;
579
579
 
@@ -592,8 +592,10 @@ function installNavigate(
592
592
  commitRscPatchNavigation({ target, patch, fromCache, replace: options.replace, requestScroll });
593
593
  if (caches.replayPatch(target, navId, (patch) => commitPatch(patch, true))) return;
594
594
  const taken = caches.takePrefetch(target, signal);
595
+ if (!taken?.arrived) PendingNavigation.wait(pending);
595
596
  const prefetched = (await taken?.response) ?? undefined;
596
597
  if (signal.aborted) return;
598
+ if (!prefetched) PendingNavigation.wait(pending);
597
599
  servedFromCache = !!prefetched && !taken?.fresh;
598
600
  const fetched = await fetchRsc(target, {
599
601
  replaceOnRedirect,
@@ -611,6 +613,7 @@ function installNavigate(
611
613
  return;
612
614
  }
613
615
  caches.forgetPatch(target);
616
+ PendingNavigation.wait(pending);
614
617
  const fallback = await fetchRsc(target, {
615
618
  replaceOnRedirect,
616
619
  sendRouterState: false,
@@ -688,7 +691,7 @@ window.addEventListener("popstate", (event) => {
688
691
 
689
692
  if (!keepsPage)
690
693
  void globalThis
691
- .__AKAN_RSC_NAVIGATE__?.(window.location.href, { replace: true, scrollToTop: false, scrollY })
694
+ .__AKAN_RSC_NAVIGATE__?.(window.location.href, { replace: true, scrollToTop: false, scrollY, traversal: true })
692
695
  ?.catch((error: unknown) => hardNavigateAfterRscFailure(window.location.href, true, error));
693
696
  else {
694
697
 
@@ -6,6 +6,7 @@ interface RscPrefetchEntry<B> {
6
6
  whole: boolean;
7
7
  optedOut: boolean;
8
8
  startedAt: number;
9
+ arrived: boolean;
9
10
  controller: AbortController;
10
11
  response: Promise<Response | null>;
11
12
  release: () => void;
@@ -19,6 +20,8 @@ interface RscPrefetchQueued {
19
20
  export interface RscPrefetched {
20
21
  response: Promise<Response | null>;
21
22
  fresh: boolean;
23
+
24
+ arrived: boolean;
22
25
  }
23
26
 
24
27
  export interface RscPrefetchCacheOptions<B = undefined> {
@@ -120,7 +123,11 @@ export class RscPrefetchCache<B = undefined> {
120
123
  return null;
121
124
  }
122
125
  signal?.addEventListener("abort", () => entry.controller.abort(), { once: true });
123
- return { response: entry.response, fresh: this.#now() - entry.startedAt <= this.#freshMs };
126
+ return {
127
+ response: entry.response,
128
+ fresh: this.#now() - entry.startedAt <= this.#freshMs,
129
+ arrived: entry.arrived,
130
+ };
124
131
  }
125
132
 
126
133
  prune(): void {
@@ -181,6 +188,7 @@ export class RscPrefetchCache<B = undefined> {
181
188
  whole: false,
182
189
  optedOut: false,
183
190
  startedAt: this.#now(),
191
+ arrived: false,
184
192
  controller,
185
193
  response: this.#fetchResponse(href, controller.signal).then(
186
194
  (response) => {
@@ -199,10 +207,16 @@ export class RscPrefetchCache<B = undefined> {
199
207
 
200
208
  const [drain, branch] = response.body.tee();
201
209
  kept = branch;
202
- void RscPrefetchCache.#readToEnd(drain, controller.signal).then(settle, () => {
203
- forget();
204
- settle();
205
- });
210
+ void RscPrefetchCache.#readToEnd(drain, controller.signal).then(
211
+ () => {
212
+ entry.arrived = true;
213
+ settle();
214
+ },
215
+ () => {
216
+ forget();
217
+ settle();
218
+ },
219
+ );
206
220
  return new Response(branch, {
207
221
  status: response.status,
208
222
  statusText: response.statusText,
@@ -0,0 +1,40 @@
1
+ "use client";
2
+
3
+ import { use, useEffect, useState, useSyncExternalStore } from "react";
4
+ import { PendingNavigation, type PendingNavigationEntry } from "../client/pendingNavigation";
5
+ import { PressLoading } from "../client/pressLoading";
6
+
7
+ const none = () => null;
8
+
9
+ const pressOf = (born: PendingNavigationEntry | null) => {
10
+ const entry = PendingNavigation.entry();
11
+
12
+ return entry && entry !== born && entry.waits && !entry.traversal ? entry : null;
13
+ };
14
+
15
+ export function AkanPressLoading({
16
+ pattern,
17
+ shadowedBy,
18
+ delayMs,
19
+ }: {
20
+ pattern: string;
21
+ shadowedBy: string[];
22
+ delayMs: number;
23
+ }): null {
24
+ const [born] = useState(() => PendingNavigation.entry());
25
+ const press = useSyncExternalStore(PendingNavigation.subscribe, () => pressOf(born), none);
26
+ const [late, setLate] = useState(false);
27
+
28
+ const waiting =
29
+ !!press && (late || (!!press.from && PressLoading.staysOnPage(pattern, shadowedBy, press.from, press.href)));
30
+ useEffect(() => {
31
+ if (!waiting) {
32
+ setLate(false);
33
+ return;
34
+ }
35
+ const timer = setTimeout(() => setLate(true), delayMs);
36
+ return () => clearTimeout(timer);
37
+ }, [waiting, delayMs]);
38
+ if (press && late) use(PendingNavigation.left(press));
39
+ return null;
40
+ }
@@ -6,6 +6,8 @@ import { readRscRoutePatch, subscribeRscRoutePatch, writeRscRoutePatch } from ".
6
6
  import { useTransitionStore } from "../webkit/useTransitionStore";
7
7
  import type { AkanHeadSnapshotV1 } from "./routeState";
8
8
 
9
+ export { AkanPressLoading } from "./rscPressLoading";
10
+
9
11
  type RscSegmentThenable = PromiseLike<ReactNode>;
10
12
 
11
13
  interface RscSegmentOutletStore {
@@ -1,5 +1,5 @@
1
1
  import { AkanError } from "akanjs/base";
2
- import type { AkanRouteHead, AkanSegmentOutlet } from "./rscSegmentOutlet";
2
+ import type { AkanPressLoading, AkanRouteHead, AkanSegmentOutlet } from "./rscSegmentOutlet";
3
3
 
4
4
  const AKAN_SEGMENT_OUTLET_REFERENCE_ID = "pkgs/akanjs/server/rscSegmentOutlet.tsx";
5
5
 
@@ -24,3 +24,4 @@ function resolveAkanSegmentOutletReference<T>(exportName: string): T {
24
24
  export const AkanSegmentOutletReference =
25
25
  resolveAkanSegmentOutletReference<typeof AkanSegmentOutlet>("AkanSegmentOutlet");
26
26
  export const AkanRouteHeadReference = resolveAkanSegmentOutletReference<typeof AkanRouteHead>("AkanRouteHead");
27
+ export const AkanPressLoadingReference = resolveAkanSegmentOutletReference<typeof AkanPressLoading>("AkanPressLoading");
@@ -415,6 +415,8 @@ export declare const pageActivityContext: import("react").Context<PageActivitySt
415
415
  export interface PathRoute {
416
416
  path: string;
417
417
  pathSegments: string[];
418
+ /** The pages matched ahead of this one that take some of its paths, as `/:lang/chat/new` does of `/:lang/chat/:id`. */
419
+ shadowedBy?: string[];
418
420
  renderPage: RouteRender;
419
421
  pageState: PageState;
420
422
  pageConfigChain?: PageConfig[];
@@ -13,7 +13,7 @@ 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
15
  export { resolveServerUrl } from "./resolveServerUrl.d.ts";
16
- 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 RouteModuleSource, type RoutePromptArgument, type RoutePromptMeta, type RouteSearchType, resolveRouteModule, rootLayout, routeArgsMarker, routeDefinitionMarker, } from "./route.d.ts";
16
+ 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
17
  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";
18
18
  export { clearRscNavigationCache, isRscNavigationFromCache, navigateRsc, type PrefetchPriority, prefetchRsc, refreshRsc, } from "./rscNavigation.d.ts";
19
19
  export { scriptHashes, scriptNonce } from "./scriptPolicy.d.ts";
@@ -1,5 +1,12 @@
1
1
  export interface PendingNavigationEntry {
2
2
  href: string;
3
+ from: string | null;
4
+ traversal: boolean;
5
+ waits: boolean;
6
+ left?: {
7
+ promise: Promise<void>;
8
+ resolve: () => void;
9
+ };
3
10
  }
4
11
  interface PendingNavigationStore {
5
12
  entry: PendingNavigationEntry | null;
@@ -10,10 +17,18 @@ declare global {
10
17
  }
11
18
  export declare class PendingNavigation {
12
19
  #private;
13
- static begin(href: string): PendingNavigationEntry;
20
+ static begin(href: string, { from, traversal }?: {
21
+ from?: string | null;
22
+ traversal?: boolean;
23
+ }): PendingNavigationEntry;
24
+ static wait(entry: PendingNavigationEntry): void;
14
25
  static end(entry: PendingNavigationEntry): void;
15
26
  static clear(): void;
16
27
  static get(): string | null;
28
+ static target(): string | null;
29
+ static entry(): PendingNavigationEntry | null;
30
+ /** Settles once `entry` is no longer the navigation in flight: it was drawn, it failed, or another began. */
31
+ static left(entry: PendingNavigationEntry): Promise<void>;
17
32
  static subscribe(listener: () => void): () => void;
18
33
  static use<Value extends string | boolean | null>(select: (href: string | null) => Value): Value;
19
34
  }
@@ -0,0 +1,4 @@
1
+ export declare class PressLoading {
2
+ static readonly defaultDelayMs = 150;
3
+ static staysOnPage(pattern: string, shadowedBy: string[], from: string, to: string): boolean;
4
+ }
@@ -8,6 +8,17 @@ export type RouteKind = "page" | "layout" | "rootLayout";
8
8
  export declare const routeDefinitionMarker: unique symbol;
9
9
  /** Interned like the marker: the declared args ride on the module's render function, read by the CSR render cache. */
10
10
  export declare const routeArgsMarker: unique symbol;
11
+ /** Interned like the marker: the delay of `.loading(…, { atPress })` rides on the module's `Loading`. */
12
+ export declare const routeLoadingAtPressMarker: unique symbol;
13
+ export interface RouteLoadingOption {
14
+ /**
15
+ * Shows the fallback once a press to another path of this page (`/chat/a` to `/chat/b`) waits on the server, in
16
+ * place of the page being left. `true` waits 150 ms first. The fallback drawn is the one of the path being left.
17
+ */
18
+ atPress?: boolean | {
19
+ delayMs: number;
20
+ };
21
+ }
11
22
  type HeadStage<Args> = Head | ((args: Args) => PromiseOrObject<Head | null | undefined>);
12
23
  export interface RouteArgResolveOption {
13
24
  /** A prompt's arguments are strings a person typed: a list is comma-separated and a bad value is refused. */
@@ -23,7 +34,7 @@ export declare abstract class RouteDefinition<Args extends RouteArgsShape = Reco
23
34
  head(head: HeadStage<RouteBaseArgs & Args>): this;
24
35
  /** Runs before any layout body; refuses with `router.redirect()` or `router.notFound()`. */
25
36
  guard(guard: (args: RouteBaseArgs & Args, request: RouteGuardRequest) => void | Promise<void>): this;
26
- loading(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>): this;
37
+ loading(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>, { atPress }?: RouteLoadingOption): this;
27
38
  render(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>): this;
28
39
  get pageConfig(): PageConfig | undefined;
29
40
  protected declare(arg: RouteArgInfo): void;
@@ -12,6 +12,8 @@ declare global {
12
12
  scrollToTop?: boolean;
13
13
  scrollY?: number;
14
14
  shallow?: boolean;
15
+ /** Back or Forward: the history entry is already the target's. */
16
+ traversal?: boolean;
15
17
  }) => Promise<void>) | undefined;
16
18
  var __AKAN_DEV_SYNC_NAVIGATION__: ((href: string, kind: "push" | "replace" | "back" | "pop") => void) | undefined;
17
19
  var __AKAN_DEV_SYNC_NAVIGATION_APPLYING__: boolean | undefined;
@@ -6,5 +6,5 @@ export interface PendingLocation {
6
6
  path: string;
7
7
  searchParams: Record<string, string | string[]>;
8
8
  }
9
- /** The location a navigation is loading, from the press until its page is drawn; `null` with none in flight. */
9
+ /** The location a navigation is loading from the server, from the press until its page is drawn; else `null`. */
10
10
  export declare const usePendingNavigation: () => PendingLocation | null;
package/types/index.d.ts CHANGED
@@ -24,6 +24,11 @@ export interface DockerImageConfig {
24
24
  * for another architecture then never runs Bun emulated. A dependency's lifecycle script runs on the build machine.
25
25
  */
26
26
  crossBuild: boolean;
27
+ /**
28
+ * False when `image` was built with the base step already run (`DOCKER_BASE_RUNS` in `@akanjs/devkit/akanConfig`),
29
+ * so a builder with no layer cache does not repeat `apt-get` on every build.
30
+ */
31
+ baseSetup: boolean;
27
32
  /**
28
33
  * `ENV` lines laid over the build's own, as the image's defaults. The config is tracked and the image shows them,
29
34
  * so never a secret.
@@ -471,6 +476,22 @@ export interface AkanPlugin {
471
476
  /** Build-time asset generation (e.g. `public/firebase-messaging-sw.js`). */
472
477
  syncAssets?: (ctx: AkanSyncContext) => Promise<void>;
473
478
  }
479
+ export interface AkanPreviewSignIn {
480
+ /** The dev server the preview opens its pages on. */
481
+ origin: string;
482
+ /** What `akan preview --as <name>` named, for an app with more than one kind of account. */
483
+ as: string | null;
484
+ }
485
+ /** Read live by `akan preview`; it carries a function, so it stays out of the serializable config results. */
486
+ export interface AkanPreviewConfig {
487
+ /**
488
+ * Signs in the pages a preview opens: the sign-in answer, whose `Set-Cookie` pairs become their cookies, or the
489
+ * cookies by name. Credentials are read from the environment here, never written in this file.
490
+ */
491
+ signIn?: (signIn: AkanPreviewSignIn) => Promise<Response | Record<string, string>>;
492
+ /** One concrete path per `[param]` route, without the locale, for `akan preview --changed` to open. */
493
+ examples?: string[];
494
+ }
474
495
  export interface AkanApiConfig {
475
496
  /** Where signal endpoints are mounted. Defaults to `/api`. */
476
497
  prefix: string;
@@ -547,6 +568,7 @@ export type AppConfigInput = Omit<DeepPartial<AppConfigResult>, "docker" | "web"
547
568
  native?: AkanNativeAppConfig;
548
569
  plugins?: AkanPlugin[];
549
570
  pipeline?: AppPipelineConfig;
571
+ preview?: AkanPreviewConfig;
550
572
  };
551
573
  export type LibConfigInput = Omit<DeepPartial<LibConfigResult>, "bin"> & {
552
574
  bin?: AkanBinConfig;
@@ -113,7 +113,7 @@ export declare class RouteElementComposer {
113
113
  gate?: RouteShellGate;
114
114
  head?: FallbackHead;
115
115
  }): Promise<ReactNode | null>;
116
- static composeRenders({ renders, owners, segments, levelBoundary, params, searchParams, navKey, notFound, gate, }: {
116
+ static composeRenders({ renders, owners, segments, levelBoundary, page, params, searchParams, navKey, notFound, gate, }: {
117
117
  renders: RouteRender[];
118
118
  /** Layouts above `renders` that this element leaves out (a patch) but whose `.notFound()` still applies. */
119
119
  owners?: RouteRender[];
@@ -121,6 +121,8 @@ export declare class RouteElementComposer {
121
121
  /** Around each level below its owner: the Flight server only references it and React's server renderer runs no
122
122
  * error boundary, so a level failing before the first byte still takes its `.error()`. */
123
123
  levelBoundary?: OwnedLevelBoundary;
124
+ /** The route whose page is the last of `renders`, named so `.loading(…, { atPress })` knows its other paths. */
125
+ page?: Pick<PathRoute, "path" | "shadowedBy">;
124
126
  params: Record<string, string>;
125
127
  searchParams: Record<string, string | string[]>;
126
128
  navKey?: string;
@@ -2,6 +2,7 @@ import type { PrefetchPriority } from "../client/rscNavigation.d.ts";
2
2
  export interface RscPrefetched {
3
3
  response: Promise<Response | null>;
4
4
  fresh: boolean;
5
+ arrived: boolean;
5
6
  }
6
7
  export interface RscPrefetchCacheOptions<B = undefined> {
7
8
  fetchResponse: (href: string, signal: AbortSignal) => Promise<Response>;
@@ -0,0 +1,5 @@
1
+ export declare function AkanPressLoading({ pattern, shadowedBy, delayMs, }: {
2
+ pattern: string;
3
+ shadowedBy: string[];
4
+ delayMs: number;
5
+ }): null;
@@ -1,5 +1,6 @@
1
1
  import { type ReactNode } from "react";
2
2
  import type { AkanHeadSnapshotV1 } from "./routeState.d.ts";
3
+ export { AkanPressLoading } from "./rscPressLoading.d.ts";
3
4
  type RscSegmentThenable = PromiseLike<ReactNode>;
4
5
  interface RscSegmentOutletStore {
5
6
  entries: Map<string, RscSegmentThenable>;
@@ -19,4 +20,3 @@ export declare function AkanRouteHead({ layouts, page }: {
19
20
  layouts: AkanHeadSnapshotV1;
20
21
  page: AkanHeadSnapshotV1;
21
22
  }): ReactNode;
22
- export {};
@@ -1,3 +1,4 @@
1
- import type { AkanRouteHead, AkanSegmentOutlet } from "./rscSegmentOutlet.d.ts";
1
+ import type { AkanPressLoading, AkanRouteHead, AkanSegmentOutlet } from "./rscSegmentOutlet.d.ts";
2
2
  export declare const AkanSegmentOutletReference: typeof AkanSegmentOutlet;
3
3
  export declare const AkanRouteHeadReference: typeof AkanRouteHead;
4
+ export declare const AkanPressLoadingReference: typeof AkanPressLoading;
@@ -12,7 +12,7 @@ export type CommonLinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "hre
12
12
  activeExact?: boolean;
13
13
  /** More paths under which the link counts as active, as a tab does for its detail pages. */
14
14
  activeMatch?: string[];
15
- /** Applied, with `data-pending`, while a page this link would be active on is still loading. */
15
+ /** Applied, with `data-pending`, while a page this link would be active on loads from the server. */
16
16
  pendingClassName?: string;
17
17
  /** @deprecated Has no effect: neither renderer reads it. */
18
18
  noCache?: boolean;
@@ -84,6 +84,7 @@ export declare function resolvePathRoutesWithFrameState(pathRoutes: PathRoute[],
84
84
  pageState: PageState;
85
85
  path: string;
86
86
  pathSegments: string[];
87
+ shadowedBy?: string[];
87
88
  renderPage: import("akanjs/client").RouteRender;
88
89
  pageConfigChain?: import("akanjs/client").PageConfig[];
89
90
  explicitPageConfigKeys?: Partial<Record<keyof import("akanjs/client").PageConfig, boolean>>;
@@ -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
+ shadowedBy?: string[];
20
21
  renderPage: import("akanjs/client").RouteRender;
21
22
  pageConfigChain?: import("akanjs/client").PageConfig[];
22
23
  explicitPageConfigKeys?: Partial<Record<keyof import("akanjs/client").PageConfig, boolean>>;
@@ -29,7 +29,7 @@ export type CommonLinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "hre
29
29
  activeExact?: boolean;
30
30
  /** More paths under which the link counts as active, as a tab does for its detail pages. */
31
31
  activeMatch?: string[];
32
- /** Applied, with `data-pending`, while a page this link would be active on is still loading. */
32
+ /** Applied, with `data-pending`, while a page this link would be active on loads from the server. */
33
33
  pendingClassName?: string;
34
34
  /** @deprecated Has no effect: neither renderer reads it. */
35
35
  noCache?: boolean;
@@ -434,7 +434,7 @@ export const ClientSsrBridge = ({ lang, prefix = "", initialPageState }: ClientS
434
434
  };
435
435
 
436
436
  const followPending = PendingNavigation.subscribe(() => {
437
- const pending = PendingNavigation.get();
437
+ const pending = PendingNavigation.target();
438
438
  if (!pending) return;
439
439
  const { pathname, search } = new URL(pending);
440
440
  const shown = ShellState.get();