akanjs 3.3.0-rc.16 → 3.3.0-rc.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -337,6 +337,12 @@
337
337
 
338
338
  (`document.readyState !== "loading"` for `DOMContentLoaded`.) A browser test that clicks or types as soon as navigation reports `load` can meet a page that has not hydrated: wait for something only the hydrated page does, such as the result of the action under a retrying assertion or a marker a client component sets in an effect, instead of `load`. If a proxy or CDN in front of the app sets its own `Content-Security-Policy-Report-Only`, set `AKAN_CONTENT_SECURITY_POLICY_REPORT_ONLY=off` or let the app's header through.
339
339
 
340
+ - f4b5aa6: A page switched in place (a tab, any move with `transition: "none"`) is now drawn before it shows, and an Android app's back button closes an open dialog before it leaves the page.
341
+
342
+ A page that draws later (an async render, or a guard on it or on a layout above it) used to swap in at once and show its loading fallbacks, so every tab switch flashed a shell. Such a page is now mounted out of sight and takes the screen once its layers are drawn, or after 300ms with whatever it has, so a slow page still answers the tap. A page that draws in the commit it mounts in, and one the stack already holds (a tab kept by `cache`, the page under the current one), switch at once as before. The page left under the current one stays asleep through that wait, so its effects do not run again for a page nobody sees.
343
+
344
+ Android's back button and back swipe now close the newest open surface (a modal, a sheet, a confirm) and only leave the page once none is open: Escape and back share the one stack `useEscapeKey` registers on. `useEscapeKey(active, onEscape, { back: false })` keeps the back button for the page, which `Tooltip` uses: a tap focuses a button on Android, so its tooltip would otherwise swallow the next back press. The third argument is optional, so no upgrade step is needed.
345
+
340
346
  - 4225827: A trace's spans say where they ran and when, database calls are spans of their own, and a developer can read a call's timing from the response.
341
347
 
342
348
  - `SpanRecord` gains `id`, `parentId`, `startMs` and optional `attrs` beside `name` and `durationMs`. The call's own span is `total`, with the trace's `spanId` as its id and its caller's span as its parent; it is recorded even when the call ran past the 64-span limit.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.16",
3
+ "version": "3.3.0-rc.18",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -47,6 +47,7 @@ export declare class CsrStack {
47
47
  */
48
48
  static redrawFor(history: History, current: Location, token: string | null): boolean;
49
49
  static leave(history: History, current: Location): void;
50
- static entriesOf({ history, location, prevLocation, pendingLocation, phase }: CsrStackState): CsrStackEntry[];
50
+ static entriesOf(state: CsrStackState): CsrStackEntry[];
51
+ static holds(state: CsrStackState, target: Location): boolean;
51
52
  }
52
53
  export {};
@@ -0,0 +1,18 @@
1
+ import type { Location, RouteRender } from "akanjs/client";
2
+ /**
3
+ * Whether a page's layers are drawn, by the entry id of the location they draw: each layer reports while it shows its
4
+ * loading fallback. A page switched in place waits on this, out of sight, so it never swaps in a shell of fallbacks.
5
+ */
6
+ export declare class CsrPageReadiness {
7
+ #private;
8
+ static report(entryId: string, layerId: string, isLoading: boolean): void;
9
+ static drop(entryId: string, layerId: string): void;
10
+ static isAsync(render?: RouteRender): boolean;
11
+ /**
12
+ * Whether a page shows a fallback before it is drawn: only an async render or a guard makes a layer wait. A root
13
+ * layout is drawn once for every page, so only its guard, asked for each page, counts.
14
+ */
15
+ static drawsLater(location: Location): boolean;
16
+ /** `false` until a layer of the page has reported, and while any of them shows its fallback. */
17
+ static isDrawn(entryId: string | undefined): boolean;
18
+ }
@@ -27,8 +27,8 @@ export declare class NativeNavigation {
27
27
  showPushesExcept(pathname: string): void;
28
28
  listen(): () => void;
29
29
  /**
30
- * Tells an Android shell whether back is the page's right now: the keyboard is up, there is history, or the
31
- * index is still to come. Otherwise the system takes it and shows its own back-to-home animation.
30
+ * Tells an Android shell whether back is the page's right now: the keyboard is up, a dialog or sheet is open, there
31
+ * is history, or the index is still to come. Otherwise the system takes it and shows its own back-to-home animation.
32
32
  */
33
33
  syncBack(force?: boolean): void;
34
34
  openDeepLink(url: string): void;
@@ -0,0 +1,6 @@
1
+ import { type Location } from "akanjs/client";
2
+ export declare class NativeSplash {
3
+ #private;
4
+ static readonly drawTimeoutMs = 4000;
5
+ static hideOnceDrawn(location: Location): () => void;
6
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The surfaces open on the page (dialogs, sheets, confirms), newest last. Escape and an app's back button close the
3
+ * newest one only: per-component listeners would all hear one key and close nested surfaces together.
4
+ */
5
+ export declare class OpenSurfaces {
6
+ #private;
7
+ static open(close: () => void, { takesBack }?: {
8
+ takesBack?: boolean;
9
+ }): () => void;
10
+ static closeForBack(): boolean;
11
+ static takesBack(): boolean;
12
+ static listen(listener: () => void): () => void;
13
+ }
@@ -13,7 +13,7 @@ interface CsrNavigationInput {
13
13
  frame: ResolvedFrame;
14
14
  keyboard: CsrKeyboard;
15
15
  }
16
- export declare const useCsrNavigation: ({ viewport, slots, setTransitionPageStateSnapshot, refs, nav, frame, keyboard: { keyboardFrame }, }: CsrNavigationInput) => {
16
+ export declare const useCsrNavigation: (input: CsrNavigationInput) => {
17
17
  shouldPrepareFrameTransition: (nextHref?: string) => boolean;
18
18
  startFrameTransition: () => Promise<void>;
19
19
  settle: (prev: LocationState["prevLocation"]) => void;
@@ -1,2 +1,7 @@
1
- /** Calls `onEscape` on Escape while `active` and this surface is the topmost active one. */
2
- export declare const useEscapeKey: (active: boolean, onEscape: () => void) => void;
1
+ /**
2
+ * Calls `onEscape` on Escape, or an app's back button, while `active` and this surface is the newest active one.
3
+ * `back: false` leaves the back button to the page: for a hint the person did not open, such as a tooltip.
4
+ */
5
+ export declare const useEscapeKey: (active: boolean, onEscape: () => void, { back }?: {
6
+ back?: boolean;
7
+ }) => void;
@@ -4,6 +4,7 @@ export type FrameSlotBucket = "active" | "pending";
4
4
  export type FrameSlotMapByBucket = Record<FrameSlotBucket, FrameSlotMap>;
5
5
  export declare const PENDING_FRAME_READY_TIMEOUT_MS = 80;
6
6
  export declare const PENDING_FRAME_READY_MAX_TIMEOUT_MS = 120;
7
+ export declare const STACK_TRANSITION_DURATION_MS = 350;
7
8
  export declare const KEYBOARD_SHOW_ANIMATION_DURATION_MS = 420;
8
9
  export declare const KEYBOARD_HIDE_ANIMATION_DURATION_MS = 90;
9
10
  export declare const KEYBOARD_SHOW_ANIMATION_EASING = "cubic-bezier(0.16, 1, 0.3, 1)";
package/ui/System/CSR.tsx CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  useState,
27
27
  } from "react";
28
28
  import { createPortal } from "react-dom";
29
+ import { NativeSplash } from "../../webkit/nativeSplash";
29
30
  import { NativeUpdates } from "../../webkit/nativeUpdates";
30
31
  import { RenderLayer } from "../../webkit/RenderLayer";
31
32
  import { animated } from "../animated";
@@ -435,6 +436,10 @@ const CSRPageContainer = ({ entry, prefix, layoutStyle }: CSRPageContainerProps)
435
436
  useEffect(() => {
436
437
  if (pageType === "current") NativeUpdates.confirm();
437
438
  }, [pageType]);
439
+ useEffect(
440
+ () => (pageType === "current" ? NativeSplash.hideOnceDrawn(location) : undefined),
441
+ [pageType, location.entryId],
442
+ );
438
443
 
439
444
  const [pageContainers, setPageContainers] = useState(() => document.getElementById("pageContainers"));
440
445
  useLayoutEffect(() => {
@@ -453,12 +458,12 @@ const CSRPageContainer = ({ entry, prefix, layoutStyle }: CSRPageContainerProps)
453
458
  ? { page: prevPage, pageContentRef: prevPageContentRef, pageClassName: "", pageBind: () => ({}) }
454
459
  : { page: null, pageContentRef: null, pageClassName: "", pageBind: () => ({}) };
455
460
 
461
+ const isLeftInPlace =
462
+ pageType === "prev" &&
463
+ currentLocation.pathRoute.pageState.transition === "none" &&
464
+ (csr.phase === "idle" || csr.pendingLocation?.pathRoute.pageState.transition === "none");
456
465
  const activity: PageActivity =
457
- pageType === "cached" ||
458
- (pageType === "prev" &&
459
- (csr.isBackgrounded || (currentLocation.pathRoute.pageState.transition === "none" && csr.phase === "idle")))
460
- ? "hidden"
461
- : pageType;
466
+ pageType === "cached" || (pageType === "prev" && csr.isBackgrounded) || isLeftInPlace ? "hidden" : pageType;
462
467
  return (
463
468
  <Activity mode={activity === "hidden" ? "hidden" : "visible"}>
464
469
  {createPortal(
package/ui/Tooltip.tsx CHANGED
@@ -52,7 +52,7 @@ const DefaultTooltip = ({ content, children, side = "top", className, variant =
52
52
  showTimer.current = null;
53
53
  };
54
54
  useEffect(() => cancelShow, []);
55
- useEscapeKey(open, () => setOpen(false));
55
+ useEscapeKey(open, () => setOpen(false), { back: false });
56
56
  if (content === undefined || content === null || content === "") return <>{children}</>;
57
57
  const landed = position?.side ?? side;
58
58
  const vertical = landed === "top" || landed === "bottom";
@@ -121,7 +121,22 @@ export class CsrStack {
121
121
  delete history.account.leaving;
122
122
  }
123
123
 
124
- static entriesOf({ history, location, prevLocation, pendingLocation, phase }: CsrStackState): CsrStackEntry[] {
124
+ static entriesOf(state: CsrStackState): CsrStackEntry[] {
125
+ const { account } = state.history;
126
+ const drawn = (entry: CsrStackEntry) => {
127
+ const kept = account?.leaving?.key === entry.key && (entry.pageType === "current" || state.phase !== "idle");
128
+ const generation = (kept ? account?.leaving?.generation : account?.generation) ?? 0;
129
+ return generation ? { ...entry, key: `${generation}:${entry.key}` } : entry;
130
+ };
131
+
132
+ return [...CsrStack.#claimed(state).values()].sort((a, b) => (a.key < b.key ? -1 : 1)).map(drawn);
133
+ }
134
+
135
+ static holds(state: CsrStackState, target: Location) {
136
+ return CsrStack.#claimed(state).has(CsrStack.keyOf(target));
137
+ }
138
+
139
+ static #claimed({ history, location, prevLocation, pendingLocation, phase }: CsrStackState) {
125
140
  const entries = new Map<string, CsrStackEntry>();
126
141
  const claim = (entryLocation: Location, pageType: CsrPageType, zIndex: number) => {
127
142
  const key = CsrStack.keyOf(entryLocation);
@@ -139,13 +154,6 @@ export class CsrStack {
139
154
  retained += 1;
140
155
  }
141
156
  for (const cached of history.cachedLocationMap.values()) if (!dormant(cached)) claim(cached, "cached", 0);
142
- const { account } = history;
143
- const drawn = (entry: CsrStackEntry) => {
144
- const kept = account?.leaving?.key === entry.key && (entry.pageType === "current" || phase !== "idle");
145
- const generation = (kept ? account?.leaving?.generation : account?.generation) ?? 0;
146
- return generation ? { ...entry, key: `${generation}:${entry.key}` } : entry;
147
- };
148
-
149
- return [...entries.values()].sort((a, b) => (a.key < b.key ? -1 : 1)).map(drawn);
157
+ return entries;
150
158
  }
151
159
  }
@@ -8,12 +8,14 @@ import {
8
8
  type ReactNode,
9
9
  useContext,
10
10
  useEffect,
11
+ useId,
11
12
  useRef,
12
13
  useState,
13
14
  useSyncExternalStore,
14
15
  } from "react";
15
16
  import { CsrGuards } from "./CsrGuards";
16
17
  import { CsrFrameDump } from "./csrFrameDump";
18
+ import { CsrPageReadiness } from "./csrPageReadiness";
17
19
  import { CsrRefresh } from "./csrRefresh";
18
20
  import { RenderFailure } from "./RenderFailure";
19
21
  import { useFetch } from "./useFetch";
@@ -57,7 +59,7 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
57
59
  <RenderLayer renders={renders} index={index + 1} params={params} searchParams={searchParams} leaf={leaf} />
58
60
  );
59
61
  const routeRender = renders[index];
60
- const isAsyncRender = isAsyncRouteRender(routeRender);
62
+ const isAsyncRender = CsrPageReadiness.isAsync(routeRender);
61
63
  const renderedRef = useRef<RenderedRoute | null>(null);
62
64
  const [, setFailures] = useState(0);
63
65
  const activity = usePageActivity();
@@ -194,10 +196,14 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
194
196
  record.subscribed = false;
195
197
  };
196
198
  }, [record]);
197
- if (!routeRender) return null;
198
- if (!isAsyncRender && (!guarded || isSyncAdmitted))
199
- return createElement(routeRender.render as never, { children, params, searchParams } as never);
199
+ const isSyncDrawn = !isAsyncRender && (!guarded || isSyncAdmitted);
200
200
  const failure = renderedRef.current?.failure;
201
+ const isRefused = isRefusedAt(renderedRef.current, locationId, fulfilled);
202
+ const drawn = isAsyncRender || isRefused ? null : drawnPropsRef.current;
203
+ const isLoading = !!routeRender && !isSyncDrawn && !failure && !isRefused && !drawn && (!value || !isAsyncRender);
204
+ useLayerReadiness(location?.entryId, isLoading);
205
+ if (!routeRender) return null;
206
+ if (isSyncDrawn) return createElement(routeRender.render as never, { children, params, searchParams } as never);
201
207
  if (failure)
202
208
  return (
203
209
  <RenderFailure
@@ -208,17 +214,24 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
208
214
  }}
209
215
  />
210
216
  );
211
-
212
- const isRefused =
213
- (!!locationId && renderedRef.current?.refusedAt === locationId) ||
214
- (!!renderedRef.current?.afterRefusal && !fulfilled);
215
- const drawn = isAsyncRender || isRefused ? null : drawnPropsRef.current;
216
217
  if (drawn) return createElement(routeRender.render as never, { children, ...drawn } as never);
217
218
  if (!value || !isAsyncRender || isRefused)
218
219
  return <>{Translator.renderAt(renderPath, () => composeLoadingFallback(renders.slice(index), params))}</>;
219
220
  return <layerChildContext.Provider value={children}>{value}</layerChildContext.Provider>;
220
221
  });
221
222
 
223
+ function isRefusedAt(rendered: RenderedRoute | null, locationId: string | null, fulfilled: boolean): boolean {
224
+ return (!!locationId && rendered?.refusedAt === locationId) || (!!rendered?.afterRefusal && !fulfilled);
225
+ }
226
+
227
+ const useLayerReadiness = (entryId: string | undefined, isLoading: boolean) => {
228
+ const layerId = useId();
229
+ useEffect(() => {
230
+ if (entryId) CsrPageReadiness.report(entryId, layerId, isLoading);
231
+ }, [entryId, isLoading]);
232
+ useEffect(() => (entryId ? () => CsrPageReadiness.drop(entryId, layerId) : undefined), [entryId]);
233
+ };
234
+
222
235
  interface LayerRun {
223
236
  render: RouteRender["render"];
224
237
  argsKey: string;
@@ -262,10 +275,6 @@ function entryPathOf(pathname: string | undefined): string | undefined {
262
275
  return new URL(`http://localhost${pathname}`).pathname;
263
276
  }
264
277
 
265
- function isAsyncRouteRender(routeRender?: RouteRender): boolean {
266
- return Boolean(routeRender?.isAsync || routeRender?.render.constructor.name === "AsyncFunction");
267
- }
268
-
269
278
  function composeLoadingFallback(renders: RouteRender[], params: Record<string, string>): ReactNode {
270
279
  let element: ReactNode = null;
271
280
  for (let i = renders.length - 1; i >= 0; i--) {
@@ -0,0 +1,43 @@
1
+ import type { Location, RouteRender } from "akanjs/client";
2
+ import { CsrGuards } from "./CsrGuards";
3
+
4
+ /**
5
+ * Whether a page's layers are drawn, by the entry id of the location they draw: each layer reports while it shows its
6
+ * loading fallback. A page switched in place waits on this, out of sight, so it never swaps in a shell of fallbacks.
7
+ */
8
+ export class CsrPageReadiness {
9
+
10
+ static readonly #pages = new Map<string, Map<string, boolean>>();
11
+
12
+ static report(entryId: string, layerId: string, isLoading: boolean) {
13
+ const layers = CsrPageReadiness.#pages.get(entryId) ?? new Map<string, boolean>();
14
+ layers.set(layerId, isLoading);
15
+ CsrPageReadiness.#pages.set(entryId, layers);
16
+ }
17
+
18
+ static drop(entryId: string, layerId: string) {
19
+ const layers = CsrPageReadiness.#pages.get(entryId);
20
+ if (!layers) return;
21
+ layers.delete(layerId);
22
+ if (!layers.size) CsrPageReadiness.#pages.delete(entryId);
23
+ }
24
+
25
+ static isAsync(render?: RouteRender) {
26
+ return Boolean(render?.isAsync || render?.render?.constructor.name === "AsyncFunction");
27
+ }
28
+
29
+ /**
30
+ * Whether a page shows a fallback before it is drawn: only an async render or a guard makes a layer wait. A root
31
+ * layout is drawn once for every page, so only its guard, asked for each page, counts.
32
+ */
33
+ static drawsLater(location: Location) {
34
+ const { renderLayouts, renderPage } = location.pathRoute;
35
+ return CsrGuards.declared(location) || [...renderLayouts, renderPage].some(CsrPageReadiness.isAsync);
36
+ }
37
+
38
+ /** `false` until a layer of the page has reported, and while any of them shows its fallback. */
39
+ static isDrawn(entryId: string | undefined) {
40
+ const layers = entryId ? CsrPageReadiness.#pages.get(entryId) : undefined;
41
+ return !!layers?.size && ![...layers.values()].some(Boolean);
42
+ }
43
+ }
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { router as clientRouter, debugFrame, normalizeDeepLinkHref } from "akanjs/client";
3
3
  import { app, appState, desktopPlatform, isNativeApp, push } from "akanjs/client/native";
4
+ import { OpenSurfaces } from "./openSurfaces";
4
5
 
5
6
  export interface NativeBackState {
6
7
  path: string;
@@ -67,9 +68,12 @@ export class NativeNavigation {
67
68
  this.back();
68
69
  }),
69
70
  app.listen("backProgress", ({ phase, progress }) => {
71
+
72
+ if (OpenSurfaces.takesBack()) return;
70
73
  if (phase !== "progressed") debugFrame("native.backProgress", { phase });
71
74
  this.options.onBackProgress?.({ phase, progress });
72
75
  }),
76
+ OpenSurfaces.listen(() => this.syncBack()),
73
77
  appState.listen("memoryWarning", ({ level }) => {
74
78
  debugFrame("native.memoryWarning", { level });
75
79
  this.options.onMemoryWarning?.();
@@ -87,13 +91,17 @@ export class NativeNavigation {
87
91
  }
88
92
 
89
93
  /**
90
- * Tells an Android shell whether back is the page's right now: the keyboard is up, there is history, or the
91
- * index is still to come. Otherwise the system takes it and shows its own back-to-home animation.
94
+ * Tells an Android shell whether back is the page's right now: the keyboard is up, a dialog or sheet is open, there
95
+ * is history, or the index is still to come. Otherwise the system takes it and shows its own back-to-home animation.
92
96
  */
93
97
  syncBack(force = false) {
94
98
  if (!isNativeApp() || !app.isSupported("setBackEnabled")) return;
95
99
  const backState = this.options.backState();
96
- const enabled = backState.keyboardVisible || this.options.historyIdx() > 0 || !this.#leavesApp(backState.path);
100
+ const enabled =
101
+ backState.keyboardVisible ||
102
+ OpenSurfaces.takesBack() ||
103
+ this.options.historyIdx() > 0 ||
104
+ !this.#leavesApp(backState.path);
97
105
  if (!force && enabled === this.#backEnabled) return;
98
106
  this.#backEnabled = enabled;
99
107
  void app.setBackEnabled({ enabled }).catch(() => undefined);
@@ -136,6 +144,7 @@ export class NativeNavigation {
136
144
  void this.options.dismissKeyboard();
137
145
  return;
138
146
  }
147
+ if (OpenSurfaces.closeForBack()) return;
139
148
  if (this.options.historyIdx() > 0) {
140
149
  backState.router.back();
141
150
  void clientRouter.navigation().catch(() => this.options.onBackProgress?.({ phase: "cancelled", progress: 0 }));
@@ -0,0 +1,30 @@
1
+ "use client";
2
+ import { debugFrame, type Location } from "akanjs/client";
3
+ import { isNativeShell } from "akanjs/client/native";
4
+ import { splashScreen } from "akanjs/client/native/splash-screen";
5
+ import { CsrPageReadiness } from "./csrPageReadiness";
6
+
7
+ export class NativeSplash {
8
+ static readonly drawTimeoutMs = 4_000;
9
+ static #hidden = false;
10
+
11
+ static hideOnceDrawn(location: Location) {
12
+ if (NativeSplash.#hidden || !isNativeShell() || !splashScreen.isSupported("hide")) return () => undefined;
13
+ const startedAt = Date.now();
14
+ let frame = 0;
15
+ const isDrawn = () =>
16
+ !CsrPageReadiness.drawsLater(location) ||
17
+ CsrPageReadiness.isDrawn(location.entryId) ||
18
+ Date.now() - startedAt >= NativeSplash.drawTimeoutMs;
19
+ const hide = () => {
20
+ NativeSplash.#hidden = true;
21
+ void splashScreen.hide().catch((error: unknown) => debugFrame("splash.hide.failed", { error: String(error) }));
22
+ };
23
+
24
+ const check = () => {
25
+ frame = requestAnimationFrame(isDrawn() ? hide : check);
26
+ };
27
+ frame = requestAnimationFrame(check);
28
+ return () => cancelAnimationFrame(frame);
29
+ }
30
+ }
@@ -0,0 +1,54 @@
1
+ interface OpenSurface {
2
+ close: () => void;
3
+ takesBack: boolean;
4
+ }
5
+
6
+ /**
7
+ * The surfaces open on the page (dialogs, sheets, confirms), newest last. Escape and an app's back button close the
8
+ * newest one only: per-component listeners would all hear one key and close nested surfaces together.
9
+ */
10
+ export class OpenSurfaces {
11
+ static readonly #stack: OpenSurface[] = [];
12
+ static readonly #listeners = new Set<() => void>();
13
+
14
+ static open(close: () => void, { takesBack = true }: { takesBack?: boolean } = {}) {
15
+ const surface: OpenSurface = { close, takesBack };
16
+ OpenSurfaces.#stack.push(surface);
17
+ if (OpenSurfaces.#stack.length === 1) window.addEventListener("keydown", OpenSurfaces.#onKeyDown);
18
+ OpenSurfaces.#notify();
19
+ return () => {
20
+ const index = OpenSurfaces.#stack.lastIndexOf(surface);
21
+ if (index !== -1) OpenSurfaces.#stack.splice(index, 1);
22
+ if (OpenSurfaces.#stack.length === 0) window.removeEventListener("keydown", OpenSurfaces.#onKeyDown);
23
+ OpenSurfaces.#notify();
24
+ };
25
+ }
26
+
27
+ static closeForBack() {
28
+ const newest = OpenSurfaces.#stack.findLast((surface) => surface.takesBack);
29
+ newest?.close();
30
+ return !!newest;
31
+ }
32
+
33
+ static takesBack() {
34
+ return OpenSurfaces.#stack.some((surface) => surface.takesBack);
35
+ }
36
+
37
+ static listen(listener: () => void) {
38
+ OpenSurfaces.#listeners.add(listener);
39
+ return () => {
40
+ OpenSurfaces.#listeners.delete(listener);
41
+ };
42
+ }
43
+
44
+ static #notify() {
45
+ for (const listener of OpenSurfaces.#listeners) listener();
46
+ }
47
+
48
+ static #onKeyDown = (event: KeyboardEvent) => {
49
+ const newest = OpenSurfaces.#stack.at(-1);
50
+ if (event.key !== "Escape" || event.defaultPrevented || !newest) return;
51
+ event.preventDefault();
52
+ newest.close();
53
+ };
54
+ }
@@ -10,6 +10,7 @@ import {
10
10
  } from "akanjs/client";
11
11
  import { useCallback } from "react";
12
12
  import { CsrStack } from "./CsrStack";
13
+ import { CsrPageReadiness } from "./csrPageReadiness";
13
14
  import type { CsrKeyboard } from "./useCsrKeyboard";
14
15
  import type { CsrLocationState } from "./useCsrLocationState";
15
16
  import { type CsrRefs, currentRouter } from "./useCsrRefs";
@@ -26,6 +27,8 @@ import {
26
27
  import type { ResolvedFrame } from "./useResolvedFrame";
27
28
  import { useBroadcastSyncNavigation } from "./useSyncNavigation";
28
29
 
30
+ const PAGE_DRAWN_TIMEOUT_MS = 300;
31
+
29
32
  interface ForwardCommit {
30
33
  kind: "push" | "replace";
31
34
  href: string;
@@ -133,12 +136,16 @@ const commitWhenFrameReady = ({
133
136
  const waitUntilReady = () => {
134
137
  if (pendingNavigation.current !== intent) return;
135
138
  const elapsedMs = Date.now() - intent.createdAt;
136
- const ready = isPendingFrameReady({
139
+ const isFrameReady = isPendingFrameReady({
137
140
  path: toLocation.pathRoute.path,
138
141
  pendingFrameSlots: latestPendingFrameSlots.current,
139
142
  elapsedMs,
140
143
  });
141
- if (ready) {
144
+ const isDrawn =
145
+ !CsrPageReadiness.drawsLater(toLocation) ||
146
+ CsrPageReadiness.isDrawn(toLocation.entryId) ||
147
+ elapsedMs >= PAGE_DRAWN_TIMEOUT_MS;
148
+ if (isFrameReady && isDrawn) {
142
149
  void commitNavigation(elapsedMs >= PENDING_FRAME_READY_TIMEOUT_MS);
143
150
  return;
144
151
  }
@@ -147,6 +154,25 @@ const commitWhenFrameReady = ({
147
154
  window.setTimeout(waitUntilReady, 16);
148
155
  };
149
156
 
157
+ const commitWhenDrawn = (
158
+ intent: NavigationIntent,
159
+ pendingNavigation: CsrRefs["pendingNavigation"],
160
+ commit: () => void,
161
+ ) => {
162
+ const waitUntilDrawn = () => {
163
+ if (pendingNavigation.current !== intent) return;
164
+ const elapsedMs = Date.now() - intent.createdAt;
165
+ if (!CsrPageReadiness.isDrawn(intent.to.entryId) && elapsedMs < PAGE_DRAWN_TIMEOUT_MS) {
166
+ window.setTimeout(waitUntilDrawn, 16);
167
+ return;
168
+ }
169
+ pendingNavigation.current = null;
170
+ debugFrame("navigation.drawn", { id: intent.id, to: intent.to.href, elapsedMs });
171
+ commit();
172
+ };
173
+ window.setTimeout(waitUntilDrawn, 16);
174
+ };
175
+
150
176
  interface CsrNavigationInput {
151
177
  viewport: ReturnType<typeof useFrameViewport>["viewport"];
152
178
  slots: ReturnType<typeof useFrameSlots>;
@@ -157,20 +183,13 @@ interface CsrNavigationInput {
157
183
  keyboard: CsrKeyboard;
158
184
  }
159
185
 
160
- export const useCsrNavigation = ({
161
- viewport,
162
- slots,
186
+ const useFrameTransitionStart = ({
163
187
  setTransitionPageStateSnapshot,
164
- refs,
165
- nav,
166
- frame,
188
+ refs: { pageStateByPathRef },
189
+ nav: { getLocation },
190
+ frame: { resolvedLocation },
167
191
  keyboard: { keyboardFrame },
168
192
  }: CsrNavigationInput) => {
169
- const { clearPendingSlots, promotePendingSlots } = slots;
170
- const { pageStateByPathRef, navigationIntentId, navigationLocked, pendingNavigation, waitingNavigation } = refs;
171
- const { pageContentRef } = refs;
172
- const { getLocation, getCurrentLocation, getPrevLocation, setHistoryForward, setLocationState, prevLocation } = nav;
173
- const { resolvedLocation } = frame;
174
193
  const shouldPrepareFrameTransition = useCallback(
175
194
  (nextHref?: string) => {
176
195
  if (keyboardFrame.visible) return true;
@@ -189,6 +208,15 @@ export const useCsrNavigation = ({
189
208
  window.setTimeout(() => setTransitionPageStateSnapshot(null), 360);
190
209
  await prepareForFrameTransition();
191
210
  }, []);
211
+ return { shouldPrepareFrameTransition, startFrameTransition };
212
+ };
213
+
214
+ export const useCsrNavigation = (input: CsrNavigationInput) => {
215
+ const { viewport, slots, setTransitionPageStateSnapshot, refs, nav, frame } = input;
216
+ const { clearPendingSlots, promotePendingSlots } = slots;
217
+ const { navigationIntentId, navigationLocked, pendingNavigation, waitingNavigation, pageContentRef } = refs;
218
+ const { getLocation, getCurrentLocation, getPrevLocation, setHistoryForward, setLocationState, prevLocation } = nav;
219
+ const { shouldPrepareFrameTransition, startFrameTransition } = useFrameTransitionStart(input);
192
220
  const settle = (prev: LocationState["prevLocation"]) =>
193
221
  setLocationState({
194
222
  location: getCurrentLocation(),
@@ -219,27 +247,36 @@ export const useCsrNavigation = ({
219
247
  ? { ...target, entryId: fromLocation.entryId }
220
248
  : target;
221
249
  const scrollTop = pageContentRef.current?.scrollTop ?? 0;
222
- const usePendingNavigation =
250
+ const slides =
223
251
  CsrStack.keyOf(toLocation) !== CsrStack.keyOf(fromLocation) &&
224
252
  shouldPrepareFrameTransition(href) &&
225
253
  toLocation.pathRoute.pageState.transition !== "none";
226
-
227
- if (!usePendingNavigation) {
254
+ const commitInPlace = () => {
228
255
  setHistoryForward({ type: kind, location: toLocation, scrollTop, scrollToTop });
229
256
  settle(kind === "replace" ? prevLocation : fromLocation);
230
257
  if (kind === "push") csrLocation.push({ akanEntryId: toLocation.entryId }, href);
231
258
  else csrLocation.replace({ akanEntryId: toLocation.entryId }, href);
259
+ };
260
+
261
+ const isDrawnAtOnce =
262
+ navigationLocked.current ||
263
+ !CsrPageReadiness.drawsLater(toLocation) ||
264
+ CsrStack.holds(
265
+ { history: nav.history.current, location: fromLocation, prevLocation, pendingLocation: null, phase: "idle" },
266
+ toLocation,
267
+ );
268
+ if (!slides && isDrawnAtOnce) {
269
+ commitInPlace();
232
270
  return;
233
271
  }
234
-
235
- if (navigationLocked.current) {
272
+ if (slides && navigationLocked.current) {
236
273
 
237
274
  const waiting = waitingNavigation.current;
238
275
  waitingNavigation.current = { kind: waiting?.kind === "push" ? "push" : kind, href, scrollToTop };
239
276
  debugFrame("navigation.wait", { kind, from: fromLocation.href, to: href });
240
277
  return;
241
278
  }
242
- navigationLocked.current = true;
279
+ if (slides) navigationLocked.current = true;
243
280
  const intent: NavigationIntent = {
244
281
  id: ++navigationIntentId.current,
245
282
  kind,
@@ -250,7 +287,12 @@ export const useCsrNavigation = ({
250
287
  createdAt: Date.now(),
251
288
  };
252
289
  pendingNavigation.current = intent;
253
- debugFrame("navigation.intent", { id: intent.id, kind, from: fromLocation.href, to: href });
290
+ debugFrame(slides ? "navigation.intent" : "navigation.drawAhead", {
291
+ id: intent.id,
292
+ kind,
293
+ from: fromLocation.href,
294
+ to: href,
295
+ });
254
296
  clearPendingSlots();
255
297
  setLocationState({
256
298
  location: fromLocation,
@@ -259,7 +301,13 @@ export const useCsrNavigation = ({
259
301
  navigationIntent: intent,
260
302
  phase: "preparing",
261
303
  });
262
-
304
+ if (!slides) {
305
+ commitWhenDrawn(intent, pendingNavigation, () => {
306
+ commitInPlace();
307
+ promotePendingSlots();
308
+ });
309
+ return;
310
+ }
263
311
  commitWhenFrameReady({
264
312
  kind,
265
313
  href,
@@ -11,10 +11,13 @@ import {
11
11
  type UseCsrTransition,
12
12
  } from "akanjs/client";
13
13
  import { clamp } from "akanjs/common";
14
- import { useCallback, useEffect, useMemo, useRef } from "react";
14
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";
15
+ import { STACK_TRANSITION_DURATION_MS } from "./useFrameRuntime";
15
16
 
16
17
  const linearEasing = (t: number) => t;
17
18
 
19
+ const stackEasing = (t: number) => 1 - (1 - t) ** 4;
20
+
18
21
  const getBottomInsetTop = (clientHeight: number, pageState: PathRoute["pageState"]) =>
19
22
  clientHeight - pageState.bottomInset - pageState.bottomSafeArea;
20
23
 
@@ -154,7 +157,8 @@ const usePlayOnForward = (
154
157
  { history, location }: RouteState,
155
158
  config: { duration: number; easing?: (t: number) => number },
156
159
  ) => {
157
- useEffect(() => {
160
+
161
+ useLayoutEffect(() => {
158
162
  if (history.current.type === "forward") {
159
163
  void transUnit.start(transUnitRange[0], { immediate: true });
160
164
  void transUnit.start(transUnitRange[1], { config });
@@ -390,7 +394,7 @@ const useStackTrans = (routeState: RouteState): UseCsrTransition => {
390
394
  };
391
395
  }, [transUnitRange]);
392
396
  useEffect(() => unlockPageScroll, [unlockPageScroll]);
393
- usePlayOnForward(spring, routeState, { duration: 150 });
397
+ usePlayOnForward(spring, routeState, { duration: STACK_TRANSITION_DURATION_MS, easing: stackEasing });
394
398
 
395
399
  const pageBind = useDrag(
396
400
  ({ first, last, movement: [mx, my], velocity: [vx], direction: [dx], initial: [ix], cancel }) => {
@@ -1,31 +1,18 @@
1
1
  "use client";
2
2
  import { useEffect, useRef } from "react";
3
+ import { OpenSurfaces } from "./openSurfaces";
3
4
 
4
- const stack: (() => void)[] = [];
5
-
6
- const onKeyDown = (event: KeyboardEvent) => {
7
- if (event.key !== "Escape" || event.defaultPrevented) return;
8
- const topmost = stack.at(-1);
9
- if (!topmost) return;
10
- event.preventDefault();
11
- topmost();
12
- };
13
-
14
- /** Calls `onEscape` on Escape while `active` and this surface is the topmost active one. */
15
- export const useEscapeKey = (active: boolean, onEscape: () => void) => {
5
+ /**
6
+ * Calls `onEscape` on Escape, or an app's back button, while `active` and this surface is the newest active one.
7
+ * `back: false` leaves the back button to the page: for a hint the person did not open, such as a tooltip.
8
+ */
9
+ export const useEscapeKey = (active: boolean, onEscape: () => void, { back = true }: { back?: boolean } = {}) => {
16
10
  const callbackRef = useRef(onEscape);
17
11
  useEffect(() => {
18
12
  callbackRef.current = onEscape;
19
13
  });
20
- useEffect(() => {
21
- if (!active) return;
22
- const entry = () => callbackRef.current();
23
- stack.push(entry);
24
- if (stack.length === 1) window.addEventListener("keydown", onKeyDown);
25
- return () => {
26
- const index = stack.lastIndexOf(entry);
27
- if (index !== -1) stack.splice(index, 1);
28
- if (stack.length === 0) window.removeEventListener("keydown", onKeyDown);
29
- };
30
- }, [active]);
14
+ useEffect(
15
+ () => (active ? OpenSurfaces.open(() => callbackRef.current(), { takesBack: back }) : undefined),
16
+ [active, back],
17
+ );
31
18
  };
@@ -28,6 +28,7 @@ export type FrameSlotBucket = "active" | "pending";
28
28
  export type FrameSlotMapByBucket = Record<FrameSlotBucket, FrameSlotMap>;
29
29
  export const PENDING_FRAME_READY_TIMEOUT_MS = 80;
30
30
  export const PENDING_FRAME_READY_MAX_TIMEOUT_MS = 120;
31
+ export const STACK_TRANSITION_DURATION_MS = 350;
31
32
  export const KEYBOARD_SHOW_ANIMATION_DURATION_MS = 420;
32
33
  export const KEYBOARD_HIDE_ANIMATION_DURATION_MS = 90;
33
34
  export const KEYBOARD_SHOW_ANIMATION_EASING = "cubic-bezier(0.16, 1, 0.3, 1)";
@@ -561,7 +562,8 @@ export function createFrameSnapshot({
561
562
  const getTransitionDuration = (type: TransitionType) => {
562
563
  if (typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches) return 1;
563
564
  if (type === "bottomUp" || type === "scaleOut") return 220;
564
- if (type === "fade" || type === "stack") return 150;
565
+ if (type === "stack") return STACK_TRANSITION_DURATION_MS;
566
+ if (type === "fade") return 150;
565
567
  return 0;
566
568
  };
567
569