// @vitest-environment jsdom import React, { act, useRef } from "react"; import { createRoot } from "react-dom/client"; import type { PlayerRef } from "@remotion/player"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { applyCaptionLineTiming, applyCaptionLineWindows, applyCaptionWordHides, captionKeyFor, livePreviewMap, previewClockMappers, TimeMap, type CaptionLine, type Segment, } from "@ossclip/core/browser"; import { captionWindowEntries, clampCaptionSpan, dragCaptionSpan, loadSourceAudio, menuPlacement, overlappingCaptionWindows, postHideLineIndices, timingAudioWindow, TranscriptPanel, } from "../src/TranscriptPanel"; import type { DeleteWordsPlan } from "../src/deleteWords"; import { rebuildCaptionTrack } from "../src/liveCaptionTrack"; import { useEdits } from "../src/useEdits"; // Same one-time act() opt-in as Overlay.test.ts/Inspector.test.ts. (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; /** * §137 review, Important 2 + Minor 3. The transcript's retype is the second * path into `patchCaption`, and the only one with no DOM attribute standing * between it and a word — it reads `liveLines` directly, so a word with no * `srcStart` reaches it as a plain object with a missing field. * * The reducer derives the key with `captionKeyFor`, which THROWS on a * non-finite anchor by design. This handler is a React `onBlur`, with no error * boundary above ``, so an unguarded commit here white-screens the editor * on any workdir the load-path repair could not fix. And the refusal has to be * at the OPEN, not the commit: gating at the commit let the user type a * correction, press Enter, and watch it silently revert — the exact experience * §137 exists to remove. */ describe("TranscriptPanel retype guard (§137)", () => { let container: HTMLDivElement; let root: ReturnType; /** A word as a REPAIRED file holds it. */ const anchored = (text: string, start: number, srcStart: number): CaptionLine => ({ words: [{ text, start, end: start + 0.3, srcStart }], start, end: start + 0.3, }); /** A word as a pre-§137 file holds it: no `srcStart` at all. */ const legacy = (text: string, start: number): CaptionLine => ({ words: [{ text, start, end: start + 0.3 } as CaptionLine["words"][number]], start, end: start + 0.3, }); function Harness({ lines }: { lines: CaptionLine[] }) { const edits = useEdits(); const playerRef = useRef(null); // The doc is rendered so the assertions can read what the retype wrote // without reaching into the hook. return React.createElement( "div", null, React.createElement("div", { "data-testid": "doc", children: JSON.stringify(edits.doc.captions), }), React.createElement(TranscriptPanel, { baseLines: lines, liveLines: lines, // No hides in this harness, so the timed track IS the rendered one — // App passes the post-hide lines (`postHideLineIndices`). timingLines: lines, workdir: null, fps: 30, playerRef, edits, onDeleteWords: () => {}, width: 300, }), ); } const dblclick = async (el: HTMLElement) => { await act(async () => { el.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); }; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it("refuses to open the retype box on a word with no source anchor", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [legacy("Claude", 0.09)] })); }); await dblclick(container.querySelector('[data-testid="transcript-word-0"]')!); expect(container.querySelector('[data-testid="transcript-edit"]')).toBeNull(); }); it("opens, and writes the SOURCE key, on a word that has one", async () => { // The other half of the guard: it must refuse the anchorless word without // refusing every word. Without this, deleting the retype entirely would // still pass the test above. await act(async () => { root.render(React.createElement(Harness, { lines: [anchored("Claude", 0.09, 1.7675)] })); }); await dblclick(container.querySelector('[data-testid="transcript-word-0"]')!); const input = container.querySelector('[data-testid="transcript-edit"]')!; expect(input).not.toBeNull(); await act(async () => { // React tracks the DOM node's own value to dedupe change events, so a // plain `input.value = …` is swallowed; set it through the prototype. Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, "value", )!.set!.call(input, "CLAWD"); input.dispatchEvent(new Event("input", { bubbles: true })); }); // `autoFocus` put the caret here (the same thing Overlay.test.ts relies // on), so a real `blur()` is the gesture the user makes — and React 17+ // maps `onBlur` to the bubbling `focusout`, which a hand-built // non-bubbling `FocusEvent("blur")` would never reach. expect(document.activeElement).toBe(input); await act(async () => { input.blur(); }); // Keyed by SOURCE time (1.7675s → w1768), never by the word's OUTPUT start // (0.09s → w90) and never by its position ("0"). const doc = JSON.parse(container.querySelector('[data-testid="doc"]')!.textContent!); expect(doc).toEqual({ w1768: { text: "CLAWD", was: "Claude" } }); }); }); /** * RTL + search normalization. An Urdu transcript in an LTR-base paragraph had * unclickable words: UAX #9 visually reordered each wrapped line's RTL run * while DOM order stayed spoken order, so the span under the cursor was not * the word the eye targeted. The fix is a first-strong `dir` on the body plus * per-word bidi isolation — and it must not disturb the §65 space text nodes, * which are the pane's only line-break opportunities. */ describe("TranscriptPanel direction and search normalization", () => { let container: HTMLDivElement; let root: ReturnType; /** One line of anchored words, 0.3s apart — the shape a repaired file holds. */ const line = (texts: string[]): CaptionLine => ({ words: texts.map((text, i) => ({ text, start: i * 0.3, end: i * 0.3 + 0.3, srcStart: i * 0.3, })), start: 0, end: texts.length * 0.3, }); function Harness({ lines }: { lines: CaptionLine[] }) { const edits = useEdits(); const playerRef = useRef(null); return React.createElement(TranscriptPanel, { baseLines: lines, liveLines: lines, // No hides here, so the timed (post-hide) track IS the rendered one. timingLines: lines, workdir: null, fps: 30, playerRef, edits, onDeleteWords: () => {}, width: 300, }); } beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it('sets dir="rtl" on the body for an Urdu transcript', async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["سلام", "دنیا"])] })); }); const body = container.querySelector('[data-testid="transcript-body"]')!; expect(body.getAttribute("dir")).toBe("rtl"); }); it('sets dir="ltr" on the body for an English transcript', async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["hello", "world"])] })); }); const body = container.querySelector('[data-testid="transcript-body"]')!; expect(body.getAttribute("dir")).toBe("ltr"); }); it("keeps the §65 spaces as BARE text nodes BETWEEN the spans, never inside them", async () => { // The §65 guard. The space moved INSIDE the preceding span for one // release (2026-08-18 round 3, to paint the selection band across the // gap) and is back out: a trailing space at the end of a visual line // HANGS and costs no width, but inside a padded inline box the box keeps // it — the e2e wrap assertion measured scrollWidth 289 vs clientWidth 285 // on the fixture, exactly one space (CI run 32195920547). The band is // bridged by `selectedStyle`'s box-shadow instead, which paints outside // the border box and adds nothing to `scrollWidth`. await act(async () => { root.render(React.createElement(Harness, { lines: [line(["سلام", "دنیا"])] })); }); const body = container.querySelector('[data-testid="transcript-body"]')!; const bareSpaces = Array.from(body.childNodes).filter( (n) => n.nodeType === Node.TEXT_NODE && n.textContent === " ", ); // One per inter-word gap — real whitespace, not a margin (§65: margins // are not line-break opportunities). expect(bareSpaces).toHaveLength(1); // No span carries whitespace of its own. const spans = Array.from(body.querySelectorAll('[data-testid^="transcript-word-"]')); expect(spans.map((s) => s.textContent)).toEqual(["سلام", "دنیا"]); expect(body.textContent).toBe("سلام دنیا"); }); it("matches a composed word from a decomposed query (NFC)", async () => { // The word carries composed \u0622 (alef-with-madda); the query spells // the SAME glyph decomposed (\u0627 alef + \u0653 madda). Escapes, not // literals: the two render identically, and a literal would let any tool // that normalizes on save quietly rewrite this test into a tautology. // Without NFC on both sides, byte-wise `includes` finds nothing. const composedWord = "\u0622\u0645"; const decomposedQuery = "\u0627\u0653\u0645"; await act(async () => { root.render(React.createElement(Harness, { lines: [line([composedWord, "\u062F\u0646\u06CC\u0627"])] })); }); const input = container.querySelector('[data-testid="transcript-search"]')!; await act(async () => { Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, "value", )!.set!.call(input, decomposedQuery); input.dispatchEvent(new Event("input", { bubbles: true })); }); expect(container.querySelector('[data-testid="transcript-match-count"]')!.textContent).toBe( "1/1 match", ); }); }); /** * Multi-word selection + the caption word-hide layer (§59b, revisited * 2026-08-18). The selection is a range over LOGICAL word indices; the hide * writes `OverrideDoc.captionWordsHidden` (source-time keys, §137) and the * word stays in the transcript struck-through — non-destructive, restorable. * Keyboard handling is PANEL-scoped (`onKeyDown` on the focusable body, never * a window listener): Overlay owns the global Delete for scenes, and a second * window listener would fire both gestures from one keypress. */ describe("TranscriptPanel selection and caption word hide (§59b revisited)", () => { let container: HTMLDivElement; let root: ReturnType; /** One line of anchored words, 0.3s apart, srcStart offset so the SOURCE * key is visibly distinct from the output start. */ const line = (texts: string[]): CaptionLine => ({ words: texts.map((text, i) => ({ text, start: i * 0.3, end: i * 0.3 + 0.3, srcStart: 10 + i, })), start: 0, end: texts.length * 0.3, }); /** A line whose SECOND word predates source anchors (no `srcStart`). */ const withAnchorless = (): CaptionLine => ({ words: [ { text: "alpha", start: 0, end: 0.3, srcStart: 10 }, { text: "beta", start: 0.3, end: 0.6 } as CaptionLine["words"][number], ], start: 0, end: 0.6, }); function Harness({ lines, baseLines, seekTo, onDeleteWords, onFrame, toPlayerSec, }: { lines: CaptionLine[]; /** Pristine pre-edit lines when they differ from the live ones — the * base-`was` capture assertions need the two to diverge. */ baseLines?: CaptionLine[]; seekTo?: (frame: number) => void; /** Spy on the plan the Delete gesture hands App. */ onDeleteWords?: (plan: DeleteWordsPlan) => void; /** Captures the panel's frameupdate listener so a test can DRIVE the * playhead — the underline-composition assertions need `currentIndex` * set, and only the player event sets it. */ onFrame?: (fire: (frame: number) => void) => void; /** The live-clock mapping App threads under a cleanup veto (step 4 * follow-up); absent takes the panel's own identity default, exactly * like a session with no veto. */ toPlayerSec?: (sec: number) => number; }) { const edits = useEdits(); // A fake player rather than a null ref: the seek-suppression assertion // needs `seekTo` observable, and the frameupdate effect needs the // listener pair to exist. const playerRef = useRef({ seekTo: seekTo ?? (() => {}), addEventListener: (name: string, cb: (e: { detail: { frame: number } }) => void) => { if (name === "frameupdate") onFrame?.((frame) => cb({ detail: { frame } })); }, removeEventListener: () => {}, } as unknown as PlayerRef); return React.createElement( "div", null, React.createElement("div", { "data-testid": "hidden-doc", children: JSON.stringify(edits.doc.captionWordsHidden), }), React.createElement("div", { "data-testid": "range-doc", children: JSON.stringify(edits.doc.captionRangeEdits), }), React.createElement("div", { "data-testid": "captions-doc", children: JSON.stringify(edits.doc.captions), }), React.createElement(TranscriptPanel, { baseLines: baseLines ?? lines, liveLines: lines, // No hides in this harness, so the timed track IS the rendered one — // App passes the post-hide lines (`postHideLineIndices`). timingLines: lines, workdir: null, fps: 30, playerRef, edits, // App's shape, collapsed for the harness: the spy stands in for the // modal opening, and the caption-only arm — the modal's preselected // default — is applied immediately so the hide-layer assertions // below exercise the same reducer path App's confirm does. onDeleteWords: (plan) => { onDeleteWords?.(plan); edits.hideCaptionWords(plan.words); }, width: 300, ...(toPlayerSec ? { toPlayerSec } : {}), }), ); } const word = (i: number) => container.querySelector(`[data-testid="transcript-word-${i}"]`)!; const click = async (el: HTMLElement, shiftKey = false) => { await act(async () => { el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, shiftKey })); }); }; const keydown = async (key: string) => { const body = container.querySelector('[data-testid="transcript-body"]')!; await act(async () => { body.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })); }); }; // The selection bar (2026-08-18, round 3: a horizontal row anchored INSIDE // the scrollable body) — the item testids carried over from the old header // toolbar and vertical menu, so tests re-anchor rather than rewrite. const menu = () => container.querySelector('[data-testid="transcript-selection-menu"]'); /** Both delete scopes live behind the bar's Delete ▾ flyout now. */ const openDeleteFlyout = async () => { await act(async () => { container .querySelector('[data-testid="transcript-delete-menu"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); }; const hiddenDoc = () => JSON.parse(container.querySelector('[data-testid="hidden-doc"]')!.textContent!); const rangeDoc = () => JSON.parse(container.querySelector('[data-testid="range-doc"]')!.textContent!); const captionsDoc = () => JSON.parse(container.querySelector('[data-testid="captions-doc"]')!.textContent!); const origGetContext = HTMLCanvasElement.prototype.getContext; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); // The Timing test below opens the popover, whose canvas draw effect // probes getContext — jsdom logs "not implemented" noise for it without // the canvas package. The effect guards a null return, so return null // quietly (the timing describe's rule). HTMLCanvasElement.prototype.getContext = (() => null) as typeof HTMLCanvasElement.prototype.getContext; }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); HTMLCanvasElement.prototype.getContext = origGetContext; }); it("click selects one word and shift-click extends the range — both directions", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c", "d"])] })); }); expect(menu()).toBeNull(); await click(word(1)); expect(menu()!.textContent).toContain("1 word"); await click(word(3), true); expect(menu()!.textContent).toContain("3 words"); // Backwards past the anchor: [0, 1], still contiguous. await click(word(0), true); expect(menu()!.textContent).toContain("2 words"); }); it("a word click seeks THROUGH the live-clock mapping — old + revived past a kept pause (step 4 follow-up)", async () => { // The real mapping, end to end: produce proposed a 2s pause at source // 5..7 and the last render cut it (oldSpans); the user vetoes it, so the // player is on the NEW clock while the panel's word times stay on the // old one (the pre-retime `appliedCaptionRanges` stream, App.tsx). const proposal: Segment[] = [ { srcIn: 0, srcOut: 5, kind: "keep" }, { srcIn: 5, srcOut: 7, kind: "remove", reason: "pause", confidence: 0.9 }, { srcIn: 7, srcOut: 10, kind: "keep" }, ]; const clocks = livePreviewMap( proposal, { reasons: { pause: false } }, [], new TimeMap(proposal).spans, )!; expect(clocks).not.toBeNull(); const m = previewClockMappers(clocks); const straddle: CaptionLine = { words: [ { text: "early", start: 3, end: 3.3, srcStart: 3 }, { text: "late", start: 6, end: 6.3, srcStart: 8 }, ], start: 3, end: 6.3, }; const seeks: number[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [straddle], seekTo: (f: number) => seeks.push(f), toPlayerSec: m.toLive, }), ); }); // "late" sits past the revived pause: old output 6 is source 8, which // the new clock plays at 8 — the unmapped seek (ceil(6 × 30) = 180) // landed exactly the revived 2s early. await click(word(1)); expect(seeks).toEqual([Math.ceil(8 * 30)]); // "early" precedes the pause and does not move. await click(word(0)); expect(seeks).toEqual([Math.ceil(8 * 30), Math.ceil(3 * 30)]); }); it("without the mapping the seek is bit-identical to before — the identity default (step 4 follow-up)", async () => { const seeks: number[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["a", "b", "c"])], seekTo: (f: number) => seeks.push(f), }), ); }); await click(word(1)); // The exact pre-change expression: Math.ceil(w.start * fps). expect(seeks).toEqual([Math.ceil(0.3 * 30)]); }); it("shift-click never seeks — extending a selection must not yank the playhead", async () => { const seeks: number[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["a", "b", "c"])], seekTo: (f: number) => seeks.push(f), }), ); }); await click(word(0)); expect(seeks).toHaveLength(1); await click(word(2), true); expect(seeks).toHaveLength(1); }); it("Escape clears the selection and closes the menu", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); expect(menu()).not.toBeNull(); await keydown("Escape"); expect(menu()).toBeNull(); }); it("Delete hands App a PLAN — SOURCE-keyed words, LIVE text as `was`, prev-end clamp", async () => { const plans: DeleteWordsPlan[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["a", "b", "c"])], onDeleteWords: (p: DeleteWordsPlan) => plans.push(p), }), ); }); await click(word(1)); await click(word(2), true); await keydown("Delete"); expect(plans).toHaveLength(1); // srcStart 11 and 12, never the output starts (0.3/0.6) or positions. expect(plans[0]!.words).toEqual([ { srcStart: 11, was: "b" }, { srcStart: 12, was: "c" }, ]); expect(plans[0]!.targets).toEqual(["caption", "caption-video"]); // The window: clamped to word 0's output end on the left, word 2's end // on the right (the deleteWords.ts smeared-start rationale). expect(plans[0]!.startSec).toBeCloseTo(0.3, 6); expect(plans[0]!.endSec).toBeCloseTo(0.9, 6); // The harness's caption-only confirm applied — same keys, live text. expect(hiddenDoc()).toEqual({ w11000: { was: "b" }, w12000: { was: "c" } }); // The gesture consumed the selection. expect(menu()).toBeNull(); }); it("keyboard Delete on an ALL-HIDDEN selection RESTORES — never a video-cut-only modal", async () => { // The toolbar already swaps Delete… for Restore on an all-hidden // selection; the keydown path must mirror it. Before this, the key still // opened the modal whose only remaining target was the DESTRUCTIVE video // cut — preselected and Enter-armed, so the Delete→Enter reflex // escalated a recoverable hide into a video cut. (The plan-null no-modal // guard itself is deleteWords.test.ts's ground.) const plans: DeleteWordsPlan[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["a", "b"])], onDeleteWords: (p: DeleteWordsPlan) => plans.push(p), }), ); }); await click(word(0)); await keydown("Delete"); // First Delete: the normal flow — one plan, and the harness hides the word. expect(plans).toHaveLength(1); expect(hiddenDoc()).toEqual({ w10000: { was: "a" } }); // Second Delete on the now all-hidden selection: NO plan, NO modal — the // key restores, exactly like the toolbar's Restore. await click(word(0)); await keydown("Delete"); expect(plans).toHaveLength(1); expect(hiddenDoc()).toEqual({}); }); it("handled keys never bubble to window — Overlay's global Delete/Escape must not double-fire", async () => { // Overlay listens for Delete (delete-scene) and Escape (deselect) on // WINDOW; the panel's div-scoped handler does not stop the keydown from // bubbling there, so before stopPropagation one Delete opened BOTH the // word modal and the scene modal. Only HANDLED keys are stopped: an // Escape with nothing selected must still reach Overlay's deselect. const seen: string[] = []; const spy = (e: KeyboardEvent) => seen.push(e.key); window.addEventListener("keydown", spy); try { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); await keydown("Delete"); // handled: selection present expect(seen).toEqual([]); await click(word(0)); await keydown("Escape"); // handled: clears the selection expect(seen).toEqual([]); await keydown("Escape"); // NOT handled: no selection — Overlay's turn expect(seen).toEqual(["Escape"]); } finally { window.removeEventListener("keydown", spy); } }); it("a hidden word stays in the transcript, struck through, with the restore hint", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); // The flyout's Delete + video… item takes the same plan path as the key. await openDeleteFlyout(); await act(async () => { container .querySelector('[data-testid="transcript-delete"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(hiddenDoc()).toEqual({ w10000: { was: "a" } }); const w = word(0); // The span holds the word and nothing else — the §65 space is a bare // text node beside it. expect(w.textContent).toBe("a"); expect(w.style.textDecoration).toBe("line-through"); expect(w.title).toBe("hidden from captions — select and Restore"); }); it("an all-hidden selection offers Restore, which DELETES the keys", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); await keydown("Delete"); expect(hiddenDoc()).toEqual({ w10000: { was: "a" } }); // Re-select the hidden word: the bar swaps the Delete ▾ slot for Restore. await click(word(0)); expect(container.querySelector('[data-testid="transcript-delete-menu"]')).toBeNull(); expect(container.querySelector('[data-testid="transcript-delete"]')).toBeNull(); await act(async () => { container .querySelector('[data-testid="transcript-restore"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(hiddenDoc()).toEqual({}); expect(word(0).style.textDecoration).toBe(""); }); it("disables Delete…, with a reason, when any selected word has no source anchor (§137)", async () => { const plans: DeleteWordsPlan[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [withAnchorless()], onDeleteWords: (p: DeleteWordsPlan) => plans.push(p), }), ); }); await click(word(0)); await click(word(1), true); await openDeleteFlyout(); const del = container.querySelector('[data-testid="transcript-delete"]')!; expect(del.disabled).toBe(true); expect(del.title).toContain("no source anchor"); // The Delete key takes the same refusal — no plan, nothing written. await keydown("Delete"); expect(plans).toEqual([]); expect(hiddenDoc()).toEqual({}); }); it("Edit on a multi-word selection opens the prefilled range editor; commit writes patchCaptionRange with the endpoints' srcStarts and the joined was", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c"])] })); }); await click(word(0)); await click(word(2), true); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; expect(input).not.toBeNull(); // Prefilled with the NFC-joined live run text — also the stored `was`. expect(input.value).toBe("a b c"); await act(async () => { Object.getOwnPropertyDescriptor( window.HTMLTextAreaElement.prototype, "value", )!.set!.call(input, "hello world"); input.dispatchEvent(new Event("input", { bubbles: true })); }); expect(document.activeElement).toBe(input); // Plain Enter commits. Blur deliberately does NOT any more (2026-08-18): // the popover carries Apply/Cancel buttons, and a blur-commit would fire // on the way to pressing Cancel. await act(async () => { input.dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }), ); }); // Keyed by the ENDPOINTS' source starts (srcStart 10 and 12), never by // panel indices or output times. expect(rangeDoc()).toEqual([ { fromKey: "w10000", toKey: "w12000", text: "hello world", was: "a b c" }, ]); // The gesture consumed the selection and closed the editor. expect(menu()).toBeNull(); expect(container.querySelector('[data-testid="transcript-range-edit"]')).toBeNull(); }); it("the range editor prefills the LIVE run but stores the BASE-joined run as `was`", async () => { // The reducer scrubs every per-word retype inside the interval in the // same commit, so the run the apply-time whole-run guard reads IS the // base run — capturing the live (post-retype) join as `was` made the // guard fail on the very next apply and the rewrite dropped permanently. await act(async () => { root.render( React.createElement(Harness, { lines: [line(["hello", "b", "c"])], // The same anchors, pre-retype text: "hello" was typed over "helo". baseLines: [line(["helo", "b", "c"])], }), ); }); await click(word(0)); await click(word(2), true); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; // The DRAFT is what the user sees — the live run, retype included. expect(input.value).toBe("hello b c"); await act(async () => { Object.getOwnPropertyDescriptor( window.HTMLTextAreaElement.prototype, "value", )!.set!.call(input, "x y"); input.dispatchEvent(new Event("input", { bubbles: true })); }); // Commit via the Apply BUTTON this time — the popover's other commit // path (its sibling test above commits with Enter). await act(async () => { container .querySelector('[data-testid="transcript-apply"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); // The stored guard is the BASE join. expect(rangeDoc()).toEqual([ { fromKey: "w10000", toKey: "w12000", text: "x y", was: "helo b c" }, ]); }); /** Type into the open range editor and press Enter to commit (blur no * longer commits — the popover has explicit Apply/Cancel buttons). */ const commitRangeDraft = async (value: string) => { const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; await act(async () => { Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call( input, value, ); input.dispatchEvent(new Event("input", { bubbles: true })); }); await act(async () => { input.dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }), ); }); }; it("Edit on a SINGLE word opens the range editor — a multi-token draft SPLITS the word", async () => { // The field case (2026-08-18): whisper merges a terminal ۔ and the next // token into one word; splitting it is a one-word range edit. await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "merged.b"])] })); }); await click(word(1)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; expect(input.value).toBe("merged.b"); await commitRangeDraft("merged. b"); // fromKey === toKey — the core's single-word run. expect(rangeDoc()).toEqual([ { fromKey: "w11000", toKey: "w11000", text: "merged. b", was: "merged.b" }, ]); expect(captionsDoc()).toEqual({}); }); it("Edit on a single word committing ONE token stays a 1:1 retype — no range entry minted", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "helo"])] })); }); await click(word(1)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); await commitRangeDraft("hello"); expect(rangeDoc()).toEqual([]); expect(captionsDoc()).toEqual({ w11000: { text: "hello", was: "helo" } }); }); /** * The two caption layers guard differently, and the one-token Edit route * writes to the STRICTER one (2026-08-19 review). `applyCaptionRangeEdits` * normalizes both sides of its whole-run comparison; `applyCaptionEdits` * compares raw (`w.text !== edit.was`). Storing the NFC join on the * per-word route therefore minted an entry that can never match a * decomposed word — it reverts on the next apply and the "could not be * placed" banner fires, on the exact text this file normalizes its search * box for. */ it("a one-token Edit on a DECOMPOSED word stores the word's RAW text as `was`", async () => { // One glyph, two encodings: composed آ (U+0622) vs alef + madda // (U+0627 U+0653). Escapes, never literals — a literal lets any tool // that normalizes on save rewrite this test into a tautology. const decomposed = "\u0627\u0653\u0645"; await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", decomposed])] })); }); await click(word(1)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); await commitRangeDraft("x"); expect(rangeDoc()).toEqual([]); // VERBATIM the caption word's own bytes — what core will compare against. expect(captionsDoc()).toEqual({ w11000: { text: "x", was: decomposed } }); expect(captionsDoc().w11000.was).not.toBe(decomposed.normalize("NFC")); }); it("Apply to all on a decomposed word stores the RAW base for EVERY occurrence", async () => { // The bulk route lands in `patchCaptionAllOccurrences` — the same // per-word layer, so the same raw-`was` rule, for the selection's own // entry AND for each occurrence the sweep found. const decomposed = "\u0627\u0653\u0645"; await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", decomposed, "b", decomposed])] })); }); await click(word(1)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const draft = container.querySelector( '[data-testid="transcript-range-edit"]', )!; await act(async () => { Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call( draft, "x", ); draft.dispatchEvent(new Event("input", { bubbles: true })); }); await act(async () => { container .querySelector('[data-testid="transcript-apply-all"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(rangeDoc()).toEqual([]); expect(captionsDoc()).toEqual({ w11000: { text: "x", was: decomposed }, w13000: { text: "x", was: decomposed }, }); }); /** * The bar and the retype box share one anchor, and the bar is NOT a * backdrop-covered menu: left on screen over an open input, its Delete * item blurred the box — committing the retype through `onBlur` — and * opened the delete confirm in the same click (2026-08-19 review). */ it("the selection bar is GONE while the retype box is open", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["alpha", "beta"])] })); }); await click(word(1)); expect(menu()).not.toBeNull(); await act(async () => { word(1).dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-edit"]')).not.toBeNull(); expect(menu()).toBeNull(); // Escape closes the box; the selection — and with it the bar — survives. await act(async () => { container .querySelector('[data-testid="transcript-edit"]')! .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); }); expect(menu()).not.toBeNull(); }); it("click seeks with CEIL — the quantized playhead may not land in the PREVIOUS word", async () => { const seeks: number[] = []; // 50ms words (the degenerate-ASR repair shape): word 1 starts at 0.05s, // 0.05 * 30fps = 1.5 — round() would seek frame 1 (t = 0.033s, inside // word 0) and box the neighbour; ceil() seeks frame 2 (t = 0.067s). const cramped: CaptionLine = { words: [ { text: "a", start: 0, end: 0.05, srcStart: 10 }, { text: "b", start: 0.05, end: 0.1, srcStart: 10.05 }, ], start: 0, end: 0.1, }; await act(async () => { root.render( React.createElement(Harness, { lines: [cramped], seekTo: (f: number) => seeks.push(f), }), ); }); await click(word(1)); expect(seeks).toEqual([2]); }); it("disables Edit, with a reason, when any selected word has no source anchor (§137)", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [withAnchorless()] })); }); await click(word(0)); await click(word(1), true); const btn = container.querySelector( '[data-testid="transcript-edit-range"]', )!; expect(btn.disabled).toBe(true); expect(btn.title).toContain("no source anchor"); }); it("clears the selection when the word COUNT changes — the positional-index caveat", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c"])] })); }); await click(word(2)); expect(menu()).not.toBeNull(); // A completed render swapping in lines with a different word count is // exactly the swap the `editing.index` caveat documents; a kept range // would highlight (or Delete) different words than the user selected. await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); expect(menu()).toBeNull(); }); it("Delete captions hides DIRECTLY — live text as `was`, no plan, no modal", async () => { // The menu names the caption-only scope on the item itself (2026-08-18), // so the modal's caption/video decision is reserved for the Delete + // video… item — this one writes the hide layer straight away. const plans: DeleteWordsPlan[] = []; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["hello", "b"])], // Diverged base: the hide layer applies AFTER retypes, so `was` // must be the LIVE text, never the base. baseLines: [line(["helo", "b"])], onDeleteWords: (p: DeleteWordsPlan) => plans.push(p), }), ); }); await click(word(0)); await openDeleteFlyout(); await act(async () => { container .querySelector('[data-testid="transcript-hide"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(plans).toEqual([]); expect(hiddenDoc()).toEqual({ w10000: { was: "hello" } }); // The gesture consumed the selection. expect(menu()).toBeNull(); }); it("disables Delete captions, with the §137 reason, on an anchorless selection", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [withAnchorless()] })); }); await click(word(0)); await click(word(1), true); await openDeleteFlyout(); const hide = container.querySelector('[data-testid="transcript-hide"]')!; expect(hide.disabled).toBe(true); expect(hide.title).toContain("no source anchor"); }); it("the bar is anchored INSIDE the body (absolute) and SURVIVES a scroll — no close listener", async () => { // Round 3 field bug: the old fixed-position menu closed on the body's // scroll event — which the playhead-follow `scrollIntoView` itself // fires whenever the followed word left the pane, so the menu could be // destroyed within a frame of appearing. Anchoring the bar in CONTENT // coordinates (absolute inside the relative body) makes it scroll with // its anchor, so no scroll/resize close listener exists at all. await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); const bar = menu()! as HTMLElement; const body = container.querySelector('[data-testid="transcript-body"]')!; expect(body.contains(bar)).toBe(true); expect(bar.style.position).toBe("absolute"); await act(async () => { body.dispatchEvent(new Event("scroll")); }); expect(menu()).not.toBeNull(); await act(async () => { window.dispatchEvent(new Event("resize")); }); expect(menu()).not.toBeNull(); }); it("the bar is a horizontal row: Edit · Timing · Delete ▾ · count", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); const bar = menu()!; expect(bar.querySelector('[data-testid="transcript-edit-range"]')).not.toBeNull(); expect(bar.querySelector('[data-testid="transcript-timing"]')).not.toBeNull(); expect(bar.querySelector('[data-testid="transcript-delete-menu"]')).not.toBeNull(); expect(bar.textContent).toContain("1 word"); // The delete scopes live behind the flyout, closed until asked for. expect(bar.querySelector('[data-testid="transcript-hide"]')).toBeNull(); expect(bar.querySelector('[data-testid="transcript-delete"]')).toBeNull(); }); it("Delete ▾ opens the two-row flyout, which closes on selection change", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); await openDeleteFlyout(); // Both scopes on offer — the routing itself is each item's own test // ("Delete captions hides DIRECTLY…" / "a hidden word stays…"). expect(container.querySelector('[data-testid="transcript-hide"]')).not.toBeNull(); expect(container.querySelector('[data-testid="transcript-delete"]')).not.toBeNull(); // A flyout that outlived the selection would offer its rows for words // the user is no longer looking at. await click(word(1)); expect(menu()).not.toBeNull(); expect(container.querySelector('[data-testid="transcript-hide"]')).toBeNull(); }); // The button is offered for ANY selection, and its title names the CAPTIONS // the gesture will move — the selection snaps to whole lines, so a two-word // selection inside one caption is still one caption (`captionLineTiming`: // a caption's on-screen life is its LINE's window). it("Timing is offered on a multi-word selection, titled with the CAPTION count", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b"])] })); }); await click(word(0)); await click(word(1), true); const timing = container.querySelector('[data-testid="transcript-timing"]')!; expect(timing.disabled).toBe(false); expect(timing.title).toBe("Adjust when this caption appears and leaves"); await click(word(0)); expect( container.querySelector('[data-testid="transcript-timing"]')!.title, ).toBe("Adjust when this caption appears and leaves"); const single = container.querySelector( '[data-testid="transcript-timing"]', )!; expect(single.disabled).toBe(false); await act(async () => { single.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); // The popover REPLACES the bar at the same anchor (the range editor's // swap idiom). Its own behaviors are the timing describe's ground. expect(container.querySelector('[data-testid="transcript-timing-popover"]')).not.toBeNull(); expect(menu()).toBeNull(); }); it("Timing is disabled with the §137 reason on an anchorless single word", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [withAnchorless()] })); }); await click(word(1)); const timing = container.querySelector('[data-testid="transcript-timing"]')!; expect(timing.disabled).toBe(true); expect(timing.title).toContain("no source anchor"); }); it("clicking another word while the range editor is open CLOSES it — nothing committed", async () => { // The round-3 field bug: the popover is anchored to the selection, so a // moved selection re-rendered it at the NEW words while it still held // its stale capture — Apply then rewrote the PREVIOUS run while // visually pointing at the new one. The click must unmount the editor // and show the bar for the new selection instead. await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c"])] })); }); await click(word(0)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-range-edit"]')).not.toBeNull(); await click(word(1)); expect(container.querySelector('[data-testid="transcript-range-edit"]')).toBeNull(); expect(menu()!.textContent).toContain("1 word"); expect(rangeDoc()).toEqual([]); // Shift-extending is a selection move too — same close. await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); await click(word(2), true); expect(container.querySelector('[data-testid="transcript-range-edit"]')).toBeNull(); expect(menu()!.textContent).toContain("2 words"); expect(rangeDoc()).toEqual([]); }); it("selection paints ONE continuous yellow band — SQUARE corners, every span filled, no outline", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c"])] })); }); await click(word(0)); await click(word(1), true); for (const i of [0, 1]) { // The band color on the span itself. expect(word(i).style.background.toLowerCase()).toMatch(/ffe14d|255,\s*225,\s*77/); expect(word(i).style.outline).toBe(""); // The gap between two selected words is a BARE space node (§65), so // the band is bridged by a box-shadow — 4px each side, the `word` // style's own horizontal padding, so each span's bridge meets its // neighbour's. Guarded here because the shadow is the ONLY thing // keeping the band continuous: without it the selection re-stripes // per word, silently. It paints outside the border box, so unlike the // trailing-space-inside-the-span version it costs no layout width // (the §65 wrap guard, CI run 32195920547). const shadow = word(i).style.boxShadow.toLowerCase(); expect(shadow).toMatch(/-4px 0(px)? 0(px)? 0(px)? (#ffe14d|rgb\(255,\s*225,\s*77\))/); expect(shadow).toMatch(/(^|,\s*)4px 0(px)? 0(px)? 0(px)? (#ffe14d|rgb\(255,\s*225,\s*77\))/); // SQUARE corners, and since 2026-08-26 they are load-bearing rather // than merely tidy: the playhead marker is a ROUNDED rect now, and the // corner is half of what tells "this is the caption being spoken" apart // from "these are the words I selected" (`selectedStyle`). expect(word(i).style.borderRadius).toBe("0"); } expect(word(2).style.background).toBe(""); // No stray bridge on an UNSELECTED word — it would paint yellow into the // gap beside a word that is not in the band. expect(word(2).style.boxShadow).toBe(""); }); it("the playhead word wears a ROUNDED-RECT background — a different hue from the band, and no bridge", async () => { let fire: ((frame: number) => void) | null = null; await act(async () => { root.render( React.createElement(Harness, { lines: [line(["a", "b", "c"])], onFrame: (f: (frame: number) => void) => { fire = f; }, }), ); }); // Frame 10 at 30fps → t ≈ 0.33s, inside word 1's [0.3, 0.6) window. await act(async () => { fire!(10); }); // The playing word: a dim-blue rounded rect (the reference screenshot), // NOT the underline it used to be — a single-property `textDecoration` // clobbered the strike-through on hidden words for as long as the // playhead sat on one. expect(word(1).style.background.toLowerCase()).toMatch(/2e5cff|46,\s*92,\s*255/); expect(word(1).style.borderRadius).toBe("4px"); expect(word(1).style.textDecoration).toBe(""); // NO shadow bridge: that trick is selection-only, and bridging here would // fuse the spoken word into its neighbours and light up three. expect(word(1).style.boxShadow).toBe(""); // Under the band when the word is also SELECTED — the band's yellow wins, // which is what keeps a selection readable as one continuous field. await click(word(0)); await click(word(2), true); expect(word(1).style.background.toLowerCase()).toMatch(/ffe14d|255,\s*225,\s*77/); expect(word(1).style.borderRadius).toBe("0"); }); it("Apply to all (n) on a single word retypes EVERY occurrence, each guarded by its own base", async () => { // Two other "hello"s besides the selection; base text diverges so the // stored `was` must be each occurrence's BASE, never the live join. await act(async () => { root.render( React.createElement(Harness, { lines: [line(["hello", "x", "hello", "hello"])], baseLines: [line(["helo", "x", "helo", "helo"])], }), ); }); await click(word(0)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const all = container.querySelector('[data-testid="transcript-apply-all"]')!; // n counts the OTHER occurrences — the selection itself is not one. expect(all.textContent).toBe("Apply to all (2)"); const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; await act(async () => { Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call( input, "world", ); input.dispatchEvent(new Event("input", { bubbles: true })); }); await act(async () => { all.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); // A single token on single words routes through patchCaption semantics — // per-word entries, no range entries minted. expect(captionsDoc()).toEqual({ w10000: { text: "world", was: "helo" }, w12000: { text: "world", was: "helo" }, w13000: { text: "world", was: "helo" }, }); expect(rangeDoc()).toEqual([]); expect(menu()).toBeNull(); expect(container.querySelector('[data-testid="transcript-range-edit"]')).toBeNull(); }); it("Apply to all on a multi-word run writes a range entry per occurrence, selection included", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "x", "a", "b"])] })); }); await click(word(0)); await click(word(1), true); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const all = container.querySelector('[data-testid="transcript-apply-all"]')!; expect(all.textContent).toBe("Apply to all (1)"); const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; await act(async () => { Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call( input, "q r", ); input.dispatchEvent(new Event("input", { bubbles: true })); }); await act(async () => { all.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(rangeDoc()).toEqual([ { fromKey: "w10000", toKey: "w11000", text: "q r", was: "a b" }, { fromKey: "w13000", toKey: "w14000", text: "q r", was: "a b" }, ]); }); it("no Apply to all button when the text occurs nowhere else", async () => { await act(async () => { root.render(React.createElement(Harness, { lines: [line(["a", "b", "c"])] })); }); await click(word(0)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-apply"]')).not.toBeNull(); expect(container.querySelector('[data-testid="transcript-apply-all"]')).toBeNull(); }); }); /** * The one-line hint + collapsed help (2026-08-18): the old always-on scope * paragraph cost four lines of pane height; the contract now lives behind a * `?` toggle, collapsed by default. */ describe("TranscriptPanel hint and help toggle", () => { let container: HTMLDivElement; let root: ReturnType; const line = (texts: string[]): CaptionLine => ({ words: texts.map((text, i) => ({ text, start: i * 0.3, end: i * 0.3 + 0.3, srcStart: 10 + i, })), start: 0, end: texts.length * 0.3, }); function Harness() { const edits = useEdits(); const playerRef = useRef(null); return React.createElement(TranscriptPanel, { baseLines: [line(["a", "b"])], liveLines: [line(["a", "b"])], timingLines: [line(["a", "b"])], workdir: null, fps: 30, playerRef, edits, onDeleteWords: () => {}, width: 300, }); } beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it("shows the one-line hint; the full help is collapsed until ? toggles it", async () => { await act(async () => { root.render(React.createElement(Harness)); }); expect(container.textContent).toContain( "Click to jump · double-click to retype · drag to select", ); expect(container.querySelector('[data-testid="transcript-help"]')).toBeNull(); const toggle = container.querySelector( '[data-testid="transcript-help-toggle"]', )!; await act(async () => { toggle.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); const help = container.querySelector('[data-testid="transcript-help"]')!; // The tightened paragraph keeps the two load-bearing distinctions: the // caption-only vs video delete, and the split-a-merged-word tip. expect(help.textContent).toContain("captions only"); expect(help.textContent).toContain("from the video too"); expect(help.textContent).toContain("split a merged one"); await act(async () => { toggle.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-help"]')).toBeNull(); }); }); /** * Base lookup by ANCHOR, not position (2026-08-18). Range edits change word * COUNT, so positional base/live pairing (`base.words[wi]`) misaligns every * word after a rewritten run — mis-titling neighbours the user never touched. * A live word with no base match at its anchor was MINTED by a rewrite and is * styled as edited, its title naming the range's `was`. */ describe("TranscriptPanel base lookup by anchor (range edits)", () => { let container: HTMLDivElement; let root: ReturnType; const lineOf = (ws: Array<[string, number]>): CaptionLine => ({ words: ws.map(([text, srcStart], i) => ({ text, start: i * 0.3, end: i * 0.3 + 0.3, srcStart, })), start: 0, end: ws.length * 0.3, }); function Harness({ baseLines, liveLines, seedRange, }: { baseLines: CaptionLine[]; liveLines: CaptionLine[]; /** A stored range edit, so a minted word's title can name its `was`. */ seedRange?: { from: number; to: number; text: string; was: string }; }) { const edits = useEdits(); const playerRef = useRef({ seekTo: () => {}, addEventListener: () => {}, removeEventListener: () => {}, } as unknown as PlayerRef); const seeded = useRef(false); React.useEffect(() => { if (!seedRange || seeded.current) return; seeded.current = true; edits.patchCaptionRange(seedRange.from, seedRange.to, seedRange.text, seedRange.was); }); return React.createElement(TranscriptPanel, { baseLines, liveLines, // No hides in this harness: the timed track is the rendered one. timingLines: liveLines, workdir: null, fps: 30, playerRef, edits, onDeleteWords: () => {}, width: 300, }); } const word = (i: number) => container.querySelector(`[data-testid="transcript-word-${i}"]`)!; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it("a NEIGHBOUR after a shrunk run keeps its OWN base — positional pairing would blame it", async () => { // Base "a b c d"; a rewrite collapsed "b c" into one word "X" (which // carries the run's fromSrc verbatim — the endpoint-preservation rule). // Positionally, live index 2 ("d") would pair with base "c" and show as // edited; by anchor it pairs with its own base "d" and stays neutral. await act(async () => { root.render( React.createElement(Harness, { baseLines: [lineOf([["a", 10], ["b", 11], ["c", 12], ["d", 13]])], liveLines: [lineOf([["a", 10], ["X", 11], ["d", 13]])], }), ); }); expect(word(1).title).toContain("was “b”"); expect(word(2).title).toBe("click to jump · double-click to retype"); expect(word(2).title).not.toContain("was “c”"); }); it("a MINTED word (no base word at its anchor) is edited-styled, titled with the range's was", async () => { // "b c" (11..12) rewritten to three tokens: the middle one's srcStart is // interpolated (11.5) and matches no base word. await act(async () => { root.render( React.createElement(Harness, { baseLines: [lineOf([["a", 10], ["b", 11], ["c", 12], ["d", 13]])], liveLines: [lineOf([["a", 10], ["t1", 11], ["t2", 11.5], ["t3", 12], ["d", 13]])], seedRange: { from: 11, to: 12, text: "t1 t2 t3", was: "b c" }, }), ); }); const minted = word(2); // Covered by the LIVE entry, so the title routes to the range editor — // the 1:1 retype is refused on it (`openRetype`'s coverage refusal). expect(minted.title).toBe("part of a rewritten range (was “b c”) — select it and use Edit"); // Same edited color as a retyped word — the base-map miss is the flag. expect(minted.style.color).toBe(word(1).style.color); expect(word(4).title).toBe("click to jump · double-click to retype"); }); it("duplicate-anchor base words pair by ORDINAL — the second claimant keeps its OWN base", async () => { // `backfillSrcStart` MANUFACTURES shared source instants // (captions.ts:44-50 — a seam's two preimages, a word clamped to a kept // edge), so two DIFFERENT words can carry one anchor. First-claimant // pairing handed the second word the first's base text ("foo"), styling // it falsely edited and capturing the wrong `was`. await act(async () => { root.render( React.createElement(Harness, { baseLines: [lineOf([["foo", 5], ["bar", 5]])], liveLines: [lineOf([["foo", 5], ["bar", 5]])], }), ); }); expect(word(0).title).toBe("click to jump · double-click to retype"); // The second claimant pairs with ITS base ("bar"), not its neighbour's. expect(word(1).title).toBe("click to jump · double-click to retype"); }); }); /** * Gestures over an ALREADY-REWRITTEN run (2026-08-18 review fixes). A live * `captionRangeEdits` entry owns every word inside its interval: the 1:1 * retype is refused on them (either it stales the whole entry or it keys to * a minted anchor no apply pass ever finds), a partial selection's Edit * expands to the entry's full run and commits under the entry's OWN pair * (minted anchors exist only while their entry does — re-keying a partial * overlap loses BOTH rewrites), and Delete never offers the video cut * through a minted word (its stamps are interpolations, not measurements). */ describe("TranscriptPanel re-editing a rewritten run", () => { let container: HTMLDivElement; let root: ReturnType; const lineOf = (ws: Array<[string, number]>): CaptionLine => ({ words: ws.map(([text, srcStart], i) => ({ text, start: i * 0.3, end: i * 0.3 + 0.3, srcStart, })), start: 0, end: ws.length * 0.3, }); // Base "a b c d"; "b c" (11..12) rewritten to "t1 t2 t3" — endpoints keep // verbatim anchors, t2's srcStart is interpolated (11.5): synthetic. const baseLines = [lineOf([["a", 10], ["b", 11], ["c", 12], ["d", 13]])]; const liveLines = [lineOf([["a", 10], ["t1", 11], ["t2", 11.5], ["t3", 12], ["d", 13]])]; function Harness({ onDeleteWords }: { onDeleteWords?: (plan: DeleteWordsPlan) => void }) { const edits = useEdits(); const playerRef = useRef({ seekTo: () => {}, addEventListener: () => {}, removeEventListener: () => {}, } as unknown as PlayerRef); const seeded = useRef(false); React.useEffect(() => { if (seeded.current) return; seeded.current = true; edits.patchCaptionRange(11, 12, "t1 t2 t3", "b c"); }); return React.createElement( "div", null, React.createElement("div", { "data-testid": "range-doc", children: JSON.stringify(edits.doc.captionRangeEdits), }), React.createElement(TranscriptPanel, { baseLines, liveLines, // No hides here: the timed (post-hide) track is the rendered one. timingLines: liveLines, workdir: null, fps: 30, playerRef, edits, onDeleteWords: onDeleteWords ?? (() => {}), width: 300, }), ); } const word = (i: number) => container.querySelector(`[data-testid="transcript-word-${i}"]`)!; const click = async (el: HTMLElement, shiftKey = false) => { await act(async () => { el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, shiftKey })); }); }; const rangeDoc = () => JSON.parse(container.querySelector('[data-testid="range-doc"]')!.textContent!); beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it("refuses the 1:1 retype on a word covered by a live rewrite — even a verbatim endpoint", async () => { await act(async () => { root.render(React.createElement(Harness, {})); }); // t1 keeps a VERBATIM base anchor (w11000), so the anchor guard alone // would let it through — the coverage refusal is what stops it: an // equal-count retype would stale the whole entry's `was` guard, and a // retype on minted t2 would key to an anchor no apply pass ever finds. await act(async () => { word(1).dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-edit"]')).toBeNull(); await act(async () => { word(2).dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-edit"]')).toBeNull(); // An uncovered neighbour still opens — the refusal is scoped to the run. await act(async () => { word(4).dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); expect(container.querySelector('[data-testid="transcript-edit"]')).not.toBeNull(); }); it("Edit on a PARTIAL selection expands to the entry's run and commits under the ORIGINAL pair", async () => { await act(async () => { root.render(React.createElement(Harness, {})); }); // Select ONLY the minted middle word. await click(word(2)); await act(async () => { container .querySelector('[data-testid="transcript-edit-range"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); // The selection expanded to the entry's whole run: the editor prefills // the FULL run's current text, not the one selected word. (The menu // itself is gone while the popover is open — the popover replaces it at // the same anchor — so the prefill is the observable expansion.) const input = container.querySelector( '[data-testid="transcript-range-edit"]', )!; expect(input.value).toBe("t1 t2 t3"); await act(async () => { Object.getOwnPropertyDescriptor( window.HTMLTextAreaElement.prototype, "value", )!.set!.call(input, "q r"); input.dispatchEvent(new Event("input", { bubbles: true })); }); await act(async () => { input.dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }), ); }); // ONE entry, keyed to the ORIGINAL pair, `was` inherited from the // original base run (`captionRangeEditWas`) — never a second entry keyed // to minted anchors that would resolve `found: null` forever. expect(rangeDoc()).toEqual([ { fromKey: "w11000", toKey: "w12000", text: "q r", was: "b c" }, ]); }); it("Delete on a selection containing a MINTED word withholds the video cut", async () => { const plans: DeleteWordsPlan[] = []; await act(async () => { root.render( React.createElement(Harness, { onDeleteWords: (p: DeleteWordsPlan) => plans.push(p) }), ); }); await click(word(1)); await click(word(3), true); // The delete scopes live behind the bar's Delete ▾ flyout (round 3). await act(async () => { container .querySelector('[data-testid="transcript-delete-menu"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); await act(async () => { container .querySelector('[data-testid="transcript-delete"]')! .dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); }); expect(plans).toHaveLength(1); // t2's stamps are interpolations — caption-only is all that is offered. expect(plans[0]!.targets).toEqual(["caption"]); }); }); /** * The timing popover — the "when does this caption appear, and when does it * leave" adjuster, CAPTION-shaped since the `captionLineTiming` rewrite. * * IT IS TESTED AGAINST A PACKED FIXTURE, and that is the point. The previous * suite's fixture gave its words 0.2s of slack between them and parked the * next word 0.8s away, "so an unclamped nudge has room to land" — on a real * transcript there is no such room (116/116 inter-line gaps and 184/184 * intra-line word boundaries measured exactly 0.0; `captionLineTiming`'s * docstring has the numbers). Against the packed stream the old per-word * clamp collapsed to each word's own `[start, end]`: every drag was clamped * to identity and Apply stored nothing — the field bug, invisible because the * fixture had slack the product does not. `describe("the fixture itself")` * below pins the packing so this can never quietly come back. * * jsdom ground rules, unchanged: no AudioContext (the waveform loader must * resolve null, never throw) and no 2d canvas context (the draw effect must * bail) — the popover still opens, drags and applies. */ /** * The TIMING WIDGET (audio-first, 2026-08-26) — the tool that replaced the * seam-nudge popover. Field case: inside a kept retake whisper puts the words * in the WRONG PLACE, so "move this caption's seam by 80ms against its * neighbour" is the wrong question; "this caption belongs on THAT sound" is * the right one. Everything below is therefore in SOURCE seconds, the * waveform's own clock and the one `captionLineWindows` stores. */ describe("TranscriptPanel timing widget", () => { let container: HTMLDivElement; let root: ReturnType; const origGetContext = HTMLCanvasElement.prototype.getContext; const origPlay = HTMLMediaElement.prototype.play; const origPause = HTMLMediaElement.prototype.pause; const origCurrentTime = Object.getOwnPropertyDescriptor( HTMLMediaElement.prototype, "currentTime", ); /** Every `play()` the widget's audio element received, with the * `currentTime` it was told to start from. */ let plays: number[] = []; let pauses = 0; /** * Three captions, GAP-FREE: every word chains onto the next, every line * ends exactly where the next begins, and each line's window is its own * words' extent. `srcStart` is the output start + 10 — a distinct key space * (§137), so a test that confused source and output time fails instead of * passing by coincidence, and an identity-plus-offset source map, which is * what a workdir with no cut inside the window has. */ const packed = (): CaptionLine[] => [ { start: 0, end: 1.2, words: [ { text: "one", start: 0, end: 0.6, srcStart: 10 }, { text: "two", start: 0.6, end: 1.2, srcStart: 10.6 }, ], }, { start: 1.2, end: 2.4, words: [ { text: "three", start: 1.2, end: 1.8, srcStart: 11.2 }, { text: "four", start: 1.8, end: 2.4, srcStart: 11.8 }, ], }, { start: 2.4, end: 3.6, words: [ { text: "five", start: 2.4, end: 3, srcStart: 12.4 }, { text: "six", start: 3, end: 3.6, srcStart: 13 }, ], }, ]; /** The three lines' keys — each caption is addressed by its FIRST word's * source anchor (`applyCaptionLineWindows`). */ const LINE_A = "w10000"; const LINE_B = "w11200"; const LINE_C = "w12400"; /** Caption B's derived SOURCE span, and the whole track's. */ const B = { start: 11.2, end: 12.4 }; /** * The clock this fixture's `srcStart`s imply: one kept span from source 10, * landing at output 0. The `timed-lines` probe below needs it because a * window is stored in source seconds and the caption track speaks output * ones — which is exactly what `applyCaptionLineWindows` converts. */ const MAP = new TimeMap([{ srcIn: 10, srcOut: 23.6, kind: "keep" }]); function Harness({ lines, seeds, seekTo, onPlay, }: { lines: CaptionLine[]; /** Pre-stored WINDOWS — the marker tests need the doc primed (the * seedRange idiom). */ seeds?: Array<{ srcStart: number; window: { srcStart: number; srcEnd: number } }>; /** The MAIN player's seek, which the widget must never call: the tool * plays its own audio element now. */ seekTo?: (frame: number) => void; onPlay?: () => void; }) { const edits = useEdits(); const playerRef = useRef({ seekTo: seekTo ?? (() => {}), play: onPlay ?? (() => {}), pause: () => {}, addEventListener: () => {}, removeEventListener: () => {}, } as unknown as PlayerRef); const seeded = useRef(false); React.useEffect(() => { if (!seeds || seeded.current) return; seeded.current = true; edits.patchCaptionLineWindows(seeds); }); // App's own layer order, collapsed to the two layers this suite // exercises: the panel RENDERS the pre-hide lines (a hidden word stays on // screen, struck through) while the window layer runs on the POST-hide // ones, which is the whole reason `timingLines` is a separate prop. const timingLines = applyCaptionWordHides(lines, edits.doc.captionWordsHidden).lines; return React.createElement( "div", null, // The doc probe: what the reducer actually stored, without reaching // into the hook. React.createElement("div", { "data-testid": "timing-doc", children: JSON.stringify(edits.doc.captionLineWindows), }), // What the RENDER will actually show: core's own apply pass over the // timed track, through the same map produce would use. A stored window // that addresses no post-hide line leaves this identical to the input, // which is the "it looks stored but the caption never moves" failure in // its observable form. React.createElement("div", { "data-testid": "timed-lines", children: JSON.stringify( applyCaptionLineWindows(timingLines, edits.doc.captionLineWindows, MAP).lines.map((l) => [ Number(l.start.toFixed(4)), Number(l.end.toFixed(4)), ]), ), }), // A placement's promise is ONE undo step for the whole gesture, however // many captions — which only the hook's own undo can prove. React.createElement("button", { "data-testid": "timing-undo", onClick: () => edits.undo(), }), React.createElement(TranscriptPanel, { baseLines: lines, // The panel is fed the PRE-timing stream (App.tsx passes the // post-range, pre-hide lines). liveLines: lines, timingLines, workdir: null, fps: 30, playerRef, edits, onDeleteWords: () => {}, width: 300, }), ); } const word = (i: number) => container.querySelector(`[data-testid="transcript-word-${i}"]`)!; const click = async (el: HTMLElement, shiftKey = false) => { await act(async () => { el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, shiftKey })); }); }; const clickTestid = async (testid: string) => { await click(container.querySelector(`[data-testid="${testid}"]`)!); }; const widget = () => container.querySelector('[data-testid="transcript-timing-popover"]'); const menu = () => container.querySelector('[data-testid="transcript-selection-menu"]'); const audioEl = () => container.querySelector('[data-testid="transcript-timing-audio"]')!; const timingDoc = () => JSON.parse(container.querySelector('[data-testid="timing-doc"]')!.textContent!); /** The timed track core would render — `[start, end]` per post-hide line. */ const timedLines = (): Array<[number, number]> => JSON.parse(container.querySelector('[data-testid="timed-lines"]')!.textContent!); /** Open the widget over word `i` — select it, then hit Timing. */ const openOn = async (i: number) => { await click(word(i)); await clickTestid("transcript-timing"); }; /** The same, over the word run `from…to` — shift-click extends. */ const openRun = async (from: number, to: number) => { await click(word(from)); await click(word(to), true); await clickTestid("transcript-timing"); }; const spanText = () => container.querySelector('[data-testid="transcript-timing-span"]')!.textContent; /** Drag a handle by dispatching pointer-typed MouseEvents (jsdom has no * PointerEvent constructor; React dispatches on the TYPE, and the handler * only reads clientX). The move and the release go to WINDOW, where a real * drag's events land the moment the pointer leaves the 12px zone. */ const dragHandle = async (testid: string, fromX: number, toX: number) => { const h = container.querySelector(`[data-testid="${testid}"]`)!; await act(async () => { h.dispatchEvent( new MouseEvent("pointerdown", { bubbles: true, cancelable: true, clientX: fromX }), ); }); await act(async () => { window.dispatchEvent( new MouseEvent("pointermove", { bubbles: true, cancelable: true, clientX: toX }), ); }); await act(async () => { window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, cancelable: true })); }); }; /** Move the widget's audio element and let it say so, the way a real * element does several times a second while it plays. */ const timeupdate = async (at: number) => { await act(async () => { audioEl().currentTime = at; audioEl().dispatchEvent(new Event("timeupdate")); }); }; /** * The px→seconds factor for a one-caption selection on caption B: its * source span ±10s (`timingAudioWindow`), clamped at 0 on the left and NOT * on the right — jsdom decodes no audio and its `