Skip to content

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

feat(annotations): place annotations anywhere on the frame, boxes that fit the text

EtienneLescotf77e8ce4811d
diff --git a/src/components/ai-edition/AnnotationLayer.test.tsx b/src/components/ai-edition/AnnotationLayer.test.tsx
new file mode 100644
index 000000000..9f2ea890c
--- /dev/null
+++ b/src/components/ai-edition/AnnotationLayer.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+import { render } from "@testing-library/react";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+import { AnnotationLayer } from "./AnnotationLayer";
+
+// react-rnd reads its offset in the parent off `getBoundingClientRect` on mount, and jsdom lays
+// nothing out: every rect is at 0, the offset comes out as minus the position, and the box is
+// drawn at twice its place. Placing each element where its translate puts it is all the layout
+// these boxes need.
+beforeAll(() => {
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (
+ this: HTMLElement,
+ ) {
+ const shift = /translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/.exec(this.style.transform);
+ const [x, y] = shift ? [Number(shift[1]), Number(shift[2])] : [0, 0];
+ return DOMRect.fromRect({ x, y, width: 0, height: 0 });
+ });
+});
+afterAll(() => vi.restoreAllMocks());
+
+function region(overrides: Partial<AxcutAnnotationRegion>): AxcutAnnotationRegion {
+ return {
+ id: "a",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "Hi",
+ position: { x: 10, y: 20 },
+ size: { width: 30, height: 40 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ },
+ zIndex: 1,
+ ...overrides,
+ };
+}
+
+// A 1000×500 frame, the footage padded in to 800×400 at (100, 50).
+const FOOTAGE = { x: 100, y: 50, width: 800, height: 400 };
+
+function layer(annotations: AxcutAnnotationRegion[]) {
+ const view = render(
+ <AnnotationLayer
+ annotations={annotations}
+ selectedAnnotationId={null}
+ currentTimeSec={0.5}
+ frameWidth={1000}
+ frameHeight={500}
+ footage={FOOTAGE}
+ onSelectAnnotation={vi.fn()}
+ onChange={vi.fn()}
+ onCommit={vi.fn()}
+ />,
+ );
+ const frame = view.container.firstElementChild as HTMLElement;
+ const boxes = [...view.container.querySelectorAll<HTMLElement>(".react-draggable")];
+ return { frame, boxes };
+}
+
+describe("AnnotationLayer", () => {
+ it("places an annotation on the frame, free of the footage", () => {
+ const { frame, boxes } = layer([region({ space: "frame" })]);
+ // Its box moves in the frame itself, so it can go over the padding.
+ expect(boxes[0].parentElement).toBe(frame);
+ expect(boxes[0].style.transform).toBe("translate(100px,100px)");
+ expect(boxes[0].style.width).toBe("300px");
+ });
+
+ it("reads an annotation saved on the footage from the footage, but lets it roam the frame", () => {
+ const { frame, boxes } = layer([region({})]);
+ expect(boxes[0].parentElement).toBe(frame);
+ // 100 + 10 % of 800, 50 + 20 % of 400: where it has always been drawn.
+ expect(boxes[0].style.transform).toBe("translate(180px,130px)");
+ expect(boxes[0].style.width).toBe("240px");
+ });
+
+ it("keeps a blur inside the footage it hides", () => {
+ const { frame, boxes } = layer([region({ type: "blur", content: "" })]);
+ const container = boxes[0].parentElement as HTMLElement;
+ expect(container).not.toBe(frame);
+ expect(container.style.left).toBe("100px");
+ expect(container.style.width).toBe("800px");
+ expect(boxes[0].style.transform).toBe("translate(80px,80px)");
+ });
+});
diff --git a/src/components/ai-edition/AnnotationLayer.tsx b/src/components/ai-edition/AnnotationLayer.tsx
index c79ed460b..7020d7967 100644
--- a/src/components/ai-edition/AnnotationLayer.tsx
+++ b/src/components/ai-edition/AnnotationLayer.tsx
@@ -4,19 +4,27 @@
// editor's schema keeps all annotation types (including blur) in one
// `document.annotations[]` array, so this uses a single filtered+sorted
// list and a single selection id instead.
+//
+// The layer covers the whole preview frame: text, images and arrows are placed on the frame
+// and move anywhere in it, padding included. A privacy blur stays on the footage, so its boxes
+// live in a child sized to the footage rect and cannot leave it (see
+// `lib/ai-edition/annotations/placement.ts`).
+import { belongsInFrame, fitTextBox, toFrameSpace } from "@/lib/ai-edition/annotations/placement";
import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
-import { AnnotationOverlay } from "./AnnotationOverlay";
+import { AnnotationOverlay, type PxRect } from "./AnnotationOverlay";
interface AnnotationLayerProps {
annotations: AxcutAnnotationRegion[];
selectedAnnotationId: string | null;
currentTimeSec: number;
- containerWidth: number;
- containerHeight: number;
+ /** The preview frame, px. */
+ frameWidth: number;
+ frameHeight: number;
+ /** The footage rect inside the frame, px (`layout.screenRect`). */
+ footage: PxRect;
onSelectAnnotation: (id: string) => void;
- onPositionChange: (id: string, position: { x: number; y: number }) => void;
- onSizeChange: (id: string, size: { width: number; height: number }) => void;
+ onChange: (id: string, patch: Partial<AxcutAnnotationRegion>) => void;
onCommit: () => void;
}
@@ -24,11 +32,11 @@ export function AnnotationLayer({
annotations,
selectedAnnotationId,
currentTimeSec,
- containerWidth,
- containerHeight,
+ frameWidth,
+ frameHeight,
+ footage,
onSelectAnnotation,
- onPositionChange,
- onSizeChange,
+ onChange,
onCommit,
}: AnnotationLayerProps) {
const currentTimeMs = Math.round(currentTimeSec * 1000);
@@ -53,28 +61,63 @@ export function AnnotationLayer({
}
};
- if (containerWidth <= 0 || containerHeight <= 0) return null;
+ if (frameWidth <= 0 || frameHeight <= 0 || footage.width <= 0 || footage.height <= 0) {
+ return null;
+ }
+
+ const frameBox: PxRect = { x: 0, y: 0, width: frameWidth, height: frameHeight };
+ const footageBox: PxRect = { x: 0, y: 0, width: footage.width, height: footage.height };
+ // The footage as fractions of the frame: the form the conversions in `placement.ts` take.
+ const footageInFrame = {
+ x: footage.x / frameWidth,
+ y: footage.y / frameHeight,
+ width: footage.width / frameWidth,
+ height: footage.height / frameHeight,
+ };
+ const fitText = (region: AxcutAnnotationRegion) => fitTextBox(region, frameWidth / frameHeight);
+
+ const overlay = (annotation: AxcutAnnotationRegion, inFrame: boolean) => {
+ const width = inFrame ? frameWidth : footage.width;
+ const height = inFrame ? frameHeight : footage.height;
+ return (
+ <AnnotationOverlay
+ // La clé ne porte plus les champs de `blurData` : ils forçaient un remontage à
+ // chaque réglage du flou, pour resynchroniser un canvas de mosaïque qui n'existe
+ // plus. La taille du conteneur y reste, elle, parce qu'elle change le rect en px.
+ key={`${annotation.id}-${width}-${height}`}
+ annotation={annotation}
+ isSelected={annotation.id === selectedAnnotationId}
+ containerWidth={width}
+ containerHeight={height}
+ // Still on the footage but moving in the frame: its stored rect reads from there
+ // until its first gesture moves it into the frame.
+ box={!inFrame ? footageBox : annotation.space === "frame" ? frameBox : footage}
+ toFrame={inFrame ? toFrameSpace(annotation, footageInFrame) : null}
+ fitText={annotation.type === "text" ? fitText : undefined}
+ onChange={onChange}
+ onCommit={onCommit}
+ onClick={handleClick}
+ zIndex={annotation.zIndex}
+ isSelectedBoost={annotation.id === selectedAnnotationId}
+ />
+ );
+ };
return (
<div className="absolute inset-0" style={{ pointerEvents: "none" }}>
- {visible.map((annotation) => (
- <AnnotationOverlay
- // La clé ne porte plus les champs de `blurData` : ils forçaient un remontage à
- // chaque réglage du flou, pour resynchroniser un canvas de mosaïque qui n'existe
- // plus. La taille du conteneur y reste, elle, parce qu'elle change le rect en px.
- key={`${annotation.id}-${containerWidth}-${containerHeight}`}
- annotation={annotation}
- isSelected={annotation.id === selectedAnnotationId}
- containerWidth={containerWidth}
- containerHeight={containerHeight}
- onPositionChange={onPositionChange}
- onSizeChange={onSizeChange}
- onCommit={onCommit}
- onClick={handleClick}
- zIndex={annotation.zIndex}
- isSelectedBoost={annotation.id === selectedAnnotationId}
- />
- ))}
+ {visible.filter((a) => belongsInFrame(a.type)).map((a) => overlay(a, true))}
+ <div
+ style={{
+ position: "absolute",
+ left: footage.x,
+ top: footage.y,
+ width: footage.width,
+ height: footage.height,
+ pointerEvents: "none",
+ }}
+ >
+ {visible.filter((a) => !belongsInFrame(a.type)).map((a) => overlay(a, false))}
+ </div>
</div>
);
}
diff --git a/src/components/ai-edition/AnnotationOverlay.tsx b/src/components/ai-edition/AnnotationOverlay.tsx
index 81f8c2592..356a740fe 100644
--- a/src/components/ai-edition/AnnotationOverlay.tsx
+++ b/src/components/ai-edition/AnnotationOverlay.tsx
@@ -12,15 +12,34 @@
import { useEffect, useRef, useState } from "react";
import { Rnd } from "react-rnd";
import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+import { clampToBound } from "@/lib/projectDefaults";
import { cn } from "@/lib/utils";
+type Region = AxcutAnnotationRegion;
+
+export interface PxRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
interface AnnotationOverlayProps {
- annotation: AxcutAnnotationRegion;
+ annotation: Region;
isSelected: boolean;
+ /** Taille, en px, de l'élément où la boîte se déplace : le cadre, ou le footage pour un flou.
+ * Chaque écriture est un pourcentage de cet élément. */
containerWidth: number;
containerHeight: number;
- onPositionChange: (id: string, position: { x: number; y: number }) => void;
- onSizeChange: (id: string, size: { width: number; height: number }) => void;
+ /** D'où se lit le rect enregistré, en px dans cet élément : l'élément lui-même, ou le rect du
+ * footage pour une annotation encore rangée sur lui mais qui se déplace dans le cadre. */
+ box: PxRect;
+ /** Le patch qui range l'annotation dans le cadre, appliqué avant son premier geste ; `null`
+ * quand elle y est déjà (ou qu'elle n'en sort jamais, comme un flou). */
+ toFrame: Partial<Region> | null;
+ /** Texte seulement : la boîte taillée sur le texte, centre conservé. */
+ fitText?: (region: Region) => Pick<Region, "position" | "size">;
+ onChange: (id: string, patch: Partial<Region>) => void;
/** Écriture disque, appelée une fois en fin de geste — le drag/resize ne fait que du live. */
onCommit?: () => void;
onClick: (id: string) => void;
@@ -28,24 +47,44 @@ interface AnnotationOverlayProps {
isSelectedBoost: boolean;
}
+const CORNERS_ONLY = {
+ top: false,
+ right: false,
+ bottom: false,
+ left: false,
+ topLeft: true,
+ topRight: true,
+ bottomLeft: true,
+ bottomRight: true,
+} as const;
+
export function AnnotationOverlay({
annotation,
isSelected,
containerWidth,
containerHeight,
- onPositionChange,
- onSizeChange,
+ box,
+ toFrame,
+ fitText,
+ onChange,
onCommit,
onClick,
zIndex,
isSelectedBoost,
}: AnnotationOverlayProps) {
- const committedX = (annotation.position.x / 100) * containerWidth;
- const committedY = (annotation.position.y / 100) * containerHeight;
- const committedWidth = (annotation.size.width / 100) * containerWidth;
- const committedHeight = (annotation.size.height / 100) * containerHeight;
+ const committedX = box.x + (annotation.position.x / 100) * box.width;
+ const committedY = box.y + (annotation.position.y / 100) * box.height;
+ const committedWidth = (annotation.size.width / 100) * box.width;
+ const committedHeight = (annotation.size.height / 100) * box.height;
const blurShape = annotation.type === "blur" ? (annotation.blurData?.shape ?? "rectangle") : null;
+ const isText = annotation.type === "text";
const isDraggingRef = useRef(false);
+ // Le geste en cours a-t-il bougé quelque chose ? Un clic sur une annotation sélectionnée passe
+ // aussi par le début et la fin d'un glissement : sans mouvement, il n'écrit rien.
+ const movedRef = useRef(false);
+ // Taille de police et hauteur de boîte au début d'un redimensionnement de texte : les poignées
+ // d'un texte agrandissent ses lettres, dans le rapport de la hauteur tirée à la hauteur de départ.
+ const resizeStartRef = useRef<{ fontSize: number; height: number } | null>(null);
const [liveRect, setLiveRect] = useState({
x: committedX,
y: committedY,
@@ -64,70 +103,107 @@ export function AnnotationOverlay({
const { x, y, width, height } = liveRect;
+ /** Un rect en px de l'élément, en pourcentages de lui : ce que le document range. */
+ const toPct = (rect: PxRect): Pick<Region, "position" | "size"> => ({
+ position: { x: (rect.x / containerWidth) * 100, y: (rect.y / containerHeight) * 100 },
+ size: {
+ width: (rect.width / containerWidth) * 100,
+ height: (rect.height / containerHeight) * 100,
+ },
+ });
+
+ // Une annotation encore sur le footage passe dans le cadre à son premier mouvement, au pixel
+ // près : les écritures qui suivent sont des pourcentages du cadre.
+ const firstMove = () => {
+ if (movedRef.current) return;
+ movedRef.current = true;
+ if (toFrame) onChange(annotation.id, toFrame);
+ };
+
+ /** La taille de police qu'une hauteur de boîte tirée donne à un texte ; rien pour les autres. */
+ const scaledText = (nextHeight: number): Partial<Region> => {
+ const start = resizeStartRef.current;
+ if (!isText || !start) return {};
+ const fontSize = Math.round(
+ clampToBound((start.fontSize * nextHeight) / start.height, "annotationFontSize"),
+ );
+ return { style: { ...(toFrame?.style ?? annotation.style), fontSize } };
+ };
+
+ // Un texte finit chaque geste taillé sur ses mots, au cas où sa boîte ne l'était pas encore
+ // (une annotation d'avant, ou une poignée lâchée entre deux tailles).
+ const settle = (patch: Partial<Region>) => {
+ const next = { ...annotation, ...toFrame, ...patch } as Region;
+ onChange(annotation.id, isText && fitText ? { ...patch, ...fitText(next) } : patch);
+ onCommit?.();
+ };
+
return (
<Rnd
position={{ x, y }}
size={{ width, height }}
onDragStart={() => {
isDraggingRef.current = true;
+ movedRef.current = false;
}}
onDrag={(_e, d) => {
+ firstMove();
setLiveRect((prev) => ({ ...prev, x: d.x, y: d.y }));
// Pousse la position PENDANT le geste : c'est le natif qui peint, il doit donc suivre
- // le curseur. `onPositionChange` ne met à jour qu'en mémoire ; l'écriture disque se
- // fait une seule fois, au relâchement (`onCommit`).
- onPositionChange(annotation.id, {
- x: (d.x / containerWidth) * 100,
- y: (d.y / containerHeight) * 100,
+ // le curseur. `onChange` ne met à jour qu'en mémoire ; l'écriture disque se fait une
+ // seule fois, au relâchement (`onCommit`).
+ onChange(annotation.id, {
+ position: toPct({ x: d.x, y: d.y, width, height }).position,
});
}}
onDragStop={(_e, d) => {
- setLiveRect((prev) => ({ ...prev, x: d.x, y: d.y }));
- const xPercent = (d.x / containerWidth) * 100;
- const yPercent = (d.y / containerHeight) * 100;
- onPositionChange(annotation.id, { x: xPercent, y: yPercent });
- onCommit?.();
+ if (movedRef.current) {
+ setLiveRect((prev) => ({ ...prev, x: d.x, y: d.y }));
+ settle({ position: toPct({ x: d.x, y: d.y, width, height }).position });
+ }
+ movedRef.current = false;
setTimeout(() => {
isDraggingRef.current = false;
}, 100);
}}
+ onResizeStart={() => {
+ movedRef.current = false;
+ const fontSize = (toFrame?.style ?? annotation.style).fontSize;
+ resizeStartRef.current = { fontSize, height: Math.max(1, height) };
+ }}
onResize={(_e, _direction, ref, _delta, position) => {
- setLiveRect({
+ const rect = {
x: position.x,
y: position.y,
width: ref.offsetWidth,
height: ref.offsetHeight,
- });
+ };
+ firstMove();
+ setLiveRect(rect);
// Même raison que le drag : le natif doit suivre la poignée en direct.
- onPositionChange(annotation.id, {
- x: (position.x / containerWidth) * 100,
- y: (position.y / containerHeight) * 100,
- });
- onSizeChange(annotation.id, {
- width: (ref.offsetWidth / containerWidth) * 100,
- height: (ref.offsetHeight / containerHeight) * 100,
- });
+ onChange(annotation.id, { ...toPct(rect), ...scaledText(rect.height) });
}}
onResizeStop={(_e, _direction, ref, _delta, position) => {
- setLiveRect({
+ const rect = {
x: position.x,
y: position.y,
width: ref.offsetWidth,
height: ref.offsetHeight,
- });
- const xPercent = (position.x / containerWidth) * 100;
- const yPercent = (position.y / containerHeight) * 100;
- const widthPercent = (ref.offsetWidth / containerWidth) * 100;
- const heightPercent = (ref.offsetHeight / containerHeight) * 100;
- onPositionChange(annotation.id, { x: xPercent, y: yPercent });
- onSizeChange(annotation.id, { width: widthPercent, height: heightPercent });
- onCommit?.();
+ };
+ if (movedRef.current) {
+ setLiveRect(rect);
+ settle({ ...toPct(rect), ...scaledText(rect.height) });
+ }
+ movedRef.current = false;
+ resizeStartRef.current = null;
}}
onClick={() => {
if (isDraggingRef.current) return;
onClick(annotation.id);
}}
bounds="parent"
+ // Un texte garde sa forme : sa boîte est celle de ses mots, seule la taille change.
+ lockAspectRatio={isText}
className={cn(
"cursor-move",
isSelected &&
@@ -146,8 +222,8 @@ export function AnnotationOverlay({
}}
// Un flou en tracé libre se déplace et se redimensionne comme les autres : ce qui le
// bloquait, c'était la zone de saisie du tracé qui capturait le pointeur — et elle est
- // partie avec l'outil.
- enableResizing={isSelected}
+ // partie avec l'outil. Un texte ne se tire que par ses coins, qui agrandissent ses lettres.
+ enableResizing={isSelected ? (isText ? CORNERS_ONLY : true) : false}
disableDragging={!isSelected}
resizeHandleStyles={{
topLeft: {
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 7caf59975..d9273e77c 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -1625,15 +1625,10 @@ export function NewEditorShell() {
tl.selection?.kind === "annotation" ? tl.selection.id : null
}
onSelectAnnotation={(id) => tl.selectRegion("annotation", id)}
- onAnnotationPositionChange={(id, position) => {
- // Live seulement : appelé à chaque mouvement de souris pour que le
- // compositeur natif suive le geste. L'écriture disque se fait une fois,
- // au relâchement, via `onAnnotationCommit`.
- tl.updateAnnotationLive(id, { position });
- }}
- onAnnotationSizeChange={(id, size) => {
- tl.updateAnnotationLive(id, { size });
- }}
+ // Live seulement : appelé à chaque mouvement de souris pour que le
+ // compositeur natif suive le geste. L'écriture disque se fait une fois,
+ // au relâchement, via `onAnnotationCommit`.
+ onAnnotationChange={tl.updateAnnotationLive}
onAnnotationBlurDataChange={(id, blurData) =>
tl.updateAnnotationLive(id, { blurData })
}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index a55efe4dd..f4ad0a5c5 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -46,8 +46,7 @@ interface PreviewProps {
annotationRegions?: AxcutAnnotationRegion[];
selectedAnnotationId?: string | null;
onSelectAnnotation?: (id: string) => void;
- onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;
- onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;
+ onAnnotationChange?: (id: string, patch: Partial<AxcutAnnotationRegion>) => void;
onAnnotationBlurDataChange?: (id: string, blurData: BlurData) => void;
onAnnotationCommit?: () => void;
seekTarget: { timeSec: number; requestId: number } | null;
@@ -82,8 +81,7 @@ export function Preview({
annotationRegions,
selectedAnnotationId,
onSelectAnnotation,
- onAnnotationPositionChange,
- onAnnotationSizeChange,
+ onAnnotationChange,
onAnnotationBlurDataChange,
onAnnotationCommit,
seekTarget,
@@ -226,8 +224,7 @@ export function Preview({
annotationRegions={annotationRegions}
selectedAnnotationId={selectedAnnotationId}
onSelectAnnotation={onSelectAnnotation}
- onAnnotationPositionChange={onAnnotationPositionChange}
- onAnnotationSizeChange={onAnnotationSizeChange}
+ onAnnotationChange={onAnnotationChange}
onAnnotationBlurDataChange={onAnnotationBlurDataChange}
onAnnotationCommit={onAnnotationCommit}
seekTarget={seekTarget}
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index f9ca4e1e8..04e150991 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -9,12 +9,14 @@
// the actual pixels come from the native canvas, not from this layout):
// .previewFrame → canvas (wallpaper bg; never receives padding
// from the slider directly).
-// .screenStage → sizes/positions the zoom/annotation overlays by
-// the composite-layout math (PiP/dual/stack/no-cam);
+// .screenStage → sizes/positions the zoom overlay by the
+// composite-layout math (PiP/dual/stack/no-cam);
// its own <video> is CSS-hidden (decode/clock only).
// .webcamSlot → drag-to-reposition hitbox for the webcam PiP,
// positioned by the same math; its <video> is
// CSS-hidden too.
+// AnnotationLayer → the whole frame: annotations are placed on it,
+// a blur on the footage rect inside it.
//
// The composite layout is computed from `.previewFrame`'s actual rendered
// size (via ResizeObserver), so the camera + screen both resize correctly
@@ -88,8 +90,8 @@ interface PreviewCanvasProps {
annotationRegions?: AxcutAnnotationRegion[];
selectedAnnotationId?: string | null;
onSelectAnnotation?: (id: string) => void;
- onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;
- onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;
+ /** Live edit of an annotation's geometry (and, for a text, its size) during a gesture. */
+ onAnnotationChange?: (id: string, patch: Partial<AxcutAnnotationRegion>) => void;
onAnnotationBlurDataChange?: (id: string, blurData: BlurData) => void;
onAnnotationCommit?: () => void;
seekTarget: { timeSec: number; requestId: number } | null;
@@ -460,23 +462,6 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
onFocusCommit={props.onZoomFocusCommit}
/>
) : null}
- {props.annotationRegions &&
- props.onSelectAnnotation &&
- props.onAnnotationPositionChange &&
- props.onAnnotationSizeChange &&
- props.onAnnotationCommit ? (
- <AnnotationLayer
- annotations={props.annotationRegions}
- selectedAnnotationId={props.selectedAnnotationId ?? null}
- currentTimeSec={props.currentTimeSec}
- containerWidth={layout.screenRect.width}
- containerHeight={layout.screenRect.height}
- onSelectAnnotation={props.onSelectAnnotation}
- onPositionChange={props.onAnnotationPositionChange}
- onSizeChange={props.onAnnotationSizeChange}
- onCommit={props.onAnnotationCommit}
- />
- ) : null}
</div>
) : null}
{layout?.webcamRect && showWebcamSlot ? (
@@ -505,14 +490,33 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
/>
</div>
) : null}
+ {/* Last, so a selected annotation over the camera takes the pointer before the
+ camera's drag hitbox does. It spans the frame: text, images and arrows move
+ anywhere in it, over the padding too. */}
+ {layout?.screenRect &&
+ props.annotationRegions &&
+ props.onSelectAnnotation &&
+ props.onAnnotationChange &&
+ props.onAnnotationCommit ? (
+ <AnnotationLayer
+ annotations={props.annotationRegions}
+ selectedAnnotationId={props.selectedAnnotationId ?? null}
+ currentTimeSec={props.currentTimeSec}
+ frameWidth={frameSize.width}
+ frameHeight={frameSize.height}
+ footage={layout.screenRect}
+ onSelectAnnotation={props.onSelectAnnotation}
+ onChange={props.onAnnotationChange}
+ onCommit={props.onAnnotationCommit}
+ />
+ ) : null}
</div>
);
}
// Screen stage: rectangle from the composite layout, converted to percentages
-// of the canvas. Positions/sizes the interactive overlays (ZoomFocusOverlay,
-// AnnotationLayer) hosted inside it and the CSS-hidden <video> (decode/clock
-// only) — no borderRadius/boxShadow here: the native canvas already draws its
+// of the canvas. Positions/sizes the zoom overlay hosted inside it and the
+// CSS-hidden <video> (decode/clock only) — no borderRadius/boxShadow here: the native canvas already draws its
// own rounded corners + shadow for this exact rect, and this container sits
// on TOP of it (z-index for the interactive layers). Duplicating the same
// decoration in CSS produced a visible "double rounded corner" — two
diff --git a/src/components/ai-edition/v4/FloatingInspector.test.tsx b/src/components/ai-edition/v4/FloatingInspector.test.tsx
index 04b3f054c..5eb43d45f 100644
--- a/src/components/ai-edition/v4/FloatingInspector.test.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.test.tsx
@@ -68,7 +68,7 @@ vi.mock("../CaptionsPane", () => ({
CaptionsPane: () => <div data-testid="captions-pane">CaptionsPane</div>,
}));
-import { AnnotationSizeField, FloatingInspector } from "./FloatingInspector";
+import { AnnotationSizeControl, AnnotationSizeField, FloatingInspector } from "./FloatingInspector";
describe("FloatingInspector", () => {
const defaultProps: React.ComponentProps<typeof FloatingInspector> = {
@@ -173,6 +173,65 @@ describe("FloatingInspector", () => {
});
});
+ describe("annotation pane", () => {
+ const text = {
+ id: "a",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "Hi",
+ space: "frame",
+ position: { x: 45, y: 45 },
+ size: { width: 10, height: 10 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ },
+ zIndex: 1,
+ };
+ const annotationTl = () => {
+ const updateAnnotationLive = vi.fn();
+ const tl = {
+ ...defaultProps.tl,
+ selection: { kind: "annotation", id: "a" },
+ annotationRegions: [text],
+ updateAnnotationLive,
+ commitAnnotationChange: vi.fn(),
+ } as unknown as React.ComponentProps<typeof FloatingInspector>["tl"];
+ return { tl, updateAnnotationLive };
+ };
+ const centreOf = (patch: { position: { x: number }; size: { width: number } }) =>
+ patch.position.x + patch.size.width / 2;
+
+ it("refits the box to the words as they are typed, around the same centre", () => {
+ const { tl, updateAnnotationLive } = annotationTl();
+ render(<FloatingInspector {...defaultProps} tl={tl} />);
+ fireEvent.change(screen.getByPlaceholderText("settings.annotation.textPlaceholder"), {
+ target: { value: "A much longer line" },
+ });
+ const patch = updateAnnotationLive.mock.calls[0][1];
+ expect(patch.content).toBe("A much longer line");
+ expect(patch.size.width).toBeGreaterThan(text.size.width);
+ expect(centreOf(patch)).toBeCloseTo(50, 6);
+ });
+
+ it("resizes the text from the preset row and refits its box", () => {
+ const { tl, updateAnnotationLive } = annotationTl();
+ render(<FloatingInspector {...defaultProps} tl={tl} />);
+ const row = screen.getByRole("group", { name: "settings.annotation.size" });
+ fireEvent.click(within(row).getByRole("button", { name: "72" }));
+ const patch = updateAnnotationLive.mock.calls[0][1];
+ expect(patch.style.fontSize).toBe(72);
+ expect(centreOf(patch)).toBeCloseTo(50, 6);
+ });
+ });
+
describe("zoom pane rows", () => {
const zoomTl = (region: Record<string, unknown>) => {
const updateZoomRotation = vi.fn();
@@ -315,3 +374,29 @@ describe("AnnotationSizeField", () => {
expect(commitTyped("900")).toHaveBeenCalledWith(200);
});
});
+
+describe("AnnotationSizeControl", () => {
+ const row = () => screen.getByRole("group", { name: "settings.annotation.size" });
+
+ it("presses the preset the size is, and picks another in one click", () => {
+ const onChange = vi.fn();
+ render(<AnnotationSizeControl size={32} onChange={onChange} />);
+ expect(within(row()).getByRole("button", { name: "32" })).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ fireEvent.click(within(row()).getByRole("button", { name: "48" }));
+ expect(onChange).toHaveBeenCalledWith(48);
+ });
+
+ it("shows a size off the row in its free field, pressing no preset", () => {
+ render(<AnnotationSizeControl size={40} onChange={vi.fn()} />);
+ for (const button of within(row()).getAllByRole("button")) {
+ expect(button).toHaveAttribute("aria-pressed", "false");
+ }
+ expect(screen.getByRole("textbox", { name: "settings.annotation.customSize" })).toHaveAttribute(
+ "placeholder",
+ "40",
+ );
+ });
+});
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index d605e82c4..9e93869b1 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -42,10 +42,16 @@ import {
} from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import { setTextPlate, type TextPlate, textPlateOf } from "@/lib/ai-edition/annotations/background";
+import {
+ convertAnnotationKind,
+ fitTextBox,
+ toFrameSpace,
+} from "@/lib/ai-edition/annotations/placement";
import {
type AnnotationTextAnimation,
TEXT_ANIMATION_VALUES,
} from "@/lib/ai-edition/annotations/textAnimation";
+import { resolveAspectRatioValue } from "@/lib/ai-edition/document/outputFormat";
import type { AxcutAnnotationRegion, AxcutClip } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { rafCoalesce } from "@/lib/ai-edition/store/rafCoalesce";
@@ -54,7 +60,7 @@ import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { formatSeconds } from "@/lib/ai-edition/timeline/format";
import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
import { clampToBound } from "@/lib/projectDefaults";
-import { zoomScaleLimit } from "@/native/sceneDescription";
+import { annotationFootageRect, zoomScaleLimit } from "@/native/sceneDescription";
import { ColorField } from "../ColorField";
import shell from "../NewEditorShell.module.css";
import {
@@ -390,37 +396,6 @@ const BLUR_DEFAULTS = {
blockSize: 12,
} as const;
-/**
- * Patch à appliquer quand l'utilisateur change le type d'une annotation.
- *
- * `content` est un slot UNIQUE partagé par le texte et l'image : la zone de saisie y écrit, et le
- * rendu d'image y lit une data URL. Changer de type sans déplacer la valeur déversait donc le
- * base64 de l'image, souvent plusieurs mégaoctets, dans le champ texte. Chaque contenu est rangé
- * dans son slot typé (`textContent` / `imageContent`) en sortant et restauré en entrant, si bien
- * qu'un aller-retour entre deux types ne perd rien.
- */
-function convertAnnotationKind(
- region: AxcutAnnotationRegion,
- next: AnnotationKind,
-): Partial<AxcutAnnotationRegion> {
- if (region.type === next) return {};
- const parked: Partial<AxcutAnnotationRegion> =
- region.type === "text"
- ? { textContent: region.content ?? "" }
- : region.type === "image"
- ? { imageContent: region.content ?? "" }
- : {};
- // Flèche et flou n'ont pas de contenu : on vide `content` plutôt que d'y laisser traîner le
- // texte ou le base64 du type précédent.
- const restored =
- next === "text"
- ? (region.textContent ?? "")
- : next === "image"
- ? (region.imageContent ?? "")
- : "";
- return { ...parked, type: next, content: restored };
-}
-
const ZOOM_DEPTHS: readonly ZoomDepth[] = [1, 2, 3, 4, 5, 6];
// The row: the default and one step either side, plus a strong close-up. The two ends of the
@@ -647,10 +622,41 @@ export function SpeedControl({
);
}
+// The sizes a text reaches for, in pixels at 1080 (`annotationScale.ts`): a caption-sized note,
+// the default, a heading and a title. Anything else, down to 8 and up to 200, is typed in the
+// field at the end of the row, the zoom level's pair.
+const TEXT_SIZE_PRESETS = [24, 32, 48, 72];
+
+/** The text size as a row of presets plus a free field, like the zoom level. */
+export function AnnotationSizeControl({
+ size,
+ onChange,
+}: {
+ size: number;
+ onChange: (size: number) => void;
+}) {
+ const ts = useScopedT("settings");
+ // A size outside the row presses no button; the field beside it shows it.
+ return paneStack(
+ ts("annotation.size"),
+ <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <ChoiceRow<number>
+ label={ts("annotation.size")}
+ options={TEXT_SIZE_PRESETS.map((value) => ({ value, label: String(value) }))}
+ value={size}
+ onChange={onChange}
+ />
+ </div>
+ <AnnotationSizeField label={ts("annotation.customSize")} size={size} onCommit={onChange} />
+ </div>,
+ );
+}
+
/**
- * The text size as a free field, committed on blur like the speed and zoom fields above it and
- * read into `SETTING_BOUNDS.annotationFontSize`. It used to write every keystroke as typed, so an
- * emptied field stored a size of 0 and the text vanished.
+ * The text size as a free field, committed on blur like the speed and zoom fields and read into
+ * `SETTING_BOUNDS.annotationFontSize`. It used to write every keystroke as typed, so an emptied
+ * field stored a size of 0 and the text vanished.
*/
export function AnnotationSizeField({
label,
@@ -703,7 +709,7 @@ export function AnnotationSizeField({
if (e.key === "Enter") e.currentTarget.blur();
}}
className={shell.control}
- style={{ width: 84, textAlign: "right" }}
+ style={{ width: 56, textAlign: "right" }}
/>
);
}
@@ -745,6 +751,31 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
liveUpdate.flush();
void tl.commitAnnotationChange();
};
+ // Largeur sur hauteur du cadre de sortie : ce sur quoi une boîte de texte est taillée.
+ const frameAspect = useMemo(
+ () => (doc ? resolveAspectRatioValue(doc, settings.aspectRatio) : 16 / 9),
+ [doc, settings.aspectRatio],
+ );
+ /** Le footage sous l'annotation, lu au moment du geste : la scène entière le calcule. */
+ const footageOf = (id: string) => {
+ const current = useProjectStore.getState().document;
+ return current ? annotationFootageRect(current, id) : null;
+ };
+ /**
+ * Une édition du texte (mots, taille), la boîte retaillée sur le résultat, centre conservé.
+ * Un texte encore rangé sur le footage passe d'abord dans le cadre, comme à son premier
+ * déplacement dans l'aperçu : c'est là que sa boîte veut dire quelque chose.
+ */
+ const textEdit = (
+ region: AxcutAnnotationRegion,
+ patch: Partial<AxcutAnnotationRegion>,
+ ): Partial<AxcutAnnotationRegion> => {
+ const footage = region.space === "frame" ? null : footageOf(region.id);
+ const toFrame = footage ? toFrameSpace(region, footage) : null;
+ const next = { ...region, ...toFrame, ...patch };
+ if (next.space !== "frame") return patch;
+ return { ...toFrame, ...patch, ...fitTextBox(next, frameAspect) };
+ };
const selection = tl.selection;
if (!selection) return null;
@@ -959,7 +990,13 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
]}
value={region.type}
onChange={(kind) => {
- tl.updateAnnotationLive(region.id, convertAnnotationKind(region, kind));
+ tl.updateAnnotationLive(
+ region.id,
+ convertAnnotationKind(region, kind, {
+ footage: footageOf(region.id),
+ frameAspect,
+ }),
+ );
void tl.commitAnnotationChange();
}}
/>,
@@ -972,7 +1009,9 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
<textarea
value={region.content ?? ""}
placeholder={ts("annotation.textPlaceholder")}
- onChange={(e) => tl.updateAnnotationLive(region.id, { content: e.target.value })}
+ onChange={(e) =>
+ tl.updateAnnotationLive(region.id, textEdit(region, { content: e.target.value }))
+ }
onBlur={commitAnnotation}
rows={2}
className={shell.control}
@@ -1008,7 +1047,6 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
reader.readAsDataURL(file);
}}
/>
- <span className={shell.hint}>{ts("annotation.supportedFormats")}</span>
</div>
) : null}
{region.type === "figure" ? (
@@ -1126,22 +1164,21 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
) : null}
</>
) : null}
- {region.type === "text"
- ? paneRow(
- ts("annotation.size"),
- // Le nombre saisi vaut « pixels à 1080 » (cf. annotationScale.ts) : preview et
- // rendu le multiplient tous deux par la hauteur de leur boîte, donc ce champ
- // veut dire la même chose des deux côtés.
- <AnnotationSizeField
- label={ts("annotation.size")}
- size={region.style?.fontSize ?? 32}
- onCommit={(fontSize) => {
- tl.updateAnnotationLive(region.id, { style: { ...region.style, fontSize } });
- commitAnnotation();
- }}
- />,
- )
- : null}
+ {region.type === "text" ? (
+ // Le nombre vaut « pixels à 1080 » (cf. annotationScale.ts) : aperçu et rendu le
+ // multiplient tous deux par la hauteur du cadre, donc il veut dire la même chose
+ // des deux côtés. La boîte suit : elle reste taillée sur le texte.
+ <AnnotationSizeControl
+ size={region.style?.fontSize ?? 32}
+ onChange={(fontSize) => {
+ tl.updateAnnotationLive(
+ region.id,
+ textEdit(region, { style: { ...region.style, fontSize } }),
+ );
+ commitAnnotation();
+ }}
+ />
+ ) : null}
{region.type === "text"
? paneStack(
ts("annotation.background"),
@@ -1151,6 +1188,8 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
// libre du flou.
<ChoiceRow<TextPlate | "custom">
label={ts("annotation.background")}
+ // Quatre libellés ne tiennent pas sur une rangée : « Personnalisé » était rogné.
+ columns={plate === "custom" ? 2 : undefined}
options={[
{ value: "none", label: ts("textPlate.none") },
{ value: "dark", label: ts("textPlate.dark") },
diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts
index 88a62263c..448437b2c 100644
--- a/src/components/video-editor/types.ts
+++ b/src/components/video-editor/types.ts
@@ -399,6 +399,8 @@ export interface AnnotationRegion {
content: string; // Legacy - still used for current type
textContent?: string; // Separate storage for text
imageContent?: string; // Separate storage for image data URL
+ /** `"frame"`: placed on the output frame. Absent: on the footage (see annotations/placement.ts). */
+ space?: "frame";
position: AnnotationPosition;
size: AnnotationSize;
style: AnnotationTextStyle;
diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json
index a6d680891..3225530d5 100644
--- a/src/i18n/locales/ar/settings.json
+++ b/src/i18n/locales/ar/settings.json
@@ -51,9 +51,9 @@
"errorReading": "حدث خطأ أثناء قراءة الملف."
},
"annotation": {
- "supportedFormats": "الصيغ المدعومة: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "مستطيل",
"size": "الحجم",
+ "customSize": "حجم مخصص",
"tipShiftTabCycle": "استخدم Shift+Tab للتنقل للخلف.",
"clearBackground": "مسح الخلفية",
"colorPalette": "لوحة الألوان",
diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.json
index aadcd24ea..0b953d38e 100644
--- a/src/i18n/locales/cs/settings.json
+++ b/src/i18n/locales/cs/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Při čtení souboru došlo k chybě."
},
"annotation": {
- "supportedFormats": "Podporované formáty: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Obdélník",
"size": "Velikost",
+ "customSize": "Vlastní velikost",
"tipShiftTabCycle": "Použijte Shift+Tab pro cyklování dozadu.",
"clearBackground": "Vymazat pozadí",
"colorPalette": "Paleta barev",
diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.json
index ad7c2c29c..2ae53aed4 100644
--- a/src/i18n/locales/de/settings.json
+++ b/src/i18n/locales/de/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Beim Lesen der Datei ist ein Fehler aufgetreten."
},
"annotation": {
- "supportedFormats": "Unterstützte Formate: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Rechteck",
"size": "Größe",
+ "customSize": "Eigene Größe",
"tipShiftTabCycle": "Mit Shift+Tab rückwärts durchlaufen.",
"clearBackground": "Hintergrund entfernen",
"colorPalette": "Farbpalette",
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index 621d63f21..31085ce3f 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -51,9 +51,9 @@
"errorReading": "There was an error reading the file."
},
"annotation": {
- "supportedFormats": "Supported formats: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Rectangle",
"size": "Size",
+ "customSize": "Custom size",
"tipShiftTabCycle": "Use Shift+Tab to cycle backwards.",
"clearBackground": "Clear Background",
"colorPalette": "Color palette",
diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json
index d35196fb7..b22b8eaf5 100644
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Hubo un error al leer el archivo."
},
"annotation": {
- "supportedFormats": "Formatos compatibles: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Rectángulo",
"size": "Tamaño",
+ "customSize": "Tamaño personalizado",
"tipShiftTabCycle": "Usa Shift+Tab para recorrer hacia atrás.",
"clearBackground": "Quitar fondo",
"colorPalette": "Paleta de colores",
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 25bdc6531..d42d331d1 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Une erreur s'est produite lors de la lecture du fichier."
},
"annotation": {
- "supportedFormats": "Formats supportés : JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Rectangle",
"size": "Taille",
+ "customSize": "Taille personnalisée",
"tipShiftTabCycle": "Utilisez Shift+Tab pour cycler en sens inverse.",
"clearBackground": "Supprimer l'arrière-plan",
"colorPalette": "Palette de couleurs",
diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json
index a0066e6b6..a4acb69b0 100644
--- a/src/i18n/locales/it/settings.json
+++ b/src/i18n/locales/it/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Si è verificato un errore durante la lettura del file."
},
"annotation": {
- "supportedFormats": "Formati supportati: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Rettangolo",
"size": "Dimensione",
+ "customSize": "Dimensione personalizzata",
"tipShiftTabCycle": "Usa Maiusc+Tab per scorrere all'indietro.",
"clearBackground": "Rimuovi sfondo",
"colorPalette": "Tavolozza dei colori",
diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json
index adfd2a485..cdfa2ab17 100644
--- a/src/i18n/locales/ja-JP/settings.json
+++ b/src/i18n/locales/ja-JP/settings.json
@@ -51,9 +51,9 @@
"errorReading": "ファイルの読み取り中にエラーが発生しました。"
},
"annotation": {
- "supportedFormats": "サポートされている形式: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "長方形",
"size": "サイズ",
+ "customSize": "カスタムサイズ",
"tipShiftTabCycle": "Shift+Tabキーを使用して逆順に切り替えます。",
"clearBackground": "背景をクリア",
"colorPalette": "カラーパレット",
diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json
index c87367c87..110a2d4c8 100644
--- a/src/i18n/locales/ko-KR/settings.json
+++ b/src/i18n/locales/ko-KR/settings.json
@@ -51,9 +51,9 @@
"errorReading": "파일을 읽는 중 오류가 발생했습니다."
},
"annotation": {
- "supportedFormats": "지원 형식: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "사각형",
"size": "크기",
+ "customSize": "사용자 지정 크기",
"tipShiftTabCycle": "Shift+Tab으로 역방향 순환할 수 있습니다.",
"clearBackground": "배경 지우기",
"colorPalette": "색상 팔레트",
diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json
index 62c6500b3..8d0010fcd 100644
--- a/src/i18n/locales/pt-BR/settings.json
+++ b/src/i18n/locales/pt-BR/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Ocorreu um erro ao ler o arquivo."
},
"annotation": {
- "supportedFormats": "Formatos suportados: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Retângulo",
"size": "Tamanho",
+ "customSize": "Tamanho personalizado",
"tipShiftTabCycle": "Use Shift+Tab para alternar para trás.",
"clearBackground": "Limpar Fundo",
"colorPalette": "Paleta de Cores",
diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json
index 9e625bd63..ec99302b6 100644
--- a/src/i18n/locales/ru/settings.json
+++ b/src/i18n/locales/ru/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Произошла ошибка при чтении файла."
},
"annotation": {
- "supportedFormats": "Поддерживаемые форматы: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Прямоугольник",
"size": "Размер",
+ "customSize": "Свой размер",
"tipShiftTabCycle": "Используйте Shift+Tab для циклического переключения в обратном направлении.",
"clearBackground": "Очистить фон",
"colorPalette": "Палитра цветов",
diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json
index d8daf3ad6..2e2fa3ec5 100644
--- a/src/i18n/locales/tr/settings.json
+++ b/src/i18n/locales/tr/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Dosya okunurken bir hata oluştu."
},
"annotation": {
- "supportedFormats": "Desteklenen biçimler: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Dikdörtgen",
"size": "Boyut",
+ "customSize": "Özel boyut",
"tipShiftTabCycle": "Geriye doğru geçiş yapmak için Shift+Tab kullanın.",
"clearBackground": "Arka Planı Temizle",
"colorPalette": "Renk paleti",
diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json
index 1b1e65147..0ae2421fe 100644
--- a/src/i18n/locales/vi/settings.json
+++ b/src/i18n/locales/vi/settings.json
@@ -51,9 +51,9 @@
"errorReading": "Đã xảy ra lỗi khi đọc tệp."
},
"annotation": {
- "supportedFormats": "Định dạng hỗ trợ: JPG, PNG, GIF, WebP",
"blurShapeRectangle": "Chữ nhật",
"size": "Kích thước",
+ "customSize": "Kích thước tùy chỉnh",
"tipShiftTabCycle": "Sử dụng Shift+Tab để chuyển ngược lại.",
"clearBackground": "Xóa nền",
"invalidImageType": "Loại tệp không hợp lệ",
diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json
index f1a3026e6..bcaefd1c2 100644
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@ -51,9 +51,9 @@
"errorReading": "读取文件时出错。"
},
"annotation": {
- "supportedFormats": "支持的格式:JPG、PNG、GIF、WebP",
"blurShapeRectangle": "矩形",
"size": "大小",
+ "customSize": "自定义大小",
"tipShiftTabCycle": "使用 Shift+Tab 反向循环切换。",
"clearBackground": "清除背景",
"colorPalette": "颜色调色板",
diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json
index fc9d4f3dd..4db6a6596 100644
--- a/src/i18n/locales/zh-TW/settings.json
+++ b/src/i18n/locales/zh-TW/settings.json
@@ -51,9 +51,9 @@
"errorReading": "讀取檔案時出錯。"
},
"annotation": {
- "supportedFormats": "支援的格式:JPG、PNG、GIF、WebP",
"blurShapeRectangle": "矩形",
"size": "大小",
+ "customSize": "自訂大小",
"tipShiftTabCycle": "使用 Shift+Tab 反向循環切換。",
"clearBackground": "清除背景",
"colorPalette": "調色盤",
diff --git a/src/lib/ai-edition/annotations/placement.test.ts b/src/lib/ai-edition/annotations/placement.test.ts
new file mode 100644
index 000000000..8c1d46fd1
--- /dev/null
+++ b/src/lib/ai-edition/annotations/placement.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+import {
+ convertAnnotationKind,
+ fitTextBox,
+ type MeasureText,
+ measureTextBlock,
+ refitFrameAnnotations,
+ toFrameSpace,
+} from "./placement";
+
+const WIDE = 16 / 9;
+// The footage padded in to 80 % of a 16:9 frame, centred.
+const FOOTAGE = { x: 0.1, y: 0.1, width: 0.8, height: 0.8 };
+
+function region(overrides: Partial<AxcutAnnotationRegion> = {}): AxcutAnnotationRegion {
+ return {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "Hello",
+ position: { x: 35, y: 40 },
+ size: { width: 30, height: 20 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ textAnimation: "none",
+ },
+ zIndex: 1,
+ ...overrides,
+ };
+}
+
+const center = (r: Pick<AxcutAnnotationRegion, "position" | "size">) => ({
+ x: r.position.x + r.size.width / 2,
+ y: r.position.y + r.size.height / 2,
+});
+
+/** 100 px wide and 40 px tall per line, whatever the text: the box math, not the font. */
+const measure: MeasureText = (content) => ({
+ width: 100,
+ height: 40 * content.split("\n").length,
+});
+
+describe("toFrameSpace", () => {
+ it("moves an annotation off the footage without moving it on screen", () => {
+ const patch = toFrameSpace(region(), FOOTAGE);
+ expect(patch?.space).toBe("frame");
+ // 10 % + 35 % of 80 %, and so on: the same pixels, measured on the frame.
+ expect(patch?.position?.x).toBeCloseTo(38, 6);
+ expect(patch?.position?.y).toBeCloseTo(42, 6);
+ expect(patch?.size?.width).toBeCloseTo(24, 6);
+ expect(patch?.size?.height).toBeCloseTo(16, 6);
+ });
+
+ it("keeps the letters their size: the text size follows the reference box's height", () => {
+ // 32 px of an 80 %-high footage is 25.6 px of the frame, rounded.
+ expect(toFrameSpace(region(), FOOTAGE)?.style?.fontSize).toBe(26);
+ });
+
+ it("leaves a blur on the footage, and an annotation already on the frame alone", () => {
+ expect(toFrameSpace(region({ type: "blur" }), FOOTAGE)).toBeNull();
+ expect(toFrameSpace(region({ space: "frame" }), FOOTAGE)).toBeNull();
+ });
+});
+
+describe("fitTextBox", () => {
+ it("hugs the text: its width plus the plate's margin, measured against the frame", () => {
+ const { size } = fitTextBox(region({ space: "frame" }), WIDE, measure);
+ // 100 px + (0.4 em of plate + 0.25 em of slack) × 32, on a 1920-wide reference frame.
+ expect(size.width).toBeCloseTo(((100 + 0.65 * 32) / 1920) * 100, 6);
+ // 40 px + (0.2 em + 0.125 em) × 32, on 1080.
+ expect(size.height).toBeCloseTo(((40 + 0.325 * 32) / 1080) * 100, 6);
+ });
+
+ it("keeps the box where it was: its centre does not move", () => {
+ const before = region({ space: "frame" });
+ const after = fitTextBox(before, WIDE, measure);
+ expect(center(after).x).toBeCloseTo(center(before).x, 6);
+ expect(center(after).y).toBeCloseTo(center(before).y, 6);
+ });
+
+ it("grows with the words and with the size", () => {
+ const one = fitTextBox(region({ space: "frame" }), WIDE, measure).size;
+ const two = fitTextBox(region({ space: "frame", content: "a\nb" }), WIDE, measure).size;
+ expect(two.height).toBeGreaterThan(one.height);
+ const big = fitTextBox(
+ region({ space: "frame", style: { ...region().style, fontSize: 96 } }),
+ WIDE,
+ measureTextBlock,
+ ).size;
+ const small = fitTextBox(region({ space: "frame" }), WIDE, measureTextBlock).size;
+ expect(big.width / small.width).toBeCloseTo(3, 6);
+ });
+
+ it("stays in the frame at its edge, never at a negative position", () => {
+ const atEdge = fitTextBox(
+ region({ space: "frame", position: { x: 99, y: 99 }, size: { width: 1, height: 1 } }),
+ WIDE,
+ measure,
+ );
+ expect(atEdge.position.x + atEdge.size.width).toBeCloseTo(100, 6);
+ expect(atEdge.position.y + atEdge.size.height).toBeCloseTo(100, 6);
+ const huge = fitTextBox(
+ region({ space: "frame", content: "x".repeat(400) }),
+ WIDE,
+ measureTextBlock,
+ );
+ expect(huge.size.width).toBeGreaterThan(100);
+ expect(huge.position.x).toBe(0);
+ });
+});
+
+describe("measureTextBlock without a canvas", () => {
+ it("counts lines and the longest one", () => {
+ const one = measureTextBlock("abcd", region().style);
+ const two = measureTextBlock("ab\nabcd", region().style);
+ expect(two.width).toBe(one.width);
+ expect(two.height).toBe(one.height * 2);
+ });
+});
+
+describe("convertAnnotationKind", () => {
+ const context = { footage: FOOTAGE, frameAspect: WIDE, measure };
+
+ it("puts a blur on the footage, at the default size, where the text was", () => {
+ const text = region({
+ space: "frame",
+ position: { x: 45, y: 45 },
+ size: { width: 10, height: 10 },
+ });
+ const patch = convertAnnotationKind(text, "blur", context);
+ expect(patch.type).toBe("blur");
+ expect(patch.space).toBeUndefined();
+ expect("space" in patch).toBe(true);
+ expect(patch.size).toEqual({ width: 30, height: 20 });
+ // Centred on the text's centre, (50, 50) on the frame, which is (50, 50) on the footage.
+ expect(center({ position: patch.position!, size: patch.size! })).toEqual({ x: 50, y: 50 });
+ });
+
+ it("takes a blur back to the frame without moving it on screen", () => {
+ const blur = region({ type: "blur", content: "" });
+ const patch = convertAnnotationKind(blur, "figure", context);
+ expect(patch.space).toBe("frame");
+ expect(patch.position?.x).toBeCloseTo(38, 6);
+ expect(patch.size?.width).toBeCloseTo(24, 6);
+ });
+
+ it("keeps the box between image and arrow, and fits a text to its words", () => {
+ const arrow = region({ type: "figure", content: "", space: "frame" });
+ const image = convertAnnotationKind(arrow, "image", context);
+ expect({ position: image.position, size: image.size }).toEqual({
+ position: arrow.position,
+ size: arrow.size,
+ });
+ const text = convertAnnotationKind(arrow, "text", context);
+ expect(text.size).toEqual(fitTextBox({ ...arrow, space: "frame" }, WIDE, measure).size);
+ expect(center({ position: text.position!, size: text.size! }).x).toBeCloseTo(
+ center(arrow).x,
+ 6,
+ );
+ });
+
+ it("parks each content in its slot and brings it back", () => {
+ const text = region({ space: "frame", content: "hello" });
+ const toImage = convertAnnotationKind(text, "image", context);
+ expect(toImage).toMatchObject({ textContent: "hello", content: "" });
+ const back = convertAnnotationKind(
+ { ...text, ...toImage, content: "data:image/png;base64,AAAA" },
+ "text",
+ context,
+ );
+ expect(back).toMatchObject({ content: "hello", imageContent: "data:image/png;base64,AAAA" });
+ });
+
+ it("changes only the kind when no footage is known", () => {
+ const patch = convertAnnotationKind(region(), "figure", { ...context, footage: null });
+ expect(patch).toEqual({ textContent: "Hello", type: "figure", content: "" });
+ });
+});
+
+describe("refitFrameAnnotations", () => {
+ it("keeps each frame annotation's shape and centre across a format change", () => {
+ const text = region({
+ space: "frame",
+ position: { x: 45, y: 40 },
+ size: { width: 10, height: 6 },
+ });
+ const [after] = refitFrameAnnotations([text], WIDE, 9 / 16);
+ // A width measured on the frame's height: three times the share of a frame three times
+ // narrower in pixels.
+ expect(after.size.width).toBeCloseTo(10 * (WIDE / (9 / 16)), 6);
+ expect(after.size.height).toBe(6);
+ expect(center(after).x).toBeCloseTo(50, 6);
+ expect(after.position.y).toBe(40);
+ });
+
+ it("leaves the footage's annotations, and an unchanged format, alone", () => {
+ const blur = region({ type: "blur" });
+ expect(refitFrameAnnotations([blur], WIDE, 1)[0]).toBe(blur);
+ const list = [region({ space: "frame" })];
+ expect(refitFrameAnnotations(list, WIDE, WIDE)).toBe(list);
+ });
+});
diff --git a/src/lib/ai-edition/annotations/placement.ts b/src/lib/ai-edition/annotations/placement.ts
new file mode 100644
index 000000000..a156bb4af
--- /dev/null
+++ b/src/lib/ai-edition/annotations/placement.ts
@@ -0,0 +1,311 @@
+// Où vit une annotation sur l'image, et les conversions entre ses deux repères.
+//
+// Texte, image et flèche se placent sur le CADRE de sortie (`space: "frame"`), comme les
+// sous-titres depuis #396 : ni le padding ni la taille du footage ne les déplacent, et elles vont
+// où l'on veut, fond compris. Le flou reste mesuré sur le FOOTAGE (pas de `space`) : un masque de
+// confidentialité doit rester sur ce qu'il cache quand le padding redimensionne l'enregistrement
+// dessous, et le compositeur le fait suivre le zoom et l'inclinaison 3D sur cette base
+// (`FrameGeometry::privacy_mask`).
+//
+// Une annotation enregistrée avant ce changement n'a pas de `space` et se dessine toujours sur le
+// footage, comme avant. L'éditeur la passe dans le cadre la première fois qu'on touche à sa
+// géométrie (`toFrameSpace`) : c'est le seul moment où la conversion ne peut surprendre personne.
+
+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+import { clampToBound } from "@/lib/projectDefaults";
+import { resolveTextFontFamily } from "@/lib/textFonts";
+import { ANNOTATION_REFERENCE_HEIGHT } from "../annotationScale";
+
+type Region = AxcutAnnotationRegion;
+type Geometry = Pick<Region, "position" | "size">;
+
+/** Un rect en fractions (0..1) du cadre de sortie : la forme de `layout.screenRect` dans la scène. */
+export interface FrameRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** Un rect en pourcentages de sa boîte de référence, comme `position` et `size` dans le document. */
+interface PctRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** Taille d'une image, d'une flèche ou d'un flou neufs, en % de leur boîte de référence. */
+export const DEFAULT_ANNOTATION_BOX = { width: 30, height: 20 } as const;
+
+/** Le repère d'un type : le cadre, sauf pour le flou. */
+export function belongsInFrame(type: Region["type"]): boolean {
+ return type !== "blur";
+}
+
+const rectOf = (region: Geometry): PctRect => ({
+ x: region.position.x,
+ y: region.position.y,
+ width: region.size.width,
+ height: region.size.height,
+});
+
+const centerOf = (rect: PctRect) => ({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 });
+
+const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
+
+/**
+ * Un rect de `width` × `height` centré sur `center`, poussé dans sa boîte tant qu'il y tient. Plus
+ * grand qu'elle, il part du bord gauche ou haut : le schéma refuse une position négative.
+ */
+function around(center: { x: number; y: number }, width: number, height: number): Geometry {
+ const w = Math.max(width, 0.1);
+ const h = Math.max(height, 0.1);
+ return {
+ position: {
+ x: clamp(center.x - w / 2, 0, Math.max(0, 100 - w)),
+ y: clamp(center.y - h / 2, 0, Math.max(0, 100 - h)),
+ },
+ size: { width: w, height: h },
+ };
+}
+
+const within = (rect: PctRect): Geometry => around(centerOf(rect), rect.width, rect.height);
+
+/** Un rect en % du footage, reporté en % du cadre. */
+function footageToFrame(rect: PctRect, footage: FrameRect): PctRect {
+ return {
+ x: footage.x * 100 + rect.x * footage.width,
+ y: footage.y * 100 + rect.y * footage.height,
+ width: rect.width * footage.width,
+ height: rect.height * footage.height,
+ };
+}
+
+/** Un rect en % du cadre, reporté en % du footage. */
+function frameToFootage(rect: PctRect, footage: FrameRect): PctRect {
+ return {
+ x: (rect.x - footage.x * 100) / footage.width,
+ y: (rect.y - footage.y * 100) / footage.height,
+ width: rect.width / footage.width,
+ height: rect.height / footage.height,
+ };
+}
+
+/**
+ * Le patch qui passe une annotation du footage au cadre sans la bouger d'un pixel : son rect est
+ * reporté dans le cadre à travers `footage`, et la taille du texte, mesurée sur la hauteur de la
+ * boîte de référence (`annotationScale.ts`), suit le même rapport. `null` pour une annotation déjà
+ * dans le cadre, et pour un flou, qui n'en sort jamais.
+ */
+export function toFrameSpace(region: Region, footage: FrameRect): Partial<Region> | null {
+ if (region.space === "frame" || !belongsInFrame(region.type)) return null;
+ if (!(footage.width > 0 && footage.height > 0)) return null;
+ return {
+ space: "frame",
+ ...within(footageToFrame(rectOf(region), footage)),
+ style: {
+ ...region.style,
+ fontSize: Math.round(
+ clampToBound(region.style.fontSize * footage.height, "annotationFontSize"),
+ ),
+ },
+ };
+}
+
+/** Le bloc qu'un texte occupe, en px à `ANNOTATION_REFERENCE_HEIGHT` : l'unité de `fontSize`. */
+export interface TextBlock {
+ width: number;
+ height: number;
+}
+
+export type MeasureText = (content: string, style: Region["style"]) => TextBlock;
+
+// Sans canvas (les tests), une estimation : chasse moyenne d'une police proportionnelle,
+// interligne des familles livrées.
+const FALLBACK_ADVANCE_EM = 0.56;
+const FALLBACK_LINE_EM = 1.25;
+
+let measuringContext: OffscreenCanvasRenderingContext2D | null | undefined;
+
+/** `OffscreenCanvas` : il lit les polices de `document.fonts`, et jsdom n'en a pas. */
+function measuringCanvas(): OffscreenCanvasRenderingContext2D | null {
+ if (measuringContext === undefined) {
+ measuringContext =
+ typeof OffscreenCanvas === "undefined" ? null : new OffscreenCanvas(1, 1).getContext("2d");
+ }
+ return measuringContext;
+}
+
+/** La police CSS d'un style, dans la famille que le compositeur dessinera vraiment. */
+export function textCssFont(style: Region["style"]): string {
+ const italic = style.fontStyle === "italic" ? "italic " : "";
+ const bold = style.fontWeight === "bold" ? "bold " : "";
+ return `${italic}${bold}${style.fontSize}px "${resolveTextFontFamily(style.fontFamily)}"`;
+}
+
+/**
+ * Mesure un texte dans les fichiers de police que le compositeur charge lui aussi
+ * (`registerTextFontFaces`). Une ligne par retour à la ligne saisi : une annotation ne revient
+ * jamais à la ligne d'elle-même, sa boîte est taillée sur sa ligne la plus longue.
+ */
+export const measureTextBlock: MeasureText = (content, style) => {
+ const size = style.fontSize;
+ const lines = content.split("\n");
+ const ctx = measuringCanvas();
+ if (!ctx) {
+ const longest = Math.max(0, ...lines.map((line) => [...line].length));
+ return {
+ width: longest * FALLBACK_ADVANCE_EM * size,
+ height: lines.length * FALLBACK_LINE_EM * size,
+ };
+ }
+ ctx.font = textCssFont(style);
+ const font = ctx.measureText("");
+ const line = font.fontBoundingBoxAscent + font.fontBoundingBoxDescent;
+ return {
+ width: Math.max(0, ...lines.map((text) => ctx.measureText(text).width)),
+ height: lines.length * (Number.isFinite(line) && line > 0 ? line : FALLBACK_LINE_EM * size),
+ };
+};
+
+// La plaque déborde du texte de 0,2 em à gauche et à droite, de 0,1 em dessus et dessous
+// (`crates/compositor/src/text_plate.rs`) : la boîte la contient, sinon le compositeur la rogne.
+const PLATE_PAD_X_EM = 0.2;
+const PLATE_PAD_Y_EM = 0.1;
+// Marge de mesure. Le compositeur compose le texte dans la boîte et passe à la ligne dès qu'une
+// ligne dépasse : mesurée ici par Chromium, là par DirectWrite, CoreText ou cosmic-text, une
+// largeur peut différer d'un cheveu, et une boîte juste à un cheveu près envoie le dernier mot à
+// la ligne suivante.
+const MEASURE_SLACK_EM = 0.25;
+// Une annotation vidée garde une boîte qu'on peut encore attraper.
+const MIN_TEXT_WIDTH_EM = 1;
+
+/**
+ * Le rect d'un texte dans le cadre, taillé sur ses mots : ce qu'on sélectionne est le texte, pas
+ * une boîte cinq fois plus grande que lui. Le centre ne bouge pas. `frameAspect` = largeur sur
+ * hauteur du cadre de sortie.
+ */
+export function fitTextBox(
+ region: Region,
+ frameAspect: number,
+ measure: MeasureText = measureTextBlock,
+): Geometry {
+ const size = region.style.fontSize;
+ // Le même texte que celui que la scène envoie au compositeur (`sceneDescription.ts`).
+ const block = measure(region.content || region.textContent || "", region.style);
+ const widthPx =
+ Math.max(block.width, MIN_TEXT_WIDTH_EM * size) +
+ (2 * PLATE_PAD_X_EM + MEASURE_SLACK_EM) * size;
+ const heightPx = block.height + (2 * PLATE_PAD_Y_EM + MEASURE_SLACK_EM / 2) * size;
+ const aspect = frameAspect > 0 ? frameAspect : 16 / 9;
+ return around(
+ centerOf(rectOf(region)),
+ (widthPx / (ANNOTATION_REFERENCE_HEIGHT * aspect)) * 100,
+ (heightPx / ANNOTATION_REFERENCE_HEIGHT) * 100,
+ );
+}
+
+/**
+ * Patch à appliquer quand l'utilisateur change le type d'une annotation.
+ *
+ * `content` est un slot UNIQUE partagé par le texte et l'image : la zone de saisie y écrit, et le
+ * rendu d'image y lit une data URL. Changer de type sans déplacer la valeur déversait donc le
+ * base64 de l'image, souvent plusieurs mégaoctets, dans le champ texte. Chaque contenu est rangé
+ * dans son slot typé (`textContent` / `imageContent`) en sortant et restauré en entrant, si bien
+ * qu'un aller-retour entre deux types ne perd rien.
+ *
+ * La géométrie change de repère avec le type (le flou vit sur le footage, le reste dans le cadre)
+ * sans bouger à l'image, à travers `footage`, le rect du footage dans le cadre. Une boîte de texte
+ * épouse ses mots, bien trop petite pour une image, une flèche ou un flou : ceux-là repartent de la
+ * taille par défaut, centrés au même endroit. `footage` inconnu (aucun clip sous l'annotation) :
+ * les nombres restent tels quels.
+ */
+export function convertAnnotationKind(
+ region: Region,
+ next: Region["type"],
+ context: { footage: FrameRect | null; frameAspect: number; measure?: MeasureText },
+): Partial<Region> {
+ if (region.type === next) return {};
+ const parked: Partial<Region> =
+ region.type === "text"
+ ? { textContent: region.content ?? "" }
+ : region.type === "image"
+ ? { imageContent: region.content ?? "" }
+ : {};
+ // Flèche et flou n'ont pas de contenu : on vide `content` plutôt que d'y laisser traîner le
+ // texte ou le base64 du type précédent.
+ const restored =
+ next === "text"
+ ? (region.textContent ?? "")
+ : next === "image"
+ ? (region.imageContent ?? "")
+ : "";
+ const content: Partial<Region> = { ...parked, type: next, content: restored };
+
+ const { footage } = context;
+ const usable = footage && footage.width > 0 && footage.height > 0 ? footage : null;
+ const onFrame =
+ region.space === "frame"
+ ? rectOf(region)
+ : usable
+ ? footageToFrame(rectOf(region), usable)
+ : null;
+ if (!onFrame || !usable) return content;
+ const center = centerOf(onFrame);
+ const fromText = region.type === "text";
+
+ if (!belongsInFrame(next)) {
+ const inFootage = frameToFootage(onFrame, usable);
+ return {
+ ...content,
+ space: undefined,
+ ...(fromText
+ ? around(centerOf(inFootage), DEFAULT_ANNOTATION_BOX.width, DEFAULT_ANNOTATION_BOX.height)
+ : within(inFootage)),
+ };
+ }
+ if (next === "text") {
+ const placed: Region = {
+ ...region,
+ ...content,
+ position: { x: onFrame.x, y: onFrame.y },
+ size: { width: onFrame.width, height: onFrame.height },
+ };
+ return {
+ ...content,
+ space: "frame",
+ ...fitTextBox(placed, context.frameAspect, context.measure),
+ };
+ }
+ return {
+ ...content,
+ space: "frame",
+ ...(fromText
+ ? around(center, DEFAULT_ANNOTATION_BOX.width, DEFAULT_ANNOTATION_BOX.height)
+ : within(onFrame)),
+ };
+}
+
+/**
+ * Les annotations du cadre après un changement de format, de `fromAspect` à `toAspect` (largeur
+ * sur hauteur). Chacune garde son centre, et sa forme à l'image : sa largeur est mesurée, comme
+ * la police, sur la hauteur du cadre. Sans ça, un texte taillé en 16:9 garde en 9:16 le même
+ * pourcentage d'une largeur trois fois plus petite en pixels, et le compositeur le renvoie à la
+ * ligne ; une flèche penche. Le reste ne bouge pas : un flou suit le footage, qui garde son ratio.
+ */
+export function refitFrameAnnotations<T extends Region>(
+ annotations: T[],
+ fromAspect: number,
+ toAspect: number,
+): T[] {
+ if (!(fromAspect > 0 && toAspect > 0) || Math.abs(fromAspect - toAspect) < 1e-6) {
+ return annotations;
+ }
+ const scale = fromAspect / toAspect;
+ return annotations.map((annotation) => {
+ if (annotation.space !== "frame") return annotation;
+ const rect = rectOf(annotation);
+ return { ...annotation, ...around(centerOf(rect), rect.width * scale, rect.height) };
+ });
+}
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index c0cda3e97..844ed8e90 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -460,6 +460,12 @@ export const annotationRegionSchema = endGteStart(
content: z.string().default(""),
textContent: z.string().optional(),
imageContent: z.string().optional(),
+ // The box `position`, `size` and the text size are measured against. `"frame"`, the output
+ // frame: where text, images and arrows are placed, so padding and the footage's size never
+ // move them. Absent, the footage (screen rect): a privacy blur always, since it must stay on
+ // what it hides, and every annotation saved before frame placement existed. See
+ // `annotations/placement.ts`.
+ space: z.literal("frame").optional(),
position: z.object({
x: z.number().min(0).max(100),
y: z.number().min(0).max(100),
diff --git a/src/lib/ai-edition/store/useEditorSettings.test.ts b/src/lib/ai-edition/store/useEditorSettings.test.ts
index 157c3c421..bb991aa1b 100644
--- a/src/lib/ai-edition/store/useEditorSettings.test.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.test.ts
@@ -174,6 +174,45 @@ describe("useEditorSettings drag snapshots", () => {
expect(radiusOf(useProjectStore.getState().document)).toBe(10);
});
+ it("refits the frame's annotations with a new format, in the same undo step", async () => {
+ const text: AxcutDocument["annotations"][number] = {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "hi",
+ space: "frame",
+ position: { x: 45, y: 40 },
+ size: { width: 10, height: 6 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ },
+ zIndex: 1,
+ };
+ useProjectStore.setState({
+ document: { ...docA, annotations: [text], legacyEditor: { aspectRatio: "16:9" } },
+ });
+ const { result } = renderHook(() => useEditorSettings());
+ await act(async () => {
+ await result.current.set({ aspectRatio: "9:16" });
+ });
+
+ const after = useProjectStore.getState().document?.annotations[0];
+ // Its width is a share of a frame now 3.16 times narrower in pixels: the share grows by
+ // as much, around the same centre, so the text keeps its line and its place.
+ expect(after?.size.width).toBeCloseTo((10 * (16 / 9)) / (9 / 16), 6);
+ expect((after?.position.x ?? 0) + (after?.size.width ?? 0) / 2).toBeCloseTo(50, 6);
+ expect(undo()).toBe(true);
+ expect(useProjectStore.getState().document?.annotations[0]).toEqual(text);
+ });
+
it("still records the pre-drag document when the drag does reach its commit", async () => {
// The guards above must not cost the feature they are guarding: a drag that
// ends the way a drag normally ends is still ONE undo step, back to before it.
diff --git a/src/lib/ai-edition/store/useEditorSettings.ts b/src/lib/ai-edition/store/useEditorSettings.ts
index facf361c1..d104f5454 100644
--- a/src/lib/ai-edition/store/useEditorSettings.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.ts
@@ -9,10 +9,12 @@
// preview to update without round-tripping every pixel).
//
// The hook is intentionally thin: it reads from the project store, applies
-// the patch through `patchEditorSettings`, and persists via the store. No
+// the patch through `applySettingsPatch`, and persists via the store. No
// extra state, no caches — the document is the single source of truth.
import { useCallback, useEffect, useMemo, useRef } from "react";
+import { refitFrameAnnotations } from "../annotations/placement";
+import { resolveAspectRatioValue } from "../document/outputFormat";
import type { AxcutDocument } from "../schema";
import {
type EditorSettingsPatch,
@@ -22,6 +24,25 @@ import {
} from "./editorSettings";
import { useProjectStore } from "./projectStore";
+/**
+ * `patchEditorSettings`, plus what a new format does to the annotations placed on the frame:
+ * each keeps its shape and its centre (`refitFrameAnnotations`), in the same write, so one undo
+ * takes both back.
+ */
+export function applySettingsPatch(doc: AxcutDocument, patch: EditorSettingsPatch): AxcutDocument {
+ const next = patchEditorSettings(doc, patch);
+ // ponytail: only a format picked in the settings refits. Under Auto the frame can also
+ // reshape when clips change, and those annotations keep their shares of the frame; refit
+ // there too if that shows up in practice.
+ if (patch.aspectRatio === undefined) return next;
+ const annotations = refitFrameAnnotations(
+ next.annotations,
+ resolveAspectRatioValue(doc, getEditorSettings(doc).aspectRatio),
+ resolveAspectRatioValue(next, getEditorSettings(next).aspectRatio),
+ );
+ return annotations === next.annotations ? next : { ...next, annotations };
+}
+
export interface UseEditorSettingsResult {
settings: EditorSettingsSnapshot;
/** True when there's a project loaded — `set`/`setLive` are no-ops otherwise. */
@@ -48,7 +69,7 @@ export function useEditorSettings(): UseEditorSettingsResult {
async (patch: EditorSettingsPatch) => {
const doc = useProjectStore.getState().document;
if (!doc) return false;
- const next = patchEditorSettings(doc, patch);
+ const next = applySettingsPatch(doc, patch);
// The optimistic write is not the edit — the save is. Only the one that can
// fail records, and it names `doc` as what Ctrl+Z returns to because by then
// the store already holds `next`.
@@ -101,7 +122,7 @@ export function useEditorSettings(): UseEditorSettingsResult {
(patch: EditorSettingsPatch) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- const next = patchEditorSettings(doc, patch);
+ const next = applySettingsPatch(doc, patch);
if (liveDocRef.current !== doc) liveBaseRef.current = doc;
setDocument(next, { history: false });
liveDocRef.current = next;
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index e4aa812e2..c31483a28 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -13,6 +13,7 @@ import type {
} from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import { DEFAULT_TEXT_PLATE } from "../annotations/background";
+import { fitTextBox } from "../annotations/placement";
import {
collapseTracksToPills,
patchAudioTrack,
@@ -21,6 +22,7 @@ import {
trackGroupId,
} from "../document/audioTracks";
import { createId } from "../document/ids";
+import { resolveAspectRatioValue } from "../document/outputFormat";
import {
duplicateClip as duplicateClipInDocument,
moveClip as moveClipInDocument,
@@ -46,6 +48,7 @@ import {
import { dropTrimPillsByIds, resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
import { MAX_ZOOM_SCALE, MIN_ZOOM_SCALE } from "../timeline/zoom-scale";
import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
+import { getEditorSettings } from "./editorSettings";
import { saveWithDeadline, useProjectStore, waitForDocumentSaves } from "./projectStore";
import { currentWriteEpoch } from "./undoStack";
import { useSequentialTimelineOps } from "./useSequentialTimelineOps";
@@ -436,7 +439,7 @@ export function useTimeline() {
async (durationSec = DEFAULT_NEW_REGION_SEC) => {
if (!document) return;
const timeMs = Math.round(playheadSec() * 1000);
- const ann: AnnotationRegion = {
+ const draft: AnnotationRegion = {
id: createId("ann"),
startMs: timeMs,
endMs: timeMs + Math.round(durationSec * 1000),
@@ -449,10 +452,11 @@ export function useTimeline() {
// `content || textContent` and seeding both would just duplicate it.
content: ts("annotation.defaultText"),
textContent: "",
- // Centred: the position is the box's top-left corner, so {50, 50} dropped the text
- // into the bottom-right quarter.
- position: { x: 35, y: 40 },
- size: { width: 30, height: 20 },
+ // On the frame, free of the footage: padding never moves it.
+ space: "frame",
+ // A point at the centre of the frame; `fitTextBox` below grows the box around it.
+ position: { x: 50, y: 50 },
+ size: { width: 0, height: 0 },
style: {
color: "#ffffff",
backgroundColor: DEFAULT_TEXT_PLATE,
@@ -466,6 +470,11 @@ export function useTimeline() {
},
zIndex: document.annotations.length + 1,
};
+ const frameAspect = resolveAspectRatioValue(
+ document,
+ getEditorSettings(document).aspectRatio,
+ );
+ const ann: AnnotationRegion = { ...draft, ...fitTextBox(draft, frameAspect) };
const created = anchorRegionsWithDerivedMs([ann], document.timeline.clips, () =>
createId("ann"),
);
diff --git a/src/lib/textFonts.ts b/src/lib/textFonts.ts
index c78bbf30c..33f0b1f51 100644
--- a/src/lib/textFonts.ts
+++ b/src/lib/textFonts.ts
@@ -34,8 +34,10 @@ export function textFontFile(family: TextFontFamily, weight: "normal" | "bold"):
/**
* Makes the shipped files the renderer's faces too, so the picker shows each family exactly as
- * the compositor will draw it, offline included. Faces load lazily, on first use. Cosmetic, so
- * it never throws: a picker without specimens still picks.
+ * the compositor will draw it, offline included. Faces load right away, not on first use: a text
+ * annotation's box is measured in them (`annotations/placement.ts`), and a measure taken before
+ * its face arrived would size the box for a fallback font. Never throws: a picker without
+ * specimens still picks.
*/
export function registerTextFontFaces(): void {
if (typeof FontFace === "undefined" || typeof document === "undefined" || !document.fonts) {
@@ -45,7 +47,9 @@ export function registerTextFontFaces(): void {
for (const family of TEXT_FONT_FAMILIES) {
for (const weight of ["normal", "bold"] as const) {
const url = getAssetPath(textFontFile(family, weight));
- document.fonts.add(new FontFace(family, `url("${url}")`, { weight }));
+ const face = new FontFace(family, `url("${url}")`, { weight });
+ document.fonts.add(face);
+ face.load().catch((error) => console.warn(`[fonts] ${family} ${weight}:`, error));
}
}
} catch (error) {
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index ae2fe1526..515645a19 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -21,7 +21,12 @@ import { axcutSchemaVersion } from "@/lib/ai-edition/schema";
import { DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";
import { DEVICE_FRAMES } from "@/lib/projectDefaults";
import { getFocusBoundsForScale } from "@/lib/zoomMath/focusUtils";
-import { buildSceneDescription, wallpaperAcceptsMotion, zoomScaleLimit } from "./sceneDescription";
+import {
+ annotationFootageRect,
+ buildSceneDescription,
+ wallpaperAcceptsMotion,
+ zoomScaleLimit,
+} from "./sceneDescription";
// --- Fixture helpers --------------------------------------------------------
// Keep fixtures minimal & deterministic — every field the serializer consults is filled in;
@@ -2344,7 +2349,101 @@ describe("buildSceneDescription.captions", () => {
expect(rects[2].fontSizeRel).toBe(rects[0].fontSizeRel);
});
- it("leaves the space key off a real annotation entirely", () => {
+ it("holds an annotation placed on the frame still while padding shrinks the footage", () => {
+ // The annotation twin of the caption test above: a text on the frame goes wherever the
+ // user put it, and the padding slider sizes the footage, not it.
+ const text = (padding: number) => {
+ const base = docWithCaptions(false);
+ const scene = buildSceneDescription({
+ ...base,
+ annotations: [
+ {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "hi",
+ space: "frame",
+ position: { x: 2, y: 3 },
+ size: { width: 12, height: 6 },
+ style: {
+ color: "#fff",
+ backgroundColor: "transparent",
+ fontSize: 48,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ textAnimation: "none",
+ },
+ zIndex: 1,
+ },
+ ],
+ legacyEditor: {
+ ...(base.legacyEditor as Record<string, unknown>),
+ padding,
+ aspectRatio: "16:9",
+ },
+ } as AxcutDocument);
+ const annotation = scene.annotations.find((a) => a.id.startsWith("ann1"));
+ if (!annotation) throw new Error("annotation absente");
+ return {
+ screenWidth: scene.layout.screenRect?.width,
+ space: annotation.space,
+ rect: [annotation.x, annotation.y, annotation.w, annotation.h],
+ fontSizeRel: annotation.text?.fontSizeRel,
+ };
+ };
+ const [flush, padded] = [text(0), text(100)];
+ expect(padded.screenWidth).not.toBe(flush.screenWidth);
+ expect(flush.space).toBe("frame");
+ // Over the padding, where the footage is not: 2 % from the frame's left edge.
+ expect(padded.rect).toEqual([0.02, 0.03, 0.12, 0.06]);
+ expect(padded).toEqual({ ...flush, screenWidth: padded.screenWidth });
+ });
+
+ it("names the footage an annotation sits on, in fractions of the frame", () => {
+ const base = docWithCaptions(false);
+ const doc = {
+ ...base,
+ annotations: [
+ {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "blur",
+ content: "",
+ position: { x: 10, y: 10 },
+ size: { width: 20, height: 10 },
+ style: {
+ color: "#fff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "normal",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ },
+ zIndex: 1,
+ },
+ ],
+ legacyEditor: {
+ ...(base.legacyEditor as Record<string, unknown>),
+ padding: 50,
+ aspectRatio: "16:9",
+ },
+ } as AxcutDocument;
+ const rect = annotationFootageRect(doc, "ann1");
+ expect(rect).toEqual(buildSceneDescription(doc).layout.screenRect);
+ // Padded in: the footage is smaller than the frame and centred in it.
+ expect(rect?.width).toBeLessThan(1);
+ expect(rect?.x).toBeCloseTo((1 - (rect?.width ?? 0)) / 2, 6);
+ expect(annotationFootageRect(doc, "nope")).toBeNull();
+ });
+
+ it("leaves the space key off an annotation still on the footage", () => {
// Not `space: undefined` — an explicit key would change the annotation payload that
// shipped binaries already parse. `in` is the only check that tells them apart.
const doc = makeDoc({
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index fc61f607c..0a7238e9d 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -164,10 +164,11 @@ export interface SceneSpeedRegion {
* selection outline in the editor overlay still sits on the unzoomed rect.
*
* `space: "frame"` opts an entry out of that and measures it against the output frame instead.
- * Only captions set it: an annotation is authored on top of the visible video, so it must track
- * the screen rect, whereas a subtitle belongs to the frame the viewer sees and has to hold still
- * when padding resizes the footage under it (issue #396). The key is omitted entirely for
- * annotations, so their payload — and the older binaries that read it — are unchanged. */
+ * Captions set it, since a subtitle belongs to the frame the viewer sees and has to hold still
+ * when padding resizes the footage under it (issue #396), and so do text, image and arrow
+ * annotations, which are placed anywhere on the frame for the same reason. A blur never does,
+ * and neither does an annotation saved before frame placement: the key is omitted entirely
+ * there, so their payload is unchanged (see `annotations/placement.ts`). */
export interface SceneAnnotation {
id: string;
startSec: number;
@@ -179,7 +180,7 @@ export interface SceneAnnotation {
underTrim?: boolean;
kind: "text" | "image" | "figure" | "blur";
/** Which box `x`/`y`/`w`/`h` — and `text.fontSizeRel` — are fractions of. Absent means
- * `"screen"`, the historical behaviour and the only one annotations ever use. */
+ * `"screen"`: a blur, or an annotation saved before frame placement. */
space?: "frame";
/** Rect as fractions of the box named by `space` (x, y top-left). */
x: number;
@@ -699,6 +700,32 @@ export function zoomScaleLimit(document: AxcutDocument, regionId: string): numbe
return limit;
}
+/**
+ * Where the footage under the annotation `annotationId` sits in the output frame, as fractions
+ * of it: the layout of the clip the annotation is on, exactly as the scene lays it out. What the
+ * inspector converts through when an annotation changes box (`annotations/placement.ts`). The
+ * first clip's when the annotation is on none; `null` when there is no clip at all.
+ */
+export function annotationFootageRect(
+ document: AxcutDocument,
+ annotationId: string,
+): SceneRect | null {
+ const region = (document.annotations ?? []).find((a) => a.id === annotationId);
+ if (!region) return null;
+ const scene = buildSceneDescription(document);
+ const [piece] = projectRegionsToSource(
+ [region],
+ resolveVisibleClips(document),
+ document.timeline.clips,
+ () => "",
+ );
+ return (
+ scene.layout.layoutByClip?.[piece?.clipIndex ?? 0]?.screenRect ??
+ scene.layout.screenRect ??
+ null
+ );
+}
+
/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
export function buildSceneDescription(
document: AxcutDocument,
@@ -940,10 +967,11 @@ export function buildSceneDescription(
// overlay and absent from the composited pixels — the exact preview/render gap the annotation
// work above closed. They are derived on the fly and never stored (see lib/ai-edition/captions).
//
- // What they do NOT share is the reference box: each caption region carries `space: "frame"`,
- // so the compositor measures it against the output frame while annotations stay on the screen
- // rect. Subtitles have to sit where the viewer's frame ends, not where the footage does, or
- // they slide inward the moment padding shrinks the screen rect (issue #396).
+ // The reference box travels with each region: every caption carries `space: "frame"`, so the
+ // compositor measures it against the output frame. Subtitles have to sit where the viewer's
+ // frame ends, not where the footage does, or they slide inward the moment padding shrinks the
+ // screen rect (issue #396). Text, image and arrow annotations carry the same key for the same
+ // reason; a privacy blur never does (see `annotations/placement.ts`).
//
// The output aspect is what decides the caption column and the default inset (a
// caption 5% off the bottom of a 16:9 export sits under the platform's own chrome
@@ -1266,9 +1294,9 @@ export function buildSceneDescription(
annotations: projectedAnnotations
.map((region) => {
const style = region.style;
- // Only captions carry a space; annotations must keep emitting the exact same keys
- // they always have, so the field is omitted rather than sent as null/undefined.
- const space = (region as { space?: "frame" }).space;
+ // Omitted rather than sent as null/undefined when absent: an annotation still on the
+ // footage keeps emitting the exact keys it always has.
+ const space = region.space;
// Same treatment, same reason: only captions pin an edge. That includes the
// caption annotations `openscreen captions` writes, whose box is the editor's
// caption box: bottom-anchored, a caption that wraps grows upward from the inset
diff --git a/website/docs/editing-timeline.md b/website/docs/editing-timeline.md
index f3c5fc281..264b059e9 100644
--- a/website/docs/editing-timeline.md
+++ b/website/docs/editing-timeline.md
@@ -80,12 +80,14 @@ A span where the webcam fills the frame instead of sitting in its layout box —
### Annotations
-Four types, switchable from the **Type** dropdown in the inspector. Switching type keeps the region's span and box, so a mis-pick costs one click rather than a redraw.
+Four types, picked from the **Type** row in the inspector. Switching type keeps the region's span and its place in the picture.
-- **Text** — content, size, background color with an on/off toggle, text color, and an appearance animation (None / Fade / Rise / Pop / Slide Left / Typewriter / Pulse).
+Text, images and arrows sit on the frame: drag them anywhere, over the padding too. Padding and the recording's size never move them, and a format change keeps their shape. A blur stays on the recording, over what it hides.
+
+- **Text** — content, size (24, 32, 48 or 72, or any size typed next to them), background (None / Dark / Light), text color, and an appearance animation (None / Fade / Rise / Pop / Slide Left / Typewriter / Pulse). The selection box is the text itself: drag a corner to resize it.
- **Image** — upload a JPG, PNG, GIF, or WebP.
- **Arrow** — eight directions, stroke width (1–20), and color.
-- **Blur** — a privacy mask. Smooth or Mosaic, rectangle or oval, with intensity (or mosaic block size). Drag and resize it over the preview like any other annotation.
+- **Blur** — a privacy mask. Smooth or Mosaic, rectangle or oval. Drag and resize it over the recording like any other annotation.
:::note
Freehand blur shapes can no longer be drawn. Existing ones still render, but as their bounding box — deliberately over-covering rather than leaving something you marked private visible in the export. The inspector says so when it sees one.
diff --git a/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md
index 5e3e702a8..b207be33b 100644
--- a/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ Ein Abschnitt, in dem die Webcam das Bild füllt, statt in ihrem Layout-Rahmen z
### Annotationen {#annotations}
-Vier Arten, umschaltbar über die Liste **Type** im Inspektor. Beim Umschalten bleiben Zeitspanne und Rahmen des Bereichs erhalten, ein falsch gewählter Typ kostet also einen Klick statt einer neuen Zeichnung.
+Vier Arten, wählbar in der Zeile **Type** im Inspektor. Beim Umschalten bleiben die Zeitspanne des Bereichs und seine Stelle im Bild erhalten.
-- **Text**: Inhalt, Größe, Hintergrundfarbe mit Ein/Aus-Schalter, Textfarbe und eine Einblendanimation (None / Fade / Rise / Pop / Slide Left / Typewriter / Pulse).
+Texte, Bilder und Pfeile liegen auf dem Bildrahmen: Zieh sie, wohin du willst, auch über den Abstand. Weder der Abstand noch die Größe der Aufnahme verschieben sie, und ein Formatwechsel behält ihre Form bei. Eine Unschärfe bleibt auf der Aufnahme, über dem, was sie verdeckt.
+
+- **Text**: Inhalt, Größe (24, 32, 48 oder 72, oder jede daneben eingetippte Größe), Hintergrund (Keine / Dunkel / Hell), Textfarbe und eine Einblendanimation (None / Fade / Rise / Pop / Slide Left / Typewriter / Pulse). Der Auswahlrahmen ist der Text selbst: Zieh an einer Ecke, um ihn zu skalieren.
- **Image**: ein JPG, PNG, GIF oder WebP hochladen.
- **Arrow**: acht Richtungen, Strichstärke (1–20) und Farbe.
-- **Blur**: eine Maske für den Datenschutz. Gaussian oder Mosaic, Rechteck oder Oval, mit Stärke (oder Blockgröße beim Mosaik). Zieh und skaliere sie über der Vorschau wie jede andere Annotation.
+- **Blur**: eine Maske für den Datenschutz. Gaussian oder Mosaic, Rechteck oder Oval. Zieh und skaliere sie über der Aufnahme wie jede andere Annotation.
:::note
Freihand-Unschärfeformen lassen sich nicht mehr zeichnen. Vorhandene werden weiterhin gerendert, aber als ihr umschließendes Rechteck. Das deckt absichtlich zu viel ab, statt etwas, das du als privat markiert hast, im Export sichtbar zu lassen. Der Inspektor weist darauf hin, wenn er eine solche Form findet.
diff --git a/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md
index 69a04437c..7d18385fa 100644
--- a/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ Un tramo en el que la cámara web llena el cuadro en lugar de ocupar su recuadro
### Anotaciones {#annotations}
-Cuatro tipos, que se cambian desde el menú desplegable **Tipo** del inspector. Cambiar de tipo conserva el tramo y el recuadro de la región, así que equivocarse al elegir cuesta un clic y no volver a dibujarla.
+Cuatro tipos, que se eligen en la fila **Tipo** del inspector. Cambiar de tipo conserva el tramo de la región y su lugar en la imagen.
-- **Texto**: contenido, tamaño, color de fondo con un interruptor para activarlo, color del texto y una animación de aparición (Ninguna / Desvanecimiento / Ascender / Aparecer / Deslizar izquierda / Máquina de escribir / Pulso).
+Los textos, las imágenes y las flechas se colocan sobre el cuadro: arrástralos a donde quieras, también sobre el relleno. Ni el relleno ni el tamaño de la grabación los mueven, y un cambio de formato conserva su forma. Un desenfoque se queda sobre la grabación, encima de lo que oculta.
+
+- **Texto**: contenido, tamaño (24, 32, 48 o 72, o cualquier tamaño escrito al lado), fondo (Ninguna / Oscura / Clara), color del texto y una animación de aparición (Ninguna / Desvanecimiento / Ascender / Aparecer / Deslizar izquierda / Máquina de escribir / Pulso). El recuadro de selección es el propio texto: arrastra una esquina para cambiar su tamaño.
- **Imagen**: sube un JPG, PNG, GIF o WebP.
- **Flecha**: ocho direcciones, grosor del trazo (1–20) y color.
-- **Desenfoque**: una máscara de privacidad. Gaussiano o Mosaico, rectángulo u óvalo, con intensidad (o tamaño del bloque de mosaico). Arrástrala y cambia su tamaño sobre la vista previa como cualquier otra anotación.
+- **Desenfoque**: una máscara de privacidad. Gaussiano o Mosaico, rectángulo u óvalo. Arrástrala y cambia su tamaño sobre la grabación como cualquier otra anotación.
:::note
Ya no se pueden dibujar formas de desenfoque a mano alzada. Las que ya existen se siguen renderizando, pero como su rectángulo delimitador: cubren de más a propósito en lugar de dejar visible en la exportación algo que marcaste como privado. El inspector lo indica cuando detecta una.
diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md
index e7c502714..f0d39d81d 100644
--- a/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ Un passage où la webcam remplit le cadre au lieu de rester dans l'emplacement q
### Annotations {#annotations}
-Quatre types, que l'on change avec la liste déroulante **Type** de l'inspecteur. Changer de type conserve la plage et le cadre de la région : une erreur de choix coûte un clic, pas un nouveau tracé.
+Quatre types, à choisir dans la rangée **Type** de l'inspecteur. Changer de type conserve la plage de la région et sa place à l'image.
-- **Texte** : contenu, taille, couleur de fond avec interrupteur, couleur du texte et animation d'apparition (Aucune / Fondu / Monter / Apparition / Glisser à gauche / Machine à écrire / Pulsation).
-- **Image** : importez un JPG, PNG, GIF ou WebP.
-- **Flèche** : huit directions, épaisseur du trait (1–20) et couleur.
-- **Flou** : un masque de confidentialité. Gaussien ou Mosaïque, rectangle ou ovale, avec une intensité (ou une taille de blocs pour la mosaïque). Faites-le glisser et redimensionnez-le sur l'aperçu comme toute autre annotation.
+Textes, images et flèches se posent sur le cadre : faites-les glisser où vous voulez, marge comprise. Ni la marge ni la taille de l'enregistrement ne les déplacent, et un changement de format garde leur forme. Un flou reste sur l'enregistrement, sur ce qu'il cache.
+
+- **Texte** : contenu, taille (24, 32, 48 ou 72, ou toute taille saisie à côté), arrière-plan (Aucune / Sombre / Claire), couleur du texte et animation d'apparition (Aucune / Fondu / Monter / Apparition / Glisser à gauche / Machine à écrire / Pulsation). Le cadre de sélection est le texte lui-même : tirez un coin pour le redimensionner.
+- **Image** : importez un JPG, PNG, GIF ou WebP.
+- **Flèche** : huit directions, épaisseur du trait (1–20) et couleur.
+- **Flou** : un masque de confidentialité. Gaussien ou Mosaïque, rectangle ou ovale. Faites-le glisser et redimensionnez-le sur l'enregistrement comme toute autre annotation.
:::note
Il n'est plus possible de dessiner des formes de flou à main levée. Celles qui existent s'affichent encore, mais sous la forme de leur boîte englobante : elles couvrent volontairement trop, plutôt que de laisser visible dans l'export quelque chose que vous aviez marqué comme privé. L'inspecteur le signale quand il en rencontre une.
diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md
index 9361466d6..dcb50c8ea 100644
--- a/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ keywords:
### 注釈 {#annotations}
-注釈には 4 つの種類があり、インスペクターの**種類**ドロップダウンで切り替えます。種類を切り替えても範囲の区間と枠は保たれるので、選び間違えてもクリック 1 回で直せ、描き直す必要はありません。
+注釈には 4 つの種類があり、インスペクターの**種類**の行で選びます。種類を切り替えても、範囲の区間と画面上の位置は保たれます。
-- **テキスト**:内容、サイズ、背景色(オン/オフの切り替え付き)、文字色、表示時のアニメーション(なし / フェード / 上昇 / ポップ / 左へスライド / タイプライター / パルス)。
+テキスト、画像、矢印はフレームの上に置かれます。余白の上も含めて、好きな場所へドラッグできます。余白や録画のサイズを変えても動かず、フォーマットを変えても形は保たれます。ぼかしは録画の上にとどまり、隠している部分を覆い続けます。
+
+- **テキスト**:内容、サイズ(24、32、48、72 のいずれか、または横の欄に入力した任意のサイズ)、背景(なし / ダーク / ライト)、文字色、表示時のアニメーション(なし / フェード / 上昇 / ポップ / 左へスライド / タイプライター / パルス)。選択枠はテキストそのものです。角をドラッグするとサイズが変わります。
- **画像**:JPG、PNG、GIF、WebP を読み込みます。
- **矢印**:8 方向、線の太さ(1〜20)、色。
-- **ぼかし**:プライバシー保護用のマスクです。ガウスまたはモザイク、長方形または楕円を選び、強さ(モザイクの場合はブロックのサイズ)を設定します。ほかの注釈と同じように、プレビュー上でドラッグしたりサイズを変えたりできます。
+- **ぼかし**:プライバシー保護用のマスクです。ガウスまたはモザイク、長方形または楕円を選べます。ほかの注釈と同じように、録画の上でドラッグしたりサイズを変えたりできます。
:::note
自由形状のぼかしは、新たに描くことはできなくなりました。既存のものは引き続き表示されますが、外接する矩形として描画されます。非公開にしたい箇所がエクスポートで見えてしまうよりは、あえて広めに覆う設計です。インスペクターは、自由形状のぼかしを見つけるとその旨を表示します。
diff --git a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md
index 49e5f4ce5..976ee3f15 100644
--- a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ Um trecho em que a webcam preenche o quadro em vez de ficar na caixa do layout
### Anotações {#annotations}
-Quatro tipos, alternados pela lista **Tipo** no inspetor. Trocar o tipo mantém o trecho e a caixa da região, então uma escolha errada custa um clique, e não um redesenho.
+Quatro tipos, escolhidos na linha **Tipo** do inspetor. Trocar o tipo mantém o trecho da região e o lugar dela na imagem.
-- **Texto** — conteúdo, tamanho, cor de fundo com botão para ativar/desativar, cor do texto e uma animação de entrada (Nenhuma / Esmaecer / Subir / Aparecer / Deslizar à Esquerda / Máquina de Escrever / Pulsar).
+Textos, imagens e setas ficam sobre o quadro: arraste-os para onde quiser, inclusive sobre o espaçamento. Nem o espaçamento nem o tamanho da gravação os movem, e uma troca de formato mantém a forma deles. Um desfoque fica sobre a gravação, em cima do que ele esconde.
+
+- **Texto** — conteúdo, tamanho (24, 32, 48 ou 72, ou qualquer tamanho digitado ao lado), fundo (Nenhuma / Escura / Clara), cor do texto e uma animação de entrada (Nenhuma / Esmaecer / Subir / Aparecer / Deslizar à Esquerda / Máquina de Escrever / Pulsar). A caixa de seleção é o próprio texto: arraste um canto para redimensioná-lo.
- **Imagem** — envie um JPG, PNG, GIF ou WebP.
- **Seta** — oito direções, largura do traço (1–20) e cor.
-- **Desfoque** — uma máscara de privacidade. Gaussiano ou Mosaico, retângulo ou oval, com intensidade (ou tamanho do bloco do mosaico). Arraste e redimensione sobre a pré-visualização, como qualquer outra anotação.
+- **Desfoque** — uma máscara de privacidade. Gaussiano ou Mosaico, retângulo ou oval. Arraste e redimensione sobre a gravação, como qualquer outra anotação.
:::note
Não é mais possível desenhar formas de desfoque à mão livre. As que já existem continuam sendo renderizadas, mas como a caixa delimitadora delas — cobrindo mais do que o necessário, de propósito, em vez de deixar visível na exportação algo que você marcou como privado. O inspetor avisa quando encontra uma.
diff --git a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md
index 384ad246e..7e7b8d115 100644
--- a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ keywords:
### 标注 {#annotations}
-共有四种类型,可以在检查器的**类型**下拉菜单中切换。切换类型时,区间的时间范围和框都会保留,所以选错了只需再点一下,不必重新绘制。
+共有四种类型,在检查器的**类型**一行中选择。切换类型时,区间的时间范围和它在画面中的位置都会保留。
-- **文本**:内容、大小、可开关的背景颜色、文字颜色,以及出现动画(无 / 淡入淡出 / 上升 / 弹出 / 向左滑动 / 打字机 / 脉动)。
+文本、图片和箭头放在画框上:可以拖到任意位置,内边距区域也可以。内边距和录制画面的大小都不会移动它们,更换格式也会保持它们的形状。模糊则留在录制画面上,始终盖住它要遮挡的内容。
+
+- **文本**:内容、大小(24、32、48 或 72,也可在旁边输入任意大小)、背景(无 / 深色 / 浅色)、文字颜色,以及出现动画(无 / 淡入淡出 / 上升 / 弹出 / 向左滑动 / 打字机 / 脉动)。选择框就是文字本身:拖动一个角即可调整大小。
- **图片**:上传 JPG、PNG、GIF 或 WebP。
- **箭头**:八个方向、线条粗细(1–20)和颜色。
-- **模糊**:隐私遮罩。高斯或马赛克,矩形或椭圆,可调强度(或马赛克块大小)。和其他标注一样,可以在预览上拖动并调整大小。
+- **模糊**:隐私遮罩。高斯或马赛克,矩形或椭圆。和其他标注一样,可以在录制画面上拖动并调整大小。
:::note
现在已无法再绘制自由形状的模糊。已有的自由形状仍会渲染,但会按其外接矩形呈现:宁可有意多遮一些,也不让你标记为隐私的内容在导出中露出来。检查器遇到这类形状时会给出说明。
diff --git a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md
index 83a90efb6..c05de7d81 100644
--- a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md
+++ b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md
@@ -80,12 +80,14 @@ keywords:
### 標註 {#annotations}
-共有四種類型,可以從檢查器中的**類型**下拉選單切換。切換類型時會保留區域的時間範圍與框框位置,所以選錯了只要再點一下就好,不必重畫。
+共有四種類型,在檢查器的**類型**一列中選擇。切換類型時會保留區域的時間範圍,以及它在畫面中的位置。
-- **文字**:內容、大小、可開關的背景顏色、文字顏色,以及出場動畫(無/淡入淡出/上升/彈出/向左滑動/打字機/脈動)。
+文字、圖片與箭頭放在畫框上:可以拖曳到任何位置,內邊距區域也可以。內邊距與錄製畫面的大小都不會移動它們,更換格式也會保留它們的形狀。模糊則留在錄製畫面上,持續蓋住它要遮擋的內容。
+
+- **文字**:內容、大小(24、32、48 或 72,也可在旁邊輸入任意大小)、背景(無/深色/淺色)、文字顏色,以及出場動畫(無/淡入淡出/上升/彈出/向左滑動/打字機/脈動)。選取框就是文字本身:拖曳一個角即可調整大小。
- **圖片**:上傳 JPG、PNG、GIF 或 WebP。
- **箭頭**:八個方向、描邊寬度(1–20)與顏色。
-- **模糊**:隱私遮罩。可選高斯或馬賽克、矩形或橢圓,並可調整強度(或馬賽克區塊大小)。和其他標註一樣,可以在預覽上拖曳與調整大小。
+- **模糊**:隱私遮罩。可選高斯或馬賽克、矩形或橢圓。和其他標註一樣,可以在錄製畫面上拖曳與調整大小。
:::note
現在已經無法繪製手繪形狀的模糊。既有的手繪模糊仍會算繪,但會以其外接矩形呈現:這是刻意寧可多遮一些,也不讓你標記為隱私的內容在匯出中露出。檢查器偵測到這類模糊時會加以說明。