Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ui): a Chrome-style zoom bubble and a smooth zoom glide

rubenluetke10-beepba3d3202d049
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index d226677154..a3d5be31de 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -49,6 +49,7 @@ const QuickSwitcher = lazy(() =>
import { eventMatchesChord } from "@/lib/quickSwitchChord";
import { useQuickSwitchSettings } from "@/store/quickSwitchSettings";
import { useAppZoom } from "@/hooks/useAppZoom";
+import { ZoomIndicator } from "@/components/ZoomIndicator";
import { useQuickSwitcher } from "@/store/quickSwitcher";
import { JarvisDock } from "@/components/JarvisDock";
import { CliConnectPoller } from "@/components/CliConnectPoller";
@@ -347,6 +348,7 @@ export default function App() {
<ToastLayer />
<CommandActivityLayer />
<EditContextMenu />
+ <ZoomIndicator />
{shortcutsOpen && (
<Suspense fallback={null}>
<ShortcutOverlay open onOpenChange={setShortcutsOpen} />
@@ -442,6 +444,8 @@ export default function App() {
/>
</Suspense>
)}
+ {/* Names the level after Ctrl + Plus / Minus, like Chrome's zoom bubble. */}
+ <ZoomIndicator />
{/* `?` anywhere in the app opens this; the chunk loads on first use. */}
{shortcutsOpen && (
<Suspense fallback={null}>
diff --git a/jarvis/ui/web/frontend/src/components/ZoomIndicator.test.tsx b/jarvis/ui/web/frontend/src/components/ZoomIndicator.test.tsx
new file mode 100644
index 0000000000..c3a75c7b6b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ZoomIndicator.test.tsx
@@ -0,0 +1,69 @@
+/**
+ * The zoom bubble names the level, steps with its own buttons, resets, and
+ * hides itself unless the pointer rests on it.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+
+import { ZOOM_INDICATOR_MS, ZoomIndicator } from "./ZoomIndicator";
+import { showZoomIndicator, useZoomIndicator } from "@/hooks/useAppZoom";
+import { APP_ZOOM_STORAGE_KEY, readAppZoomSettings, useAppZoomSettings } from "@/store/appZoomSettings";
+
+describe("ZoomIndicator", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ window.localStorage.removeItem(APP_ZOOM_STORAGE_KEY);
+ useAppZoomSettings.setState(readAppZoomSettings());
+ useZoomIndicator.setState({ open: false, seq: 0 });
+ });
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it("stays hidden until a zoom step", () => {
+ render(<ZoomIndicator />);
+ expect(screen.queryByTestId("zoom-indicator")).toBeNull();
+ });
+
+ it("shows the level and steps with its buttons", () => {
+ useAppZoomSettings.getState().setLevel(1.1);
+ render(<ZoomIndicator />);
+ act(() => showZoomIndicator());
+ expect(screen.getByTestId("zoom-indicator-level").textContent).toBe("110 %");
+
+ fireEvent.click(screen.getByTestId("zoom-indicator-in"));
+ expect(useAppZoomSettings.getState().level).toBe(1.25);
+ fireEvent.click(screen.getByTestId("zoom-indicator-out"));
+ fireEvent.click(screen.getByTestId("zoom-indicator-out"));
+ expect(screen.getByTestId("zoom-indicator-level").textContent).toBe("100 %");
+ expect((screen.getByTestId("zoom-indicator-reset") as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.click(screen.getByTestId("zoom-indicator-in"));
+ fireEvent.click(screen.getByTestId("zoom-indicator-reset"));
+ expect(useAppZoomSettings.getState().level).toBe(1);
+ });
+
+ it("hides itself after a moment, and every step restarts the clock", () => {
+ render(<ZoomIndicator />);
+ act(() => showZoomIndicator());
+ act(() => vi.advanceTimersByTime(ZOOM_INDICATOR_MS - 500));
+ act(() => showZoomIndicator());
+ act(() => vi.advanceTimersByTime(ZOOM_INDICATOR_MS - 500));
+ expect(screen.getByTestId("zoom-indicator")).toBeTruthy();
+ act(() => vi.advanceTimersByTime(600));
+ expect(screen.queryByTestId("zoom-indicator")).toBeNull();
+ });
+
+ it("stays while the pointer rests on it", () => {
+ render(<ZoomIndicator />);
+ act(() => showZoomIndicator());
+ fireEvent.pointerEnter(screen.getByTestId("zoom-indicator"));
+ act(() => vi.advanceTimersByTime(ZOOM_INDICATOR_MS * 3));
+ expect(screen.getByTestId("zoom-indicator")).toBeTruthy();
+
+ fireEvent.pointerLeave(screen.getByTestId("zoom-indicator"));
+ act(() => vi.advanceTimersByTime(ZOOM_INDICATOR_MS + 10));
+ expect(screen.queryByTestId("zoom-indicator")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ZoomIndicator.tsx b/jarvis/ui/web/frontend/src/components/ZoomIndicator.tsx
new file mode 100644
index 0000000000..26302294f9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ZoomIndicator.tsx
@@ -0,0 +1,125 @@
+/**
+ * The bubble that names the zoom level after a zoom step, the way Chrome shows
+ * one under its address bar: the percentage, a minus and a plus, and a way
+ * back to 100 %.
+ *
+ * It hides itself after a moment, but not while the pointer rests on it or a
+ * keyboard user is inside it — a bubble that vanishes under the cursor on the
+ * way to its own buttons is worse than none. Every further step (keys or its
+ * own buttons) restarts the timer.
+ *
+ * Colours come from theme tokens only, so it reads in light and dark.
+ */
+import { useEffect, useRef, useState } from "react";
+import { Minus, Plus } from "lucide-react";
+
+import { hideZoomIndicator, showZoomIndicator, useZoomIndicator } from "@/hooks/useAppZoom";
+import { useT } from "@/i18n";
+import { APP_ZOOM_LEVELS, nextAppZoom } from "@/lib/appZoom";
+import { cn } from "@/lib/utils";
+import { useAppZoomSettings } from "@/store/appZoomSettings";
+
+/** Chrome keeps its bubble up for about this long after the last step. */
+export const ZOOM_INDICATOR_MS = 2000;
+
+const ICON_BUTTON =
+ "inline-flex h-8 w-8 items-center justify-center rounded-full text-foreground transition-colors " +
+ "hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " +
+ "disabled:pointer-events-none disabled:opacity-40 [&>svg]:h-4 [&>svg]:w-4";
+
+export function ZoomIndicator() {
+ const t = useT();
+ const open = useZoomIndicator((s) => s.open);
+ const seq = useZoomIndicator((s) => s.seq);
+ const level = useAppZoomSettings((s) => s.level);
+ const setLevel = useAppZoomSettings((s) => s.setLevel);
+ const [held, setHeld] = useState(false);
+ const root = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open || held) return;
+ const timer = window.setTimeout(hideZoomIndicator, ZOOM_INDICATOR_MS);
+ return () => window.clearTimeout(timer);
+ }, [open, held, seq]);
+
+ // Closing must not strand the hover/focus hold for the next opening.
+ useEffect(() => {
+ if (!open) setHeld(false);
+ }, [open]);
+
+ if (!open) return null;
+
+ const step = (next: number) => {
+ setLevel(next);
+ showZoomIndicator();
+ };
+ const min = APP_ZOOM_LEVELS[0];
+ const max = APP_ZOOM_LEVELS[APP_ZOOM_LEVELS.length - 1];
+
+ return (
+ <div
+ ref={root}
+ role="status"
+ aria-live="polite"
+ data-testid="zoom-indicator"
+ onPointerEnter={() => setHeld(true)}
+ onPointerLeave={() => {
+ if (!root.current?.contains(document.activeElement)) setHeld(false);
+ }}
+ onFocus={() => setHeld(true)}
+ onBlur={(event) => {
+ if (!root.current?.contains(event.relatedTarget as Node | null)) setHeld(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") hideZoomIndicator();
+ }}
+ className={cn(
+ "fixed right-4 top-14 z-[100] flex items-center gap-1 rounded-2xl border border-border-strong",
+ "bg-popover py-2 pl-5 pr-2 text-popover-foreground shadow-float",
+ "animate-in fade-in-0 slide-in-from-top-1 duration-150 motion-reduce:animate-none",
+ )}
+ >
+ <span
+ className="mr-4 min-w-[3.5rem] text-sm tabular-nums text-foreground"
+ data-testid="zoom-indicator-level"
+ >
+ {Math.round(level * 100)} %
+ </span>
+ <button
+ type="button"
+ className={ICON_BUTTON}
+ aria-label={t("settings_view.app_zoom.out_label")}
+ title={t("settings_view.app_zoom.out_label")}
+ data-testid="zoom-indicator-out"
+ disabled={level <= min}
+ onClick={() => step(nextAppZoom(level, "out"))}
+ >
+ <Minus />
+ </button>
+ <button
+ type="button"
+ className={ICON_BUTTON}
+ aria-label={t("settings_view.app_zoom.in_label")}
+ title={t("settings_view.app_zoom.in_label")}
+ data-testid="zoom-indicator-in"
+ disabled={level >= max}
+ onClick={() => step(nextAppZoom(level, "in"))}
+ >
+ <Plus />
+ </button>
+ <button
+ type="button"
+ className={cn(
+ "ml-3 h-9 rounded-full border border-border-strong px-4 text-sm font-medium text-accent transition-colors",
+ "hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ "disabled:pointer-events-none disabled:opacity-40",
+ )}
+ data-testid="zoom-indicator-reset"
+ disabled={level === 1}
+ onClick={() => step(1)}
+ >
+ {t("settings_view.app_zoom.reset_button")}
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx b/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx
index 2a89a912be..2df6a10842 100644
--- a/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx
@@ -5,7 +5,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, renderHook, waitFor } from "@testing-library/react";
-import { useAppZoom, useAppZoomSupport } from "./useAppZoom";
+import { resetAppZoomApplyState, useAppZoom, useAppZoomSupport, useZoomIndicator } from "./useAppZoom";
import {
APP_ZOOM_STORAGE_KEY,
readAppZoomSettings,
@@ -27,6 +27,8 @@ describe("useAppZoom", () => {
window.localStorage.removeItem(APP_ZOOM_STORAGE_KEY);
useAppZoomSettings.setState(readAppZoomSettings());
useAppZoomSupport.setState({ support: "unknown" });
+ useZoomIndicator.setState({ open: false, seq: 0 });
+ resetAppZoomApplyState();
(window as Host).__JARVIS_EMBEDDED_DESKTOP = true;
});
afterEach(() => {
@@ -49,8 +51,36 @@ describe("useAppZoom", () => {
fireEvent.keyDown(document.body, { key: "0", code: "Digit0", ctrlKey: true });
expect(useAppZoomSettings.getState().level).toBe(1);
- await waitFor(() => expect(sentFactors(fetchMock)).toEqual([1, 1.1, 1, 0.9, 1]));
+ // Steps pressed while a request is out are folded into the newest one; the
+ // last factor sent is always the level the user ended on.
+ await waitFor(() => expect(sentFactors(fetchMock).at(-1)).toBe(1));
+ expect(sentFactors(fetchMock)[0]).toBe(1);
expect(readAppZoomSettings().level).toBe(1);
+ expect(useZoomIndicator.getState().open).toBe(true);
+ });
+
+ it("never lets the requests of a held-down key overtake each other", async () => {
+ const pending: (() => void)[] = [];
+ const sent: number[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn((_url: string, init: RequestInit) => {
+ sent.push(JSON.parse(String(init.body)).factor);
+ return new Promise<Response>((resolve) => {
+ pending.push(() => resolve(new Response(JSON.stringify({ ok: true }), { status: 200 })));
+ });
+ }),
+ );
+ renderHook(() => useAppZoom());
+ await waitFor(() => expect(sent).toEqual([1]));
+
+ for (let i = 0; i < 4; i++) {
+ fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true });
+ }
+ expect(sent).toEqual([1]); // still one in flight
+ pending.shift()?.();
+ await waitFor(() => expect(sent).toEqual([1, 1.75])); // 1.1, 1.25, 1.5 skipped
+ pending.shift()?.();
});
it("re-applies a remembered level when the window opens", async () => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts b/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts
index dc1e00f2c2..6a2fdd40c3 100644
--- a/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts
@@ -28,6 +28,7 @@ import { create } from "zustand";
import { hasEmbeddedDesktopBridge } from "@/components/voice/BrowserRealtimeControl";
import { appZoomIntentFor, nextAppZoom } from "@/lib/appZoom";
+import { armZoomTransition, installZoomTransition } from "@/lib/zoomTransition";
import { useAppZoomSettings } from "@/store/appZoomSettings";
import { useEventStore } from "@/store/events";
@@ -38,12 +39,65 @@ export const useAppZoomSupport = create<{ support: AppZoomSupport }>(() => ({
support: "unknown",
}));
+/**
+ * The Chrome-style bubble that names the new level after a zoom step. `seq`
+ * changes on every step so the bubble restarts its hide timer.
+ */
+export const useZoomIndicator = create<{ open: boolean; seq: number }>(() => ({
+ open: false,
+ seq: 0,
+}));
+
+export function showZoomIndicator(): void {
+ useZoomIndicator.setState((s) => ({ open: true, seq: s.seq + 1 }));
+}
+
+export function hideZoomIndicator(): void {
+ useZoomIndicator.setState({ open: false });
+}
+
function windowView(): string | null {
const { solo, activeSection } = useEventStore.getState();
return solo ? activeSection : null;
}
+/**
+ * One request in flight at a time, and only the newest level waits behind it.
+ * A held-down key repeats faster than the shell answers; firing a request per
+ * repeat let them overtake each other, and the window visibly stepped back
+ * and forth on its way to the level the user asked for.
+ */
+let inFlight = false;
+let queued: number | null = null;
+let applied: number | null = null;
+
+/** Forget what this window applied — for tests, which share the module. */
+export function resetAppZoomApplyState(): void {
+ inFlight = false;
+ queued = null;
+ applied = null;
+}
+
async function applyWindowZoom(level: number): Promise<void> {
+ if (inFlight) {
+ queued = level;
+ return;
+ }
+ inFlight = true;
+ try {
+ await sendWindowZoom(level);
+ } finally {
+ inFlight = false;
+ const next = queued;
+ queued = null;
+ if (next !== null && next !== applied) void applyWindowZoom(next);
+ }
+}
+
+async function sendWindowZoom(level: number): Promise<void> {
+ // The engine's resize is the cue for the glide (lib/zoomTransition); the
+ // first apply at start-up has nothing to glide from.
+ if (applied !== null && applied !== level) armZoomTransition();
try {
const res = await fetch("/api/window/zoom", {
method: "POST",
@@ -52,6 +106,7 @@ async function applyWindowZoom(level: number): Promise<void> {
});
const body = (res.ok ? await res.json() : null) as { ok?: boolean; reason?: string } | null;
if (body?.ok) {
+ applied = level;
useAppZoomSupport.setState({ support: "native" });
return;
}
@@ -75,6 +130,8 @@ export function useAppZoom(): void {
if (!embedded) useAppZoomSupport.setState({ support: "browser" });
}, [embedded]);
+ useEffect(() => (embedded ? installZoomTransition(window) : undefined), [embedded]);
+
// Apply the level to THIS window — on start (the window opens at 100 %), on
// every step, and when another window changed it through storage.
useEffect(() => {
@@ -96,6 +153,9 @@ export function useAppZoom(): void {
const { level: current, setLevel } = useAppZoomSettings.getState();
const next = nextAppZoom(current, intent);
if (next !== current) setLevel(next);
+ // Shown even at the ends of the range, like Chrome: the bubble is how
+ // the user learns that 300 % is as far as it goes.
+ showZoomIndicator();
};
document.addEventListener("keydown", onKeyDown, true);
return () => document.removeEventListener("keydown", onKeyDown, true);
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index c69e471bf8..480dd3d987 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2681,6 +2681,7 @@
"in_label": "Hineinzoomen",
"out_label": "Herauszoomen",
"reset_label": "Zurück auf 100 %",
+ "reset_button": "Zurücksetzen",
"problem_typing_key": "Diese Taste allein würde bei jedem Tippen zoomen. Nimm Strg, Alt oder Command dazu — oder eine Funktionstaste wie F9.",
"problem_os_reserved": "Die Windows-Taste gehört dem System (Windows + Plus öffnet die Bildschirmlupe). Wähle eine Kombination mit Strg oder Alt.",
"problem_duplicate": "Ein anderer Zoom-Schritt nutzt genau diese Kombination schon.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index caeea6b718..fa4f636959 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2714,6 +2714,7 @@
"in_label": "Zoom in",
"out_label": "Zoom out",
"reset_label": "Back to 100 %",
+ "reset_button": "Reset",
"problem_typing_key": "This key alone would zoom every time you type it. Add Ctrl, Alt or Command — or use a function key such as F9.",
"problem_os_reserved": "The Windows key belongs to the system (Windows + Plus opens the magnifier). Pick a chord with Ctrl or Alt.",
"problem_duplicate": "Another zoom step already uses exactly this combination.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 2c56a8c493..66e8c13361 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2681,6 +2681,7 @@
"in_label": "Acercar",
"out_label": "Alejar",
"reset_label": "Volver al 100 %",
+ "reset_button": "Restablecer",
"problem_typing_key": "Esta tecla sola haría zoom cada vez que la escribes. Añade Ctrl, Alt o Command, o usa una tecla de función como F9.",
"problem_os_reserved": "La tecla Windows pertenece al sistema (Windows + Más abre la lupa). Elige una combinación con Ctrl o Alt.",
"problem_duplicate": "Otro paso de zoom ya usa exactamente esta combinación.",
diff --git a/jarvis/ui/web/frontend/src/lib/zoomTransition.test.ts b/jarvis/ui/web/frontend/src/lib/zoomTransition.test.ts
new file mode 100644
index 0000000000..3a480b3e1f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/zoomTransition.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { armZoomTransition, installZoomTransition, ZOOM_TRANSITION_MS } from "./zoomTransition";
+
+interface Played {
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+}
+
+describe("installZoomTransition", () => {
+ let played: Played[];
+ let cleanup: () => void;
+
+ function setViewport(dpr: number, inner: number, outer = 1600) {
+ Object.defineProperty(window, "devicePixelRatio", { configurable: true, value: dpr });
+ Object.defineProperty(window, "innerWidth", { configurable: true, value: inner });
+ Object.defineProperty(window, "outerWidth", { configurable: true, value: outer });
+ }
+
+ beforeEach(() => {
+ played = [];
+ setViewport(1, 1600);
+ document.documentElement.animate = vi.fn((keyframes: Keyframe[], options: KeyframeAnimationOptions) => {
+ played.push({ keyframes, options });
+ return { cancel: vi.fn(), onfinish: null, oncancel: null } as unknown as Animation;
+ }) as unknown as HTMLElement["animate"];
+ cleanup = installZoomTransition(window);
+ });
+ afterEach(() => cleanup());
+
+ it("glides from the old size after a zoom this window asked for", () => {
+ armZoomTransition();
+ setViewport(1.25, 1280);
+ window.dispatchEvent(new Event("resize"));
+
+ expect(played).toHaveLength(1);
+ expect(played[0].keyframes[0].transform).toBe("scale(0.8)");
+ expect(played[0].keyframes[1].transform).toBe("scale(1)");
+ expect(played[0].keyframes[0].transformOrigin).toBe("0 0");
+ expect(played[0].options.duration).toBe(ZOOM_TRANSITION_MS);
+ });
+
+ it("reads the viewport width where the pixel ratio does not move", () => {
+ armZoomTransition();
+ setViewport(1, 2000);
+ window.dispatchEvent(new Event("resize"));
+ expect(played[0].keyframes[0].transform).toBe("scale(1.25)");
+ });
+
+ it("stays still for a resize nobody asked to zoom", () => {
+ setViewport(1, 1200, 1200); // dragging the window edge
+ window.dispatchEvent(new Event("resize"));
+ expect(played).toHaveLength(0);
+ });
+
+ it("stays still when the window itself was resized during the zoom", () => {
+ armZoomTransition();
+ setViewport(1, 1200, 1300);
+ window.dispatchEvent(new Event("resize"));
+ expect(played).toHaveLength(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/zoomTransition.ts b/jarvis/ui/web/frontend/src/lib/zoomTransition.ts
new file mode 100644
index 0000000000..0c8df7dbe5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/zoomTransition.ts
@@ -0,0 +1,121 @@
+/**
+ * A short, smooth scale from the old zoom level to the new one, so a zoom step
+ * glides instead of jumping.
+ *
+ * ## How it stays in sync with the engine
+ *
+ * The zoom itself is the WebView engine's (see hooks/useAppZoom), and it lands
+ * whenever the desktop shell gets round to it — a round trip later. Animating
+ * on the keypress would run ahead of it and then jump a second time when the
+ * engine catches up. So the animation starts from the engine's own signal
+ * instead: an engine zoom resizes the CSS viewport, which fires `resize` in the
+ * same rendering step that lays the page out at the new size, BEFORE that
+ * frame is painted. Setting the starting scale there means the first painted
+ * frame already looks like the old size, and the page then eases to the new
+ * one. Nothing is ever drawn at the wrong size.
+ *
+ * The step is FLIP-style: the page is already laid out at the new level and is
+ * scaled back to how big it looked before (old / new), then released to 1.
+ * The origin is the top-left corner, which is also where the engine anchors
+ * the reflow, so the sidebar and the title strip grow from where they already
+ * are instead of sliding.
+ *
+ * A held-down key fires steps faster than the animation runs. Each new step
+ * starts from the scale currently on screen, so a run of steps reads as one
+ * continuous glide rather than a series of restarts.
+ *
+ * Only armed around a zoom this window asked for: a `resize` from dragging
+ * the window edge, or from moving it to a screen with a different DPI, also
+ * changes the numbers below and must not animate.
+ */
+
+/** Long enough to feel like motion, short enough that a step never lags the key. */
+export const ZOOM_TRANSITION_MS = 200;
+const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
+
+/** How long after a request an engine resize still counts as its answer. */
+const ARM_WINDOW_MS = 1500;
+
+let armedUntil = 0;
+let running: Animation | null = null;
+
+/** Mark the next engine resize as the answer to a zoom this window asked for. */
+export function armZoomTransition(now: number = performance.now()): void {
+ armedUntil = now + ARM_WINDOW_MS;
+}
+
+/** The scale the root element is drawn at right now (1 when nothing runs). */
+function currentScale(el: HTMLElement): number {
+ if (!running) return 1;
+ const transform = getComputedStyle(el).transform;
+ const match = /^matrix\(([-\d.e]+)/.exec(transform ?? "");
+ const scale = match ? Number(match[1]) : 1;
+ return Number.isFinite(scale) && scale > 0 ? scale : 1;
+}
+
+/** Ease the page from `from` (a scale factor) back to its real size. */
+export function playZoomTransition(el: HTMLElement, from: number): void {
+ if (typeof el.animate !== "function") return;
+ const start = currentScale(el) * from;
+ running?.cancel();
+ if (Math.abs(start - 1) < 0.002) {
+ running = null;
+ return;
+ }
+ // A page scaled above 1 overflows the window for a moment; without this
+ // the viewport would flash scrollbars while it shrinks back.
+ el.style.overflow = "hidden";
+ const animation = el.animate(
+ [
+ { transform: `scale(${start})`, transformOrigin: "0 0" },
+ { transform: "scale(1)", transformOrigin: "0 0" },
+ ],
+ { duration: ZOOM_TRANSITION_MS, easing: EASING },
+ );
+ running = animation;
+ const settle = () => {
+ if (running !== animation) return;
+ running = null;
+ el.style.overflow = "";
+ };
+ animation.onfinish = settle;
+ animation.oncancel = settle;
+}
+
+/**
+ * Watch `win` for engine zoom steps and animate each one, returning a cleanup
+ * function.
+ */
+export function installZoomTransition(win: Window = window): () => void {
+ let lastDpr = win.devicePixelRatio || 1;
+ let lastInner = win.innerWidth;
+ let lastOuter = win.outerWidth;
+
+ const onResize = () => {
+ const dpr = win.devicePixelRatio || 1;
+ const inner = win.innerWidth;
+ const outer = win.outerWidth;
+ const before = { dpr: lastDpr, inner: lastInner, outer: lastOuter };
+ lastDpr = dpr;
+ lastInner = inner;
+ lastOuter = outer;
+
+ if (performance.now() > armedUntil) return;
+ if (win.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
+
+ // The device pixel ratio carries the zoom on Chromium and WebKit. Where it
+ // does not, the CSS viewport of an unchanged window shrank or grew by the
+ // same factor, which says the same thing.
+ let from = 1;
+ if (Math.abs(dpr - before.dpr) > 0.001) from = before.dpr / dpr;
+ else if (outer === before.outer && before.inner > 0 && inner !== before.inner) from = inner / before.inner;
+ if (from === 1) return;
+ playZoomTransition(win.document.documentElement, from);
+ };
+
+ win.addEventListener("resize", onResize);
+ return () => {
+ win.removeEventListener("resize", onResize);
+ running?.cancel();
+ };
+}