Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): text that cannot be made unreadable
EtienneLescot3cbb5ff2e836
diff --git a/src/components/ai-edition/CaptionsPane.tsx b/src/components/ai-edition/CaptionsPane.tsxindex 36fb9627f..20c3bc111 100644--- a/src/components/ai-edition/CaptionsPane.tsx+++ b/src/components/ai-edition/CaptionsPane.tsx@@ -12,10 +12,21 @@import { Captions as CaptionsIcon, Languages, Loader2, Trash2, X } from "lucide-react";import { useMemo, useState } from "react";import { useScopedT } from "@/contexts/I18nContext";-import type { CaptionAnchorH, CaptionAnchorV } from "@/lib/ai-edition/captions";+import type {+ CaptionAnchorH,+ CaptionAnchorV,+ CaptionPlate,+ CaptionStyleId,+} from "@/lib/ai-edition/captions";import {CAPTION_INSET_X_MAX,CAPTION_INSET_Y_MAX,+ CAPTION_PLATE_OPACITY_MAX,+ CAPTION_PLATE_OPACITY_MIN,+ CAPTION_STYLES,+ captionPlateOf,+ captionPlatePatch,+ captionStyleOf,DEFAULT_CAPTION_SETTINGS,untranslatedUnits,} from "@/lib/ai-edition/captions";@@ -32,9 +43,9 @@ import { useCaptions } from "@/lib/ai-edition/store/useCaptions";import { firstTimelineBusyView } from "@/lib/ai-edition/transcription/status";import { TEXT_FONT_FAMILIES } from "@/lib/textFonts";import { nativeBridgeClient } from "@/native";-import { ColorField } from "./ColorField";import styles from "./NewEditorShell.module.css";-import { SliderCell, Toggle } from "./RightPanes";+import { ChoiceRow, SliderCell, Toggle } from "./RightPanes";+import { TextColorField } from "./TextColorField";import { useTranscriptionLabel } from "./TranscriptionStatus";import { transcriptionBusyLabel } from "./transcriptionBusyLabel";@@ -113,6 +124,7 @@ export function CaptionsPane({ onClose }: { onClose?: () => void } = {}) {);const disabled = !hasDocument;+ const plate = captionPlateOf(settings);const languageOptions = useMemo(() => Object.values(translations), [translations]);const handleTranslate = async () => {@@ -323,6 +335,26 @@ export function CaptionsPane({ onClose }: { onClose?: () => void } = {}) {</div>) : null}+ {/* ── Style ──────────────────────────────────────────────── */}+ {/* Named looks first: each sets font, size, colour and plate together, and is a+ readable pair by construction. Tuning anything below leaves none selected. */}+ <div className={styles.sectionLabel}>{t("captions.style")}</div>+ <div style={{ margin: "0 var(--sp-4) 12px" }}>+ <ChoiceRow<CaptionStyleId | "custom">+ label={t("captions.style")}+ disabled={disabled}+ columns={2}+ options={CAPTION_STYLE_IDS.map((id) => ({+ value: id,+ label: t(`captions.styles.${id}`),+ }))}+ value={captionStyleOf(settings) ?? "custom"}+ onChange={(id) => {+ if (id !== "custom") void set(CAPTION_STYLES[id]);+ }}+ />+ </div>+{/* ── Language ───────────────────────────────────────────── */}<div className={styles.sectionLabel}>{t("captions.language")}</div><div className={styles.paneRow}>@@ -407,94 +439,103 @@ export function CaptionsPane({ onClose }: { onClose?: () => void } = {}) {{t("captions.translationIsNonDestructive")}</p>- {/* ── Text ───────────────────────────────────────────────── */}- <div className={styles.sectionLabel}>{t("captions.text")}</div>- <div className={styles.paneRow}>- <span className={styles.label}>{t("captions.font")}</span>- <select- value={settings.fontFamily}- disabled={disabled}- onChange={(e) => void set({ fontFamily: e.target.value })}- style={selectStyle}- >- {/* Only the families the compositor ships: it never reads the machine's- installed fonts, so any other name would draw a fallback. */}- {TEXT_FONT_FAMILIES.map((font) => (- <option key={font} value={font} style={{ fontFamily: font }}>- {font}- </option>- ))}- </select>- </div>- <div className={styles.paneRow}>- <span className={styles.label}>{t("captions.bold")}</span>- <Toggle- checked={settings.fontWeight === "bold"}- disabled={disabled}- onChange={(next) => void set({ fontWeight: next ? "bold" : "normal" })}- />- </div>- <div className={styles.sliderGrid}>- <SliderCell- label={t("captions.fontSize")}- value={settings.fontSize}- min={16}- max={140}- defaultValue={DEFAULT_CAPTION_SETTINGS.fontSize}- suffix="px"- disabled={disabled}- onChange={(v) => setLive({ fontSize: v })}- onCommit={() => void commit()}- />- </div>- <div className={styles.paneRow}>- <span className={styles.label}>{t("captions.textColor")}</span>- <ColorField- label={t("captions.textColor")}- value={settings.color}- disabled={disabled}- onChange={(color) => setLive({ color })}- onCommit={() => void commit()}- />- </div>-- {/* ── Background ─────────────────────────────────────────── */}- <div className={styles.sectionLabel}>{t("captions.background")}</div>- {/* Colour + switch on one row, exactly like the annotation pane's text- background: the swatch keeps showing the remembered colour while the- plate is off, because that is what turning it back on will draw. */}- <div className={styles.paneRow}>- <span className={styles.label}>{t("captions.background")}</span>- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>- <ColorField- label={t("captions.backgroundColor")}- value={settings.backgroundColor}+ {/* ── Customise ─────────────────────────────────────────── */}+ {/* The detailed look controls, folded behind the named styles above: still one+ click away, never the first thing to read. */}+ <details>+ <summary className={styles.sectionLabel} style={{ cursor: "pointer" }}>+ {t("captions.customize")}+ </summary>+ <div className={styles.sectionLabel}>{t("captions.text")}</div>+ <div className={styles.paneRow}>+ <span className={styles.label}>{t("captions.font")}</span>+ <select+ value={settings.fontFamily}disabled={disabled}- onChange={(backgroundColor) => setLive({ backgroundColor })}- onCommit={() => void commit()}- />+ onChange={(e) => void set({ fontFamily: e.target.value })}+ style={selectStyle}+ >+ {/* Only the families the compositor ships: it never reads the machine's+ installed fonts, so any other name would draw a fallback. */}+ {TEXT_FONT_FAMILIES.map((font) => (+ <option key={font} value={font} style={{ fontFamily: font }}>+ {font}+ </option>+ ))}+ </select>+ </div>+ <div className={styles.paneRow}>+ <span className={styles.label}>{t("captions.bold")}</span><Toggle- checked={settings.backgroundEnabled}+ checked={settings.fontWeight === "bold"}disabled={disabled}- onChange={(next) => void set({ backgroundEnabled: next })}+ onChange={(next) => void set({ fontWeight: next ? "bold" : "normal" })}/></div>- </div>- {settings.backgroundEnabled ? (<div className={styles.sliderGrid}><SliderCell- label={t("captions.backgroundOpacity")}- value={Math.round(settings.backgroundOpacity * 100)}- min={0}- max={100}- defaultValue={Math.round(DEFAULT_CAPTION_SETTINGS.backgroundOpacity * 100)}- suffix="%"+ label={t("captions.fontSize")}+ value={settings.fontSize}+ min={16}+ max={140}+ defaultValue={DEFAULT_CAPTION_SETTINGS.fontSize}+ suffix="px"disabled={disabled}- onChange={(v) => setLive({ backgroundOpacity: v / 100 })}+ onChange={(v) => setLive({ fontSize: v })}onCommit={() => void commit()}/></div>- ) : null}+ <div className={styles.paneRow}>+ <span className={styles.label}>{t("captions.textColor")}</span>+ <TextColorField+ label={t("captions.textColor")}+ value={settings.color}+ plate={settings.backgroundEnabled ? settings.backgroundColor : "transparent"}+ disabled={disabled}+ onChange={(color) => setLive({ color })}+ onCommit={() => void commit()}+ />+ </div>++ {/* ── Background ─────────────────────────────────────────── */}+ {/* Named plates, like the annotation pane's: the plate choice alone turns it on+ or off, and choosing one moves text that would vanish on it. An older free+ colour stays shown while the project carries it. */}+ <div className={styles.sectionLabel}>{t("captions.background")}</div>+ <div style={{ margin: "0 var(--sp-4) 10px" }}>+ <ChoiceRow<CaptionPlate | "custom">+ label={t("captions.background")}+ disabled={disabled}+ options={[+ { value: "none", label: t("textPlate.none") },+ { value: "dark", label: t("textPlate.dark") },+ { value: "light", label: t("textPlate.light") },+ ...(plate === "custom"+ ? [{ value: "custom" as const, label: t("textPlate.custom") }]+ : []),+ ]}+ value={plate}+ onChange={(next) => {+ if (next !== "custom") void set(captionPlatePatch(settings, next));+ }}+ />+ </div>+ {settings.backgroundEnabled ? (+ <div className={styles.sliderGrid}>+ <SliderCell+ label={t("captions.backgroundOpacity")}+ value={Math.round(settings.backgroundOpacity * 100)}+ min={CAPTION_PLATE_OPACITY_MIN * 100}+ max={CAPTION_PLATE_OPACITY_MAX * 100}+ defaultValue={Math.round(DEFAULT_CAPTION_SETTINGS.backgroundOpacity * 100)}+ suffix="%"+ disabled={disabled}+ onChange={(v) => setLive({ backgroundOpacity: v / 100 })}+ onCommit={() => void commit()}+ />+ </div>+ ) : null}+ </details>{/* ── Placement ──────────────────────────────────────────── */}{/* One control per axis, each naming the edge it measures from. The old pane@@ -620,6 +661,8 @@ const WORD_COUNTS = Array.from((_, i) => i + CAPTION_WORDS_PER_LINE_MIN,);+const CAPTION_STYLE_IDS = Object.keys(CAPTION_STYLES) as CaptionStyleId[];+const selectStyle: React.CSSProperties = {height: 32,padding: "0 10px",diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 9898dad43..53e41e728 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -778,30 +778,39 @@ function TranscriptLaneSwitch({* input, no OS dialog. That is the trap `useWallpaperFileInput` documents above, and* it is worth re-checking if a picker is ever added to captions.*/-function CaptionSettingsButton() {+function CaptionSettingsButton({ onShowCaptions }: { onShowCaptions?: () => void }) {const ts = useScopedT("settings");const [open, setOpen] = useState(false);return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <button type="button" className={styles.paneHeadBtn} aria-expanded={open}>- <CaptionsIcon size={14} />- {ts("facets.captions")}+ <>+ {/* Captions are off by default: once there is speech to caption, offer them where+ the transcript is, rather than leaving them behind the settings popover. */}+ {onShowCaptions ? (+ <button type="button" className={styles.paneHeadBtn} onClick={onShowCaptions}>+ {ts("captions.turnOn")}</button>- </PopoverTrigger>- <PopoverContent- align="end"- side="bottom"- sideOffset={8}- collisionPadding={16}- animated={false}- className="w-auto border-0 bg-transparent p-0 shadow-none z-50"- >- <div className={styles.captionsPopover}>- <CaptionsPane onClose={() => setOpen(false)} />- </div>- </PopoverContent>- </Popover>+ ) : null}+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button type="button" className={styles.paneHeadBtn} aria-expanded={open}>+ <CaptionsIcon size={14} />+ {ts("facets.captions")}+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ side="bottom"+ sideOffset={8}+ collisionPadding={16}+ animated={false}+ className="w-auto border-0 bg-transparent p-0 shadow-none z-50"+ >+ <div className={styles.captionsPopover}>+ <CaptionsPane onClose={() => setOpen(false)} />+ </div>+ </PopoverContent>+ </Popover>+ </>);}@@ -991,12 +1000,21 @@ export function TranscriptPane({);}+ const hasSpeech = sections.some((section) => (section.transcript?.segments.length ?? 0) > 0);return (<Panetitle={ts("transcript.title")}icon={<FileText size={16} />}helpText={helpText}- actions={<CaptionSettingsButton />}+ actions={+ <CaptionSettingsButton+ onShowCaptions={+ hasSpeech && !captionSettings.enabled+ ? () => void setCaptionSettings({ enabled: true })+ : undefined+ }+ />+ }>{laneSwitch}{/* The gestures are invisible until tried: nothing on a plain word stream saysdiff --git a/src/components/ai-edition/TextColorField.test.tsx b/src/components/ai-edition/TextColorField.test.tsxnew file mode 100644index 000000000..e9119068c--- /dev/null+++ b/src/components/ai-edition/TextColorField.test.tsx@@ -0,0 +1,39 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@/contexts/I18nContext";+import { TextColorField } from "./TextColorField";++afterEach(cleanup);++function renderOn(plate: string, onChange = vi.fn()) {+ render(+ <I18nProvider>+ <TextColorField label="Text colour" value="#ffffff" plate={plate} onChange={onChange} />+ </I18nProvider>,+ );+ return onChange;+}++const swatch = (color: string) => screen.queryByTitle(color);++describe("TextColorField", () => {+ it("offers only the palette colours that read on a dark plate", () => {+ renderOn("rgba(0, 0, 0, 0.7)");+ expect(swatch("#ffffff")).toBeInTheDocument();+ expect(swatch("#111111")).not.toBeInTheDocument();+ });++ it("offers the whole palette when there is no plate", () => {+ renderOn("transparent");+ expect(swatch("#ffffff")).toBeInTheDocument();+ expect(swatch("#111111")).toBeInTheDocument();+ });++ it("applies a swatch on click", () => {+ const onChange = renderOn("rgba(255, 255, 255, 0.85)");+ fireEvent.click(swatch("#1d4ed8") as HTMLElement);+ expect(onChange).toHaveBeenCalledWith("#1d4ed8");+ });+});diff --git a/src/components/ai-edition/TextColorField.tsx b/src/components/ai-edition/TextColorField.tsxnew file mode 100644index 000000000..fd326fde1--- /dev/null+++ b/src/components/ai-edition/TextColorField.tsx@@ -0,0 +1,67 @@+import { useScopedT } from "@/contexts/I18nContext";+import { paletteFor, readableText } from "@/lib/ai-edition/textContrast";+import { ColorField } from "./ColorField";++/**+ * The colour of text that sits on a plate: the palette entries that read on that plate first,+ * the free wheel last, folded behind its swatch. A pair under 4.5:1 is never offered, and a+ * wheel colour that would vanish on the plate is pushed just far enough toward white or black.+ */+export function TextColorField({+ value,+ plate,+ label,+ disabled,+ onChange,+ onCommit,+}: {+ value: string;+ /** The plate behind the text, as CSS; `"transparent"` when there is none. */+ plate: string;+ label: string;+ disabled?: boolean;+ onChange: (next: string) => void;+ onCommit?: () => void;+}) {+ const te = useScopedT("editor");+ const palette = paletteFor(plate);+ return (+ <div role="group" aria-label={label} style={{ display: "flex", alignItems: "center", gap: 6 }}>+ {palette.map((color) => {+ const active = value.toLowerCase() === color;+ return (+ <button+ key={color}+ type="button"+ title={color}+ aria-label={te("inspector.setColor", { color })}+ aria-pressed={active}+ disabled={disabled}+ onClick={() => {+ onChange(color);+ onCommit?.();+ }}+ style={{+ width: 22,+ height: 22,+ padding: 0,+ borderRadius: 999,+ background: color,+ border: active ? "2px solid var(--accent)" : "1px solid var(--border-hi)",+ cursor: disabled ? "default" : "pointer",+ opacity: disabled ? 0.5 : 1,+ }}+ />+ );+ })}+ <ColorField+ label={label}+ value={value}+ disabled={disabled}+ presets={palette}+ onChange={(next) => onChange(readableText(next, plate))}+ onCommit={onCommit}+ />+ </div>+ );+}diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsxindex 8878fcd19..9faa264f2 100644--- a/src/components/ai-edition/v4/FloatingInspector.tsx+++ b/src/components/ai-edition/v4/FloatingInspector.tsx@@ -42,12 +42,7 @@ import {type ZoomDepth,} from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";-import {- hasTextBackground,- setTextBackgroundColor,- textBackgroundColor,- toggleTextBackground,-} from "@/lib/ai-edition/annotations/background";+import { setTextPlate, type TextPlate, textPlateOf } from "@/lib/ai-edition/annotations/background";import {type AnnotationTextAnimation,TEXT_ANIMATION_VALUES,@@ -74,6 +69,7 @@ import {TranscriptPane,VideoEffectsPane,} from "../RightPanes";+import { TextColorField } from "../TextColorField";import styles from "./EditorShellV4.module.css";type TimelineApi = ReturnType<typeof useTimeline>;@@ -948,7 +944,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }if (selection.kind === "annotation") {const region = tl.annotationRegions.find((a) => a.id === selection.id);if (!region) return null;- const hasBackground = hasTextBackground(region.style);+ const plate = textPlateOf(region.style);return (<div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>{paneHeader(@@ -1168,34 +1164,47 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }): null}{region.type === "text"- ? paneRow(+ ? paneStack(ts("annotation.background"),- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>- {/* La pastille montre la couleur mémorisée même fond éteint : c'est celle que- le rallumage rendra, et un noir affiché à la place mentirait. Choisir une- couleur allume le fond, sinon le sélecteur n'aurait aucun effet visible. */}- <ColorField- label={ts("annotation.background")}- value={textBackgroundColor(region.style)}- onChange={(next) =>- liveUpdate(region.id, {- style: setTextBackgroundColor(region.style, next),- })- }- onCommit={commitAnnotation}- />- {/* Une bascule plutôt qu'un bouton « effacer » : avoir un fond ou non est un- état, pas une action. La pilule des panneaux, pas une case système. */}- <Toggle- checked={hasBackground}- onChange={(next) => {- tl.updateAnnotationLive(region.id, {- style: toggleTextBackground(region.style, next),- });- void tl.commitAnnotationChange();- }}- />- </div>,+ // Trois plaques nommées : la plaque porte seule l'état allumé/éteint, et en+ // choisir une ajuste un texte qui y deviendrait illisible. Une couleur libre+ // d'un projet plus ancien reste montrée tant qu'elle est là, comme le tracé+ // libre du flou.+ <ChoiceRow<TextPlate | "custom">+ label={ts("annotation.background")}+ options={[+ { value: "none", label: ts("textPlate.none") },+ { value: "dark", label: ts("textPlate.dark") },+ { value: "light", label: ts("textPlate.light") },+ ...(plate === "custom"+ ? [{ value: "custom" as const, label: ts("textPlate.custom") }]+ : []),+ ]}+ value={plate}+ onChange={(next) => {+ if (next === "custom") return;+ tl.updateAnnotationLive(region.id, {+ style: setTextPlate(region.style, next),+ });+ void tl.commitAnnotationChange();+ }}+ />,+ )+ : null}+ {region.type === "text"+ ? paneStack(+ ts("annotation.color"),+ <TextColorField+ label={ts("annotation.color")}+ value={region.style?.color ?? "#ffffff"}+ plate={region.style?.backgroundColor ?? "transparent"}+ onChange={(next) =>+ liveUpdate(region.id, {+ style: { ...region.style, color: next },+ })+ }+ onCommit={commitAnnotation}+ />,): null}{region.type === "text"@@ -1221,21 +1230,6 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }/>,): null}- {region.type === "text"- ? paneRow(- ts("annotation.color"),- <ColorField- label={ts("annotation.color")}- value={region.style?.color ?? "#ffffff"}- onChange={(next) =>- liveUpdate(region.id, {- style: { ...region.style, color: next },- })- }- onCommit={commitAnnotation}- />,- )- : null}<button type="button" onClick={deleteAndClose} className={PANE_BUTTON}><Trash2 size={16} style={{ color: "var(--danger)" }} />{ts("annotation.deleteAnnotation")}diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex fdfc06d22..5c8c6ba03 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -240,7 +240,16 @@"font": "الخط","translating": "جارٍ الترجمة…","show": "إظهار الترجمة",- "textColor": "لون النص"+ "textColor": "لون النص",+ "style": "النمط",+ "styles": {+ "classic": "كلاسيكي",+ "bold": "عريض",+ "minimal": "بسيط",+ "light": "فاتح"+ },+ "customize": "تخصيص",+ "turnOn": "إظهار الترجمة"},"panes": {"help": "مساعدة"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "حذف منطقة القص"+ },+ "textPlate": {+ "none": "بلا",+ "dark": "داكنة",+ "light": "فاتحة",+ "custom": "مخصصة"}}diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.jsonindex a0ba401c0..08402026e 100644--- a/src/i18n/locales/cs/settings.json+++ b/src/i18n/locales/cs/settings.json@@ -240,7 +240,16 @@"font": "Písmo","translating": "Překládání…","show": "Zobrazit titulky",- "textColor": "Barva textu"+ "textColor": "Barva textu",+ "style": "Styl",+ "styles": {+ "classic": "Klasický",+ "bold": "Tučný",+ "minimal": "Minimální",+ "light": "Světlý"+ },+ "customize": "Upravit",+ "turnOn": "Zobrazit titulky"},"panes": {"help": "Nápověda"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Smazat oblast oříznutí"+ },+ "textPlate": {+ "none": "Žádný",+ "dark": "Tmavý",+ "light": "Světlý",+ "custom": "Vlastní"}}diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.jsonindex 1d2cd095b..ef7d046cc 100644--- a/src/i18n/locales/de/settings.json+++ b/src/i18n/locales/de/settings.json@@ -240,7 +240,16 @@"font": "Schrift","translating": "Übersetzung läuft…","show": "Untertitel anzeigen",- "textColor": "Textfarbe"+ "textColor": "Textfarbe",+ "style": "Stil",+ "styles": {+ "classic": "Klassisch",+ "bold": "Fett",+ "minimal": "Minimal",+ "light": "Hell"+ },+ "customize": "Anpassen",+ "turnOn": "Untertitel anzeigen"},"panes": {"help": "Hilfe"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Trim-Bereich löschen"+ },+ "textPlate": {+ "none": "Keine",+ "dark": "Dunkel",+ "light": "Hell",+ "custom": "Eigene"}}diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex 553a7a000..a64ce3691 100644--- a/src/i18n/locales/en/settings.json+++ b/src/i18n/locales/en/settings.json@@ -240,7 +240,16 @@"font": "Font","translating": "Translating…","show": "Show captions",- "textColor": "Text color"+ "textColor": "Text color",+ "style": "Style",+ "styles": {+ "classic": "Classic",+ "bold": "Bold",+ "minimal": "Minimal",+ "light": "Light"+ },+ "customize": "Customize",+ "turnOn": "Show captions"},"panes": {"help": "Help"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Delete Trim Region"+ },+ "textPlate": {+ "none": "None",+ "dark": "Dark",+ "light": "Light",+ "custom": "Custom"}}diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex b38f75eac..1853c6764 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -240,7 +240,16 @@"font": "Fuente","translating": "Traduciendo…","show": "Mostrar subtítulos",- "textColor": "Color del texto"+ "textColor": "Color del texto",+ "style": "Estilo",+ "styles": {+ "classic": "Clásico",+ "bold": "Negrita",+ "minimal": "Minimalista",+ "light": "Claro"+ },+ "customize": "Personalizar",+ "turnOn": "Mostrar subtítulos"},"panes": {"help": "Ayuda"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Eliminar región de recorte"+ },+ "textPlate": {+ "none": "Ninguna",+ "dark": "Oscura",+ "light": "Clara",+ "custom": "Personalizada"}}diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.jsonindex 4b414ed75..d69ca4764 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -240,7 +240,16 @@"font": "Police","translating": "Traduction…","show": "Afficher les sous-titres",- "textColor": "Couleur du texte"+ "textColor": "Couleur du texte",+ "style": "Style",+ "styles": {+ "classic": "Classique",+ "bold": "Gras",+ "minimal": "Minimal",+ "light": "Clair"+ },+ "customize": "Personnaliser",+ "turnOn": "Afficher les sous-titres"},"panes": {"help": "Aide"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Supprimer la région de coupe"+ },+ "textPlate": {+ "none": "Aucune",+ "dark": "Sombre",+ "light": "Claire",+ "custom": "Personnalisée"}}diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 05fce4a59..d151431a5 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -240,7 +240,16 @@"font": "Carattere","translating": "Traduzione…","show": "Mostra sottotitoli",- "textColor": "Colore del testo"+ "textColor": "Colore del testo",+ "style": "Stile",+ "styles": {+ "classic": "Classico",+ "bold": "Grassetto",+ "minimal": "Minimale",+ "light": "Chiaro"+ },+ "customize": "Personalizza",+ "turnOn": "Mostra sottotitoli"},"panes": {"help": "Aiuto"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Elimina regione taglio"+ },+ "textPlate": {+ "none": "Nessuna",+ "dark": "Scura",+ "light": "Chiara",+ "custom": "Personalizzata"}}diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.jsonindex 33456679e..5514274b5 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -240,7 +240,16 @@"font": "フォント","translating": "翻訳中…","show": "字幕を表示",- "textColor": "文字色"+ "textColor": "文字色",+ "style": "スタイル",+ "styles": {+ "classic": "クラシック",+ "bold": "太字",+ "minimal": "ミニマル",+ "light": "ライト"+ },+ "customize": "カスタマイズ",+ "turnOn": "字幕を表示"},"panes": {"help": "ヘルプ"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "トリム範囲を削除"+ },+ "textPlate": {+ "none": "なし",+ "dark": "ダーク",+ "light": "ライト",+ "custom": "カスタム"}}diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex f938a625b..db5a8c8cb 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -240,7 +240,16 @@"font": "글꼴","translating": "번역 중…","show": "자막 표시",- "textColor": "글자 색"+ "textColor": "글자 색",+ "style": "스타일",+ "styles": {+ "classic": "클래식",+ "bold": "굵게",+ "minimal": "미니멀",+ "light": "밝게"+ },+ "customize": "사용자 지정",+ "turnOn": "자막 표시"},"panes": {"help": "도움말"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "트림 구간 삭제"+ },+ "textPlate": {+ "none": "없음",+ "dark": "어둡게",+ "light": "밝게",+ "custom": "사용자 지정"}}diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex 1b9c883cc..7d1e5380c 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -240,7 +240,16 @@"font": "Fonte","translating": "Traduzindo…","show": "Mostrar legendas",- "textColor": "Cor do texto"+ "textColor": "Cor do texto",+ "style": "Estilo",+ "styles": {+ "classic": "Clássico",+ "bold": "Negrito",+ "minimal": "Minimalista",+ "light": "Claro"+ },+ "customize": "Personalizar",+ "turnOn": "Mostrar legendas"},"panes": {"help": "Ajuda"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Excluir Região de Recorte"+ },+ "textPlate": {+ "none": "Nenhuma",+ "dark": "Escura",+ "light": "Clara",+ "custom": "Personalizada"}}diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.jsonindex a06902c22..4c8a2b03c 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -240,7 +240,16 @@"font": "Шрифт","translating": "Перевод…","show": "Показывать субтитры",- "textColor": "Цвет текста"+ "textColor": "Цвет текста",+ "style": "Стиль",+ "styles": {+ "classic": "Классический",+ "bold": "Жирный",+ "minimal": "Минимальный",+ "light": "Светлый"+ },+ "customize": "Настроить",+ "turnOn": "Показать субтитры"},"panes": {"help": "Справка"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Удалить область обрезки"+ },+ "textPlate": {+ "none": "Нет",+ "dark": "Тёмная",+ "light": "Светлая",+ "custom": "Своя"}}diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex 2c42629d0..9e2b17e0d 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -240,7 +240,16 @@"font": "Yazı tipi","translating": "Çevriliyor…","show": "Altyazıları göster",- "textColor": "Metin rengi"+ "textColor": "Metin rengi",+ "style": "Stil",+ "styles": {+ "classic": "Klasik",+ "bold": "Kalın",+ "minimal": "Minimal",+ "light": "Açık"+ },+ "customize": "Özelleştir",+ "turnOn": "Altyazıları göster"},"panes": {"help": "Yardım"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Kırpma Bölgesini Sil"+ },+ "textPlate": {+ "none": "Yok",+ "dark": "Koyu",+ "light": "Açık",+ "custom": "Özel"}}diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 33ba830b5..e182f5e7b 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -240,7 +240,16 @@"font": "Phông chữ","translating": "Đang dịch…","show": "Hiện phụ đề",- "textColor": "Màu chữ"+ "textColor": "Màu chữ",+ "style": "Kiểu",+ "styles": {+ "classic": "Cổ điển",+ "bold": "Đậm",+ "minimal": "Tối giản",+ "light": "Sáng"+ },+ "customize": "Tùy chỉnh",+ "turnOn": "Hiện phụ đề"},"panes": {"help": "Trợ giúp"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "Xóa vùng cắt"+ },+ "textPlate": {+ "none": "Không",+ "dark": "Tối",+ "light": "Sáng",+ "custom": "Tùy chỉnh"}}diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.jsonindex 80db1f9f7..a15a1db89 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -240,7 +240,16 @@"font": "字体","translating": "翻译中…","show": "显示字幕",- "textColor": "文字颜色"+ "textColor": "文字颜色",+ "style": "样式",+ "styles": {+ "classic": "经典",+ "bold": "粗体",+ "minimal": "简约",+ "light": "浅色"+ },+ "customize": "自定义",+ "turnOn": "显示字幕"},"panes": {"help": "帮助"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "删除剪辑区域"+ },+ "textPlate": {+ "none": "无",+ "dark": "深色",+ "light": "浅色",+ "custom": "自定义"}}diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex 233c5cb93..57dba7ff1 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -240,7 +240,16 @@"font": "字型","translating": "翻譯中…","show": "顯示字幕",- "textColor": "文字顏色"+ "textColor": "文字顏色",+ "style": "樣式",+ "styles": {+ "classic": "經典",+ "bold": "粗體",+ "minimal": "簡約",+ "light": "淺色"+ },+ "customize": "自訂",+ "turnOn": "顯示字幕"},"panes": {"help": "說明"@@ -438,5 +447,11 @@},"trim": {"deleteRegion": "刪除剪輯區域"+ },+ "textPlate": {+ "none": "無",+ "dark": "深色",+ "light": "淺色",+ "custom": "自訂"}}diff --git a/src/lib/ai-edition/annotations/background.test.ts b/src/lib/ai-edition/annotations/background.test.tsindex cd0f07199..38685f245 100644--- a/src/lib/ai-edition/annotations/background.test.ts+++ b/src/lib/ai-edition/annotations/background.test.ts@@ -5,7 +5,10 @@ import {DEFAULT_TEXT_BACKGROUND,hasTextBackground,setTextBackgroundColor,+ setTextPlate,+ TEXT_PLATES,textBackgroundColor,+ textPlateOf,toggleTextBackground,} from "./background";@@ -73,3 +76,23 @@ describe("text background", () => {expect(toggled.fontSize).toBe(48);});});++describe("named text plates", () => {+ it("names the three plates and keeps an older free colour as custom", () => {+ expect(textPlateOf(styleWith({ backgroundColor: "transparent" }))).toBe("none");+ expect(textPlateOf(styleWith({ backgroundColor: TEXT_PLATES.dark }))).toBe("dark");+ expect(textPlateOf(styleWith({ backgroundColor: "rgba(0,0,0,0.7)" }))).toBe("dark");+ expect(textPlateOf(styleWith({ backgroundColor: TEXT_PLATES.light }))).toBe("light");+ expect(textPlateOf(styleWith({ backgroundColor: "#3b82f6" }))).toBe("custom");+ });++ it("choosing a plate adjusts text that would vanish on it, and keeps text that reads", () => {+ const white = styleWith({ color: "#ffffff", backgroundColor: "transparent" });+ expect(setTextPlate(white, "light")).toMatchObject({+ backgroundColor: TEXT_PLATES.light,+ color: "#111111",+ });+ expect(setTextPlate(white, "dark").color).toBe("#ffffff");+ expect(setTextPlate(white, "none").backgroundColor).toBe("transparent");+ });+});diff --git a/src/lib/ai-edition/annotations/background.ts b/src/lib/ai-edition/annotations/background.tsindex b6acb11af..ade92d56c 100644--- a/src/lib/ai-edition/annotations/background.ts+++ b/src/lib/ai-edition/annotations/background.ts@@ -7,6 +7,7 @@// réversible sans donner un second sens à `backgroundColor`.import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";+import { textForPlate } from "@/lib/ai-edition/textContrast";type AnnotationStyle = AxcutAnnotationRegion["style"];@@ -45,3 +46,41 @@ export function toggleTextBackground(style: AnnotationStyle, next: boolean): Annexport function setTextBackgroundColor(style: AnnotationStyle, color: string): AnnotationStyle {return { ...style, backgroundColor: color, lastBackgroundColor: color };}++/**+ * Les plaques nommées d'une annotation : aucune, sombre, claire. Trois états qu'on voit, au lieu+ * d'une roue qui laissait choisir une plaque de la couleur même du texte. `rgba()` et non un hex+ * à 8 chiffres, la forme que lit le compositeur (`parse_hex`). La sombre est celle que #793 donne+ * à toute annotation neuve.+ */+export const TEXT_PLATES = {+ none: "transparent",+ dark: "rgba(0, 0, 0, 0.7)",+ light: "rgba(255, 255, 255, 0.85)",+} as const;++export type TextPlate = keyof typeof TEXT_PLATES;++const compact = (css: string) => css.replace(/\s+/g, "").toLowerCase();++/**+ * La plaque nommée que porte ce style, ou `"custom"` pour une couleur libre d'un projet plus+ * ancien : elle s'ouvre inchangée, et le choix reste montré tant qu'elle est là.+ */+export function textPlateOf(style: AnnotationStyle): TextPlate | "custom" {+ if (!hasTextBackground(style)) return "none";+ const color = compact(style.backgroundColor);+ if (color === compact(TEXT_PLATES.dark)) return "dark";+ if (color === compact(TEXT_PLATES.light)) return "light";+ return "custom";+}++/** Style résultant du choix d'une plaque : un texte devenu illisible dessus change avec elle. */+export function setTextPlate(style: AnnotationStyle, plate: TextPlate): AnnotationStyle {+ const backgroundColor = TEXT_PLATES[plate];+ return {+ ...style,+ backgroundColor,+ color: textForPlate(style.color ?? "#ffffff", backgroundColor),+ };+}diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.tsindex d487078d5..86d0ea2a5 100644--- a/src/lib/ai-edition/captions/captions.test.ts+++ b/src/lib/ai-edition/captions/captions.test.ts@@ -1,12 +1,19 @@import { describe, expect, it } from "vitest";import { insertGeneratedClip } from "../document/insertion";import type { AxcutDocument, AxcutTranscript } from "../schema";+import { contrastRatio, MIN_TEXT_CONTRAST } from "../textContrast";import { captionCuesToTextRegions, deriveCaptionCues } from "./cues";import type { CaptionSettings } from "./settings";import {+ CAPTION_PLATE_OPACITY_MAX,+ CAPTION_PLATE_OPACITY_MIN,+ CAPTION_STYLES,captionBackgroundCss,captionBoxRect,+ captionPlateOf,+ captionPlatePatch,captionSafeColumn,+ captionStyleOf,DEFAULT_CAPTION_SETTINGS,defaultCaptionInsetX,defaultCaptionInsetY,@@ -159,6 +166,57 @@ describe("caption settings", () => {});});+describe("caption styles and plates", () => {+ const stored = (captions: Record<string, unknown>) =>+ getCaptionSettings(doc({ legacyEditor: { captions } } as Partial<AxcutDocument>));++ it("opens a fresh project on the Classic style", () => {+ expect(captionStyleOf(getCaptionSettings(doc()))).toBe("classic");+ });++ it("names a style only while every look field still matches it", () => {+ expect(captionStyleOf({ ...ON, ...CAPTION_STYLES.bold })).toBe("bold");+ expect(captionStyleOf({ ...ON, ...CAPTION_STYLES.bold, fontSize: 61 })).toBeNull();+ });++ it("every named style is a readable pair within the opacity bounds", () => {+ for (const look of Object.values(CAPTION_STYLES)) {+ expect(contrastRatio(look.color, look.backgroundColor)).toBeGreaterThanOrEqual(+ MIN_TEXT_CONTRAST,+ );+ expect(look.backgroundOpacity).toBeGreaterThanOrEqual(CAPTION_PLATE_OPACITY_MIN);+ expect(look.backgroundOpacity).toBeLessThanOrEqual(CAPTION_PLATE_OPACITY_MAX);+ }+ });++ it("choosing a plate turns it on and moves text that would vanish on it", () => {+ const off = { ...ON, backgroundEnabled: false, color: "#ffffff" };+ expect(captionPlatePatch(off, "light")).toEqual({+ backgroundEnabled: true,+ backgroundColor: "#ffffff",+ color: "#111111",+ });+ expect(captionPlatePatch(ON, "none")).toEqual({ backgroundEnabled: false });+ expect(captionPlateOf({ ...ON, backgroundColor: "#16171d" })).toBe("custom");+ });++ it("reads a stored opacity into the bounded range, a near-zero one as no plate", () => {+ expect(stored({ backgroundEnabled: true, backgroundOpacity: 0 })).toMatchObject({+ backgroundEnabled: false,+ });+ expect(stored({ backgroundEnabled: true, backgroundOpacity: 0.25 }).backgroundOpacity).toBe(+ 0.4,+ );+ expect(stored({ backgroundEnabled: true, backgroundOpacity: 1 }).backgroundOpacity).toBe(0.9);+ expect(stored({ backgroundEnabled: true, backgroundOpacity: 0.7 }).backgroundOpacity).toBe(0.7);+ });++ it("keeps a patched opacity inside the bounds", () => {+ const next = patchCaptionSettings(doc(), { backgroundOpacity: 0.1 });+ expect(getCaptionSettings(next).backgroundOpacity).toBe(CAPTION_PLATE_OPACITY_MIN);+ });+});+describe("caption anchoring", () => {// THE invariant of the redesign, asserted as a property rather than as numbers.// The old model placed a fixed 22% band and let each renderer centre the ink in it,diff --git a/src/lib/ai-edition/captions/index.ts b/src/lib/ai-edition/captions/index.tsindex f827d62c0..2db6a320c 100644--- a/src/lib/ai-edition/captions/index.ts+++ b/src/lib/ai-edition/captions/index.ts@@ -11,15 +11,23 @@ export type {CaptionAnchorH,CaptionAnchorV,CaptionBoxRect,+ CaptionPlate,CaptionSettings,CaptionSettingsPatch,+ CaptionStyleId,} from "./settings";export {CAPTION_INSET_X_MAX,CAPTION_INSET_Y_MAX,+ CAPTION_PLATE_OPACITY_MAX,+ CAPTION_PLATE_OPACITY_MIN,+ CAPTION_STYLES,captionBackgroundCss,captionBoxRect,+ captionPlateOf,+ captionPlatePatch,captionSafeColumn,+ captionStyleOf,DEFAULT_CAPTION_SETTINGS,defaultCaptionInsetX,defaultCaptionInsetY,diff --git a/src/lib/ai-edition/captions/settings.ts b/src/lib/ai-edition/captions/settings.tsindex 31119b25a..3ab6fcb91 100644--- a/src/lib/ai-edition/captions/settings.ts+++ b/src/lib/ai-edition/captions/settings.ts@@ -12,6 +12,7 @@import { DEFAULT_TEXT_FONT_FAMILY, resolveTextFontFamily } from "@/lib/textFonts";import { clamp } from "@/utils/math";import type { AxcutDocument } from "../schema";+import { textForPlate } from "../textContrast";import { type TranscriptLane, voiceoverPlacements } from "../timeline/aggregated-transcript";import { CAPTION_WORDS_PER_LINE_MAX, CAPTION_WORDS_PER_LINE_MIN } from "./wordsPerLine";@@ -125,6 +126,133 @@ export const DEFAULT_CAPTION_SETTINGS: CaptionSettings = {maxWordsPerLine: 7,};+/**+ * Plate opacity bounds. The on/off state belongs to the plate choice alone: an opacity+ * that reached 0 was a second way to switch the plate off, and one past 90% hid the plate's+ * edge against a dark frame for no gain in legibility.+ */+export const CAPTION_PLATE_OPACITY_MIN = 0.4;+export const CAPTION_PLATE_OPACITY_MAX = 0.9;++/** The named caption plates. Colour only: the opacity is its own bounded slider. */+export const CAPTION_PLATES = { dark: "#000000", light: "#ffffff" } as const;++export type CaptionPlate = "none" | keyof typeof CAPTION_PLATES;++/** The named plate these settings carry, or `"custom"` for an older free colour. */+export function captionPlateOf(settings: CaptionSettings): CaptionPlate | "custom" {+ if (!settings.backgroundEnabled) return "none";+ const color = settings.backgroundColor.toLowerCase();+ if (color === CAPTION_PLATES.dark) return "dark";+ if (color === CAPTION_PLATES.light) return "light";+ return "custom";+}++/** Choosing a plate turns it on (or off), and moves text that would vanish on it. */+export function captionPlatePatch(+ settings: CaptionSettings,+ plate: CaptionPlate,+): CaptionSettingsPatch {+ if (plate === "none") return { backgroundEnabled: false };+ const backgroundColor = CAPTION_PLATES[plate];+ return {+ backgroundEnabled: true,+ backgroundColor,+ color: textForPlate(settings.color, backgroundColor),+ };+}++/** The look fields a named style sets together. Placement and line length are not look. */+type CaptionLook = Pick<+ CaptionSettings,+ | "fontFamily"+ | "fontWeight"+ | "fontSize"+ | "color"+ | "backgroundEnabled"+ | "backgroundColor"+ | "backgroundOpacity"+>;++/**+ * Named caption styles, first in the pane. Each is a readable pair by construction (the+ * test asserts it); the detailed controls below them stay available for everything else.+ * Classic is the default look, so a fresh project opens with it selected.+ */+export const CAPTION_STYLES = {+ classic: {+ fontFamily: "Inter",+ fontWeight: "bold",+ fontSize: 48,+ color: "#ffffff",+ backgroundEnabled: true,+ backgroundColor: CAPTION_PLATES.dark,+ backgroundOpacity: 0.55,+ },+ bold: {+ fontFamily: "Oswald",+ fontWeight: "bold",+ fontSize: 60,+ color: "#fde047",+ backgroundEnabled: true,+ backgroundColor: CAPTION_PLATES.dark,+ backgroundOpacity: 0.85,+ },+ minimal: {+ fontFamily: "Inter",+ fontWeight: "normal",+ fontSize: 40,+ color: "#ffffff",+ backgroundEnabled: true,+ backgroundColor: CAPTION_PLATES.dark,+ backgroundOpacity: 0.4,+ },+ light: {+ fontFamily: "Inter",+ fontWeight: "bold",+ fontSize: 48,+ color: "#111111",+ backgroundEnabled: true,+ backgroundColor: CAPTION_PLATES.light,+ backgroundOpacity: 0.9,+ },+} as const satisfies Record<string, CaptionLook>;++export type CaptionStyleId = keyof typeof CAPTION_STYLES;++/** The named style these settings match exactly, or `null` once anything was tuned. */+export function captionStyleOf(settings: CaptionSettings): CaptionStyleId | null {+ for (const [id, look] of Object.entries(CAPTION_STYLES) as [CaptionStyleId, CaptionLook][]) {+ const matches = (Object.keys(look) as (keyof CaptionLook)[]).every((key) =>+ typeof look[key] === "string"+ ? String(settings[key]).toLowerCase() === String(look[key]).toLowerCase()+ : settings[key] === look[key],+ );+ if (matches) return id;+ }+ return null;+}++/**+ * A stored opacity read into the bounded range. Below 20% the plate was all but invisible,+ * which is what "off" draws; between 20 and 40% the nearest valid value is 40%.+ */+function readPlate(+ enabled: boolean,+ opacity: number,+): Pick<CaptionSettings, "backgroundEnabled" | "backgroundOpacity"> {+ if (enabled && opacity < 0.2) {+ return {+ backgroundEnabled: false,+ backgroundOpacity: DEFAULT_CAPTION_SETTINGS.backgroundOpacity,+ };+ }+ return {+ backgroundEnabled: enabled,+ backgroundOpacity: clamp(opacity, CAPTION_PLATE_OPACITY_MIN, CAPTION_PLATE_OPACITY_MAX),+ };+}+/** Reference frame height the px-valued settings are authored against, matching* `annotationScale.ts` — `fontSize` is "pixels at a 1080-high frame". */const CAPTION_REFERENCE_FRAME_HEIGHT = 1080;@@ -453,7 +581,11 @@ export function getCaptionSettings(),);const fontSize = readNumber(raw.fontSize, d.fontSize, 12, 200);- const backgroundEnabled = readBoolean(raw.backgroundEnabled, d.backgroundEnabled);+ const plate = readPlate(+ readBoolean(raw.backgroundEnabled, d.backgroundEnabled),+ readNumber(raw.backgroundOpacity, d.backgroundOpacity, 0, 1),+ );+ const { backgroundEnabled } = plate;// New fields win whenever they are present, so the migration runs once and is inert// afterwards; it only speaks for a document that still carries the old ones.@@ -484,9 +616,8 @@ export function getCaptionSettings(fontFamily: resolveTextFontFamily(raw.fontFamily),fontWeight: readEnum(raw.fontWeight, ["normal", "bold"] as const, d.fontWeight),color: readString(raw.color, d.color),- backgroundEnabled,+ ...plate,backgroundColor: readString(raw.backgroundColor, d.backgroundColor),- backgroundOpacity: readNumber(raw.backgroundOpacity, d.backgroundOpacity, 0, 1),...placement,minWordsPerLine: Math.min(minWords, maxWords),maxWordsPerLine: Math.max(minWords, maxWords),@@ -536,6 +667,11 @@ export function patchCaptionSettings(const next: CaptionSettings = { ...getCaptionSettings(doc, aspectValue), ...patch };next.insetY = clamp(next.insetY, 0, CAPTION_INSET_Y_MAX);next.insetX = clamp(next.insetX, 0, CAPTION_INSET_X_MAX);+ next.backgroundOpacity = clamp(+ next.backgroundOpacity,+ CAPTION_PLATE_OPACITY_MIN,+ CAPTION_PLATE_OPACITY_MAX,+ );return {...doc,legacyEditor: {diff --git a/src/lib/ai-edition/textContrast.test.ts b/src/lib/ai-edition/textContrast.test.tsnew file mode 100644index 000000000..9bb5b9ffc--- /dev/null+++ b/src/lib/ai-edition/textContrast.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import {+ contrastRatio,+ isReadableOn,+ MIN_TEXT_CONTRAST,+ paletteFor,+ parseRgb,+ readableText,+ TEXT_PALETTE,+ textForPlate,+} from "./textContrast";++const DARK = "rgba(0, 0, 0, 0.7)";+const LIGHT = "rgba(255, 255, 255, 0.85)";++describe("text contrast", () => {+ it("reads the forms the compositor parses", () => {+ expect(parseRgb("#fff")).toEqual({ r: 255, g: 255, b: 255 });+ expect(parseRgb("#1d4ed8")).toEqual({ r: 29, g: 78, b: 216 });+ expect(parseRgb("rgba(0, 0, 0, 0.7)")).toEqual({ r: 0, g: 0, b: 0 });+ expect(parseRgb("transparent")).toBeNull();+ });++ it("matches the WCAG reference ratios", () => {+ expect(contrastRatio("#ffffff", "#000000")).toBeCloseTo(21, 5);+ expect(contrastRatio("#777777", "#ffffff")).toBeCloseTo(4.48, 2);+ });++ it("offers four palette colours on each plate and all eight without one", () => {+ expect(paletteFor(DARK)).toHaveLength(4);+ expect(paletteFor(LIGHT)).toHaveLength(4);+ expect(paletteFor("transparent")).toEqual([...TEXT_PALETTE]);+ });++ it("never offers text the colour of its plate", () => {+ for (const plate of [DARK, LIGHT, "#000000", "#ffffff"]) {+ for (const c of paletteFor(plate)) {+ expect(contrastRatio(c, plate)).toBeGreaterThanOrEqual(MIN_TEXT_CONTRAST);+ }+ }+ });++ it("keeps readable text and swaps unreadable text when the plate changes", () => {+ expect(textForPlate("#fde047", DARK)).toBe("#fde047");+ expect(textForPlate("#ffffff", LIGHT)).toBe("#111111");+ expect(textForPlate("#111111", DARK)).toBe("#ffffff");+ expect(textForPlate("#111111", "transparent")).toBe("#111111");+ });++ it("pushes a free colour just far enough to read, keeping its hue", () => {+ const fixed = readableText("#3b82f6", DARK);+ expect(isReadableOn(fixed, DARK)).toBe(true);+ expect(fixed).not.toBe("#ffffff");+ expect(isReadableOn(readableText("#3b82f6", LIGHT), LIGHT)).toBe(true);+ expect(readableText("#ffffff", DARK)).toBe("#ffffff");+ });+});diff --git a/src/lib/ai-edition/textContrast.ts b/src/lib/ai-edition/textContrast.tsnew file mode 100644index 000000000..3a2f4a5da--- /dev/null+++ b/src/lib/ai-edition/textContrast.ts@@ -0,0 +1,129 @@+// Text that cannot be made unreadable: a short palette, named plates, and a WCAG contrast+// floor between the two. Shared by annotations and captions, which draw the same thing (text+// on an optional plate) and used to let the text take the plate's own colour in two clicks.++/** WCAG 2 AA for normal text. */+export const MIN_TEXT_CONTRAST = 4.5;++/**+ * The eight text colours offered first: four light ones for a dark plate, four dark ones for+ * a light plate. Without a plate all eight are offered. Hex6, which every renderer parses.+ */+export const TEXT_PALETTE: readonly string[] = [+ "#ffffff",+ "#fde047",+ "#86efac",+ "#7dd3fc",+ "#111111",+ "#1d4ed8",+ "#b91c1c",+ "#166534",+];++interface Rgb {+ r: number;+ g: number;+ b: number;+}++const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;+const RGB_FN = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+\s*)?\)$/i;++/**+ * The forms the compositor's `parse_hex` reads: hex3, hex6, `rgb()` / `rgba()`. The alpha is+ * dropped on purpose, see {@link contrastRatio}. `transparent` and anything else → `null`.+ */+export function parseRgb(value: string): Rgb | null {+ const s = value.trim();+ const fn = RGB_FN.exec(s);+ if (fn) return { r: Number(fn[1]), g: Number(fn[2]), b: Number(fn[3]) };+ const hex = HEX.exec(s)?.[1];+ if (!hex) return null;+ const full = hex.length === 3 ? [...hex].map((c) => c + c).join("") : hex;+ return {+ r: Number.parseInt(full.slice(0, 2), 16),+ g: Number.parseInt(full.slice(2, 4), 16),+ b: Number.parseInt(full.slice(4, 6), 16),+ };+}++function channel(v: number): number {+ const c = v / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+}++/** WCAG relative luminance. */+function luminance({ r, g, b }: Rgb): number {+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++function ratio(a: Rgb, b: Rgb): number {+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);+ return (hi + 0.05) / (lo + 0.05);+}++/**+ * Contrast between a text colour and its plate, or `null` when there is no plate to measure+ * against (`transparent`, unparseable).+ *+ * ponytail: measured against the plate's opaque colour. What shows through a translucent+ * plate is the video, which nothing here knows; compositing over a sampled frame is the+ * upgrade if a 40% plate over a white page ever proves too weak.+ */+export function contrastRatio(text: string, plate: string): number | null {+ const fg = parseRgb(text);+ const bg = parseRgb(plate);+ return fg && bg ? ratio(fg, bg) : null;+}++/** True when the pair reads, or when there is no plate to read against. */+export function isReadableOn(text: string, plate: string): boolean {+ const r = contrastRatio(text, plate);+ return r === null || r >= MIN_TEXT_CONTRAST;+}++/** The palette entries that read on this plate: all of them without a plate. */+export function paletteFor(plate: string): string[] {+ return TEXT_PALETTE.filter((c) => isReadableOn(c, plate));+}++/**+ * The text colour to keep when the plate changes: the current one if it still reads, else+ * the palette colour with the most contrast on the new plate. Choosing a plate never leaves+ * text the colour of its plate.+ */+export function textForPlate(text: string, plate: string): string {+ if (isReadableOn(text, plate)) return text;+ const bg = parseRgb(plate);+ if (!bg) return text;+ return [...TEXT_PALETTE].sort(+ (a, b) => ratio(parseRgb(b) as Rgb, bg) - ratio(parseRgb(a) as Rgb, bg),+ )[0];+}++const toHex = ({ r, g, b }: Rgb) =>+ `#${[r, g, b].map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;++/**+ * A free colour, pushed just far enough toward white or black to read on the plate. Used on+ * the wheel, where the user asked for a hue: keep the hue, fix the lightness.+ */+export function readableText(text: string, plate: string): string {+ if (isReadableOn(text, plate)) return text;+ const fg = parseRgb(text);+ const bg = parseRgb(plate);+ if (!fg || !bg) return text;+ const white = { r: 255, g: 255, b: 255 };+ const black = { r: 0, g: 0, b: 0 };+ const pole = ratio(white, bg) >= ratio(black, bg) ? white : black;+ for (let t = 0.05; t < 1; t += 0.05) {+ const mixed = {+ r: fg.r + (pole.r - fg.r) * t,+ g: fg.g + (pole.g - fg.g) * t,+ b: fg.b + (pole.b - fg.b) * t,+ };+ const hex = toHex(mixed);+ if (isReadableOn(hex, plate)) return hex;+ }+ return toHex(pole);+}