Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(captions): draw the anchor line and the column while the pane is open
EtienneLescot7fb41bde997f
diff --git a/src/components/ai-edition/CaptionGuideOverlay.test.tsx b/src/components/ai-edition/CaptionGuideOverlay.test.tsxnew file mode 100644index 000000000..0030de548--- /dev/null+++ b/src/components/ai-edition/CaptionGuideOverlay.test.tsx@@ -0,0 +1,127 @@+// @vitest-environment jsdom+// The caption guide is DOM, and the last DOM caption layer was deleted for good+// reason (it painted the same text through a second wrapping engine and the two+// disagreed). What these tests pin is the boundary that makes this one safe: it+// draws no text, it only appears while the pane that explains it is open, and it+// tracks the same geometry function the compositor is handed.++import "@testing-library/jest-dom";+import { cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { captionBoxRect, getCaptionSettings } from "@/lib/ai-edition/captions";+import type { AxcutAsset, AxcutDocument } from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { useCaptionGuideBus } from "@/lib/ai-edition/store/useCaptionGuideBus";+import { CaptionGuideOverlay } from "./CaptionGuideOverlay";++vi.mock("@/native", () => ({ nativeBridgeClient: { aiEdition: {} } }));+vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: {} } }));++const ASSET: AxcutAsset = {+ id: "asset_1",+ kind: "video",+ label: "recording.mp4",+ originalPath: "/rec.mp4",+ durationSec: 12,+ cameraTrack: null,+};++function documentWith(captions: Record<string, unknown>): AxcutDocument {+ return {+ schemaVersion: 7,+ project: {+ id: "proj_1",+ title: "Test",+ createdAt: "2026-06-25T10:00:00.000Z",+ updatedAt: "2026-06-25T10:00:00.000Z",+ primaryAssetId: ASSET.id,+ },+ assets: [ASSET],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [+ {+ id: "clip_1",+ assetId: ASSET.id,+ sourceStartSec: 0,+ sourceEndSec: 12,+ timelineStartSec: 0,+ timelineEndSec: 12,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ gaps: [],+ trimRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: { captions },+ } as unknown as AxcutDocument;+}++function show(captions: Record<string, unknown>, open: boolean) {+ const document = documentWith(captions);+ useProjectStore.setState({+ projectId: document.project.id,+ document,+ status: "ready",+ error: null,+ dirty: false,+ });+ useCaptionGuideBus.setState({ open });+ return { document, ...render(<CaptionGuideOverlay />) };+}++beforeEach(() => {+ useProjectStore.getState().clear();+ useCaptionGuideBus.setState({ open: false });+});++afterEach(() => {+ cleanup();+});++describe("caption guide overlay", () => {+ it("draws nothing while the captions pane is closed", () => {+ const { container } = show({ enabled: true }, false);+ expect(container).toBeEmptyDOMElement();+ });++ it("draws nothing when captions are off, even with the pane open", () => {+ const { container } = show({ enabled: false }, true);+ expect(container).toBeEmptyDOMElement();+ });++ it("puts the anchor line exactly where the compositor pins the caption", () => {+ const { container, document } = show({ enabled: true, anchorV: "bottom", insetY: 12 }, true);+ const line = container.querySelector('div[style*="height: 2px"]');+ expect(line).toBeInTheDocument();+ // 100 − insetY: the same number `captionBoxRect` puts the box's bottom edge at,+ // so the guide cannot drift from the thing it is drawing.+ expect((line as HTMLElement).style.top).toBe("88%");++ const box = captionBoxRect(getCaptionSettings(document, 16 / 9), 16 / 9);+ expect(box.y + box.height).toBeCloseTo(88, 6);+ });++ it("follows the anchor to the top edge", () => {+ const { container } = show({ enabled: true, anchorV: "top", insetY: 9 }, true);+ const line = container.querySelector('div[style*="height: 2px"]');+ expect((line as HTMLElement).style.top).toBe("9%");+ });++ it("carries no text — it is a guide, not a second caption painter", () => {+ const { container } = show({ enabled: true }, true);+ expect(container.textContent).toBe("");+ // And it is inert: it must never eat a click meant for the canvas beneath.+ const root = container.firstElementChild as HTMLElement;+ expect(root.style.pointerEvents).toBe("none");+ expect(root).toHaveAttribute("aria-hidden", "true");+ });+});diff --git a/src/components/ai-edition/CaptionGuideOverlay.tsx b/src/components/ai-edition/CaptionGuideOverlay.tsxnew file mode 100644index 000000000..a298b36dc--- /dev/null+++ b/src/components/ai-edition/CaptionGuideOverlay.tsx@@ -0,0 +1,95 @@+// The caption guide: the anchor line the user is actually setting, plus the edges of+// the column captions wrap in. Shown only while the Captions pane is open.+//+// Why it exists: the pane's controls are all edge-referenced now, but two of those+// edges (the column's) are derived from the output aspect rather than chosen, so+// "why does Left stop there?" has no answer on screen without this. The anchor line+// is the stronger reason — it IS the invariant the distance slider sets, and watching+// it hold still while a caption grows is the fastest way to understand the model.+//+// This is NOT a second caption painter. `CaptionLayer.tsx` was deleted because it+// drew the same TEXT through a second wrapping engine and the two disagreed on line+// breaks; a rule and two hairlines have no glyphs to disagree about. The precedent is+// `AnnotationOverlay` — the DOM painter went, the selection chrome stayed. A <div>+// also has no route into `buildSceneDescription`, so it cannot reach an export.++import { useMemo } from "react";+import { captionBoxRect, getCaptionSettings } from "@/lib/ai-edition/captions";+import { resolveAspectRatioValue } from "@/lib/ai-edition/document/outputFormat";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { useCaptionGuideBus } from "@/lib/ai-edition/store/useCaptionGuideBus";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";++/**+ * Mounted as a direct child of `.previewFrame`, NOT of `.screenStage`.+ *+ * That is load-bearing: `.screenStage` is the screen rect, which shrinks as the+ * padding slider grows, while captions are measured against the output frame+ * (`space: "frame"`, issue #396). Drawing the guide on the screen rect would+ * reproduce that exact bug inside the guide meant to explain it. Inside+ * `.previewFrame`, frame-percent → CSS-percent is the identity, so there is no+ * letterbox arithmetic here and no second geometry to keep in sync.+ */+export function CaptionGuideOverlay() {+ const open = useCaptionGuideBus((s) => s.open);+ const document = useProjectStore((s) => s.document);+ const { settings: editorSettings } = useEditorSettings();++ const guide = useMemo(() => {+ if (!document) return null;+ const aspect = resolveAspectRatioValue(document, editorSettings.aspectRatio);+ const captions = getCaptionSettings(document, aspect);+ if (!captions.enabled) return null;+ const box = captionBoxRect(captions, aspect);+ return {+ // The edge the caption is pinned to — the one number the distance slider sets,+ // and the one that must not move when the text wraps.+ anchorPct: captions.anchorV === "bottom" ? 100 - captions.insetY : captions.insetY,+ leftPct: box.x,+ rightPct: box.x + box.width,+ };+ }, [document, editorSettings.aspectRatio]);++ if (!open || !guide) return null;++ return (+ <div+ aria-hidden="true"+ style={{+ position: "absolute",+ inset: 0,+ pointerEvents: "none",+ zIndex: 3,+ }}+ >+ {/* The column's edges, faint: they answer "why does Left stop there?" and+ nothing else, so they must not compete with the anchor line. */}+ {[guide.leftPct, guide.rightPct].map((pct) => (+ <div+ key={pct}+ style={{+ position: "absolute",+ top: 0,+ bottom: 0,+ left: `${pct}%`,+ width: 1,+ background: "color-mix(in srgb, var(--accent) 35%, transparent)",+ }}+ />+ ))}+ {/* The anchor line. Deliberately the loudest thing here. */}+ <div+ style={{+ position: "absolute",+ left: `${guide.leftPct}%`,+ width: `${guide.rightPct - guide.leftPct}%`,+ top: `${guide.anchorPct}%`,+ height: 2,+ marginTop: -1,+ background: "var(--accent)",+ borderRadius: 1,+ }}+ />+ </div>+ );+}diff --git a/src/components/ai-edition/CaptionsPane.tsx b/src/components/ai-edition/CaptionsPane.tsxindex 6d6a776c9..13e0b1c8b 100644--- a/src/components/ai-edition/CaptionsPane.tsx+++ b/src/components/ai-edition/CaptionsPane.tsx@@ -10,7 +10,7 @@// "Original" goes straight back to the SSOT text.import { Captions as CaptionsIcon, Languages, Loader2, Trash2 } from "lucide-react";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useScopedT } from "@/contexts/I18nContext";import type { CaptionAnchorH, CaptionAnchorV } from "@/lib/ai-edition/captions";import {@@ -23,6 +23,7 @@ import {useTimelineTranscriptGate,useTranscriptionStore,} from "@/lib/ai-edition/store/transcriptionStore";+import { useCaptionGuideBus } from "@/lib/ai-edition/store/useCaptionGuideBus";import { useCaptions } from "@/lib/ai-edition/store/useCaptions";import { nativeBridgeClient } from "@/native";import { ColorField } from "./ColorField";@@ -117,6 +118,15 @@ export function CaptionsPane() {const disabled = !hasDocument;const languageOptions = useMemo(() => Object.values(translations), [translations]);+ // The preview draws the anchor line and the column edges while this pane is open.+ // `FacetBody` mounts exactly one pane at a time, so mounting is the signal — no+ // prop to thread down through the inspector, and nothing to remember to turn off.+ const setGuideOpen = useCaptionGuideBus((s) => s.setOpen);+ useEffect(() => {+ setGuideOpen(true);+ return () => setGuideOpen(false);+ }, [setGuideOpen]);+const handleTranslate = async () => {const doc = useProjectStore.getState().document;if (!doc) return;diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 6f59e066f..70980fa33 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -55,6 +55,7 @@ import { getCssClipPath } from "@/lib/webcamMaskShapes";import { computeCameraFullscreenProgress } from "@/lib/zoomMath/cameraFullscreenUtils";import { clamp, clamp01 } from "@/utils/math";import { AnnotationLayer } from "./AnnotationLayer";+import { CaptionGuideOverlay } from "./CaptionGuideOverlay";import { NativeCompositorOverlay } from "./NativeCompositorOverlay";import styles from "./NewEditorShell.module.css";import { type VideoSource, VirtualPreview } from "./VirtualPreview";@@ -405,6 +406,11 @@ export function PreviewCanvas(props: PreviewCanvasProps) {hitbox) still render on top as normal DOM so they stay clickable. No moredual preview path. */}<NativeCompositorOverlay />+ {/* Sibling of `.screenStage`, never a child of it: captions are measured+ against the output FRAME, and `.screenStage` shrinks with the padding+ slider — so a guide mounted inside it would drift away from the thing+ it is drawing (issue #396, in the guide meant to explain it). */}+ <CaptionGuideOverlay />{layout?.screenRect ? (<div className={styles.screenStage} style={screenStyle}>{(() => {diff --git a/src/lib/ai-edition/store/useCaptionGuideBus.ts b/src/lib/ai-edition/store/useCaptionGuideBus.tsnew file mode 100644index 000000000..8219b4c36--- /dev/null+++ b/src/lib/ai-edition/store/useCaptionGuideBus.ts@@ -0,0 +1,20 @@+import { create } from "zustand";++// Tiny decoupled bus so the preview can draw the caption guide while the Captions+// pane is open, without the pane reaching across the layout to the canvas or the+// canvas importing the inspector.+//+// Same shape and same reason as `useChatPromptBus`. The pane owns the signal because+// it is the thing that knows it is open: `FacetBody` mounts exactly one pane at a+// time, so mounting IS "the user is editing captions" and unmounting is the end of it.++interface CaptionGuideBusState {+ /** True while the Captions pane is mounted. Nothing else may set it. */+ open: boolean;+ setOpen: (open: boolean) => void;+}++export const useCaptionGuideBus = create<CaptionGuideBusState>((set) => ({+ open: false,+ setOpen: (open) => set({ open }),+}));diff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.mdindex 2d34225fe..389d0abce 100644--- a/technical-documentation/architecture/transcription-and-captions.md+++ b/technical-documentation/architecture/transcription-and-captions.md@@ -519,7 +519,7 @@ unit falls back to the original words (`untranslatedUnits`,Caption appearance lives in `document.legacyEditor.captions`, accessedthrough `getCaptionSettings` / `patchCaptionSettings`-([`src/lib/ai-edition/captions/settings.ts:279,324`](../../src/lib/ai-edition/captions/settings.ts:279)).+([`src/lib/ai-edition/captions/settings.ts:387,445`](../../src/lib/ai-edition/captions/settings.ts:387)).| Field | Default | Notes ||---|---|---|@@ -528,11 +528,11 @@ through `getCaptionSettings` / `patchCaptionSettings`| `fontSize` | `48` | Pixels at a 1080-high frame; `annotationFontSizeFraction` turns that into a fraction of the box being drawn into (`src/lib/ai-edition/annotationScale.ts`), resolution-free. || `fontFamily`, `fontWeight`, `color` | `Inter`, `bold`, `#ffffff` | Drawn from the same font families `src/index.css` already loads — anything else would render in the preview but fall back to a default in the export canvas. || `backgroundEnabled`, `backgroundColor`, `backgroundOpacity` | `true`, `#000000`, `0.55` | When off, the text draws straight over the video with no plate. |-| `verticalPosition` | `bottom` | `top` / `middle` / `bottom`. `captionBandRect` anchors the band; `offsetY` nudges it from there. |-| `offsetY` | `0` | Fine nudge in % of **frame** height, on top of the anchor. Positive moves down. |-| `offsetX` | `0` | Fine nudge in % of **frame** width. Positive moves toward the right edge of the exported frame — frame geometry, so an RTL interface locale never mirrors it. |-| `width` | `80` | Band width in % of frame width. |-| `minWordsPerLine` / `maxWordsPerLine` | `2` / `7` | Line-group bounds; `groupTimedCaptionWordsIntoLines` packs inside the range, `[1, 12]` after clamp. |+| `anchorV` | `bottom` | `bottom` / `top` — which frame edge the drawn block is pinned to. It grows AWAY from that edge, so the edge never moves. |+| `insetY` | `5` (12.5 on a vertical export) | Distance from the edge named by `anchorV` to the near edge of what is DRAWN, in % of frame height. Always ≥ 0. |+| `anchorH` | `center` | `left` / `center` / `right` — which edge of the block is pinned horizontally, and the ragged edge when the text wraps. |+| `insetX` | the column's own margin | Distance from the edge named by `anchorH`. Ignored when `anchorH` is `center`, which has no edge to measure from. |+| `minWordsPerLine` / `maxWordsPerLine` | `2` / `7` | Line-group bounds; `groupTimedCaptionWordsIntoLines` packs inside the range, `[1, 12]` after clamp. Also the only control over how much text is on screen — there is no width slider. |#### Coordinate space@@ -558,45 +558,83 @@ The **font denominator follows the same box.** Flipping the rect without thedenominator would hold a caption still while its glyphs kept shrinking with thepadding slider, which is why both come off one `anchor` local in each backend.-#### Reach+#### Anchoring-`CAPTION_BAND_HEIGHT_PCT = 22`+**A caption is placed by pinning one edge of the drawn block, never by centring it+in a box.** `captionBoxRect`([`src/lib/ai-edition/captions/settings.ts`](../../src/lib/ai-edition/captions/settings.ts))-is generous enough for two wrapped lines at the default size — the-renderers clip to it, so it is deliberately not tight.--The band is a **box**; the visible caption is a strip centred inside it. All three-rasterizers centre the text vertically, so a box stopped flush against the frame-edge leaves its glyphs half a band short of it. `captionOffsetRange` therefore-lets the box hang off the top or bottom by exactly its empty margin — the ink-reaches the edge, and nothing drawn leaves the frame. The size of that margin is-derived from `fontSize`, because the slice of the band that carries ink is: a-200px caption fills the whole band, gets no overhang, and stays whole.--`captionOffsetRange` is also what the inspector's sliders take their bounds from,-so the reachable span and the slider span are the same span. Before #396 both-ends were hardcoded to ±45 while the result was clamped separately, which left-the bottom anchor honouring only −45…+3 — nearly half the slider moved the handle-and nothing else.--#### Position presets--`verticalPosition` and `offsetX`/`offsetY` are independent fields — a preset is-not a separate mode the offsets are locked out of, it's just a point on the same-range the slider already covers. `activeVerticalPositionPreset` /-`activeHorizontalPositionPreset` (`settings.ts`, right after `captionOffsetRange`)-read "is a preset active" back out of that: a preset counts as active only while-its axis' offset is (within a small epsilon) exactly the value that preset would-set, so dragging a slider away from a preset silently un-highlights it with no-separate "active preset" field to keep in sync. Clicking a preset writes that-clean value back (`offsetY: 0` for a vertical preset; `captionHorizontalPositionOffset`-for a horizontal one) rather than leaving whatever nudge was already there, which-is what makes the click read as "go here" instead of "go here, plus whatever was-left over." `CaptionHorizontalPosition` (left/center/right) is a new axis of-meaning distinct from `CaptionTextAlign` (same three words, but for aligning the-text *inside* the band) — there is no stored `horizontalPosition` field; it is-derived from `offsetX` exactly the way the vertical preset is derived from-`offsetY`.+returns the box plus a `verticalAlign`, and the compositor puts the block flush+against that edge of it. The invariant, which the tests assert as a property:++> Bottom anchor: the drawn block's bottom edge is at `100 − insetY` % of frame+> height. Top anchor: its top edge is at `insetY` %. For every font size, every+> background state, every word count, every wrap outcome, every output resolution.++No estimate of the block's height participates in placing it. The box's height is+**headroom** — how many lines can be drawn before the renderer clips — so being+wrong about it costs a clipped fourth line, not a moved subtitle.++That distinction is the whole of the redesign. The model this replaced put the+caption in a fixed 22 % box and let all three rasterizers centre the ink inside it.+A centred block moves BOTH its edges as it grows, so:++- wrapping to another line shifted the caption vertically, and so did anything that+ changed wrapping — which is how the *width* slider ended up moving the caption on+ the *vertical* axis;+- the box had to be allowed to hang off the frame by its own empty margin for the+ glyphs to reach the edge at all, and that margin was derived from `fontSize`;+- the offset therefore had to be signed and clamped against a reachable range that+ moved with four other fields, which is why the inspector could show `-7.3 %` —+ a number that corresponds to nothing in any subtitle format.++All of that is deleted. An inset is a distance from a named edge, so it means the+same thing whatever else changes, and `patchCaptionSettings` has no re-clamping+pass any more.++Bottom-anchored growth is not an invention here: it is the default in every+subtitle format. `tts:displayAlign="after"` (TTML/IMSC, which the BBC requires on+every region), `\an2` with `MarginV` measured from the bottom (ASS), `line:auto`+resolving to −1 and pushing the box upward (WebVTT), roll-up scrolling (CEA-708).+Deliberately absent: a "middle" anchor. XSL 1.1 defines `display-align: center` as+keeping both edge distances equal — which is precisely the pathology above — and a+bottom anchor with a large `insetY` reaches the same place while still growing+upward.++#### The column, and why there is no width control++`captionSafeColumn` derives the wrap width from the output aspect — 68 % of a 16:9+frame, 90 % of a squarer or vertical one (the BBC line-length table; 68 % at 48 px+on 1080p is ≈45 characters, inside the Netflix 42 / BBC 37 band). It is never+stored and never exposed.++It used to be a `width` slider, and that control could not be understood: the+background plate hugs the TEXT, not the box, so moving it changed nothing visible+until the text happened to be long enough to wrap. What it actually controlled is+how much text is on screen — a question `minWordsPerLine` / `maxWordsPerLine`+already answers in words rather than in percent.++The horizontal axis has one control, `anchorH`, which reaches the rasterizers as+the existing `textAlign`. That is not a coincidence: their plate maths already+snaps the plate onto the box's left or right edge (`text_linux.rs`'s `plate_x`,+and its two mirrors), so the alignment *is* the pivot. The model before this had+two controls fighting over that one outcome — `offsetX` moved an invisible band and+`textAlign` moved the text inside it — and neither could be read without seeing the+band.++#### The guide overlay++`CaptionGuideOverlay`+([`src/components/ai-edition/CaptionGuideOverlay.tsx`](../../src/components/ai-edition/CaptionGuideOverlay.tsx))+draws the anchor line and the column's edges over the preview while the Captions+pane is open, signalled by `useCaptionGuideBus`. It mounts as a child of+`.previewFrame` and **not** of `.screenStage`: the latter is the screen rect, which+shrinks with the padding slider, so a guide mounted there would reproduce #396+inside the guide meant to explain it.++This does not revive the deleted DOM caption painter described below. That one drew+the same *text* through a second wrapping engine and the two disagreed on line+breaks; a rule and two hairlines have no glyphs to disagree about, and a `<div>` has+no route into `buildSceneDescription`, so it cannot reach an export.The Captions pane itself([`src/components/ai-edition/CaptionsPane.tsx`](../../src/components/ai-edition/CaptionsPane.tsx))