okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Route change: the view transition's update callback no longer waits for requestAnimationFrame (#3673)642f5120a

main
6.4 KiB178 linesraw
1/** Hash router — no dependency, survives static hosting and file:// shells. */
2import { useEffect, useState } from 'react';
3
4export const ROUTES = [
5  'setup',
6  'chat',
7  'models',
8  'tuning',
9  'serving',
10  'monitor',
11  'tasks',
12  'skills',
13  'settings',
14] as const;
15
16export type Route = (typeof ROUTES)[number];
17
18export interface Location {
19  route: Route;
20  param: string | null;
21  query: URLSearchParams;
22}
23
24export function parseLocation(hash: string): Location {
25  const raw = hash.replace(/^#\/?/, '');
26  const [pathPart, queryPart] = raw.split('?');
27  const segments = pathPart.split('/').filter(Boolean);
28  const first = segments[0] as Route | undefined;
29  // Chat is the landing screen; an unknown or retired route (a stale #/launch
30  // bookmark) falls back to it rather than rendering nothing.
31  const route: Route = first && (ROUTES as readonly string[]).includes(first) ? first : 'chat';
32  const query = new URLSearchParams(queryPart ?? '');
33  if (route === 'settings') query.set('settings', '1');
34  return {
35    route: route === 'settings' ? 'chat' : route,
36    param: segments[1] ?? null,
37    query,
38  };
39}
40
41export function useLocation(): Location {
42  const [loc, setLoc] = useState<Location>(() => {
43    const initial = parseLocation(window.location.hash);
44    normalise(initial);
45    return initial;
46  });
47  useEffect(() => {
48    const onHash = () => {
49      const next = parseLocation(window.location.hash);
50      normalise(next);
51      setLoc(next);
52    };
53    window.addEventListener('hashchange', onHash);
54    return () => window.removeEventListener('hashchange', onHash);
55  }, []);
56  return loc;
57}
58
59/**
60 * Rewrite a retired or unknown hash to the screen actually being shown, so a
61 * stale `#/launch` bookmark does not leave a dead URL in the address bar.
62 */
63function normalise(loc: Location): void {
64  const raw = window.location.hash.replace(/^#\/?/, '');
65  const first = raw.split('?')[0].split('/').filter(Boolean)[0];
66  if (first === 'settings') {
67    window.history.replaceState(null, '', locationHref(loc));
68  } else if (first && !(ROUTES as readonly string[]).includes(first)) {
69    window.history.replaceState(null, '', `#/${loc.route}`);
70  }
71}
72
73/**
74 * Navigate, morphing between screens when the browser can.
75 *
76 * A view transition needs the DOM update to happen inside its callback, and
77 * React commits asynchronously — so we wait for the commit (never for a frame: see afterRouteUpdate). It is
78 * skipped while a response is streaming (the transcript is being appended to on
79 * every token, and snapshotting it mid-stream would fight the SSE updates) and
80 * when the user has asked for reduced motion.
81 */
82export function navigate(route: Route, param?: string, query?: Record<string, string>) {
83  const next = route === 'settings' ? settingsHref(window.location.hash) : locationHref({route, param: param ?? null, query: new URLSearchParams(query)});
84  navigateHash(next, route !== 'settings');
85}
86
87export function closeSettings() {
88  const location = parseLocation(window.location.hash);
89  location.query.delete('settings');
90  navigateHash(locationHref(location), false);
91}
92
93/**
94 * WebKitGTK (the Linux app window; Safari does not exist on Linux) crashes its own UI process with a null pointer in
95 * AcceleratedBackingStore::update when a page calls the View Transitions API (seen on Ubuntu 24.04 and 26.04, WebKitGTK
96 * 2.52, under Xvfb and on a real NVIDIA/Wayland desktop alike; one startViewTransition call is enough). The route
97 * cross-fade is only a nicety, so on that engine a route changes at once.
98 */
99export function isWebKitGtk(ua: string = navigator.userAgent): boolean {
100  return /AppleWebKit/.test(ua) && /Linux|X11/.test(ua) && !/Chrome|Chromium|CriOS|Edg|OPR|Android/.test(ua);
101}
102
103/**
104 * Resolve once the new route has been drawn into the page, or after a short deadline, whichever comes first.
105 *
106 * The update callback of a view transition must not wait for requestAnimationFrame: while the callback is pending the browser holds
107 * rendering (Chromium and Firefox both do), so a frame callback never runs, and every click waits for the browser's own guard,
108 * about 4 s in Chromium and the WebView2 window, about 5 s in Firefox (#3673). A DOM change after the hash flipped means React has
109 * committed the new screen; the deadline covers a route that changes nothing visible.
110 */
111export function afterRouteUpdate(done: () => void, timeoutMs = 150): void {
112  let settled = false;
113  let observer: MutationObserver | undefined;
114  const finish = () => {
115    if (settled) return;
116    settled = true;
117    observer?.disconnect();
118    done();
119  };
120  try {
121    if (typeof MutationObserver === 'function' && typeof document !== 'undefined' && document.body) {
122      observer = new MutationObserver(() => setTimeout(finish, 0));
123      observer.observe(document.body, { childList: true, subtree: true });
124    }
125  } catch {
126    /* the deadline alone is enough */
127  }
128  setTimeout(finish, timeoutMs);
129}
130
131function navigateHash(next: string, morph = true) {
132  if (window.location.hash === next) return;
133
134  const root = document.documentElement;
135  const mayMorph =
136    morph &&
137    typeof document.startViewTransition === 'function' &&
138    !isWebKitGtk() &&
139    root.dataset.motion !== 'reduced' &&
140    !window.matchMedia('(prefers-reduced-motion: reduce)').matches &&
141    root.dataset.streaming !== 'true';
142
143  if (!mayMorph) {
144    window.location.hash = next;
145    return;
146  }
147
148  const transition = document.startViewTransition(
149    () =>
150      new Promise<void>((resolve) => {
151        window.location.hash = next;
152        afterRouteUpdate(resolve);
153      }),
154  );
155  // A transition is *expected* to be skipped when one is already running (rapid
156  // ⌘1…⌘9) or the document is hidden. That is not an error, and the rejected
157  // promises would otherwise surface as unhandled rejections in the console.
158  transition.ready.catch(() => {});
159  transition.updateCallbackDone.catch(() => {});
160  transition.finished.catch(() => {});
161}
162
163
164export function href(route: Route, param?: string): string {
165  return route === 'settings' ? settingsHref(window.location.hash) : `#/${route}${param ? `/${param}` : ''}`;
166}
167
168function locationHref(location: Location) {
169  const query = location.query.toString();
170  return `#/${location.route}${location.param ? `/${location.param}` : ''}${query ? `?${query}` : ''}`;
171}
172
173/** Keep the working page mounted while Settings is open, including its draft. */
174export function settingsHref(hash: string) {
175  const location = parseLocation(hash);
176  location.query.set('settings', '1');
177  return locationHref(location);
178}