Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

56.5 KB
Raw Blame
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { Profiler, type ProfilerOnRenderCallback } from "react";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

// The regression under test is geometric, so the environment has to have a size:
// jsdom reports 0 for every box, which would leave `pxPerSec` at 0 (the
// "unmeasured" case) and hide exactly the thing being checked.
const VIEWPORT_PX = 900;
const TOTAL_SEC = 1800; // a 30-minute recording, as in the report

// Every string renders as its bare key, except in the lane-hint tests, which swap in the real
// English copy to read the key interpolated into it.
const i18n = vi.hoisted(() => ({
	translate: null as
		| null
		| ((namespace: string, key: string, vars?: Record<string, string | number>) => string),
}));
vi.mock("@/contexts/I18nContext", () => ({
	useScopedT: (namespace: string) => (key: string, vars?: Record<string, string | number>) =>
		i18n.translate ? i18n.translate(namespace, key, vars) : key,
}));
vi.mock("sonner", () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
// The audio lane's pill renders a ClipWaveform; no decode in this geometry suite.
vi.mock("@/hooks/useAudioPeaks", () => ({ useAudioPeaks: () => null }));

// The duration gate reads its timecode's width off a canvas context. jsdom has
// no canvas, so every test here runs against this stub: 6px a character, the
// same figure the component's no-canvas fallback assumes, which keeps the width
// arithmetic in the tests below the one the first cut reasoned in. The
// measured-path test re-aims it at a wider face and expects the gate to follow.
const measureText = vi.fn((text: string) => ({ width: text.length * 6 }));

import { ShortcutsProvider } from "@/contexts/ShortcutsContext";
import type { I18nNamespace } from "@/i18n/config";
import { getAvailableLocales, translate } from "@/i18n/loader";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { DEFAULT_SHORTCUTS, formatBinding } from "@/lib/shortcuts";
import { zoomTransitionMs } from "@/lib/zoomMath/constants";
import { V4Timeline } from "./V4Timeline";

beforeEach(() => useProjectStore.setState({ currentTimeSec: 0 }));

beforeAll(() => {
	globalThis.ResizeObserver = class {
		// jsdom has none, and the width it would report is stubbed below anyway.
		observe() {
			/* noop */
		}
		unobserve() {
			/* noop */
		}
		disconnect() {
			/* noop */
		}
	} as unknown as typeof ResizeObserver;
	Object.defineProperty(HTMLElement.prototype, "clientWidth", {
		configurable: true,
		get: () => VIEWPORT_PX,
	});
	Object.defineProperty(HTMLElement.prototype, "getBoundingClientRect", {
		configurable: true,
		value: () => ({
			x: 0,
			y: 0,
			left: 0,
			top: 0,
			right: VIEWPORT_PX,
			bottom: 100,
			width: VIEWPORT_PX,
			height: 100,
			toJSON() {
				/* unused by the component */
			},
		}),
	});
	vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(
		() => ({ measureText }) as unknown as CanvasRenderingContext2D,
	);
});

afterEach(() => {
	measureText.mockImplementation((text: string) => ({ width: text.length * 6 }));
});

function clip(startSec: number, endSec: number) {
	return {
		id: `c@${startSec}`,
		assetId: "a1",
		timelineStartSec: startSec,
		timelineEndSec: endSec,
		sourceStartSec: 0,
		sourceEndSec: endSec - startSec,
	};
}

/** The asset every clip above points at. With no camera, only screen-only is available. */
const NO_CAMERA_ASSET = { id: "a1", label: "rec", durationSec: TOTAL_SEC };
/** The same recording with a camera track: camera layout presets become available. */
const CAMERA_ASSET = {
	...NO_CAMERA_ASSET,
	cameraTrack: { sourcePath: "/tmp/cam.webm", startMs: 0, offsetMs: 0, visible: true },
};

/** By default one 30-minute clip carrying a single one-second annotation, and a store that
 *  holds an edit region (so Clear timeline shows); `overrides` replaces any `tl` member. */
function renderTimeline(
	clips = [clip(0, TOTAL_SEC)],
	annotation = { id: "ann1", startMs: 10_000, endMs: 11_000 },
	assets: Array<Record<string, unknown>> = [NO_CAMERA_ASSET],
	onRender?: ProfilerOnRenderCallback,
	overrides: Record<string, unknown> = {},
) {
	const tl = {
		clips,
		// Marks for added words are read straight off the transcript (see the pane's
		// amber words) — no project here has any.
		transcripts: [],
		assets,
		annotationRegions: [annotation],
		speedRegions: [],
		cameraFullscreenRegions: [],
		shaderEffectRanges: [],
		shaderEffects: [],
		layoutSegments: [],
		hasDoc: true,
		zoomRegions: [],
		trimRanges: [],
		hasEditRegions: true,
		selection: null,
		multiSelection: [],
		clipSelection: null,
		audioTracks: [],
		selectedAudioTrackId: null,
		selectAudioTrack: vi.fn(),
		clearSelection: vi.fn(),
		selectRegion: vi.fn(),
		selectClip: vi.fn(),
		updateAnnotationSpan: vi.fn(async () => {
			/* the drag only awaits it */
		}),
		addZoom: vi.fn(async () => {
			/* the toolbar only awaits it */
		}),
		clearTimeline: vi.fn(async () => {
			/* the toolbar only awaits it */
		}),
		...overrides,
	};
	const setCurrentTime = vi.fn();
	const onAnnotationRowCountChange = vi.fn();
	const timeline = (variant: "edit" | "media" = "edit") => (
		<ShortcutsProvider>
			<V4Timeline
				variant={variant}
				// Only the members the lanes and the clip row read are mocked; the prop
				// stays typed as the real API rather than widened to `any` (AGENTS.md).
				tl={tl as unknown as ReturnType<typeof useTimeline>}
				setCurrentTime={setCurrentTime}
				playing={false}
				onTogglePlay={vi.fn()}
				onEditClip={vi.fn()}
				onAddVoiceover={vi.fn()}
				onAnnotationRowCountChange={onAnnotationRowCountChange}
			/>
		</ShortcutsProvider>
	);
	const view = render(
		onRender ? (
			<Profiler id="timeline" onRender={onRender}>
				{timeline()}
			</Profiler>
		) : (
			timeline()
		),
	);
	return {
		rerenderVariant: (variant: "edit" | "media") => view.rerender(timeline(variant)),
		onAnnotationRowCountChange,
		// A getter: a test that empties `annotationRegions` renders no such pill, and an eager
		// lookup would throw before its own assertions ran.
		get pill() {
			return screen.getByTitle(/^toolbar\.newAnnotation/);
		},
		clipEls: Array.from(document.querySelectorAll<HTMLElement>("[data-clip-id]")),
		tl,
		setCurrentTime,
	};
}

afterEach(() => {
	vi.unstubAllGlobals();
});

/** Drag a handle by `dxPx`. The move/up listeners live on `window`, so the drag
 *  is driven by pointer deltas alone — the handle may re-mount under it. */
function dragHandle(handle: Element, dxPx: number) {
	fireEvent.pointerDown(handle, { clientX: 0 });
	window.dispatchEvent(new MouseEvent("pointermove", { clientX: dxPx }));
	window.dispatchEvent(new MouseEvent("pointerup", { clientX: dxPx }));
}

/** Ctrl+wheel up = zoom in; the handler is a native listener, so dispatch real events.
 *  Takes the target element so a test can prove the listener isn't confined to the
 *  lanes — it fires from wherever in the pane the cursor happens to be. */
function wheelZoomOn(el: HTMLElement, notches: number) {
	for (let i = 0; i < notches; i++) {
		fireEvent.wheel(el, { ctrlKey: true, deltaY: -100, clientX: 0 });
	}
}
function zoomIn(notches: number) {
	wheelZoomOn(document.querySelector("[class*=tlTracks]") as HTMLElement, notches);
}

describe("timeline tracks", () => {
	afterEach(cleanup);

	it("shows identical nested annotations on separate rows and selects each independently", () => {
		const { tl } = renderTimeline(undefined, undefined, undefined, undefined, {
			annotationRegions: [
				{ id: "main", startMs: 0, endMs: 67000, type: "text", content: "Same", zIndex: 1 },
				{ id: "second", startMs: 35000, endMs: 40000, type: "text", content: "Same", zIndex: 1 },
			],
		});
		const pills = [...document.querySelectorAll<HTMLElement>("[data-region-id]")];
		expect(pills).toHaveLength(2);
		expect(new Set(pills.map((p) => p.style.top)).size).toBe(2);
		for (const pill of pills) {
			fireEvent.keyDown(pill, { key: "Enter" });
			expect(tl.selectRegion).toHaveBeenLastCalledWith("annotation", pill.dataset.regionId, {
				additive: false,
			});
		}
	});

	it("reuses a single row for back-to-back annotations and keeps the empty lane free of drag hints", () => {
		renderTimeline(undefined, undefined, undefined, undefined, {
			annotationRegions: Array.from({ length: 10 }, (_, i) => ({
				id: `ann-${i}`,
				startMs: i * 1000,
				endMs: (i + 1) * 1000,
				zIndex: i + 1,
			})),
		});
		const lane = document.querySelector<HTMLElement>(
			'[data-track-kind="annotation"]',
		) as HTMLElement;
		expect(lane.style.height).toBe("24px");
		expect(lane.title).toBe("");
		expect(
			new Set([...lane.querySelectorAll<HTMLElement>("[data-region-id]")].map((p) => p.style.top))
				.size,
		).toBe(1);
		expect(lane.querySelector<HTMLElement>("[data-region-id]")?.title).toContain("tracks.dragHint");
		cleanup();
		renderTimeline(undefined, undefined, undefined, undefined, { annotationRegions: [] });
		expect(document.querySelector<HTMLElement>('[data-track-kind="annotation"]')?.title).toBe("");
	});

	it("creates a separate live row when a horizontal drag moves into an existing annotation", () => {
		const { tl, onAnnotationRowCountChange } = renderTimeline(
			undefined,
			undefined,
			undefined,
			undefined,
			{
				annotationRegions: [
					{ id: "main", startMs: 0, endMs: 100000, zIndex: 1 },
					{ id: "second", startMs: 200000, endMs: 300000, zIndex: 1 },
				],
			},
		);
		expect(onAnnotationRowCountChange).toHaveBeenLastCalledWith(1);
		const second = document.querySelector<HTMLElement>('[data-region-id="second"]') as HTMLElement;
		const main = document.querySelector<HTMLElement>('[data-region-id="main"]') as HTMLElement;
		fireEvent.pointerDown(second, { clientX: 100, clientY: 10 });
		act(() => {
			window.dispatchEvent(new MouseEvent("pointermove", { clientX: 10, clientY: 10 }));
		});
		expect(onAnnotationRowCountChange).toHaveBeenLastCalledWith(2);
		expect(second.style.top).not.toBe(main.style.top);
		expect(
			document.querySelector<HTMLElement>('[data-track-kind="annotation"]')?.style.height,
		).toBe("51px");
		act(() => {
			window.dispatchEvent(new MouseEvent("pointerup"));
		});
		expect(tl.updateAnnotationSpan).toHaveBeenCalledWith("second", 20000, 120000);
	});

	it("moves annotations vertically between existing layers and creates layers above and below", () => {
		const { tl } = renderTimeline(undefined, undefined, undefined, undefined, {
			annotationRegions: [
				{ id: "low", startMs: 0, endMs: 100000, zIndex: 0 },
				{ id: "high", startMs: 0, endMs: 100000, zIndex: 4 },
			],
		});
		const low = document.querySelector<HTMLElement>('[data-region-id="low"]') as HTMLElement;
		expect(low.dataset.trackRow).toBe("1");
		for (const dy of [-27, -54, 27]) {
			fireEvent.pointerDown(low, { clientX: 10, clientY: 100 });
			act(() => {
				window.dispatchEvent(new MouseEvent("pointermove", { clientX: 10, clientY: 100 + dy }));
			});
			act(() => {
				window.dispatchEvent(new MouseEvent("pointerup"));
			});
			expect(tl.updateAnnotationSpan).toHaveBeenLastCalledWith("low", 0, 100000, {
				row: 1 + dy / 27,
				direction: dy < 0 ? "up" : "down",
			});
		}
	});

	it("keeps speed regions in a single lane", () => {
		renderTimeline(undefined, undefined, undefined, undefined, {
			annotationRegions: [],
			speedRegions: [
				{ id: "a", startMs: 0, endMs: 67000, speed: 2 },
				{ id: "b", startMs: 35000, endMs: 40000, speed: 3 },
			],
		});
		const pills = [
			...document.querySelectorAll<HTMLElement>('[data-track-kind="speed"] [data-region-id]'),
		];
		expect(pills).toHaveLength(2);
		expect(pills[0].style.top).toBe(pills[1].style.top);
	});
});

describe("V4Timeline scrubbing", () => {
	it("publishes at most one React scrub-state update per animation frame", () => {
		const frames = new Map<number, FrameRequestCallback>();
		let nextFrameId = 1;
		vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
			const frameId = nextFrameId++;
			frames.set(frameId, callback);
			return frameId;
		});
		vi.stubGlobal("cancelAnimationFrame", (frameId: number) => {
			frames.delete(frameId);
		});
		const onRender = vi.fn<ProfilerOnRenderCallback>();
		const { setCurrentTime } = renderTimeline(
			[clip(0, TOTAL_SEC)],
			{ id: "ann1", startMs: 10_000, endMs: 11_000 },
			[NO_CAMERA_ASSET],
			onRender,
		);
		const ruler = document.querySelector<HTMLElement>("[class*=tlRulerRow]");
		expect(ruler).not.toBeNull();

		// What ONE scrub-state update costs in commits, measured on the pointer-down seek
		// (which sets it once, synchronously) rather than hardcoded: the toolbar's Radix
		// tooltip triggers re-attach their ref on every commit and add a nested one.
		const commitsBeforePointerDown = onRender.mock.calls.length;
		fireEvent.pointerDown(ruler as HTMLElement, { button: 0, clientX: 90 });
		const commitsPerUpdate = onRender.mock.calls.length - commitsBeforePointerDown;
		expect(commitsPerUpdate).toBeGreaterThan(0);

		// Over two frames: no pointer move commits, and each frame costs exactly one
		// update however many moves it coalesced.
		for (const [clientXs, expectedSec] of [
			[[180, 270, 360], 720],
			[[450, 540], 1080],
		] as const) {
			const commitsBeforeFrame = onRender.mock.calls.length;
			setCurrentTime.mockClear();
			for (const clientX of clientXs) fireEvent.pointerMove(window, { clientX });

			expect(onRender).toHaveBeenCalledTimes(commitsBeforeFrame);
			expect(setCurrentTime).not.toHaveBeenCalled();
			expect(frames.size).toBe(1);

			const [[frameId, frame]] = frames;
			frames.delete(frameId);
			act(() => frame(0));

			expect(onRender).toHaveBeenCalledTimes(commitsBeforeFrame + commitsPerUpdate);
			expect(setCurrentTime).toHaveBeenCalledTimes(1);
			expect(setCurrentTime).toHaveBeenCalledWith(expectedSec);
		}
		fireEvent.pointerUp(window);
	});
});

describe("V4Timeline lane pills", () => {
	it("draws a pill exactly as wide as its region, at any zoom", () => {
		// 1 s of 1800 s. The old `Math.max(1.5, …)` floor drew this as 1.5% — 27
		// seconds of ruler for a one-second annotation — and did it at every zoom,
		// since the floor was a percentage of the timeline rather than of the screen.
		const { pill } = renderTimeline();
		const expected = (1 / TOTAL_SEC) * 100;
		expect(Number.parseFloat(pill.style.width)).toBeCloseTo(expected, 6);

		// The canvas is what scales with zoom, so the pill's share of it must not
		// move at all — only the chrome inside it may react (below).
		zoomIn(40);
		expect(Number.parseFloat(pill.style.width)).toBeCloseTo(expected, 6);
	});

	it("keeps both resize handles reachable when the pill is thinner than they are", () => {
		// 0.5 px wide at this zoom: the handles cannot sit inside the box without
		// swallowing it whole, so they mount outside it and the body stays a move
		// target. Resizing a hairline stays possible — it is the pointer precision
		// that is coarse there, not the affordance that is missing.
		const { pill } = renderTimeline();
		const [left, right] = Array.from(pill.querySelectorAll("span"));
		expect(left.style.left).toBe("-10px");
		expect(right.style.right).toBe("-10px");
		// Nothing legible fits, so no icon/label is rendered (the title attribute
		// still carries the value on hover).
		expect(pill.textContent).toBe("");

		// Zoomed to the 50× ceiling the same second is 25 px wide and hosts its own
		// chrome again.
		zoomIn(40);
		expect(left.style.left).toBe("0px");
		expect(right.style.right).toBe("0px");
	});

	it("grows and shrinks a hairline pill from its outside handles", () => {
		// Growing is unbounded by the pill's own size: 90 px right of a 900 px canvas
		// is a tenth of the 1800 s timeline, so the 10–11 s annotation ends at 191 s.
		// The chrome re-flows inside the box as it crosses PILL_HANDLES_MIN_PX
		// mid-drag, which the gesture never notices — the deltas come from the
		// pointer and the listeners live on `window`, not on the handle.
		const { pill, tl } = renderTimeline();
		const [left, right] = Array.from(pill.querySelectorAll("span"));
		dragHandle(right, 90);
		expect(tl.updateAnnotationSpan).toHaveBeenCalledWith("ann1", 10_000, 191_000);

		// Shrinking stops at the storage grid (1 ms), not at the old flat 200 ms
		// floor that refused the last fifth of a second however far you zoomed in.
		dragHandle(left, 90_000);
		expect(tl.updateAnnotationSpan).toHaveBeenLastCalledWith("ann1", 10_999, 11_000);

		// 18 s short of the timeline end: 9 px away on screen, so it stays where it
		// was dropped. The snap radius used to be 1.2% of the timeline — a 21-second
		// magnet here — which is what made a grown edge jump to a clip boundary it
		// was nowhere near, the more so the longer the recording.
		dragHandle(right, 885.5);
		expect(tl.updateAnnotationSpan).toHaveBeenLastCalledWith("ann1", 10_000, 1_782_000);
	});

	// Two regions with nothing to tell them apart, 100–130 s and 130–160 s: one pill over
	// 50–80 px. An edit must reach the one the user pointed at, or the pill never splits.
	const MERGED = {
		annotationRegions: [
			{ id: "ann1", startMs: 100_000, endMs: 130_000 },
			{ id: "ann2", startMs: 130_000, endMs: 160_000 },
		],
	};

	it("selects the region under the pointer on a pill merged from two (#1017)", () => {
		const { pill, tl } = renderTimeline(undefined, undefined, undefined, undefined, MERGED);
		for (const [clientX, id] of [
			[75, "ann2"],
			[55, "ann1"],
		] as const) {
			fireEvent.pointerDown(pill, { clientX });
			window.dispatchEvent(new MouseEvent("pointerup", { clientX }));
			expect(tl.selectRegion).toHaveBeenLastCalledWith("annotation", id, { additive: false });
		}
	});

	it("moves a merged pill by the region it was grabbed by, which keeps the selection alive", () => {
		const { pill, tl } = renderTimeline(undefined, undefined, undefined, undefined, MERGED);
		fireEvent.pointerDown(pill, { clientX: 75 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 165 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 165 }));
		expect(tl.updateAnnotationSpan).toHaveBeenCalledWith(
			"ann2",
			expect.any(Number),
			expect.any(Number),
		);
	});

	it("draws a merged pill selected whichever of its regions is", () => {
		const { pill } = renderTimeline(undefined, undefined, undefined, undefined, {
			...MERGED,
			selection: { kind: "annotation", id: "ann2" },
		});
		expect(pill.className).toContain("lanePillSel");
	});
});

describe("V4Timeline effects lane", () => {
	// CSS modules hash the class to `_tlLane_<hash>` under Vitest.
	const lanes = () =>
		Array.from(document.querySelectorAll("div")).filter((el) =>
			Array.from(el.classList).some((c) => /^_tlLane_/.test(c)),
		).length;

	it("shows only while the project has an effect, and names the pill after it", () => {
		renderTimeline();
		const without = lanes();
		cleanup();

		renderTimeline(undefined, undefined, undefined, undefined, {
			shaderEffects: [{ id: "fx_1", name: "Dim" }],
			shaderEffectRanges: [{ id: "fxr_1", startMs: 20_000, endMs: 21_000, effectId: "fx_1" }],
		});
		expect(lanes()).toBe(without + 1);
		expect(screen.getByTitle("Dim").className).toContain("laneShaderEffect");
	});
});

describe("V4Timeline lane pill keyboard", () => {
	// A pill carries `role="button"` and `tabIndex={0}`, so it is reachable by Tab and
	// announced as activatable. Selection was pointer-only, which meant a keyboard user
	// could focus a region and then reach nothing that acts on a selection — Delete,
	// copy/paste and the inspector all key off `tl.selection`.
	it("selects the focused pill on Enter", () => {
		const { pill, tl } = renderTimeline();
		fireEvent.keyDown(pill, { key: "Enter" });
		expect(tl.selectRegion).toHaveBeenCalledWith("annotation", "ann1", { additive: false });
	});

	it("selects it on Space too, the other key a button answers to", () => {
		const { pill, tl } = renderTimeline();
		fireEvent.keyDown(pill, { key: " " });
		expect(tl.selectRegion).toHaveBeenCalledWith("annotation", "ann1", { additive: false });
	});

	it("adds to the selection when Shift is held, matching shift-click", () => {
		const { pill, tl } = renderTimeline();
		fireEvent.keyDown(pill, { key: "Enter", shiftKey: true });
		expect(tl.selectRegion).toHaveBeenCalledWith("annotation", "ann1", { additive: true });
	});

	it("leaves every other key to the shell's shortcut handler", () => {
		// The editor binds single letters (Z adds a zoom, T a trim, D deletes). Swallowing
		// them here would silently disable every shortcut while a pill has focus.
		const { pill, tl } = renderTimeline();
		for (const key of ["z", "t", "d", "Escape", "ArrowRight"]) {
			fireEvent.keyDown(pill, { key });
		}
		expect(tl.selectRegion).not.toHaveBeenCalled();
	});

	it("stops Enter and Space reaching the window listener", () => {
		// Space is bound to play/pause on WINDOW, above React's root container. Without
		// stopping the NATIVE event the same keystroke would select the pill and toggle
		// playback; the synthetic `stopPropagation` alone does not reach that far.
		const onWindowKey = vi.fn();
		window.addEventListener("keydown", onWindowKey);
		try {
			const { pill } = renderTimeline();
			fireEvent.keyDown(pill, { key: " " });
			fireEvent.keyDown(pill, { key: "Enter" });
			expect(onWindowKey).not.toHaveBeenCalled();

			// A key the pill ignores still gets there, or the shortcuts would be dead.
			fireEvent.keyDown(pill, { key: "z" });
			expect(onWindowKey).toHaveBeenCalledTimes(1);
		} finally {
			window.removeEventListener("keydown", onWindowKey);
		}
	});
});

describe("V4Timeline create-from-toolbar", () => {
	// The button asks for a DURATION worth a fixed number of pixels at the current
	// zoom, so the pill you get is always the same size on screen — which is what
	// the flat 2 s could not do: on this 30-minute fixture zoomed out it is one
	// pixel. (It used to look fine only because the removed 1.5% minimum width
	// inflated it in the rendering.)
	const durationOf = (tl: { addZoom: ReturnType<typeof vi.fn> }) =>
		tl.addZoom.mock.calls.at(-1)?.[0] as number;

	it("scales the new region's duration with the zoom", () => {
		const { tl } = renderTimeline();
		fireEvent.click(screen.getByLabelText("buttons.addZoom"));
		// 900px viewport / 1800 s = 0.5 px per second, so a 96px pill is 192 s.
		expect(durationOf(tl)).toBeCloseTo(192, 3);

		// Zoomed to the 50x ceiling the same 96px is worth 3.84 s: same pill on
		// screen, a region 50x shorter.
		zoomIn(40);
		fireEvent.click(screen.getByLabelText("buttons.addZoom"));
		expect(durationOf(tl)).toBeCloseTo(3.84, 3);
	});

	it("zooms from a wheel over the ruler too, not just the lanes", () => {
		// The ruler row is pinned above .tlTracks (so its ticks don't scroll away
		// with the lanes) and isn't a descendant of it. The wheel listener used to
		// live on .tlTracks alone, so Ctrl/Shift+scrolling anywhere else in the
		// pane — the ruler included — silently did nothing.
		const { tl } = renderTimeline();
		const ruler = document.querySelector("[class*=tlRulerRow]") as HTMLElement;
		wheelZoomOn(ruler, 40);
		fireEvent.click(screen.getByLabelText("buttons.addZoom"));
		expect(durationOf(tl)).toBeCloseTo(3.84, 3);
	});

	it("pans from a wheel over the ruler too, not just the lanes", () => {
		// Same gap as the zoom case above, but for the Shift+wheel pan path.
		// Panning is a no-op fully zoomed out (nav already spans the whole
		// timeline, so there is nowhere to pan to), so zoom in first — from the
		// ruler too — to open up room to pan within.
		renderTimeline();
		const ruler = document.querySelector("[class*=tlRulerRow]") as HTMLElement;
		wheelZoomOn(ruler, 40);
		const navWindow = document.querySelector("[class*=tlNavWindow]") as HTMLElement;
		const before = navWindow.style.left;
		fireEvent.wheel(ruler, { shiftKey: true, deltaY: 100, clientX: 0 });
		expect(navWindow.style.left).not.toBe(before);
	});

	it("never asks for a slice too short to be worth creating", () => {
		// Past ~30x on a short timeline the pixels are worth hundredths of a
		// second; the region would be born unusable, so the duration floors.
		const { tl } = renderTimeline([clip(0, 3)]);
		zoomIn(40);
		fireEvent.click(screen.getByLabelText("buttons.addZoom"));
		expect(durationOf(tl)).toBeCloseTo(0.25, 3);
	});

	// Clear timeline (#723) follows the STORED edit regions (`tl.hasEditRegions`), never the
	// pills the lanes draw: a trim whose clip is gone is stored, cleared, and has no pill.
	// Absent, never greyed out, when there is nothing to clear.
	const toolbarOf = () => screen.getByRole("toolbar", { name: "toolbar.timelineTools" });
	const dividersIn = (toolbar: HTMLElement) =>
		Array.from(toolbar.querySelectorAll("[class*=tlToolSep]"));

	it("shows no Clear timeline button while the store holds no edit region, and no divider for it", () => {
		// A pill is drawn, and the button still follows the store.
		renderTimeline(undefined, undefined, undefined, undefined, { hasEditRegions: false });
		expect(screen.queryByLabelText("buttons.clearTimeline")).not.toBeInTheDocument();
		// Only the divider after the auto-enhance button: none is left dangling at the end.
		expect(dividersIn(toolbarOf())).toHaveLength(1);
	});

	it("shows it for a stored region no lane draws, and one click asks the store to clear", () => {
		const { tl } = renderTimeline(undefined, undefined, undefined, undefined, {
			annotationRegions: [],
			hasEditRegions: true,
		});
		expect(document.querySelector("[class*=lanePill]")).toBeNull();
		fireEvent.click(screen.getByLabelText("buttons.clearTimeline"));
		expect(tl.clearTimeline).toHaveBeenCalledTimes(1);
	});

	it("puts Clear timeline last, behind a divider, after the layout button", () => {
		renderTimeline(undefined, undefined, [CAMERA_ASSET]);
		const toolbar = toolbarOf();
		const buttons = Array.from(toolbar.querySelectorAll("button"));
		const clear = screen.getByLabelText("buttons.clearTimeline");
		expect(buttons.at(-1)).toBe(clear);

		const divider = clear.previousElementSibling;
		expect(divider?.className).toContain("tlToolSep");
		expect(divider?.previousElementSibling).toBe(screen.getByLabelText("layouts.changeHere"));
		expect(dividersIn(toolbar)).toHaveLength(2);
	});

	it.each([
		"media",
		"no-document",
		"empty-timeline",
	] as const)("closes the layout picker and ignores shortcuts while %s, without reopening on return", (condition) => {
		const { tl, rerenderVariant } = renderTimeline();
		const clips = tl.clips;
		const openPicker = () => act(() => window.dispatchEvent(new Event("openscreen:change-layout")));
		openPicker();
		expect(screen.getByRole("group", { name: "layouts.title" })).toBeInTheDocument();
		if (condition === "no-document") tl.hasDoc = false;
		if (condition === "empty-timeline") tl.clips = [];
		rerenderVariant(condition === "media" ? "media" : "edit");
		expect(screen.queryByRole("group", { name: "layouts.title" })).not.toBeInTheDocument();
		openPicker();
		tl.hasDoc = true;
		tl.clips = clips;
		rerenderVariant("edit");
		expect(screen.queryByRole("group", { name: "layouts.title" })).not.toBeInTheDocument();
		openPicker();
		expect(screen.getByRole("group", { name: "layouts.title" })).toBeInTheDocument();
	});

	it("keeps layout changes available for screen-only footage", () => {
		renderTimeline();
		const button = screen.getByRole("button", { name: "layouts.changeHere" });
		expect(button).toBeEnabled();
		expect(button).toHaveTextContent("");
	});

	it("only offers a layout change inside footage and closes its menu at gaps and the final end", () => {
		renderTimeline([clip(2, 4), clip(8, 12)]);
		const button = screen.getByRole("button", { name: "layouts.changeHere" });
		const seek = (currentTimeSec: number) =>
			act(() => useProjectStore.setState({ currentTimeSec }));
		const open = () => act(() => window.dispatchEvent(new Event("openscreen:change-layout")));
		const menu = () => screen.queryByRole("group", { name: "layouts.title" });
		expect(button).toBeDisabled();
		open();
		expect(menu()).not.toBeInTheDocument();
		seek(2);
		expect(button).toBeEnabled();
		fireEvent.click(button);
		expect(menu()).toBeInTheDocument();
		seek(3.999);
		expect(button).toBeEnabled();
		expect(menu()).toBeInTheDocument();
		seek(4);
		expect(button).toBeDisabled();
		expect(menu()).not.toBeInTheDocument();
		open();
		expect(menu()).not.toBeInTheDocument();
		seek(6);
		expect(button).toBeDisabled();
		seek(8);
		expect(button).toBeEnabled();
		expect(menu()).not.toBeInTheDocument();
		open();
		expect(menu()).toBeInTheDocument();
		seek(12);
		expect(button).toBeDisabled();
		expect(menu()).not.toBeInTheDocument();
		open();
		expect(menu()).not.toBeInTheDocument();
		seek(13);
		expect(button).toBeDisabled();
	});

	it("enables layout changes as soon as a clip's asset carries one", () => {
		renderTimeline(undefined, undefined, [
			{
				...NO_CAMERA_ASSET,
				cameraTrack: { sourcePath: "/tmp/cam.webm", startMs: 0, offsetMs: 0, visible: true },
			},
		]);
		expect(screen.getByRole("button", { name: "layouts.changeHere" })).toBeEnabled();
	});

	// The disabled button is only half the promise: an empty lane advertises the shortcut
	// that fills it, so on a camera-less project it was still inviting a `C` press that
	// `addCameraFullscreen` now refuses. It borrows the Layout pane's "No Webcam" wording
	// instead, so the two surfaces agree about the same project.
	it("does not advertise the C shortcut on a lane that cannot be filled", () => {
		renderTimeline();
		expect(screen.queryByTestId("layout-lane")).not.toBeInTheDocument();
		expect(screen.queryByText("hints.pressCameraFullscreen")).not.toBeInTheDocument();
	});

	it("advertises it again once a camera is on the timeline", () => {
		renderTimeline(undefined, undefined, [
			{
				...NO_CAMERA_ASSET,
				cameraTrack: { sourcePath: "/tmp/cam.webm", startMs: 0, offsetMs: 0, visible: true },
			},
		]);
		expect(screen.queryByTestId("layout-lane")).not.toBeInTheDocument();
		expect(screen.queryByText("layout.noWebcam")).not.toBeInTheDocument();
	});
});

describe("V4Timeline clip row", () => {
	// Three clips = two junctions. As a flex row with `gap: 6px`, each junction
	// added 6px while every clip shrank proportionally to pay for it, so a clip's
	// left edge missed its true start: measured in a browser on this very fixture,
	// clip 2 by +2px and clip 3 by +6px, while the pills and ruler above them sat
	// at the true position. Being a fixed px error in a proportional layout, it was
	// worth 5 s and 15 s of timeline zoomed out but a fraction of a second zoomed
	// in — which is what reads as "the pills move when I zoom".
	const CLIPS = [clip(0, 600), clip(600, 900), clip(900, TOTAL_SEC)];
	const startsAt = (sec: number) => `${(sec / TOTAL_SEC) * 100}%`;

	it("anchors every clip to its own start time, and keeps it there under zoom", () => {
		// The annotation starts exactly where the second clip does, so the pill and
		// the clip edge under it must resolve to the very same coordinate.
		const { clipEls, pill } = renderTimeline(CLIPS, {
			id: "ann1",
			startMs: 600_000,
			endMs: 601_000,
		});
		expect(clipEls.map((el) => el.style.left)).toEqual([startsAt(0), startsAt(600), startsAt(900)]);
		expect(pill.style.left).toBe(clipEls[1].style.left);

		// Zoom scales the canvas these coordinates live in, so the coordinates
		// themselves must not move: same values, same agreement with the pill.
		zoomIn(40);
		expect(clipEls.map((el) => el.style.left)).toEqual([startsAt(0), startsAt(600), startsAt(900)]);
		expect(pill.style.left).toBe(clipEls[1].style.left);
	});

	it("shows each clip's edited duration on the card", () => {
		renderTimeline(CLIPS);
		// 600s / 300s / 900s of an 1800s source: each card reads the clip's own
		// length on the timeline (out − in), not the asset's original length. A
		// speed region over the clip changes how long it plays, not this number.
		expect(screen.getByText("10:00.0")).toBeInTheDocument();
		expect(screen.getByText("5:00.0")).toBeInTheDocument();
		expect(screen.getByText("15:00.0")).toBeInTheDocument();
	});

	it("withholds the duration from a card too small to hold it", () => {
		// 250s at this zoom is a 125px card: past the narrow gate, so it still shows
		// its edit button, but not wide enough for the timecode — which would
		// otherwise escape the label pill and sit on the delete button. Measured in
		// the running window, not derived here.
		renderTimeline([clip(0, 250), clip(250, TOTAL_SEC)]);

		expect(screen.queryByText("4:10.0")).not.toBeInTheDocument();
		// The card that does have the room still reads its length.
		expect(screen.getByText("25:50.0")).toBeInTheDocument();
	});

	it("asks for the room this card's own timecode needs, not the shortest one", () => {
		// 600s of 4000s is a 129px card. `0:12.0` would fit there (50 + 38 + 6×6 =
		// 124); `10:00.0` is a character wider and does not (130), and `formatSec`
		// has no hour field to stop the string growing — a clip past a hundred
		// minutes reads `100:00.0`. A single fixed width would have let those
		// through onto the delete button.
		renderTimeline([clip(0, 600), clip(600, 4000)]);

		expect(screen.queryByText("10:00.0")).not.toBeInTheDocument();
		expect(screen.getByText("56:40.0")).toBeInTheDocument();
	});

	it("measures the timecode where a canvas exists, rather than averaging its length", () => {
		// The stubbed face costs 9px a character against the 6px the default stub
		// charges. A 700s clip of this 4315s span is a 140px card — roomy enough by
		// the count (50 + 38 + 7×6 = 130) and too tight once the face is read
		// (50 + 38 + 7×9 = 151) — so only a measured gate withholds it.
		measureText.mockImplementation((text: string) => ({ width: text.length * 9 }));
		renderTimeline([clip(0, 700), clip(700, 4315)]);

		expect(screen.queryByText("11:40.0")).not.toBeInTheDocument();
		expect(screen.getByText("60:15.0")).toBeInTheDocument();
	});

	it("counts every digit at the widest digit's width, as tabular numerals render", () => {
		// The card shows its timecode in tabular numerals, where a "1" is as wide as a "0"; canvas
		// measures proportional ones. Here "1" is a third of the other digits: measured as drawn,
		// `1:11.1` would seem to fit this ~118px card (50 + 38 + 18) and then overflow it
		// (50 + 38 + 42 once each digit takes the widest advance).
		measureText.mockImplementation((text: string) => ({
			width: [...text].reduce((w, ch) => w + ("1:.".includes(ch) ? 3 : 9), 0),
		}));
		renderTimeline([clip(0, 71.1), clip(71.1, 516)]);

		expect(screen.queryByText("1:11.1")).not.toBeInTheDocument();
		expect(screen.getByText("7:24.9")).toBeInTheDocument();
	});

	it("takes the card gutter out of each clip's own width", () => {
		// The 6px is what separates two cards. Taken off the clip's width it stays
		// local to that clip; inserted between them (a flex gap) it displaced every
		// clip that followed. The 1px floor keeps a clip shorter than the gutter
		// from collapsing to nothing on a long timeline.
		const { clipEls } = renderTimeline(CLIPS);
		const widths = clipEls.map((el) => el.style.width);
		// (jsdom re-serialises the percentage to 4 decimals, hence the numeric read)
		// The last card has nothing to be separated from, so it reaches the end.
		expect(widths.map((w) => w.endsWith("- 6px)"))).toEqual([true, true, false]);
		for (const [i, durSec] of [600, 300, 900].entries()) {
			expect(Number.parseFloat(widths[i].replace("calc(", ""))).toBeCloseTo(
				(durSec / TOTAL_SEC) * 100,
				3,
			);
		}
	});
});

// Issue #350 — dragging an imported audio track on its lane. The pixel→second
// math and the single-write commit are what these pin; the clamp/guard math is
// covered by document/audioTracks.test.ts.
describe("V4Timeline audio lane drag", () => {
	const AUDIO_ASSET = { id: "aud", label: "voiceover", originalPath: "/vo.mp3", durationSec: 60 };
	// A 60s track whose head sits at raw 100s.
	const makeTrack = () => ({
		id: "trk1",
		assetId: "aud",
		kind: "music" as const,
		startMs: 100_000,
		endMs: 160_000,
		durationSec: 60,
		offsetMs: 0,
		gainDb: 0,
		loop: false,
		fadeInMs: 0,
		fadeOutMs: 0,
		muted: false,
		label: "vo",
		origin: "user" as const,
	});

	function renderAudioTracks(tracks: Array<ReturnType<typeof makeTrack>>) {
		return renderAudio({}, {}, tracks);
	}

	function renderAudio(
		trackOverrides: Partial<ReturnType<typeof makeTrack>> = {},
		props: { onAddVoiceover?: () => void } = {},
		tracks?: Array<ReturnType<typeof makeTrack>>,
	) {
		const placeAudioTrack = vi.fn(
			async (_id: string, _span: { startMs: number; endMs: number; offsetMs?: number }) => {
				/* the drag only awaits it */
			},
		);
		const selectAudioTrack = vi.fn();
		const tl = {
			clips: [clip(0, TOTAL_SEC)],
			assets: [AUDIO_ASSET],
			annotationRegions: [],
			speedRegions: [],
			cameraFullscreenRegions: [],
			layoutSegments: [],
			hasDoc: true,
			shaderEffectRanges: [],
			shaderEffects: [],
			zoomRegions: [],
			trimRanges: [],
			selection: null,
			multiSelection: [],
			clipSelection: null,
			audioTracks: tracks ?? [{ ...makeTrack(), ...trackOverrides }],
			// The lane reads these for the amber added-word marks (#540); this fixture
			// is about audio geometry, so it has none.
			transcripts: [],
			selectedAudioTrackId: null,
			selectAudioTrack,
			placeAudioTrack,
			clearSelection: vi.fn(),
			selectRegion: vi.fn(),
			selectClip: vi.fn(),
			updateAnnotationSpan: vi.fn(async () => undefined),
			addZoom: vi.fn(async () => undefined),
		};
		const { container } = render(
			<ShortcutsProvider>
				<V4Timeline
					tl={tl as unknown as ReturnType<typeof useTimeline>}
					setCurrentTime={vi.fn()}
					playing={false}
					onTogglePlay={vi.fn()}
					onEditClip={vi.fn()}
					onAddVoiceover={props.onAddVoiceover ?? vi.fn()}
				/>
			</ShortcutsProvider>,
		);
		// `pill` is a getter: the multi-track cases render no "vo" pill, and an
		// eager lookup would throw before their own assertions ran.
		return {
			get pill() {
				return screen.getByTitle((t) => t.startsWith("vo "));
			},
			container,
			placeAudioTrack,
			selectAudioTrack,
		};
	}

	// 900px / 1800s = 0.5 px per second, so +90px is +180s.
	const secForPx = (px: number) => (px / VIEWPORT_PX) * TOTAL_SEC;

	it("offers both audio paths behind one toolbar button", () => {
		// A mic and a music note side by side both just said "audio"; one button
		// with a named menu is what tells a first-time user the two paths apart.
		const onAddVoiceover = vi.fn();
		renderAudio({}, { onAddVoiceover });
		fireEvent.click(screen.getByLabelText("toolbar.addAudioTooltip"));
		fireEvent.click(screen.getByText("audio.addVoiceover"));
		expect(onAddVoiceover).toHaveBeenCalledTimes(1);
	});

	it("teaches the key that does the same thing", () => {
		// Read off the live bindings rather than hardcoded here, so a rebind in the
		// shortcuts dialog moves the menu with it instead of teaching a stale key.
		renderAudio();
		fireEvent.click(screen.getByLabelText("toolbar.addAudioTooltip"));
		const keys = Array.from(document.querySelectorAll("kbd"), (k) => k.textContent);
		expect(keys).toEqual([
			formatBinding(DEFAULT_SHORTCUTS.addVoiceover, false),
			formatBinding(DEFAULT_SHORTCUTS.addAudio, false),
		]);
	});

	it("marks where a looping track starts its file over", () => {
		// A 60s file under a 180s span repeats twice more after the first pass, so
		// there are two boundaries to show — at a third and two thirds.
		const { pill } = renderAudio({ loop: true, endMs: 100_000 + 180_000 });
		expect(pill.querySelectorAll('[data-testid="audio-loop-mark"]')).toHaveLength(2);
	});

	it("draws no loop marks when the track fits inside its source", () => {
		const { pill } = renderAudio({ loop: true });
		expect(pill.querySelectorAll('[data-testid="audio-loop-mark"]')).toHaveLength(0);
	});

	it("stacks overlapping tracks on separate rows", () => {
		// Three takes over the same stretch used to draw at the same height, one
		// hiding the next — you could not tell which pill you were about to drag.
		const { container } = renderAudioTracks([
			{ ...makeTrack(), id: "a", label: "a", startMs: 0, endMs: 60_000 },
			{ ...makeTrack(), id: "b", label: "b", startMs: 10_000, endMs: 70_000 },
			{ ...makeTrack(), id: "c", label: "c", startMs: 20_000, endMs: 80_000 },
		]);
		const tops = ["a", "b", "c"].map(
			(l) => (screen.getByTitle((t) => t.startsWith(`${l} `)) as HTMLElement).style.top,
		);
		expect(new Set(tops).size).toBe(3);
		// ...and the lane grew to hold them rather than clipping.
		const lane = container.querySelector('[class*="tlLaneAudio"]') as HTMLElement;
		expect(Number.parseInt(lane.style.height, 10)).toBeGreaterThan(60);
	});

	it("keeps non-overlapping tracks on one row", () => {
		renderAudioTracks([
			{ ...makeTrack(), id: "a", label: "a", startMs: 0, endMs: 10_000 },
			{ ...makeTrack(), id: "b", label: "b", startMs: 20_000, endMs: 30_000 },
		]);
		const tops = ["a", "b"].map(
			(l) => (screen.getByTitle((t) => t.startsWith(`${l} `)) as HTMLElement).style.top,
		);
		expect(new Set(tops).size).toBe(1);
	});

	it("selects the track on pointer-down before any movement", () => {
		const { pill, selectAudioTrack } = renderAudio();
		fireEvent.pointerDown(pill, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 0 }));
		expect(selectAudioTrack).toHaveBeenCalledWith("trk1");
	});

	it("body drag slides the head and commits once, trims untouched", () => {
		const { pill, placeAudioTrack } = renderAudio();
		fireEvent.pointerDown(pill, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 90 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 90 }));
		expect(placeAudioTrack).toHaveBeenCalledTimes(1);
		const [id, placement] = placeAudioTrack.mock.calls[0];
		expect(id).toBe("trk1");
		// The span slides whole: head moves, length is unchanged.
		expect(placement.startMs / 1000).toBeCloseTo(100 + secForPx(90), 3);
		expect((placement.endMs - placement.startMs) / 1000).toBeCloseTo(60, 3);
	});

	it("left-handle drag trims into the source instead of sliding the audio", () => {
		// A left-edge drag is a trim IN: the head moves right by N seconds and the
		// same N is skipped in the file, so what plays under the pill stays put.
		// Committing the span alone left `offsetMs` untouched, which just slid the
		// whole track along — the "my music starts five seconds late" symptom.
		const { pill, placeAudioTrack } = renderAudio();
		const handle = pill.firstElementChild as Element;
		fireEvent.pointerDown(handle, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 15 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 15 }));
		expect(placeAudioTrack).toHaveBeenCalledTimes(1);
		const [, placement] = placeAudioTrack.mock.calls[0];
		const movedSec = placement.startMs / 1000 - 100;
		expect(movedSec).toBeGreaterThan(0);
		// The head moved and the source in-point advanced by the same amount.
		expect((placement.offsetMs ?? 0) / 1000).toBeCloseTo(movedSec, 3);
		// The tail is untouched, so the span shortens by exactly what was trimmed.
		expect((placement.endMs - placement.startMs) / 1000).toBeCloseTo(60 - movedSec, 3);
	});

	it("a plain move leaves the source in-point alone", () => {
		const { pill, placeAudioTrack } = renderAudio();
		fireEvent.pointerDown(pill, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 90 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 90 }));
		const [, placement] = placeAudioTrack.mock.calls[0];
		expect(placement.offsetMs).toBe(0);
	});

	it("caps the out-point at the source length when the track does not loop", () => {
		// A non-looping track has nothing to play past the end of its file, so the
		// right edge stops there however far the pointer goes.
		const { pill, placeAudioTrack } = renderAudio();
		const handle = pill.lastElementChild as Element;
		fireEvent.pointerDown(handle, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 400 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 400 }));
		const [, placement] = placeAudioTrack.mock.calls[0];
		expect((placement.endMs - placement.startMs) / 1000).toBeCloseTo(60, 3);
	});

	it("lets a looping track be pulled out past the end of its file", () => {
		// This is what makes the loop toggle mean anything: the span has to be able
		// to EXCEED the source, or the audio always plays exactly once and turning
		// loop on does nothing at all.
		const { pill, placeAudioTrack } = renderAudio({ loop: true });
		const handle = pill.lastElementChild as Element;
		fireEvent.pointerDown(handle, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: 400 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: 400 }));
		const [, placement] = placeAudioTrack.mock.calls[0];
		expect((placement.endMs - placement.startMs) / 1000).toBeGreaterThan(60);
	});

	it("right-handle drag pulls the out-point in, head fixed", () => {
		const { pill, placeAudioTrack } = renderAudio();
		// The right resize handle is the last child of the pill.
		const handle = pill.lastElementChild as Element;
		fireEvent.pointerDown(handle, { clientX: 0 });
		window.dispatchEvent(new MouseEvent("pointermove", { clientX: -30 }));
		window.dispatchEvent(new MouseEvent("pointerup", { clientX: -30 }));
		expect(placeAudioTrack).toHaveBeenCalledTimes(1);
		const [, placement] = placeAudioTrack.mock.calls[0];
		// The head is pinned; only the tail comes in, so the span gets shorter.
		expect(placement.startMs).toBe(100_000);
		expect(placement.endMs - placement.startMs).toBeLessThan(60_000);
	});
});

// #966. An empty lane advertises the shortcut that fills it. The letter used to be written into
// the string, so after a rebind the hint kept teaching a key that did nothing while the toolbar
// chip, read off the live binding, showed the right one.
describe("V4Timeline empty-lane hints", () => {
	afterEach(() => {
		i18n.translate = null;
		(window as unknown as { electronAPI?: unknown }).electronAPI = undefined;
	});

	function useEnglish() {
		i18n.translate = (namespace, key, vars) =>
			translate("en", namespace as I18nNamespace, key, vars);
	}

	it("names the default keys", () => {
		useEnglish();
		renderTimeline(undefined, { id: "ann1", startMs: 10_000, endMs: 11_000 }, [CAMERA_ASSET]);
		expect(screen.getByText("Press Z to add zoom")).toBeInTheDocument();
		expect(screen.getByText("Press T to add trim")).toBeInTheDocument();
		expect(screen.getByText("Press S to add speed")).toBeInTheDocument();
		expect(
			screen.getByLabelText(translate("en", "timeline", "layouts.changeHere")),
		).toBeInTheDocument();
		expect(screen.getByText("Press M to add audio, V to record a voiceover")).toBeInTheDocument();
	});

	it("names the key the user rebound, formatted like the toolbar chip", async () => {
		useEnglish();
		const getShortcuts = vi.fn(async () => ({
			addZoom: { key: "x" },
			addTrim: { key: "t", ctrl: true, shift: true },
			addAnnotation: { key: "n" },
			addSpeed: { key: "j" },
			addCameraFullscreen: { key: "k" },
			addAudio: { key: "u" },
			addVoiceover: { key: "r", alt: true },
		}));
		(window as unknown as { electronAPI?: unknown }).electronAPI = { getShortcuts };
		renderTimeline(
			undefined,
			{ id: "ann1", startMs: 10_000, endMs: 11_000 },
			[CAMERA_ASSET],
			undefined,
			{
				annotationRegions: [],
			},
		);
		expect(await screen.findByText("Press X to add zoom")).toBeInTheDocument();
		expect(screen.getByText("Press Ctrl + Shift + T to add trim")).toBeInTheDocument();
		expect(screen.getByText("Press N to add annotation")).toBeInTheDocument();
		expect(screen.getByText("Press J to add speed")).toBeInTheDocument();
		expect(
			screen.getByLabelText(translate("en", "timeline", "layouts.changeHere")),
		).toBeInTheDocument();
		expect(
			screen.getByText("Press U to add audio, Alt + R to record a voiceover"),
		).toBeInTheDocument();
		expect(screen.queryByText("Press Z to add zoom")).not.toBeInTheDocument();
	});

	// The component test reads English only; a locale that renamed or dropped a placeholder
	// would render the raw `{{key}}`, or the stale letter, with every key set still matching.
	it.each(getAvailableLocales())("%s interpolates the key into every hint", (locale) => {
		const vars = { key: "⌘ + X", audioKey: "⌘ + U", voiceoverKey: "⌥ + R" };
		for (const key of [
			"hints.pressZoom",
			"hints.pressTrim",
			"hints.pressAnnotation",
			"hints.pressSpeed",
			"hints.pressCameraFullscreen",
		]) {
			const text = translate(locale, "timeline", key, vars);
			expect(text, key).toContain("⌘ + X");
			expect(text, key).not.toContain("{{");
		}
		const audio = translate(locale, "timeline", "hints.pressAudio", vars);
		expect(audio).toContain("⌘ + U");
		expect(audio).toContain("⌥ + R");
		expect(audio).not.toContain("{{");
	});
});

describe("V4Timeline toolbar tooltips", () => {
	afterEach(() => {
		(window as unknown as { electronAPI?: unknown }).electronAPI = undefined;
	});

	const toolbarOf = () => screen.getByRole("toolbar", { name: "toolbar.timelineTools" });

	/** Opens a toolbar button's tooltip the way the keyboard does (focus opens it at once), and
	 *  returns the text and the chip of the visible copy. */
	async function tooltipOn(name: string) {
		const control = screen.getByLabelText(name);
		// A keyboard focus: one the mouse gave opens no tooltip.
		fireEvent.keyDown(window, { key: "Tab" });
		act(() => control.focus());
		await screen.findByRole("tooltip");
		const visible = document.querySelector('[data-slot="tooltip-content"]');
		const result = {
			text: screen.getByRole("tooltip").textContent,
			chip: visible?.querySelector("kbd")?.textContent ?? null,
		};
		act(() => control.blur());
		return result;
	}

	it("shows each creator's default key as a chip, and no key in its name", async () => {
		renderTimeline(undefined, undefined, [CAMERA_ASSET]);
		const chips: Record<string, string | null> = {};
		for (const name of [
			"buttons.addZoom",
			"buttons.addTrim",
			"buttons.addSpeed",
			"buttons.addAnnotation",
			"layouts.changeHere",
			// Its menu also records a voiceover, but the key, like the lane's "Press M", adds audio.
			"toolbar.addAudioTooltip",
		]) {
			chips[name] = (await tooltipOn(name)).chip;
			// The name is the string alone: a "(Z)" in it would be a second, stale copy of the key.
			expect(screen.getByLabelText(name)).toHaveAccessibleName(name);
		}
		expect(chips).toEqual({
			"buttons.addZoom": "Z",
			"buttons.addTrim": "T",
			"buttons.addSpeed": "S",
			"buttons.addAnnotation": "A",
			"layouts.changeHere": "C",
			"toolbar.addAudioTooltip": "M",
		});
	});

	// The creators are remappable, so the chip must follow the saved binding, not the default.
	it("shows the key the user remapped, not the default", async () => {
		const getShortcuts = vi.fn(async () => ({
			addZoom: { key: "q" },
			addTrim: { key: "t", ctrl: true, shift: true },
			addAudio: { key: "b" },
		}));
		(window as unknown as { electronAPI?: unknown }).electronAPI = { getShortcuts };
		renderTimeline();
		await vi.waitFor(() => expect(getShortcuts).toHaveBeenCalled());
		await act(() => Promise.resolve());
		expect((await tooltipOn("buttons.addZoom")).chip).toBe("Q");
		expect((await tooltipOn("buttons.addTrim")).chip).toBe("Ctrl + Shift + T");
		expect((await tooltipOn("toolbar.addAudioTooltip")).chip).toBe("B");
		// Unset actions keep their default.
		expect((await tooltipOn("buttons.addSpeed")).chip).toBe("S");
	});

	it("gives Auto-Focus one name and one tip for both states, with the state in aria-pressed", async () => {
		renderTimeline();
		const button = screen.getByLabelText("buttons.autoFocusAll");
		expect(button).toHaveAttribute("aria-pressed");
		const before = await tooltipOn("buttons.autoFocusAll");
		fireEvent.click(button);
		expect(screen.getByLabelText("buttons.autoFocusAll")).toBe(button);
		const after = await tooltipOn("buttons.autoFocusAll");
		expect(before.text).toBe("buttons.autoFocusAllTip");
		expect(after.text).toBe(before.text);
		expect(before.chip).toBeNull();
	});

	it("says what Clear timeline removes in its tooltip, without a chip", async () => {
		renderTimeline();
		const clear = await tooltipOn("buttons.clearTimeline");
		expect(clear.text).toBe("buttons.clearTimeline");
		expect(clear.chip).toBeNull();
	});

	// A native `title` next to the shared tooltip is a second, slower tooltip on the same button.
	it("uses no native title on the toolbar buttons that have the shared tooltip", () => {
		renderTimeline(undefined, undefined, [CAMERA_ASSET]);
		const buttons = Array.from(toolbarOf().querySelectorAll("button"));
		expect(buttons.length).toBeGreaterThanOrEqual(8);
		for (const button of buttons) expect(button).not.toHaveAttribute("title");
	});

	it("shows the annotation drag hint on pills of any width", () => {
		// A hairline pill draws nothing, so the title is the only place its name is.
		renderTimeline();
		const hairline = screen.getByTitle(/^toolbar\.newAnnotation/);
		expect(hairline.textContent).toBe("");

		// A wide annotation still teaches vertical dragging on hover.
		cleanup();
		renderTimeline(undefined, { id: "ann1", startMs: 0, endMs: TOTAL_SEC * 1000 });
		const wide = document.querySelector("[class*=lanePill]") as HTMLElement;
		expect(wide).toHaveTextContent("toolbar.newAnnotation");
		expect(wide.title).toContain("tracks.dragHint");
	});
});

// A zoom pill shows the hold; its camera moves run outside it (#1028).
describe("V4Timeline zoom trails", () => {
	afterEach(() => {
		i18n.translate = null;
	});

	const W_SEC = zoomTransitionMs(1.8) / 1000; // ≈ 0.92 s at the default depth
	const ZOOM = { id: "z1", startMs: 10_000, endMs: 12_000, depth: 3 };
	const pct = (sec: number) => (sec / TOTAL_SEC) * 100;
	const trail = (side: "in" | "out" | "pan") =>
		document.querySelector<HTMLElement>(`[data-zoom-trail="${side}"]`) as HTMLElement;

	function renderZoom(overrides: Record<string, unknown>, clips?: ReturnType<typeof clip>[]) {
		i18n.translate = (namespace, key, vars) =>
			translate("en", namespace as I18nNamespace, key, vars);
		renderTimeline(clips, undefined, [NO_CAMERA_ASSET], undefined, {
			zoomRegions: [ZOOM],
			...overrides,
		});
	}

	it("hatches the zoom-out a trim at the pill's end removes (issue #1028 repro)", () => {
		renderZoom({
			trimRanges: [
				{ id: "t1", assetId: "a1", clipId: "c@0", startSec: 12, endSec: 14, origin: "user" },
			],
		});
		expect(trail("in")).toHaveAccessibleName("Zoom-in: the view moves in until the zoom starts");
		expect(trail("in").querySelector("[data-zoom-trail-cut]")).toBeNull();
		expect(Number.parseFloat(trail("in").style.left)).toBeCloseTo(pct(10 - W_SEC), 6);

		expect(trail("out")).toHaveAccessibleName(
			`A trim removes ${W_SEC.toFixed(2)} s of the zoom-out. The export jumps at the cut.`,
		);
		expect(Number.parseFloat(trail("out").style.left)).toBeCloseTo(pct(12), 6);
		const cut = trail("out").querySelector<HTMLElement>("[data-zoom-trail-cut]");
		expect(Number.parseFloat(cut?.style.left ?? "")).toBeCloseTo(0, 6);
		expect(Number.parseFloat(cut?.style.width ?? "")).toBeCloseTo(100, 6);
	});

	it("hatches the part of a zoom-out past a clip junction, naming the junction", () => {
		renderZoom({}, [clip(0, 12.5), clip(12.5, TOTAL_SEC)]);
		const lost = 12 + W_SEC - 12.5;
		expect(trail("out")).toHaveAccessibleName(
			`A clip junction removes ${lost.toFixed(2)} s of the zoom-out. The export jumps at the junction.`,
		);
		const cut = trail("out").querySelector<HTMLElement>("[data-zoom-trail-cut]");
		expect(Number.parseFloat(cut?.style.left ?? "")).toBeCloseTo((0.5 / W_SEC) * 100, 6);
		expect(Number.parseFloat(cut?.style.width ?? "")).toBeCloseTo((lost / W_SEC) * 100, 6);
		expect(trail("in").querySelector("[data-zoom-trail-cut]")).toBeNull();
	});

	it("does not call the end of the timeline a junction", () => {
		const end = TOTAL_SEC * 1000;
		renderZoom({ zoomRegions: [{ ...ZOOM, startMs: end - 2000, endMs: end - 500 }] });
		expect(trail("out")).toHaveAccessibleName(
			"Zoom-out: the view moves back out after the zoom ends",
		);
	});

	it("draws one pan between chained zooms instead of a zoom-out and a zoom-in", () => {
		renderZoom({ zoomRegions: [ZOOM, { id: "z2", startMs: 12_500, endMs: 14_000, depth: 3 }] });
		const trails = [...document.querySelectorAll<HTMLElement>("[data-zoom-trail]")];
		expect(trails.map((el) => el.dataset.zoomTrail)).toEqual(["in", "pan", "out"]);
		const pan = trail("pan");
		expect(pan).toHaveAccessibleName("Pan: the view moves straight to the next zoom");
		expect(Number.parseFloat(pan.style.left)).toBeCloseTo(pct(12), 6);
		expect(Number.parseFloat(pan.style.width)).toBeCloseTo(pct(1), 6);
	});

	it("stretches the zoom-out across a speed region, uncut", () => {
		renderZoom({ speedRegions: [{ id: "s1", startMs: 12_000, endMs: 20_000, speed: 3 }] });
		expect(Number.parseFloat(trail("out").style.width)).toBeCloseTo(pct(3 * W_SEC), 6);
		expect(Number.parseFloat(trail("in").style.width)).toBeCloseTo(pct(W_SEC), 6);
		expect(trail("out")).toHaveAccessibleName(
			"Zoom-out: the view moves back out after the zoom ends",
		);
		expect(trail("out").querySelector("[data-zoom-trail-cut]")).toBeNull();
	});
});