Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(inspector): pick the zoom level from a row of buttons
超超超超超级喜欢你的达妮娅28ec754b4773
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsxindex 949e307d0..5c0cc6867 100644--- a/src/components/ai-edition/v4/FloatingInspector.tsx+++ b/src/components/ai-edition/v4/FloatingInspector.tsx@@ -36,6 +36,7 @@ import {MOVING_ROTATION_3D_PRESETS,type Rotation3DPreset,ZOOM_DEPTH_SCALES,+ type ZoomDepth,} from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import {@@ -428,7 +429,142 @@ function convertAnnotationKind(return { ...parked, type: next, content: restored };}-const ZOOM_DEPTHS = [1, 2, 3, 4, 5, 6] as const;+const ZOOM_DEPTHS: readonly ZoomDepth[] = [1, 2, 3, 4, 5, 6];++/**+ * The six zoom levels as one row of buttons, so a level is one click away instead of two+ * (open the select, then pick). Six short labels fit the 300px pane on their own line, which+ * is why this is a stacked label/row rather than a `paneRow`.+ *+ * `aria-pressed` buttons inside a labelled `role="group"` is `TranscriptLaneSwitch`'s pattern+ * (the facet rail is the same buttons without the wrapper, since its own label carries), so+ * every level stays in the Tab order and reads like its neighbours. Arrow keys step through+ * the levels, which is what the `<select>` this replaces did once focused — and the one+ * keyboard path that survives the editor shell's Tab binding (it cycles annotations whenever+ * any exist, from any focused element).+ */+export function ZoomLevelControl({+ region,+ tl,+}: {+ region: { id: string; depth: ZoomDepth };+ tl: Pick<TimelineApi, "updateZoomDepth">;+}) {+ const ts = useScopedT("settings");+ const buttonsRef = useRef<Array<HTMLButtonElement | null>>([]);+ // Last depth this instance asked for, and the generation of that request.+ // Depth values repeat (only 1–6), so a Set of depths cannot tell "our older+ // 4 landed" from "the latest request is 4" or from an undo that happens to+ // land on 4. Each click/key gets a new gen. Every gen belonging to this+ // region epoch is removed from `pending` when it settles — a superseded 4+ // must still drain, or `pending` stays non-empty and undo/redo can never+ // overwrite `requestedRef`. Only the latest gen may change `requestedRef`.+ const requestedRef = useRef<ZoomDepth>(region.depth);+ const genRef = useRef(0);+ const pendingRef = useRef(new Set<number>());+ const regionRef = useRef(region);+ regionRef.current = region;++ // biome-ignore lint/correctness/useExhaustiveDependencies: region.id is the trigger, not a read — the body resets request state; depth is taken from the render's ref so a same-depth other pill still clears the previous pill's pending gen.+ useEffect(() => {+ genRef.current += 1;+ pendingRef.current.clear();+ requestedRef.current = regionRef.current.depth;+ }, [region.id]);++ useEffect(() => {+ if (pendingRef.current.size > 0) return;+ requestedRef.current = region.depth;+ }, [region.depth]);++ const setDepth = (depth: ZoomDepth) => {+ // Re-pressing the current level is not an edit: no save, no undo entry.+ if (depth === requestedRef.current) return;+ requestedRef.current = depth;+ const gen = ++genRef.current;+ pendingRef.current.add(gen);+ const regionId = region.id;+ void Promise.resolve(tl.updateZoomDepth(regionId, depth)).then(+ (ok) => {+ pendingRef.current.delete(gen);+ if (gen !== genRef.current) return;+ if (ok === false) requestedRef.current = regionRef.current.depth;+ },+ () => {+ pendingRef.current.delete(gen);+ if (gen !== genRef.current) return;+ requestedRef.current = regionRef.current.depth;+ },+ );+ };++ return (+ <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>+ <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>+ {ts("zoom.level")}+ </span>+ <div+ role="group"+ aria-label={ts("zoom.level")}+ style={{ display: "flex", gap: 4 }}+ onKeyDown={(e) => {+ // A button activates on Enter and Space by itself — but the shell's play/pause+ // shortcut is Space on WINDOW, and it `preventDefault()`s the keydown, which+ // cancels that activation. Unstopped, Space on a level changed nothing and+ // started playback instead. Stop the keystroke here so the button keeps its own+ // key, and do NOT `preventDefault()` it, or the activation dies the same way.+ if (e.key === "Enter" || e.key === " ") {+ e.nativeEvent.stopPropagation();+ return;+ }+ const step =+ e.key === "ArrowRight" || e.key === "ArrowDown"+ ? 1+ : e.key === "ArrowLeft" || e.key === "ArrowUp"+ ? -1+ : 0;+ if (step === 0) return;+ // `nativeEvent.stopPropagation()`, not just the synthetic one: the editor shell+ // listens on WINDOW, above React's root container, and ArrowLeft/ArrowRight seek+ // the playhead there. Same reason as the pill's own keydown in V4Timeline.+ e.preventDefault();+ e.nativeEvent.stopPropagation();+ // Step from the FOCUSED button, not from the selected level. Every level is a Tab+ // stop, so the two can part company — and stepping from the selection then threw+ // focus across the row (ArrowRight on the last button landed it in the middle).+ // Focus moves one place and the level follows it; at either end neither moves.+ const focused = buttonsRef.current.findIndex((b) => b === document.activeElement);+ const from = focused >= 0 ? focused : ZOOM_DEPTHS.indexOf(requestedRef.current);+ const next = ZOOM_DEPTHS[from + step];+ if (next === undefined) return;+ buttonsRef.current[next - 1]?.focus();+ setDepth(next);+ }}+ >+ {ZOOM_DEPTHS.map((d) => {+ const pressed = d === region.depth;+ return (+ <button+ key={d}+ ref={(el) => {+ buttonsRef.current[d - 1] = el;+ }}+ type="button"+ aria-pressed={pressed}+ onClick={() => setDepth(d)}+ style={pressed ? zoomLevelPressedStyle : zoomLevelBtnStyle}+ >+ {/* La table, pas une formule : ce libellé annonçait « 2.0× » là où la pastille de la+ timeline affiche « 1.80× » et où le rendu applique 1.8. */}+ {ZOOM_DEPTH_SCALES[d]}×+ </button>+ );+ })}+ </div>+ </div>+ );+}+// The speeds people actually reach for, one row of buttons: slow down, back to normal, and three// steps up. Every other speed (the shared ladder's 0.25×, 3×, 5×, anything up to// `MAX_PLAYBACK_SPEED`) is one entry in the free field below, which is why the row stays short.@@ -569,24 +705,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }<div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>{paneHeader(<ZoomIn size={16} />, tt("labels.zoom"), onClose, tc("actions.close"))}<div style={bodyStyle}>- {paneRow(- ts("zoom.level"),- <select- value={region.depth}- onChange={(e) =>- void tl.updateZoomDepth(region.id, Number(e.target.value) as 1 | 2 | 3 | 4 | 5 | 6)- }- className={shell.control}- >- {ZOOM_DEPTHS.map((d) => (- <option key={d} value={d}>- {/* La table, pas une formule : ce libellé annonçait « 2.0× » là où la pastille de la- timeline affiche « 1.80× » et où le rendu applique 1.8. */}- {ZOOM_DEPTH_SCALES[d]}×- </option>- ))}- </select>,- )}+ <ZoomLevelControl key={region.id} region={region} tl={tl} /><div style={{ display: "flex", flexDirection: "column", gap: 4 }}>{paneRow(ts("zoom.camera.title"),@@ -1095,6 +1214,30 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }* slab outshouted every setting above it. */const PANE_BUTTON = `${shell.btn} ${shell.btnSecondary}`;+// Six of these share the pane's 266px of content width, so each gets ~41px: enough for+// "1.25×" at 12px with room either side, and no horizontal padding to lose.+const zoomLevelBtnStyle: React.CSSProperties = {+ flex: "1 1 0",+ minWidth: 0,+ height: 28,+ padding: 0,+ borderRadius: 8,+ border: "1px solid var(--border)",+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 12px var(--font-display)",+ cursor: "pointer",+};++// Same signal as the pressed facet-rail button: accent text on the soft accent fill.+const zoomLevelPressedStyle: React.CSSProperties = {+ ...zoomLevelBtnStyle,+ border: "1px solid var(--accent)",+ background: "var(--accent-soft)",+ color: "var(--accent)",+ fontWeight: 600,+};+function FacetBody({facet,onCollapse,diff --git a/src/components/ai-edition/v4/ZoomLevelControl.test.tsx b/src/components/ai-edition/v4/ZoomLevelControl.test.tsxnew file mode 100644index 000000000..eb18eba1d--- /dev/null+++ b/src/components/ai-edition/v4/ZoomLevelControl.test.tsx@@ -0,0 +1,391 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import { describe, expect, it, vi } from "vitest";+import { ZOOM_DEPTH_SCALES, type ZoomDepth } from "@/components/video-editor/types";++// The pane is only reachable with a project open and a zoom region selected, so drive the+// control directly. The translator echoes keys, as in `SpeedControl.test.tsx`.+vi.mock("@/contexts/I18nContext", () => ({+ useScopedT: () => (key: string) => key,+}));++import { ZoomLevelControl } from "./FloatingInspector";++function renderControl(depth: ZoomDepth) {+ const updateZoomDepth = vi.fn(async () => true);+ render(<ZoomLevelControl region={{ id: "z1", depth }} tl={{ updateZoomDepth }} />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ return { updateZoomDepth, group, buttons };+}++/**+ * The same control with the pane's half of the loop in place: in the editor `updateZoomDepth`+ * writes the region and the pane re-renders with the new `depth`, so the pressed button moves+ * under the keyboard. Stepping is only coherent if that feedback exists — with a frozen prop+ * every arrow would keep counting from the level the control opened on.+ */+function renderControlled(initial: ZoomDepth) {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ function Harness() {+ const [depth, setDepth] = useState<ZoomDepth>(initial);+ return (+ <ZoomLevelControl+ region={{ id: "z1", depth }}+ tl={{+ updateZoomDepth: (id, next) => {+ // Synchronously, so the re-render lands inside the `fireEvent` that caused it:+ // the next keystroke in a test then sees the same DOM a user's would.+ updateZoomDepth(id, next);+ setDepth(next);+ return Promise.resolve(true);+ },+ }}+ />+ );+ }+ render(<Harness />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ const focusLevel = (depth: ZoomDepth) => (buttons[depth - 1] as HTMLButtonElement).focus();+ return { updateZoomDepth, group, buttons, focusLevel };+}++describe("ZoomLevelControl", () => {+ it("renders one button per depth, labelled with the table value, current one pressed", () => {+ const { buttons } = renderControl(3);+ expect(buttons).toHaveLength(6);+ expect(buttons.map((b) => b.textContent)).toEqual(+ ([1, 2, 3, 4, 5, 6] as const).map((d) => `${ZOOM_DEPTH_SCALES[d]}×`),+ );+ expect(buttons.map((b) => b.getAttribute("aria-pressed"))).toEqual([+ "false",+ "false",+ "true",+ "false",+ "false",+ "false",+ ]);+ });++ it("commits a level in one click", () => {+ const { updateZoomDepth, buttons } = renderControl(3);+ fireEvent.click(buttons[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledTimes(1);+ expect(updateZoomDepth).toHaveBeenCalledWith("z1", 5);+ });++ it("does not write when the current level is clicked again", () => {+ // A no-op edit would still land a save and an undo entry.+ const { updateZoomDepth, buttons } = renderControl(3);+ fireEvent.click(buttons[2] as HTMLButtonElement);+ expect(updateZoomDepth).not.toHaveBeenCalled();+ });++ // The other half of that guard: undo/redo and the agent write the region without going+ // through this control, so a request of ours must never outlive the prop. The moment the+ // region says something else, that is the level to compare against.+ it("follows the region when the level is changed from elsewhere", async () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ const { rerender } = render(+ <ZoomLevelControl region={{ id: "z1", depth: 3 }} tl={{ updateZoomDepth }} />,+ );+ fireEvent.click(screen.getAllByRole("button")[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledWith("z1", 5);+ await act(async () => {+ // Let the request settle so the follow-effect is allowed to copy the prop.+ });++ // An undo lands on 2 instead of the 5 this control asked for.+ rerender(<ZoomLevelControl region={{ id: "z1", depth: 2 }} tl={{ updateZoomDepth }} />);+ fireEvent.click(screen.getAllByRole("button")[1] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getAllByRole("button")[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledTimes(2);+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 5);+ });++ it("steps to the neighbouring level with the arrow keys and moves focus with it", () => {+ const { updateZoomDepth, group, buttons, focusLevel } = renderControlled(3);+ focusLevel(3);+ fireEvent.keyDown(group, { key: "ArrowRight" });+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 4);+ expect(buttons[3]).toHaveFocus();+ fireEvent.keyDown(group, { key: "ArrowDown" });+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 5);+ expect(buttons[4]).toHaveFocus();+ fireEvent.keyDown(group, { key: "ArrowLeft" });+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 4);+ fireEvent.keyDown(group, { key: "ArrowUp" });+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 3);+ expect(buttons[2]).toHaveFocus();+ expect(updateZoomDepth).toHaveBeenCalledTimes(4);+ expect(buttons[2]).toHaveAttribute("aria-pressed", "true");+ });++ // Every level is a Tab stop, so focus can sit on a level that is not the selected one.+ // Counting from the selection there moved focus the wrong way across the row.+ it("steps from the button that has focus, not from the selected level", () => {+ const { updateZoomDepth, group, buttons, focusLevel } = renderControlled(2);+ focusLevel(5);+ fireEvent.keyDown(group, { key: "ArrowRight" });+ expect(buttons[5]).toHaveFocus();+ expect(updateZoomDepth).toHaveBeenCalledWith("z1", 6);+ });++ // `updateZoomDepth` writes the document, so the pressed state only catches up a tick later.+ // Focus moves in the keystroke itself, which is why holding an arrow down keeps advancing+ // instead of re-applying the same step against a `depth` prop that has not landed yet.+ it("keeps stepping while the write is still in flight", () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ function Harness() {+ const [depth, setDepth] = useState<ZoomDepth>(3);+ return (+ <ZoomLevelControl+ region={{ id: "z1", depth }}+ tl={{+ updateZoomDepth: async (id, next) => {+ await updateZoomDepth(id, next);+ setDepth(next);+ return true;+ },+ }}+ />+ );+ }+ render(<Harness />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ (buttons[2] as HTMLButtonElement).focus();+ fireEvent.keyDown(group, { key: "ArrowRight" });+ fireEvent.keyDown(group, { key: "ArrowRight" });+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5]);+ expect(buttons[4]).toHaveFocus();+ });++ // The mirror image of the test above, and the one that catches a stale read: stepping+ // BACK to where the region started. The guard that makes re-pressing the current level a+ // no-op has to compare against what was last asked for, not against a `depth` prop that+ // still says 3 because the first write has not landed -- or the user's second keystroke+ // is dropped and the level stays on 4.+ it("does not drop a step back while the first write is still in flight", () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ function Harness() {+ const [depth, setDepth] = useState<ZoomDepth>(3);+ return (+ <ZoomLevelControl+ region={{ id: "z1", depth }}+ tl={{+ updateZoomDepth: async (id, next) => {+ await updateZoomDepth(id, next);+ setDepth(next);+ return true;+ },+ }}+ />+ );+ }+ render(<Harness />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ (buttons[2] as HTMLButtonElement).focus();+ fireEvent.keyDown(group, { key: "ArrowRight" });+ fireEvent.keyDown(group, { key: "ArrowLeft" });+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 3]);+ expect(buttons[2]).toHaveFocus();+ });++ // `saveDocument` writes the returned document into the store and only then+ // resolves, so an earlier request can echo back while a later one is still in+ // flight. Copying that echo into the no-op guard made ArrowLeft look like a+ // re-press of the current level: 3 → 4 → 5, 4 lands, ArrowLeft dropped, and+ // the level stayed on 5 with focus on 4.+ it("does not treat an earlier in-flight write as the latest request", async () => {+ const resolvers: Array<() => void> = [];+ const updateZoomDepth = vi.fn((_id: string, _depth: ZoomDepth) => {+ return new Promise<boolean>((resolve) => {+ resolvers.push(() => resolve(true));+ });+ });+ function Harness() {+ const [depth, setDepth] = useState<ZoomDepth>(3);+ return (+ <ZoomLevelControl+ region={{ id: "z1", depth }}+ tl={{+ updateZoomDepth: (id, next) => {+ const pending = updateZoomDepth(id, next);+ void pending.then(() => setDepth(next));+ return pending;+ },+ }}+ />+ );+ }+ render(<Harness />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ (buttons[2] as HTMLButtonElement).focus();+ fireEvent.keyDown(group, { key: "ArrowRight" });+ fireEvent.keyDown(group, { key: "ArrowRight" });+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5]);+ expect(resolvers).toHaveLength(2);++ await act(async () => {+ resolvers[0]!();+ });+ expect(buttons[3]).toHaveAttribute("aria-pressed", "true");+ expect(buttons[4]).toHaveFocus();++ fireEvent.keyDown(group, { key: "ArrowLeft" });+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5, 4]);+ expect(buttons[3]).toHaveFocus();+ });++ // Depth values repeat, so an older request landing on 4 must not look like+ // the later request for 4 has confirmed, or the 5 in between is treated as+ // an external write and the latest 4 is lost.+ it("does not treat an older request for the same depth as the latest one", async () => {+ const resolvers: Array<() => void> = [];+ const updateZoomDepth = vi.fn((_id: string, _depth: ZoomDepth) => {+ return new Promise<boolean>((resolve) => {+ resolvers.push(() => resolve(true));+ });+ });+ function Harness() {+ const [depth, setDepth] = useState<ZoomDepth>(3);+ return (+ <ZoomLevelControl+ region={{ id: "z1", depth }}+ tl={{+ updateZoomDepth: (id, next) => {+ const pending = updateZoomDepth(id, next);+ void pending.then(() => setDepth(next));+ return pending;+ },+ }}+ />+ );+ }+ render(<Harness />);+ const group = screen.getByRole("group", { name: "zoom.level" });+ const buttons = screen.getAllByRole("button");+ (buttons[2] as HTMLButtonElement).focus();+ fireEvent.keyDown(group, { key: "ArrowRight" });+ fireEvent.keyDown(group, { key: "ArrowRight" });+ fireEvent.keyDown(group, { key: "ArrowLeft" });+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5, 4]);++ await act(async () => {+ resolvers[0]!();+ });+ await act(async () => {+ resolvers[1]!();+ });+ fireEvent.click(buttons[4] as HTMLButtonElement);+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5, 4, 5]);+ });++ it("does not leak a pending request onto a different zoom region", async () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ const { rerender } = render(+ <ZoomLevelControl region={{ id: "A", depth: 3 }} tl={{ updateZoomDepth }} />,+ );+ fireEvent.click(screen.getAllByRole("button")[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledWith("A", 5);++ rerender(<ZoomLevelControl region={{ id: "B", depth: 3 }} tl={{ updateZoomDepth }} />);+ fireEvent.click(screen.getAllByRole("button")[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenLastCalledWith("B", 5);+ expect(updateZoomDepth).toHaveBeenCalledTimes(2);+ });++ it("follows an undo after rapid steps have all settled", async () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => true);+ const { rerender } = render(+ <ZoomLevelControl region={{ id: "z1", depth: 3 }} tl={{ updateZoomDepth }} />,+ );+ const buttons = screen.getAllByRole("button");+ fireEvent.click(buttons[3] as HTMLButtonElement);+ fireEvent.click(buttons[4] as HTMLButtonElement);+ expect(updateZoomDepth.mock.calls.map(([, depth]) => depth)).toEqual([4, 5]);+ await act(async () => {+ // both generations must drain, or the follow-effect stays blocked+ });++ rerender(<ZoomLevelControl region={{ id: "z1", depth: 4 }} tl={{ updateZoomDepth }} />);+ fireEvent.click(buttons[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledTimes(3);+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 5);+ });++ it("retries the same level after a failed save", async () => {+ const updateZoomDepth = vi.fn(async (_id: string, _depth: ZoomDepth) => false);+ render(<ZoomLevelControl region={{ id: "z1", depth: 3 }} tl={{ updateZoomDepth }} />);+ const buttons = screen.getAllByRole("button");+ fireEvent.click(buttons[4] as HTMLButtonElement);+ await act(async () => {+ // settle the failed write so the same target is not stuck as current+ });+ fireEvent.click(buttons[4] as HTMLButtonElement);+ expect(updateZoomDepth).toHaveBeenCalledTimes(2);+ expect(updateZoomDepth).toHaveBeenLastCalledWith("z1", 5);+ });++ it("clamps at the lowest level instead of wrapping", () => {+ const { updateZoomDepth, group, buttons, focusLevel } = renderControlled(1);+ focusLevel(1);+ fireEvent.keyDown(group, { key: "ArrowLeft" });+ expect(updateZoomDepth).not.toHaveBeenCalled();+ expect(buttons[0]).toHaveFocus();+ });++ it("clamps at the highest level instead of wrapping", () => {+ const { updateZoomDepth, group, buttons, focusLevel } = renderControlled(6);+ focusLevel(6);+ fireEvent.keyDown(group, { key: "ArrowRight" });+ expect(updateZoomDepth).not.toHaveBeenCalled();+ expect(buttons[5]).toHaveFocus();+ });++ it("keeps its own keys off the window listener, and lets every other key through", () => {+ // The editor shell listens on WINDOW, above React's root container: ArrowLeft/ArrowRight+ // seek the playhead there and Space is play/pause. Space matters most — the shell+ // `preventDefault()`s it, which cancels the button's own activation, so an unstopped+ // Space changed no level and started playback instead.+ //+ // What this pins is the propagation rule, which is where the bug was. jsdom does not+ // dispatch a button's native activation for Space at all, so "Space commits the focused+ // level" is only provable in a browser, where it was checked against the running editor.+ const onWindowKey = vi.fn();+ window.addEventListener("keydown", onWindowKey);+ try {+ const { group } = renderControlled(3);+ for (const key of ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", " ", "Enter"]) {+ fireEvent.keyDown(group, { key });+ }+ expect(onWindowKey).not.toHaveBeenCalled();++ // Keys the group ignores still get there, or the editor shortcuts would be dead.+ fireEvent.keyDown(group, { key: "z" });+ fireEvent.keyDown(group, { key: "Tab" });+ expect(onWindowKey).toHaveBeenCalledTimes(2);+ } finally {+ window.removeEventListener("keydown", onWindowKey);+ }+ });++ // `preventDefault()` on the activation keys would cancel the button's own click, which is+ // exactly how the shell broke Space in the first place.+ it("does not cancel the default action of the activation keys", () => {+ const { group } = renderControlled(3);+ for (const key of ["Enter", " "]) {+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });+ group.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ }+ });+});diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 0d054eb83..0d3a3fd73 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -285,6 +285,7 @@ const DECLARED: WritePath[] = [w("src/lib/ai-edition/store/useTimeline.ts", "removeClip", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "removeRegion", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "removeRegions", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "saveZoomPatch", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "setTrimEntries", "save", "gesture"),// The live halves of the two drags.w("src/lib/ai-edition/store/useTimeline.ts", "updateAnnotationLive", "set", "automatic"),@@ -294,11 +295,7 @@ const DECLARED: WritePath[] = [w("src/lib/ai-edition/store/useTimeline.ts", "updateSpeedValue", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "updateTrim", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomClickImpact", "save", "gesture"),- w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomDepth", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomFocusLive", "set", "automatic"),- w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomFocusMode", "save", "gesture"),- w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomHideCursor", "save", "gesture"),- w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomRotation", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomSpan", "save", "gesture"),// Source-dimension backfill for assets a migration left unprobed. On load, for// every project, whether or not the user touches anything.diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.tsindex 797f39eda..ed2a10478 100644--- a/src/lib/ai-edition/store/useTimeline.test.ts+++ b/src/lib/ai-edition/store/useTimeline.test.ts@@ -1197,6 +1197,75 @@ describe("useTimeline undo history", () => {expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(2);});+ // Holds the first document save until the test releases it; every later one lands at once.+ const gateFirstSave = () => {+ const gate: { release?: () => void } = {};+ let calls = 0;+ bridgeMocks.save.mockImplementation(async (doc: AxcutDocument) => {+ calls += 1;+ if (calls === 1) {+ await new Promise<void>((resolve) => {+ gate.release = resolve;+ });+ }+ return { success: true, document: doc };+ });+ return gate;+ };++ it("lands rapid zoom-level steps in order, one undo step each", async () => {+ seed(docWithZoom);+ const gate = gateFirstSave();+ const { result } = renderTimeline();++ const p4 = result.current.updateZoomDepth("zoom_a", 4);+ const p5 = result.current.updateZoomDepth("zoom_a", 5);+ await waitFor(() => expect(gate.release).toEqual(expect.any(Function)));+ await act(async () => {+ gate.release?.();+ await Promise.all([p4, p5]);+ });++ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(5);+ act(() => {+ expect(undo()).toBe(true);+ });+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(4);+ });++ it("keeps a pending zoom level when the 3D tilt is changed before it lands", async () => {+ seed(docWithZoom);+ const gate = gateFirstSave();+ const { result } = renderTimeline();++ const pDepth = result.current.updateZoomDepth("zoom_a", 4);+ const pRotation = result.current.updateZoomRotation("zoom_a", "iso");+ await waitFor(() => expect(gate.release).toEqual(expect.any(Function)));+ await act(async () => {+ gate.release?.();+ await Promise.all([pDepth, pRotation]);+ });++ expect(useProjectStore.getState().document?.zoomRanges[0]).toMatchObject({+ depth: 4,+ rotationPreset: "iso",+ });+ });++ it("resolves a zoom-level write with whether the save took effect", async () => {+ seed(docWithZoom);+ const { result } = renderTimeline();+ bridgeMocks.save.mockResolvedValueOnce({ success: false, error: "read-only" });++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.updateZoomDepth("zoom_a", 4);+ });++ expect(ok).toBe(false);+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(3);+ });+it("leaves no undo step behind a focus drag whose commit failed", async () => {// The drag used to push its pre-drag document from the FIRST `setDocument`. When// the commit then failed, `commitZoomFocus` restored that same document throughdiff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex 72a074f53..73a3a87a5 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -44,6 +44,7 @@ import {import { dropTrimPillsByIds, resolveTimelineSpanToTrim } from "../timeline/trim-mapping";import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";import { useProjectStore, waitForDocumentSaves } from "./projectStore";+import { useSequentialTimelineOps } from "./useSequentialTimelineOps";// How long a region lasts when the caller doesn't say. The timeline's toolbar// passes its own duration instead, derived from the current zoom so the new pill@@ -705,21 +706,42 @@ export function useTimeline() {}}, [saveDocument]);+ // The zoom pane's own write chain -- see `saveZoomPatch`. Only `enqueue` is used, so+ // there is no fallback document to hand it.+ const { enqueue: enqueueZoomWrite } = useSequentialTimelineOps({+ fallbackDocument: null,+ saveDocument,+ });++ // The zoom pane's one-field writes: level, 3D tilt, focus mode, cursor. Each is a+ // whole-document save, so they share one chain and read the document INSIDE it. The level+ // buttons step while the previous save is still out, and 3 -> 4 -> 5 built both saves from+ // the render's depth-3 document: the main process does not order them, so the 4 could land+ // last, and even in order one Ctrl+Z skipped a level. A neighbouring select changed while a+ // level was pending rebuilt from that same document and put 3 back. Resolves+ // `saveDocument`'s answer, so the level buttons can retry a failed write.+ const saveZoomPatch = useCallback(+ (id: string, patch: Partial<AxcutDocument["zoomRanges"][number]>) =>+ enqueueZoomWrite(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return false;+ return saveDocument(+ {+ ...doc,+ zoomRanges: patchPillById(doc.zoomRanges, id, patch) as AxcutDocument["zoomRanges"],+ },+ { history: true },+ );+ }),+ [enqueueZoomWrite, saveDocument],+ );+// Zoom-level control for the region-settings panel (1-6, matches// zoomRegionSchema's depth literal union — 1.0x..3.5x in 0.5x steps per// the `depth/2 + 0.5` label formula used throughout the timeline UI).const updateZoomDepth = useCallback(- async (id: string, depth: 1 | 2 | 3 | 4 | 5 | 6) => {- if (!document) return;- const next: AxcutDocument = {- ...document,- zoomRanges: patchPillById(document.zoomRanges, id, {- depth,- }) as AxcutDocument["zoomRanges"],- };- await saveDocument(next, { history: true });- },- [document, saveDocument],+ (id: string, depth: 1 | 2 | 3 | 4 | 5 | 6) => saveZoomPatch(id, { depth }),+ [saveZoomPatch],);// Same story as `focusMode` below: the 3D tilt was implemented end to end — schema@@ -728,17 +750,9 @@ export function useTimeline() {// `undefined` clears the preset back to a flat frame; `migrate.ts` already drops the field// when it is falsy, so absent and "no rotation" are the same state.const updateZoomRotation = useCallback(- async (id: string, rotationPreset: Rotation3DPreset | undefined) => {- if (!document) return;- const next: AxcutDocument = {- ...document,- zoomRanges: patchPillById(document.zoomRanges, id, {- rotationPreset,- }) as AxcutDocument["zoomRanges"],- };- await saveDocument(next, { history: true });- },- [document, saveDocument],+ (id: string, rotationPreset: Rotation3DPreset | undefined) =>+ saveZoomPatch(id, { rotationPreset }),+ [saveZoomPatch],);// Nothing could set `focusMode`: "auto" only ever arrived from the automatic suggestion pass@@ -750,31 +764,14 @@ export function useTimeline() {// Writing "manual" explicitly is safe even though `migrate.ts` only persists "auto": an absent// field MEANS manual, so both forms resolve identically.const updateZoomFocusMode = useCallback(- async (id: string, focusMode: "manual" | "auto") => {- if (!document) return;- const next: AxcutDocument = {- ...document,- zoomRanges: patchPillById(document.zoomRanges, id, {- focusMode,- }) as AxcutDocument["zoomRanges"],- };- await saveDocument(next, { history: true });- },- [document, saveDocument],+ (id: string, focusMode: "manual" | "auto") => saveZoomPatch(id, { focusMode }),+ [saveZoomPatch],);const updateZoomHideCursor = useCallback(- async (id: string, hideCursor: boolean | undefined) => {- if (!document) return;- const next: AxcutDocument = {- ...document,- zoomRanges: patchPillById(document.zoomRanges, id, {- hideCursor: hideCursor ? true : undefined,- }) as AxcutDocument["zoomRanges"],- };- await saveDocument(next, { history: true });- },- [document, saveDocument],+ (id: string, hideCursor: boolean | undefined) =>+ saveZoomPatch(id, { hideCursor: hideCursor ? true : undefined }),+ [saveZoomPatch],);// Per-region, like the preset it animates. `undefined` rather than `false` so the documentdiff --git a/tests/e2e/v4-shell.spec.ts b/tests/e2e/v4-shell.spec.tsindex 1df64a83d..79c1dd4b4 100644--- a/tests/e2e/v4-shell.spec.ts+++ b/tests/e2e/v4-shell.spec.ts@@ -14,6 +14,18 @@ const EDITOR_URL = `${BASE_URL}/?windowType=editor`;// 300 MB exactly, so MediaStage's formatSize renders "300 MB".const SIZED_BYTES = 314_572_800;+// Only what a zoom region needs to survive `documentSchema` and reach the timeline.+interface ZoomFixture {+ id: string;+ startMs: number;+ endMs: number;+ clipId: string;+ sourceStartSec: number;+ sourceEndSec: number;+ depth: 1 | 2 | 3 | 4 | 5 | 6;+ focus: { cx: number; cy: number };+}+function makeAsset(id: string, label: string, sizeBytes?: number) {return {id,@@ -64,7 +76,7 @@ function makeDoc() {captionRanges: [],},annotations: [],- zoomRanges: [],+ zoomRanges: [] as ZoomFixture[],legacyEditor: null,agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },preview: { strategy: "seek" as const, revision: 0 },@@ -73,6 +85,26 @@ function makeDoc() {};}+// Same fixture with one zoom region on the only clip, so the inspector's zoom pane —+// and the level row inside it — has something to select. Depth 3 is the editor's default,+// and `ZOOM_DEPTH_SCALES` renders it as the "1.80×" the pill is addressed by below.+function makeZoomDoc(): ReturnType<typeof makeDoc> {+ const doc = makeDoc();+ doc.zoomRanges = [+ {+ id: "zoom_e2e",+ startMs: 60_000,+ endMs: 180_000,+ clipId: "clip_e2e",+ sourceStartSec: 60,+ sourceEndSec: 180,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ },+ ];+ return doc;+}+// Same fixture, split into two clips: FloatingInspector's "Edit clip" button// only renders its picker popover past one clip (clips.length === 1 jumps// straight to onEditClip instead), so testing the popover needs a second clip.@@ -243,6 +275,60 @@ test.describe("v4 editor shell", () => {expect(await storeTimeSec()).toBeGreaterThan(400);});+ // The zoom levels are buttons rather than a `<select>` (issue #670), which puts them+ // under the shell's WINDOW key handling: Space there is play/pause and it+ // `preventDefault()`s the keydown, which cancels a button's own activation outright.+ // jsdom dispatches no native activation for Space at all, so a browser is the only+ // place that can hold the line that Space still commits the focused level.+ test("the zoom level row commits the focused level on Space and keeps focus in place", async ({+ page,+ }) => {+ await seedAndOpen(page, makeZoomDoc());+ await page.locator('[class*="lanePill"][title="1.80×"]').first().click();++ const levels = page.getByRole("group", { name: "Zoom Level" }).getByRole("button");+ await expect(levels).toHaveCount(6);++ // One row inside the 300px pane, with every label intact: the reason this control+ // stacks its own label instead of sitting in a `paneRow` like its neighbours.+ const tops = await levels.evaluateAll((els) =>+ els.map((el) => Math.round(el.getBoundingClientRect().top)),+ );+ expect(new Set(tops).size).toBe(1);+ expect(+ await levels.evaluateAll((els) => els.every((el) => el.scrollWidth <= el.clientWidth + 1)),+ ).toBe(true);++ const depth = () =>+ page.evaluate(+ () =>+ (+ window as unknown as {+ __osProjectStore: {+ getState: () => { document: { zoomRanges: Array<{ depth: number }> } | null };+ };+ }+ ).__osProjectStore.getState().document?.zoomRanges[0]?.depth ?? null,+ );+ expect(await depth()).toBe(3);++ await levels.nth(3).focus(); // 2.2×, depth 4+ await page.keyboard.press("Space");+ await expect.poll(depth).toBe(4);+ await expect(levels.nth(3)).toBeFocused();++ // Arrows step from the focused level, not from the selected one: every level is a+ // Tab stop, so ArrowRight on the last button has nowhere to go — and must not throw+ // focus back across the row to wherever the selection happens to be.+ await levels.nth(5).focus();+ await page.keyboard.press("ArrowRight");+ await expect(levels.nth(5)).toBeFocused();+ expect(await depth()).toBe(4);+ await page.keyboard.press("ArrowLeft");+ await expect.poll(depth).toBe(5);+ await expect(levels.nth(4)).toBeFocused();+ });+test("clicking outside the clip picker popover closes it", async ({ page }) => {await seedAndOpen(page, makeTwoClipDoc());