Skip to content

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

fix(annotations): one standard colour field, a reversible background switch, a pane that scrolls

Etienne Lescot6dab5cadb01b
diff --git a/poc-d3d/src/regions.rs b/poc-d3d/src/regions.rs
index 37155f6ec..ff21a92ea 100644
--- a/poc-d3d/src/regions.rs
+++ b/poc-d3d/src/regions.rs
@@ -233,13 +233,13 @@ pub fn arrow_segments_viewbox(direction: &str) -> [[f32; 4]; 3] {
"up" => [[50.0, 20.0, 50.0, 80.0], [50.0, 20.0, 35.0, 35.0], [50.0, 20.0, 65.0, 35.0]],
"down" => [[50.0, 20.0, 50.0, 80.0], [50.0, 80.0, 35.0, 65.0], [50.0, 80.0, 65.0, 65.0]],
"left" => [[80.0, 50.0, 20.0, 50.0], [20.0, 50.0, 35.0, 35.0], [20.0, 50.0, 35.0, 65.0]],
- "up-right" => [[25.0, 75.0, 75.0, 25.0], [75.0, 25.0, 54.9, 31.7], [75.0, 25.0, 68.3, 45.1]],
- "up-left" => [[75.0, 75.0, 25.0, 25.0], [25.0, 25.0, 45.1, 31.7], [25.0, 25.0, 31.7, 45.1]],
+ "up-right" => [[25.0, 75.0, 75.0, 25.0], [75.0, 25.0, 53.8, 25.0], [75.0, 25.0, 75.0, 46.2]],
+ "up-left" => [[75.0, 75.0, 25.0, 25.0], [25.0, 25.0, 25.0, 46.2], [25.0, 25.0, 46.2, 25.0]],
"down-right" => {
- [[25.0, 25.0, 75.0, 75.0], [75.0, 75.0, 68.3, 54.9], [75.0, 75.0, 54.9, 68.3]]
+ [[25.0, 25.0, 75.0, 75.0], [75.0, 75.0, 75.0, 53.8], [75.0, 75.0, 53.8, 75.0]]
}
"down-left" => {
- [[75.0, 25.0, 25.0, 75.0], [25.0, 75.0, 31.7, 54.9], [25.0, 75.0, 45.1, 68.3]]
+ [[75.0, 25.0, 25.0, 75.0], [25.0, 75.0, 46.2, 75.0], [25.0, 75.0, 25.0, 53.8]]
}
// "right" et tout ce qui n'est pas reconnu — même défaut que le schéma côté app.
_ => [[20.0, 50.0, 80.0, 50.0], [80.0, 50.0, 65.0, 35.0], [80.0, 50.0, 65.0, 65.0]],
@@ -620,6 +620,43 @@ mod zoom_focus_tests {
mod arrow_tests {
use super::*;
+ /// Ouverture d'une barbe par rapport au fût, en degrés. C'est ce paramètre — plus que la
+ /// longueur — qui décide si une pointe ressemble à une flèche ou à un crochet.
+ fn barb_opening_deg(dir: &str, barb: usize) -> f32 {
+ let segs = arrow_segments_viewbox(dir);
+ let tip = (segs[barb][0], segs[barb][1]);
+ // direction du fût vue depuis la pointe : c'est celle de ses deux extrémités qui n'est
+ // PAS la pointe.
+ let shaft = segs[0];
+ let back = if (shaft[0] - tip.0).abs() + (shaft[1] - tip.1).abs() < 1e-3 {
+ (shaft[2] - tip.0, shaft[3] - tip.1)
+ } else {
+ (shaft[0] - tip.0, shaft[1] - tip.1)
+ };
+ let b = (segs[barb][2] - tip.0, segs[barb][3] - tip.1);
+ let dot = back.0 * b.0 + back.1 * b.1;
+ let mag = (back.0.hypot(back.1)) * (b.0.hypot(b.1));
+ (dot / mag).clamp(-1.0, 1.0).acos().to_degrees()
+ }
+
+ #[test]
+ fn every_arrowhead_opens_at_the_same_angle() {
+ // La déformation des diagonales ne venait pas que de la taille : leurs barbes ouvraient à
+ // ~25° du fût quand les cardinales ouvrent à 45°, ce qui donnait une pointe étroite,
+ // avalée par le fût dès que le trait épaississait. Corriger la longueur seule ne suffisait
+ // pas — ce test verrouille l'angle, qui est le paramètre réellement visible.
+ for dir in ["up", "down", "left", "right", "up-right", "up-left", "down-right", "down-left"]
+ {
+ for barb in 1..=2 {
+ let deg = barb_opening_deg(dir, barb);
+ assert!(
+ (deg - 45.0).abs() < 1.0,
+ "{dir} barbe {barb} ouvre à {deg:.1}°, attendu 45°"
+ );
+ }
+ }
+ }
+
#[test]
fn a_diagonal_head_is_as_large_as_a_cardinal_one() {
// Les barbes diagonales faisaient 15,8 unités contre 21,2 pour les cardinales : une
diff --git a/src/components/ai-edition/ArrowSvgs.tsx b/src/components/ai-edition/ArrowSvgs.tsx
index 47bb7f9a4..fffbb08a5 100644
--- a/src/components/ai-edition/ArrowSvgs.tsx
+++ b/src/components/ai-edition/ArrowSvgs.tsx
@@ -2,10 +2,13 @@
// compositor replicates them identically — cf. `arrow_segments_viewbox` in regions.rs,
// which carries the same numbers and is pinned to them by a test).
//
-// Les barbes des quatre DIAGONALES ont été allongées pour égaler celles des cardinales
-// (21,2 unités de viewBox contre 15,8 auparavant). À l'origine, une flèche diagonale avait
-// une tête ~25 % plus petite que sa voisine horizontale, ce qui se lisait comme une
-// déformation — d'autant plus qu'avec un trait épais la tête se fondait dans la hampe.
+// Les barbes des quatre DIAGONALES ont été refaites pour égaler les cardinales sur les DEUX
+// paramètres qui font une pointe de flèche : la longueur (21,2 unités de viewBox, contre 15,8
+// à l'origine) ET l'ouverture. C'est l'angle qui trahissait le plus : les cardinales ouvrent à
+// ±45° du fût, les diagonales à ±25° seulement, donnant un crochet étroit qui se fondait dans
+// le fût dès que le trait épaississait. Les barbes sont désormais dérivées de la direction du
+// fût par rotation de ±45°, la même règle qui produit exactement les (35,35)/(65,35) des
+// cardinales — la géométrie est donc uniforme par construction, pas par retouche.
import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
@@ -110,7 +113,7 @@ export function ArrowUpRight({ color, strokeWidth, className }: ArrowSvgProps) {
</filter>
</defs>
<path
- d="M 25 75 L 75 25 M 75 25 L 54.9 31.7 M 75 25 L 68.3 45.1"
+ d="M 25 75 L 75 25 M 75 25 L 53.8 25 M 75 25 L 75 46.2"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
@@ -131,7 +134,7 @@ export function ArrowUpLeft({ color, strokeWidth, className }: ArrowSvgProps) {
</filter>
</defs>
<path
- d="M 75 75 L 25 25 M 25 25 L 45.1 31.7 M 25 25 L 31.7 45.1"
+ d="M 75 75 L 25 25 M 25 25 L 25 46.2 M 25 25 L 46.2 25"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
@@ -152,7 +155,7 @@ export function ArrowDownRight({ color, strokeWidth, className }: ArrowSvgProps)
</filter>
</defs>
<path
- d="M 25 25 L 75 75 M 75 75 L 68.3 54.9 M 75 75 L 54.9 68.3"
+ d="M 25 25 L 75 75 M 75 75 L 75 53.8 M 75 75 L 53.8 75"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
@@ -173,7 +176,7 @@ export function ArrowDownLeft({ color, strokeWidth, className }: ArrowSvgProps)
</filter>
</defs>
<path
- d="M 75 25 L 25 75 M 25 75 L 31.7 54.9 M 25 75 L 45.1 68.3"
+ d="M 75 25 L 25 75 M 25 75 L 46.2 75 M 25 75 L 25 53.8"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
diff --git a/src/components/ai-edition/ColorField.test.tsx b/src/components/ai-edition/ColorField.test.tsx
new file mode 100644
index 000000000..18e8113c8
--- /dev/null
+++ b/src/components/ai-edition/ColorField.test.tsx
@@ -0,0 +1,101 @@
+import "@testing-library/jest-dom";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+// Le traducteur renvoie la clé : une assertion lit mieux contre une clé que contre une phrase qui
+// bouge à chaque relecture de copie.
+vi.mock("@/contexts/I18nContext", () => ({
+ useScopedT: () => (key: string, vars?: Record<string, unknown>) =>
+ vars ? `${key}:${Object.values(vars).join(",")}` : key,
+}));
+
+import { COLOR_PRESETS, ColorField } from "./ColorField";
+
+beforeAll(() => {
+ // Le popover Radix mesure sa cible ; jsdom n'a pas de ResizeObserver.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+function renderField(value = "#3b82f6") {
+ const onChange = vi.fn();
+ const onCommit = vi.fn();
+ render(
+ <ColorField value={value} onChange={onChange} onCommit={onCommit} label="annotation.color" />,
+ );
+ return { onChange, onCommit, trigger: screen.getByLabelText("annotation.color") };
+}
+
+describe("ColorField", () => {
+ it("keeps the picker closed until the swatch is clicked", () => {
+ const { trigger } = renderField();
+ expect(screen.queryByLabelText("annotation.colorPalette")).not.toBeInTheDocument();
+ fireEvent.click(trigger);
+ expect(screen.getByLabelText("annotation.colorPalette")).toBeInTheDocument();
+ });
+
+ it("offers the presets inside the picker, not beside the field", () => {
+ // Le point de la demande : une seule pastille dans le panneau, les présélections à
+ // l'intérieur du sélecteur pour que chaque fonctionnalité offre le même contrôle.
+ const { trigger } = renderField();
+ fireEvent.click(trigger);
+ const palette = screen.getByLabelText("annotation.colorPalette");
+ expect(palette.children).toHaveLength(COLOR_PRESETS.length);
+ });
+
+ it("applies a preset and commits it in one click", () => {
+ const { onChange, onCommit, trigger } = renderField();
+ fireEvent.click(trigger);
+ fireEvent.click(screen.getByLabelText("inspector.setColor:#22c55e"));
+ expect(onChange).toHaveBeenCalledWith("#22c55e");
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ });
+
+ it("marks the current colour as pressed so the picker shows where you are", () => {
+ const { trigger } = renderField("#22c55e");
+ fireEvent.click(trigger);
+ expect(screen.getByLabelText("inspector.setColor:#22c55e")).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ expect(screen.getByLabelText("inspector.setColor:#ffffff")).toHaveAttribute(
+ "aria-pressed",
+ "false",
+ );
+ });
+
+ it("pushes a typed hex once it is complete, and not before", () => {
+ const { onChange, trigger } = renderField();
+ fireEvent.click(trigger);
+ const hex = screen.getByLabelText("annotation.colorWheel");
+ fireEvent.change(hex, { target: { value: "#22c5" } });
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.change(hex, { target: { value: "#22c55e" } });
+ expect(onChange).toHaveBeenCalledWith("#22c55e");
+ });
+
+ it("accepts a hex typed without its leading #", () => {
+ const { onChange, trigger } = renderField();
+ fireEvent.click(trigger);
+ fireEvent.change(screen.getByLabelText("annotation.colorWheel"), {
+ target: { value: "22c55e" },
+ });
+ expect(onChange).toHaveBeenCalledWith("#22c55e");
+ });
+
+ it("commits once when the picker closes, not on every wheel event", () => {
+ // La roue émet en continu ; committer à chaque événement reconstruisait toute la scène et
+ // rendait le contrôle inutilisable (c'est le lag rapporté).
+ const { onCommit, trigger } = renderField();
+ fireEvent.click(trigger);
+ expect(onCommit).not.toHaveBeenCalled();
+ fireEvent.keyDown(document.body, { key: "Escape" });
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/components/ai-edition/ColorField.tsx b/src/components/ai-edition/ColorField.tsx
new file mode 100644
index 000000000..a64de2ece
--- /dev/null
+++ b/src/components/ai-edition/ColorField.tsx
@@ -0,0 +1,199 @@
+import * as Popover from "@radix-ui/react-popover";
+import Colorful from "@uiw/react-color-colorful";
+import { useEffect, useState } from "react";
+import { useScopedT } from "@/contexts/I18nContext";
+
+/**
+ * Un champ de couleur : une pastille qui ouvre le sélecteur.
+ *
+ * Les présélections vivent DANS le sélecteur, pas alignées à côté du champ. Une rangée de pastilles
+ * posée dans le panneau donne à croire que le choix se limite à ce que quelqu'un d'autre a décidé,
+ * elle mange la largeur d'une ligne de réglage, et chaque fonctionnalité finit par se recopier sa
+ * propre rangée. Ici il n'y a qu'un contrôle à réutiliser : roue, valeur hexadécimale et
+ * présélections, les mêmes partout.
+ *
+ * Le sélecteur est rendu dans un portail, donc il déborde librement du panneau — celui-ci découpe
+ * son contenu (coins arrondis + flou), un popover en flux y serait tronqué.
+ */
+
+/** Présélections communes : quatre neutres puis les teintes vives, deux rangées de huit. */
+export const COLOR_PRESETS: readonly string[] = [
+ "#ffffff",
+ "#bcc0c6",
+ "#6b7280",
+ "#16171d",
+ "#0f172a",
+ "#10b981",
+ "#22c55e",
+ "#3b82f6",
+ "#0ea5e9",
+ "#6366f1",
+ "#8b5cf6",
+ "#ec4899",
+ "#f43f5e",
+ "#ef4444",
+ "#f97316",
+ "#f59e0b",
+];
+
+const HEX_COMPLETE = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
+
+/** Ce que la roue sait afficher : tout le reste (dont `"transparent"`) retombe sur du noir. */
+function wheelColor(value: string): string {
+ return HEX_COMPLETE.test(value) ? value : "#000000";
+}
+
+interface ColorFieldProps {
+ value: string;
+ /** Appelé en continu pendant le glissement — au site d'appel de regrouper les écritures. */
+ onChange: (next: string) => void;
+ /** Fin de geste : fermeture du sélecteur, ou clic sur une présélection. */
+ onCommit?: () => void;
+ /** Nom du réglage (« Couleur du texte »…), pour le lecteur d'écran. */
+ label: string;
+ disabled?: boolean;
+ presets?: readonly string[];
+}
+
+export function ColorField({
+ value,
+ onChange,
+ onCommit,
+ label,
+ disabled,
+ presets = COLOR_PRESETS,
+}: ColorFieldProps) {
+ const ts = useScopedT("settings");
+ const te = useScopedT("editor");
+ const [open, setOpen] = useState(false);
+ const [hexDraft, setHexDraft] = useState(value);
+ // La valeur peut changer sous nos pieds (présélection, annulation, autre annotation
+ // sélectionnée) : le brouillon suit, sauf pendant que l'utilisateur tape dessus.
+ useEffect(() => {
+ setHexDraft(value);
+ }, [value]);
+
+ const pick = (next: string) => {
+ onChange(next);
+ onCommit?.();
+ };
+
+ return (
+ <Popover.Root
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ // Une seule écriture disque par ouverture : la roue émet en continu, et committer à
+ // chaque événement rendait le contrôle inutilisable.
+ if (!next) onCommit?.();
+ }}
+ >
+ <Popover.Trigger asChild>
+ <button
+ type="button"
+ aria-label={label}
+ disabled={disabled}
+ style={{
+ width: 40,
+ height: 28,
+ padding: 3,
+ borderRadius: 8,
+ border: "1px solid var(--border-hi)",
+ background: "var(--surface)",
+ cursor: disabled ? "default" : "pointer",
+ opacity: disabled ? 0.5 : 1,
+ }}
+ >
+ <span
+ style={{
+ display: "block",
+ width: "100%",
+ height: "100%",
+ borderRadius: 5,
+ background: value,
+ boxShadow: "inset 0 0 0 1px rgb(0 0 0 / 0.25)",
+ }}
+ />
+ </button>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ side="left"
+ align="start"
+ sideOffset={10}
+ collisionPadding={12}
+ style={{
+ zIndex: 60,
+ width: 216,
+ display: "flex",
+ flexDirection: "column",
+ gap: 10,
+ padding: 12,
+ borderRadius: 14,
+ border: "1px solid var(--border)",
+ background: "var(--surface-1)",
+ boxShadow: "var(--elev-pop)",
+ backdropFilter: "blur(18px)",
+ }}
+ >
+ <Colorful
+ color={wheelColor(value)}
+ disableAlpha
+ onChange={(next) => onChange(next.hex)}
+ style={{ width: "100%", borderRadius: 10 }}
+ />
+ <input
+ type="text"
+ aria-label={ts("annotation.colorWheel")}
+ value={hexDraft}
+ spellCheck={false}
+ onChange={(e) => {
+ // `#` implicite : on tape rarement le dièse, et l'exiger fait échouer une saisie
+ // par ailleurs valide.
+ const raw = e.target.value.trim();
+ const normalised = raw !== "" && /^[0-9A-Fa-f]/.test(raw) ? `#${raw}` : raw;
+ setHexDraft(normalised);
+ if (HEX_COMPLETE.test(normalised)) onChange(normalised);
+ }}
+ onBlur={() => onCommit?.()}
+ style={{
+ height: 30,
+ padding: "0 8px",
+ borderRadius: 8,
+ border: "1px solid var(--border)",
+ background: "var(--surface)",
+ color: "var(--fg)",
+ font: "500 12px var(--font-mono, ui-monospace), monospace",
+ textTransform: "lowercase",
+ }}
+ />
+ <div
+ aria-label={ts("annotation.colorPalette")}
+ style={{ display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gap: 5 }}
+ >
+ {presets.map((preset) => (
+ <button
+ key={preset}
+ type="button"
+ title={preset}
+ aria-label={te("inspector.setColor", { color: preset })}
+ aria-pressed={value.toLowerCase() === preset.toLowerCase()}
+ onClick={() => pick(preset)}
+ style={{
+ height: 18,
+ borderRadius: 5,
+ background: preset,
+ border:
+ value.toLowerCase() === preset.toLowerCase()
+ ? "2px solid var(--accent)"
+ : "1px solid var(--border-hi)",
+ cursor: "pointer",
+ }}
+ />
+ ))}
+ </div>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover.Root>
+ );
+}
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 91d172068..3f9c27654 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -1730,7 +1730,9 @@ export function TimelinePaneBody() {
// ─── primitives ───────────────────────────────────────────────────
-function Toggle({
+/** La pilule on/off des panneaux — exportée pour que l'inspecteur V4 l'emploie au lieu d'une
+ * case à cocher système, qui jurait avec tout le reste. */
+export function Toggle({
checked,
disabled,
onChange,
@@ -1764,6 +1766,7 @@ export function SliderCell({
disabled,
onChange,
onCommit,
+ showValue = true,
}: {
label: string;
value: number;
@@ -1775,15 +1778,20 @@ export function SliderCell({
disabled?: boolean;
onChange: (next: number) => void;
onCommit: () => void;
+ /** À passer `false` quand le libellé porte déjà la valeur (certaines chaînes i18n
+ * l'interpolent), sans quoi elle s'affiche deux fois. */
+ showValue?: boolean;
}) {
return (
<div className={styles.sliderCell}>
<div className="head">
<span className="label">{label}</span>
- <span className="val">
- {value.toFixed(decimals)}
- {suffix}
- </span>
+ {showValue ? (
+ <span className="val">
+ {value.toFixed(decimals)}
+ {suffix}
+ </span>
+ ) : null}
</div>
<input
type="range"
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 716c81bdc..9a7c02228 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -14,21 +14,30 @@ import {
ZoomIn,
} from "lucide-react";
import type { ComponentProps } from "react";
-import { useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { parseCustomPlaybackSpeedInput } from "@/components/video-editor/customPlaybackSpeed";
import { MAX_PLAYBACK_SPEED, SPEED_OPTIONS } from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
+import {
+ hasTextBackground,
+ setTextBackgroundColor,
+ textBackgroundColor,
+ toggleTextBackground,
+} from "@/lib/ai-edition/annotations/background";
import type { AxcutAnnotationRegion, AxcutClip } from "@/lib/ai-edition/schema";
+import { rafCoalesce } from "@/lib/ai-edition/store/rafCoalesce";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
import { formatSeconds } from "@/lib/ai-edition/timeline/virtual-preview";
+import { ColorField } from "../ColorField";
import {
BackgroundPane,
CursorPane,
LayoutPane,
SliderCell,
+ Toggle,
TranscriptPane,
VideoEffectsPane,
} from "../RightPanes";
@@ -222,6 +231,8 @@ function paneHeader(icon: React.ReactNode, title: string, onClose: () => void, c
gap: 8,
padding: "14px 16px 12px",
borderBottom: "1px solid var(--border-soft)",
+ // Le corps défile sous l'en-tête : sans ça, l'en-tête se comprime avec lui.
+ flexShrink: 0,
}}
>
<span style={{ display: "grid", placeItems: "center", color: "var(--muted)" }}>{icon}</span>
@@ -425,6 +436,27 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
// toggle that writes it lives in the timeline toolbar, not on this component's path.
const { settings } = useEditorSettings();
const autoFocusAll = settings.autoFocusAll;
+ // Mise à jour en direct regroupée à une par frame. `updateAnnotationLive` remplace le document
+ // dans le store, donc chaque appel fait reconstruire et re-sérialiser toute la scène avant de
+ // la pousser au natif : c'est le juste prix une fois par image, mais un `<input type="color">`
+ // émet un événement par pixel de glissement et saturait le thread. La référence garde la
+ // dernière fonction du store sans recréer le coalesceur, dont l'état en attente doit survivre
+ // aux rendus.
+ const liveUpdateRef = useRef(tl.updateAnnotationLive);
+ liveUpdateRef.current = tl.updateAnnotationLive;
+ const liveUpdate = useMemo(
+ () =>
+ rafCoalesce((id: string, patch: Partial<AxcutAnnotationRegion>) =>
+ liveUpdateRef.current(id, patch),
+ ),
+ [],
+ );
+ /** Fin de geste : on applique la dernière valeur en attente AVANT d'enregistrer, sinon la
+ * frame en vol serait perdue et le disque garderait l'avant-dernière couleur. */
+ const commitAnnotation = () => {
+ liveUpdate.flush();
+ void tl.commitAnnotationChange();
+ };
const selection = tl.selection;
if (!selection) return null;
@@ -433,11 +465,22 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
onClose();
};
+ // Le panneau découpe son contenu (coins arrondis + flou), donc un corps sans ascenseur perd
+ // silencieusement ce qui dépasse — c'est ce qui arrivait au pane d'annotation, le plus haut de
+ // tous, dès qu'on réduisait la fenêtre. L'en-tête reste fixe, le corps défile, comme les
+ // panneaux de facette (cf. `.paneBody` de NewEditorShell).
const bodyStyle: React.CSSProperties = {
padding: "16px",
display: "flex",
flexDirection: "column",
gap: 16,
+ flex: "1 1 auto",
+ minHeight: 0,
+ overflowY: "auto",
+ overflowX: "hidden",
+ overscrollBehavior: "contain",
+ scrollbarWidth: "thin",
+ scrollbarColor: "var(--border) transparent",
};
const deleteBtnStyle: React.CSSProperties = {
display: "inline-flex",
@@ -570,10 +613,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 colors = ["#ffffff", "#0f172a", "#10b981", "#f59e0b", "#f43f5e", "#6366f1"];
- // `transparent` est la façon dont le CSS — et donc le schéma — dit « pas de fond ».
- const hasBackground =
- !!region.style?.backgroundColor && region.style.backgroundColor !== "transparent";
+ const hasBackground = hasTextBackground(region.style);
return (
<div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
{paneHeader(
@@ -588,7 +628,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
label here already shipped translated. Converting keeps the span and box, so
a mistake costs one more click rather than redrawing the region. */}
{paneRow(
- ts("annotation.title"),
+ ts("annotation.type"),
<select
value={region.type}
onChange={(e) => {
@@ -615,7 +655,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
value={region.content ?? ""}
placeholder={ts("annotation.textPlaceholder")}
onChange={(e) => tl.updateAnnotationLive(region.id, { content: e.target.value })}
- onBlur={() => void tl.commitAnnotationChange()}
+ onBlur={commitAnnotation}
rows={2}
style={{
resize: "vertical",
@@ -692,19 +732,18 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
)}
{paneRow(
ts("annotation.arrowColor"),
- <input
- type="color"
+ <ColorField
+ label={ts("annotation.arrowColor")}
value={region.figureData?.color ?? "#34B27B"}
- onChange={(e) =>
- tl.updateAnnotationLive(region.id, {
+ onChange={(next) =>
+ liveUpdate(region.id, {
figureData: {
...(region.figureData ?? { arrowDirection: "right", strokeWidth: 4 }),
- color: e.target.value,
+ color: next,
},
})
}
- onBlur={() => void tl.commitAnnotationChange()}
- style={{ width: 34, height: 28, padding: 0, border: "none", background: "none" }}
+ onCommit={commitAnnotation}
/>,
)}
<SliderCell
@@ -723,6 +762,8 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
})
}
onCommit={() => void tl.commitAnnotationChange()}
+ // Le libellé i18n interpole déjà « : 11px » ; sans ça on lisait « 11px11 ».
+ showValue={false}
/>
</>
) : null}
@@ -808,7 +849,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
style: { ...region.style, fontSize: Number(e.target.value) },
})
}
- onBlur={() => void tl.commitAnnotationChange()}
+ onBlur={commitAnnotation}
style={{ ...selectStyle, width: 84, textAlign: "right" }}
/>,
)
@@ -816,120 +857,47 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
{region.type === "text"
? paneRow(
ts("annotation.background"),
- <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
- <input
- type="color"
- value={
- region.style?.backgroundColor &&
- region.style.backgroundColor !== "transparent"
- ? region.style.backgroundColor
- : "#000000"
- }
- // Live pendant le glissement, une seule écriture disque au relâchement :
- // un `<input type="color">` émet `onChange` en continu, et committer à
- // chaque événement rendait le sélecteur inutilisable.
- onChange={(e) =>
- tl.updateAnnotationLive(region.id, {
- style: { ...region.style, backgroundColor: e.target.value },
+ <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),
})
}
- onBlur={() => void tl.commitAnnotationChange()}
- style={{
- width: 34,
- height: 28,
- padding: 0,
- border: "none",
- background: "none",
- }}
+ onCommit={commitAnnotation}
/>
- {/* Une case à cocher plutôt qu'un bouton « effacer » : avoir un fond ou non est
- un état, pas une action. La couleur choisie est conservée quand on décoche,
- donc recocher la rend telle quelle au lieu d'obliger à la re-sélectionner. */}
- <label
- style={{
- display: "inline-flex",
- alignItems: "center",
- gap: 6,
- fontSize: 12.5,
- color: "var(--fg-2)",
- cursor: "pointer",
+ {/* 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();
}}
- >
- <input
- type="checkbox"
- checked={hasBackground}
- onChange={(e) => {
- tl.updateAnnotationLive(region.id, {
- style: {
- ...region.style,
- backgroundColor: e.target.checked
- ? (region.style?.backgroundColor ?? "#000000") === "transparent"
- ? "#000000"
- : (region.style?.backgroundColor ?? "#000000")
- : "transparent",
- },
- });
- void tl.commitAnnotationChange();
- }}
- />
- {ts("annotation.active")}
- </label>
+ />
</div>,
)
: null}
{region.type === "text"
? paneRow(
ts("annotation.color"),
- // Sélecteur système plutôt que six pastilles : le texte d'une annotation doit
- // pouvoir prendre n'importe quelle couleur, et une palette figée oblige à
- // choisir parmi ce que quelqu'un d'autre a décidé. Les raccourcis restent à
- // côté pour les teintes courantes.
- <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
- <input
- type="color"
- aria-label={ts("annotation.colorWheel")}
- value={region.style?.color ?? "#ffffff"}
- onChange={(e) =>
- tl.updateAnnotationLive(region.id, {
- style: { ...region.style, color: e.target.value },
- })
- }
- onBlur={() => void tl.commitAnnotationChange()}
- style={{
- width: 34,
- height: 28,
- padding: 0,
- border: "none",
- background: "none",
- }}
- />
- {colors.map((c) => (
- <button
- key={c}
- type="button"
- title={c}
- aria-label={te("inspector.setColor", { color: c })}
- aria-pressed={region.style?.color === c}
- onClick={() => {
- tl.updateAnnotationLive(region.id, {
- style: { ...region.style, color: c },
- });
- void tl.commitAnnotationChange();
- }}
- style={{
- width: 18,
- height: 18,
- borderRadius: "50%",
- background: c,
- border:
- region.style?.color === c
- ? "2px solid var(--accent)"
- : "1px solid var(--border-hi)",
- cursor: "pointer",
- }}
- />
- ))}
- </div>,
+ <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} style={deleteBtnStyle}>
@@ -1100,6 +1068,7 @@ function SimpleFacet({
alignItems: "center",
padding: "14px 16px 12px",
borderBottom: "1px solid var(--border-soft)",
+ flexShrink: 0,
}}
>
<h2
@@ -1114,7 +1083,19 @@ function SimpleFacet({
{title}
</h2>
</header>
- <div style={{ padding: "16px", display: "flex", flexDirection: "column", gap: 14 }}>
+ <div
+ style={{
+ padding: "16px",
+ display: "flex",
+ flexDirection: "column",
+ gap: 14,
+ flex: "1 1 auto",
+ minHeight: 0,
+ overflowY: "auto",
+ scrollbarWidth: "thin",
+ scrollbarColor: "var(--border) transparent",
+ }}
+ >
<p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--muted)" }}>
{description}
</p>
diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json
index 1132e5798..80cbe3653 100644
--- a/src/i18n/locales/ar/settings.json
+++ b/src/i18n/locales/ar/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "استخدم Shift+Tab للتنقل للخلف.",
"invalidImageType": "نوع ملف غير صالح",
"imageFormatsOnly": "يرجى رفع ملف صورة JPG أو PNG أو GIF أو WebP.",
- "imageUploadSuccess": "تم رفع الصورة بنجاح!"
+ "imageUploadSuccess": "تم رفع الصورة بنجاح!",
+ "type": "النوع"
},
"fontStyles": {
"classic": "كلاسيكي",
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index 5cb834889..457994dce 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Use Shift+Tab to cycle backwards.",
"invalidImageType": "Invalid file type",
"imageFormatsOnly": "Please upload a JPG, PNG, GIF, or WebP image file.",
- "imageUploadSuccess": "Image uploaded successfully!"
+ "imageUploadSuccess": "Image uploaded successfully!",
+ "type": "Type"
},
"fontStyles": {
"classic": "Classic",
diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json
index dc6a51c76..2c2937495 100644
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Usa Shift+Tab para recorrer hacia atrás.",
"invalidImageType": "Tipo de archivo no válido",
"imageFormatsOnly": "Por favor sube un archivo de imagen JPG, PNG, GIF o WebP.",
- "imageUploadSuccess": "¡Imagen subida exitosamente!"
+ "imageUploadSuccess": "¡Imagen subida exitosamente!",
+ "type": "Tipo"
},
"fontStyles": {
"classic": "Clásico",
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 15aaf4e52..39f9ba0e8 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Utilisez Shift+Tab pour cycler en sens inverse.",
"invalidImageType": "Type de fichier invalide",
"imageFormatsOnly": "Veuillez téléverser un fichier image JPG, PNG, GIF ou WebP.",
- "imageUploadSuccess": "Image téléversée avec succès !"
+ "imageUploadSuccess": "Image téléversée avec succès !",
+ "type": "Type"
},
"fontStyles": {
"classic": "Classique",
diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json
index 62e4a6781..7d48d6087 100644
--- a/src/i18n/locales/it/settings.json
+++ b/src/i18n/locales/it/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Usa Maiusc+Tab per scorrere all'indietro.",
"invalidImageType": "Tipo di file non valido",
"imageFormatsOnly": "Carica un file immagine JPG, PNG, GIF o WebP.",
- "imageUploadSuccess": "Immagine caricata con successo!"
+ "imageUploadSuccess": "Immagine caricata con successo!",
+ "type": "Tipo"
},
"fontStyles": {
"classic": "Classico",
diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json
index ffcff9c3c..ca22dc146 100644
--- a/src/i18n/locales/ja-JP/settings.json
+++ b/src/i18n/locales/ja-JP/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Shift+Tabキーを使用して逆順に切り替えます。",
"invalidImageType": "無効なファイル形式",
"imageFormatsOnly": "JPG、PNG、GIF、またはWebP画像ファイルを選択してください。",
- "imageUploadSuccess": "画像を読み込みました。"
+ "imageUploadSuccess": "画像を読み込みました。",
+ "type": "種類"
},
"fontStyles": {
"classic": "クラシック",
diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json
index 80ef36cbd..176884cec 100644
--- a/src/i18n/locales/ko-KR/settings.json
+++ b/src/i18n/locales/ko-KR/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Shift+Tab으로 역방향 순환할 수 있습니다.",
"invalidImageType": "지원하지 않는 파일 형식입니다",
"imageFormatsOnly": "JPG, PNG, GIF 또는 WebP 이미지 파일을 업로드해 주세요.",
- "imageUploadSuccess": "이미지가 성공적으로 업로드되었습니다!"
+ "imageUploadSuccess": "이미지가 성공적으로 업로드되었습니다!",
+ "type": "유형"
},
"fontStyles": {
"classic": "클래식",
diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json
index 9108aa593..79fbedb38 100644
--- a/src/i18n/locales/pt-BR/settings.json
+++ b/src/i18n/locales/pt-BR/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Use Shift+Tab para alternar para trás.",
"invalidImageType": "Tipo de imagem inválido",
"imageFormatsOnly": "Por favor, envie um arquivo de imagem JPG, PNG, GIF ou WebP.",
- "imageUploadSuccess": "Imagem enviada com sucesso!"
+ "imageUploadSuccess": "Imagem enviada com sucesso!",
+ "type": "Tipo"
},
"fontStyles": {
"classic": "Clássico",
diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json
index 688e26c16..a987a2c98 100644
--- a/src/i18n/locales/ru/settings.json
+++ b/src/i18n/locales/ru/settings.json
@@ -182,7 +182,8 @@
"tipShiftTabCycle": "Используйте Shift+Tab для циклического переключения в обратном направлении.",
"invalidImageType": "Неверный тип файла",
"imageFormatsOnly": "Пожалуйста, загрузите изображение JPG, PNG, GIF или WebP.",
- "imageUploadSuccess": "Изображение успешно загружено!"
+ "imageUploadSuccess": "Изображение успешно загружено!",
+ "type": "Тип"
},
"fontStyles": {
"classic": "Классический",
diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json
index 124eba364..3cd10664a 100644
--- a/src/i18n/locales/tr/settings.json
+++ b/src/i18n/locales/tr/settings.json
@@ -182,7 +182,8 @@
"blurType": "Bulanıklık Türü",
"blurTypeBlur": "Gauss",
"blurTypeMosaic": "Mozaik",
- "mosaicBlockSize": "Mozaik Blok Boyutu"
+ "mosaicBlockSize": "Mozaik Blok Boyutu",
+ "type": "Tür"
},
"fontStyles": {
"classic": "Klasik",
diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json
index 09da2ce4f..56ccba317 100644
--- a/src/i18n/locales/vi/settings.json
+++ b/src/i18n/locales/vi/settings.json
@@ -182,7 +182,8 @@
"imageFormatsOnly": "Vui lòng tải lên tệp hình ảnh JPG, PNG, GIF hoặc WebP.",
"imageUploadSuccess": "Tải lên hình ảnh thành công!",
"colorPalette": "Bảng màu",
- "colorWheel": "Vòng màu"
+ "colorWheel": "Vòng màu",
+ "type": "Loại"
},
"fontStyles": {
"classic": "Cổ điển",
diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json
index fe2cfd47b..14f939696 100644
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@ -182,7 +182,8 @@
"blurType": "模糊类型",
"blurTypeBlur": "高斯",
"blurTypeMosaic": "马赛克",
- "mosaicBlockSize": "马赛克块大小"
+ "mosaicBlockSize": "马赛克块大小",
+ "type": "类型"
},
"fontStyles": {
"classic": "经典",
diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json
index 3873c450a..2e44c0192 100644
--- a/src/i18n/locales/zh-TW/settings.json
+++ b/src/i18n/locales/zh-TW/settings.json
@@ -183,7 +183,8 @@
"blurType": "模糊類型",
"blurTypeBlur": "高斯",
"blurTypeMosaic": "馬賽克",
- "mosaicBlockSize": "馬賽克區塊大小"
+ "mosaicBlockSize": "馬賽克區塊大小",
+ "type": "類型"
},
"fontStyles": {
"classic": "經典",
diff --git a/src/lib/ai-edition/annotations/background.test.ts b/src/lib/ai-edition/annotations/background.test.ts
new file mode 100644
index 000000000..4e8697608
--- /dev/null
+++ b/src/lib/ai-edition/annotations/background.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+import {
+ DEFAULT_TEXT_BACKGROUND,
+ hasTextBackground,
+ setTextBackgroundColor,
+ textBackgroundColor,
+ toggleTextBackground,
+} from "./background";
+import { DEFAULT_ANNOTATION_STYLE } from "./constants";
+
+type AnnotationStyle = AxcutAnnotationRegion["style"];
+
+const styleWith = (patch: Partial<AnnotationStyle>): AnnotationStyle => ({
+ ...DEFAULT_ANNOTATION_STYLE,
+ ...patch,
+});
+
+describe("text background", () => {
+ it("reads transparent as no background", () => {
+ expect(hasTextBackground(styleWith({ backgroundColor: "transparent" }))).toBe(false);
+ expect(hasTextBackground(styleWith({ backgroundColor: "#3b82f6" }))).toBe(true);
+ });
+
+ it("remembers the colour across an off/on cycle", () => {
+ // Le bug rapporté : éteindre puis rallumer le fond rendait du noir, parce que « pas de fond »
+ // s'écrit dans le champ même qui porte la couleur.
+ const chosen = styleWith({ backgroundColor: "#3b82f6" });
+ const off = toggleTextBackground(chosen, false);
+ expect(off.backgroundColor).toBe("transparent");
+ const on = toggleTextBackground(off, true);
+ expect(on.backgroundColor).toBe("#3b82f6");
+ });
+
+ it("survives several off/on cycles rather than only the first", () => {
+ let style = setTextBackgroundColor(styleWith({}), "#f59e0b");
+ for (let i = 0; i < 3; i++) {
+ style = toggleTextBackground(style, false);
+ style = toggleTextBackground(style, true);
+ }
+ expect(style.backgroundColor).toBe("#f59e0b");
+ });
+
+ it("falls back to black only on a first switch-on", () => {
+ const never = styleWith({ backgroundColor: "transparent" });
+ expect(toggleTextBackground(never, true).backgroundColor).toBe(DEFAULT_TEXT_BACKGROUND);
+ });
+
+ it("shows the remembered colour while the background is off", () => {
+ // La pastille du sélecteur doit annoncer ce que le rallumage rendra, pas un noir arbitraire.
+ const off = toggleTextBackground(styleWith({ backgroundColor: "#ec4899" }), false);
+ expect(textBackgroundColor(off)).toBe("#ec4899");
+ });
+
+ it("ignores a remembered transparent, which is not a colour", () => {
+ const style = styleWith({ backgroundColor: "transparent", lastBackgroundColor: "transparent" });
+ expect(textBackgroundColor(style)).toBe(DEFAULT_TEXT_BACKGROUND);
+ });
+
+ it("picking a colour turns the background on and updates the memory", () => {
+ const off = styleWith({ backgroundColor: "transparent" });
+ const picked = setTextBackgroundColor(off, "#22c55e");
+ expect(picked.backgroundColor).toBe("#22c55e");
+ expect(hasTextBackground(picked)).toBe(true);
+ // et l'extinction suivante rend bien cette couleur, pas la précédente
+ expect(textBackgroundColor(toggleTextBackground(picked, false))).toBe("#22c55e");
+ });
+
+ it("leaves the rest of the style untouched", () => {
+ const style = styleWith({ color: "#ffffff", fontSize: 48 });
+ const toggled = toggleTextBackground(style, true);
+ expect(toggled.color).toBe("#ffffff");
+ expect(toggled.fontSize).toBe(48);
+ });
+});
diff --git a/src/lib/ai-edition/annotations/background.ts b/src/lib/ai-edition/annotations/background.ts
new file mode 100644
index 000000000..b6acb11af
--- /dev/null
+++ b/src/lib/ai-edition/annotations/background.ts
@@ -0,0 +1,47 @@
+// Le fond d'un bloc de texte : un booléen côté utilisateur, une couleur côté rendu.
+//
+// Tous les moteurs de rendu (compositeur natif, exporteur canvas, aperçu DOM) lisent
+// `style.backgroundColor` et traitent `"transparent"` comme « pas de fond ». Éteindre le fond
+// écrase donc la couleur choisie, et le rallumer n'avait plus rien à restaurer : il revenait
+// toujours au noir. `lastBackgroundColor` conserve cette couleur, ce qui rend la bascule
+// réversible sans donner un second sens à `backgroundColor`.
+
+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
+
+type AnnotationStyle = AxcutAnnotationRegion["style"];
+
+/** Couleur d'un premier allumage, quand l'annotation n'a jamais eu de fond. */
+export const DEFAULT_TEXT_BACKGROUND = "#000000";
+
+export function hasTextBackground(style: AnnotationStyle): boolean {
+ const color = style.backgroundColor;
+ return !!color && color !== "transparent";
+}
+
+/**
+ * Couleur à afficher dans le sélecteur, fond allumé ou éteint : éteint, on montre la couleur
+ * mémorisée plutôt qu'un noir qui ne veut rien dire — c'est bien celle que le rallumage rendra.
+ */
+export function textBackgroundColor(style: AnnotationStyle): string {
+ if (hasTextBackground(style)) return style.backgroundColor;
+ const remembered = style.lastBackgroundColor;
+ return remembered && remembered !== "transparent" ? remembered : DEFAULT_TEXT_BACKGROUND;
+}
+
+/** Style résultant de la bascule du fond, la couleur conservée dans les deux sens. */
+export function toggleTextBackground(style: AnnotationStyle, next: boolean): AnnotationStyle {
+ const remembered = textBackgroundColor(style);
+ return {
+ ...style,
+ backgroundColor: next ? remembered : "transparent",
+ lastBackgroundColor: remembered,
+ };
+}
+
+/**
+ * Style résultant du choix d'une couleur de fond. Choisir une couleur allume le fond : c'est ce
+ * que le geste veut dire, et laisser le fond éteint donnerait un sélecteur sans effet visible.
+ */
+export function setTextBackgroundColor(style: AnnotationStyle, color: string): AnnotationStyle {
+ return { ...style, backgroundColor: color, lastBackgroundColor: color };
+}
diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.ts
index 29781c9f0..f9815e863 100644
--- a/src/lib/ai-edition/schema/index.test.ts
+++ b/src/lib/ai-edition/schema/index.test.ts
@@ -145,6 +145,29 @@ describe("axcut-schema v5", () => {
expect(region.annotationSource).toBeUndefined();
});
+ it("keeps the remembered background colour through a save-path parse", () => {
+ // Le chemin d'enregistrement valide le document dans le processus principal, et zod jette
+ // tout champ non déclaré : une mémoire que l'interface écrit mais que le schéma ignore
+ // disparaît au premier enregistrement — silencieusement, ce qui est le pire cas.
+ const region = annotationRegionSchema.parse({
+ id: "ann_1",
+ startMs: 0,
+ endMs: 1500,
+ type: "text",
+ content: "hello",
+ position: { x: 4, y: 86 },
+ size: { width: 92, height: 12 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ lastBackgroundColor: "#3b82f6",
+ fontSize: 24,
+ },
+ zIndex: 1,
+ });
+ expect(region.style.lastBackgroundColor).toBe("#3b82f6");
+ });
+
it("zoomRegionSchema rejects unknown depths", () => {
expect(() =>
zoomRegionSchema.parse({
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 68b9656b9..6d9200634 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -377,6 +377,12 @@ const figureDataSchema = z
const annotationStyleSchema = z.object({
color: z.string().default("#ffffff"),
backgroundColor: z.string().default("transparent"),
+ // `backgroundColor: "transparent"` is how every renderer reads "no background", so switching
+ // the background off has to overwrite the colour the user picked — and switching it back on had
+ // nothing left to restore, which is why it always came back black. This keeps that last colour
+ // so the toggle is reversible. Nothing renders it: the paint path still reads `backgroundColor`
+ // alone.
+ lastBackgroundColor: z.string().optional(),
fontSize: z.number().nonnegative().default(32),
fontFamily: z.string().default("Inter"),
fontWeight: z.enum(["normal", "bold"]).default("bold"),
diff --git a/src/lib/ai-edition/store/rafCoalesce.test.ts b/src/lib/ai-edition/store/rafCoalesce.test.ts
new file mode 100644
index 000000000..0a9868001
--- /dev/null
+++ b/src/lib/ai-edition/store/rafCoalesce.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { rafCoalesce } from "./rafCoalesce";
+
+describe("rafCoalesce", () => {
+ let frames: Array<() => void>;
+
+ beforeEach(() => {
+ frames = [];
+ vi.stubGlobal("requestAnimationFrame", (cb: () => void) => {
+ frames.push(cb);
+ return frames.length;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (handle: number) => {
+ frames[handle - 1] = () => {};
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const runFrame = () => {
+ const due = frames;
+ frames = [];
+ for (const cb of due) cb();
+ };
+
+ it("applies one call per frame, keeping the last value", () => {
+ // Le cas du sélecteur de couleur : des dizaines d'événements entre deux images, dont un
+ // seul sera visible. Appliquer les intermédiaires ne fait que du travail jeté.
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced("#111111");
+ coalesced("#222222");
+ coalesced("#333333");
+ expect(fn).not.toHaveBeenCalled();
+ runFrame();
+ expect(fn).toHaveBeenCalledTimes(1);
+ expect(fn).toHaveBeenCalledWith("#333333");
+ });
+
+ it("schedules a fresh frame for values arriving after one flushed", () => {
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced("a");
+ runFrame();
+ coalesced("b");
+ runFrame();
+ expect(fn.mock.calls.map((c) => c[0])).toEqual(["a", "b"]);
+ });
+
+ it("flush applies the pending value immediately", () => {
+ // C'est ce qui garantit qu'un commit en fin de geste enregistre la DERNIÈRE couleur et non
+ // l'avant-dernière : sans ça, la frame en vol serait perdue.
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced("final");
+ coalesced.flush();
+ expect(fn).toHaveBeenCalledWith("final");
+ // et la frame déjà programmée ne doit pas rejouer la valeur
+ runFrame();
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("flush with nothing pending does nothing", () => {
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced.flush();
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it("cancel drops the pending value", () => {
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced("dropped");
+ coalesced.cancel();
+ runFrame();
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it("applies synchronously when requestAnimationFrame is unavailable", () => {
+ // Tests et workers n'ont pas de rAF : mieux vaut appliquer tout de suite que perdre la
+ // mise à jour.
+ vi.stubGlobal("requestAnimationFrame", undefined);
+ const fn = vi.fn();
+ const coalesced = rafCoalesce(fn);
+ coalesced("direct");
+ expect(fn).toHaveBeenCalledWith("direct");
+ });
+});
diff --git a/src/lib/ai-edition/store/rafCoalesce.ts b/src/lib/ai-edition/store/rafCoalesce.ts
new file mode 100644
index 000000000..3b5900d45
--- /dev/null
+++ b/src/lib/ai-edition/store/rafCoalesce.ts
@@ -0,0 +1,60 @@
+/**
+ * Regroupe les mises à jour continues d'un geste (glissement d'un sélecteur de couleur, d'un
+ * slider) à **une par frame**.
+ *
+ * Pourquoi c'est nécessaire ici : `updateAnnotationLive` remplace le document dans le store, ce
+ * qui fait reconstruire ET re-sérialiser toute la scène avant de la pousser au compositeur natif.
+ * C'est le bon prix à payer une fois par image ; à la cadence d'un `<input type="color">`, qui
+ * émet un `change` par pixel de déplacement, ça sature le thread et le contrôle devient
+ * inutilisable — le symptôme rapporté comme « le sélecteur de couleur lague ».
+ *
+ * Seule la DERNIÈRE valeur d'une frame est appliquée : les intermédiaires ne seraient de toute
+ * façon jamais affichées, puisqu'aucune image ne s'intercale entre elles.
+ */
+export function rafCoalesce<A extends unknown[]>(
+ fn: (...args: A) => void,
+): {
+ (...args: A): void;
+ /** Applique tout de suite ce qui est en attente — à appeler en fin de geste, avant de
+ * committer, pour que la valeur enregistrée soit bien la dernière saisie. */
+ flush: () => void;
+ cancel: () => void;
+} {
+ let handle: number | null = null;
+ let pending: A | null = null;
+
+ const run = () => {
+ handle = null;
+ const args = pending;
+ pending = null;
+ if (args) fn(...args);
+ };
+
+ const schedule = (...args: A) => {
+ pending = args;
+ if (handle !== null) return;
+ // `requestAnimationFrame` absent (tests, worker) : on applique directement plutôt que de
+ // perdre la mise à jour.
+ if (typeof requestAnimationFrame !== "function") {
+ run();
+ return;
+ }
+ handle = requestAnimationFrame(run);
+ };
+
+ schedule.flush = () => {
+ if (handle !== null && typeof cancelAnimationFrame === "function") {
+ cancelAnimationFrame(handle);
+ }
+ handle = null;
+ run();
+ };
+ schedule.cancel = () => {
+ if (handle !== null && typeof cancelAnimationFrame === "function") {
+ cancelAnimationFrame(handle);
+ }
+ handle = null;
+ pending = null;
+ };
+ return schedule;
+}