Repository Public
1import type { Lang, MotionSpec } from "../lib/contracts";2import { clamp01, displayFont, easeInCubic, easeInOutCubic, easeOutCubic, easeOutExpo, easeSpring, ellipsize, fitText, font, formatNumber, hashString, lerp, newCanvas, prog, renderCanvasVideo, roundRect, wrapText, type Ctx } from "./canvas";3import { drawHalo, drawKinetic, GOLD, goldFill, INK, kindOf, layoutBlock, makeBackdrop, rgba, SAFE, withAlpha, type BackdropVariant, type Kind, type TextBlock } from "./design";45/**6 * Moteur d'animation canvas : chaque variante de MotionSpec est dessinée trame par trame (déterministe, sans Chromium) puis encodée7 * (codec intermédiaire + silence). Direction artistique : voir design.ts (décor animé sombre de marque, accent or, Instrument Serif8 * pour le titrage, Inter pour le texte et les chiffres).9 *10 * Règles communes :11 * - zones sûres par ratio (`SAFE`) : rien sous le filigrane, rien dans la bande des sous-titres ;12 * - chaque élément ENTRE (masque + montée, « expo out »), le décor et les accents restent en mouvement pendant toute la scène, et le13 * contenu SORT (fondu + légère montée) sur les derniers dixièmes de seconde (`exit: false` pour l'empêcher) ;14 * - les temps d'entrée sont comprimés pour les scènes courtes (`k`) et modulés par l'intensité ;15 * - aucun débordement : retour à la ligne, réduction de corps bornée, puis points de suspension en dernier recours ;16 * - les graphiques n'affichent que les données fournies et leur mention de source.17 */1819export type MotionIntensity = "sobre" | "modere" | "dynamique";20interface Env {21 W: number; H: number; u: number; kind: Kind; seconds: number; lang: Lang; probe: Ctx;22 safe: { l: number; t: number; w: number; h: number; r: number; b: number };23 /** Facteur appliqué aux temps nominaux (scènes courtes et intensité). */24 k: number;25 I: { speed: number; travel: number; bounce: number; energy: number; stagger: number };26 exitDur: number;27}28type Draw = (ctx: Ctx, t: number) => void;29export interface MotionOptions { width: number; height: number; seconds: number; language: Lang; intensity: MotionIntensity; /** Graine du décor (positions des lumières, particules). Par défaut : dérivée du type d'animation. */ seed?: number; /** Sortie animée du contenu en fin de scène (défaut : oui). */ exit?: boolean }3031const INTENSITY: Record<MotionIntensity, Env["I"]> = {32 sobre: { speed: 1, travel: 0.75, bounce: 0, energy: 0.5, stagger: 1.2 },33 modere: { speed: 1.12, travel: 1, bounce: 0.22, energy: 1, stagger: 1 },34 dynamique: { speed: 1.3, travel: 1.35, bounce: 0.42, energy: 1.5, stagger: 0.8 },35};3637function makeEnv(o: MotionOptions): Env {38 const { width: W, height: H } = o;39 const kind = kindOf(W, H);40 const s = SAFE[kind];41 const I = INTENSITY[o.intensity] ?? INTENSITY.modere;42 const l = W * s.x, t = H * s.top, w = W * (1 - 2 * s.x), h = H * (1 - s.top - s.bottom);43 return {44 W, H, u: Math.min(W, H) / 1080, kind, seconds: o.seconds, lang: o.language, probe: newCanvas(8, 8).ctx, safe: { l, t, w, h, r: l + w, b: t + h },45 k: Math.min(1, Math.max(0.35, o.seconds / 4)) / I.speed, I,46 exitDur: o.exit === false || o.seconds < 1.4 ? 0 : Math.min(0.36, o.seconds * 0.12),47 };48}4950/** Entrée d'un élément non textuel : fondu + translation amortie. Temps nominaux (multipliés par `k`). */51function rise(ctx: Ctx, e: Env, t: number, start: number, draw: () => void, o: { dur?: number; dx?: number; dy?: number } = {}): void {52 const p = prog(t, start * e.k, (o.dur ?? 0.7) * e.k);53 if (p <= 0) return;54 const m = easeOutExpo(p);55 ctx.save();56 ctx.globalAlpha *= easeOutCubic(Math.min(1, p * 1.6));57 ctx.translate((1 - m) * (o.dx ?? 0) * e.u * e.I.travel, (1 - m) * (o.dy ?? 24) * e.u * e.I.travel);58 draw();59 ctx.restore();60}6162/** Rééquilibre un texte coupé en `n` lignes : cherche la largeur la plus étroite qui garde ce nombre de lignes (pas de mot orphelin). */63function balance(probe: Ctx, text: string, fontStr: string, maxWidth: number, n: number, tracking = 0): string[] {64 probe.font = fontStr;65 probe.letterSpacing = `${tracking.toFixed(2)}px`;66 let best = wrapText(probe, text, maxWidth);67 if (n > 1 && best.length === n) {68 for (let w = maxWidth * 0.97; w > maxWidth * 0.45; w -= maxWidth * 0.03) {69 const lines = wrapText(probe, text, w);70 if (lines.length !== n || Math.max(...lines.map((l) => probe.measureText(l).width)) > maxWidth) break;71 best = lines;72 }73 }74 probe.letterSpacing = "0px";75 return best;76}7778const unitSuffix = (unit: string, lang: Lang) => (!unit || unit.length > 4 ? "" : unit === "%" && lang === "en" ? "%" : ` ${unit}`);79function decimalsFor(values: number[]): number {80 let d = 0;81 for (const v of values) { const s = String(Math.round(Math.abs(v) * 100) / 100); const i = s.indexOf("."); if (i >= 0) d = Math.max(d, s.length - i - 1); }82 return Math.min(d, 2);83}84function niceTicks(lo: number, hi: number, count = 4): number[] {85 if (lo === hi) { lo -= 1; hi += 1; }86 const raw = (hi - lo) / count;87 const mag = 10 ** Math.floor(Math.log10(raw));88 const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;89 const start = Math.floor(lo / step) * step, end = Math.ceil(hi / step) * step;90 const out: number[] = [];91 for (let v = start; v <= end + step * 1e-6; v += step) out.push(Math.round(v / step) * step);92 return out;93}9495/** En-tête commun (puces, graphiques, frise) : filet or qui se trace, titre, unité. `draw(ctx, t, y)` dessine à partir de l'ordonnée y. */96function header(e: Env, title: string, unit: string, dense = false): { draw: (ctx: Ctx, t: number, y: number) => void; height: number } {97 const { safe, u } = e;98 const longUnit = unit.length > 4;99 if (!title.trim() && !longUnit) return { draw: () => {}, height: 0 };100 const track = (px: number) => -px * 0.012;101 const fit = title.trim() ? fitText(e.probe, title.trim(), { weight: 400, fontOf: (px) => displayFont(px), max: (dense ? 70 : e.kind === "wide" ? 92 : 86) * u, min: 46 * u, maxWidth: safe.w, maxLines: 2, letterSpacing: track }) : { size: 0, lines: [] as string[] };102 const cut = fit.lines.join(" ").endsWith("…") && !title.trim().endsWith("…");103 const lines = fit.lines.length === 2 && !cut ? balance(e.probe, title.trim(), displayFont(fit.size), safe.w, 2, track(fit.size)) : fit.lines;104 const block = layoutBlock(e.probe, lines, { fontOf: () => displayFont(fit.size), size: fit.size, lineHeight: 1.06, tracking: track(fit.size) });105 const unitSize = 30 * u;106 const unitLabel = longUnit ? (e.lang === "fr" ? `Unité : ${unit}` : `Unit: ${unit}`) : "";107 const ruleGap = 52 * u;108 const titleH = lines.length ? ruleGap + fit.size * 0.74 + (lines.length - 1) * block.lh : 0;109 const unitH = longUnit ? (lines.length ? 30 * u : ruleGap) + unitSize * 0.76 : 0;110 const height = Math.max(4 * u, titleH + unitH) + (dense ? 56 : 76) * u;111 return {112 height,113 draw: (ctx, t, y) => {114 ctx.fillStyle = INK.gold;115 ctx.fillRect(safe.l, y, 64 * u * easeOutExpo(prog(t, 0.05 * e.k, 0.8 * e.k)), Math.max(3, 5 * u));116 if (lines.length) drawKinetic(ctx, block, safe.l, y + ruleGap + fit.size * 0.74, { t, start: 0.12 * e.k, stagger: 0.06 * e.k, dur: 0.85 * e.k, color: INK.text });117 if (longUnit) rise(ctx, e, t, 0.3, () => {118 ctx.font = font(400, unitSize);119 ctx.fillStyle = INK.muted;120 ctx.textAlign = "left";121 ctx.fillText(ellipsize(ctx, unitLabel, safe.w), safe.l, y + titleH + (lines.length ? 30 * u : ruleGap) + unitSize * 0.76);122 }, { dy: 12 });123 },124 };125}126127/** Mention de source en pied de graphique (toujours affichée telle que fournie). Renvoie le dessin et la hauteur réservée. */128function sourceNote(e: Env, note: string): { draw: (ctx: Ctx, t: number, bottom: number) => void; height: number } {129 if (!note.trim()) return { draw: () => {}, height: 0 };130 const size = 25 * e.u;131 e.probe.font = font(400, size);132 const label = /^sources?\s*:/i.test(note.trim()) ? note.trim() : `${e.lang === "fr" ? "Source : " : "Source: "}${note.trim()}`;133 const lines = wrapText(e.probe, label, e.safe.w - 26 * e.u).slice(0, 2);134 const height = lines.length * size * 1.3 + 30 * e.u;135 return {136 height,137 draw: (ctx, t, bottom) => rise(ctx, e, t, 0.55, () => {138 ctx.fillStyle = INK.gold;139 ctx.fillRect(e.safe.l, bottom - (lines.length - 1) * size * 1.3 - size * 0.86, Math.max(2, 3 * e.u), lines.length * size * 1.3 - size * 0.22);140 ctx.font = font(400, size);141 ctx.fillStyle = INK.muted;142 ctx.textAlign = "left";143 lines.forEach((line, i) => ctx.fillText(i === 1 ? ellipsize(ctx, line, e.safe.w - 26 * e.u) : line, e.safe.l + 18 * e.u, bottom - (lines.length - 1 - i) * size * 1.3 - 4 * e.u));144 }, { dy: 10 }),145 };146}147148// ── title ────────────────────────────────────────────────────────────────────149function titleScene(spec: Extract<MotionSpec, { type: "title" }>, e: Env): Draw {150 const { safe, u } = e;151 const wide = e.kind === "wide";152 const maxW = safe.w * (wide ? 0.82 : 1);153 const track = (px: number) => -px * 0.014;154 const text = spec.title.trim();155 const fit = fitText(e.probe, text, { weight: 400, fontOf: (px) => displayFont(px), max: (wide ? 180 : e.kind === "tall" ? 200 : 168) * u, min: 60 * u, maxWidth: maxW, maxLines: wide ? 4 : 6, letterSpacing: track });156 const truncated = fit.lines.join(" ").endsWith("…") && !text.endsWith("…");157 // Emphase éditoriale : le dernier mot en italique or (à partir de trois mots).158 const tokens = text.split(/\s+/).filter(Boolean);159 let emFrom = tokens.length - 1;160 while (emFrom > 0 && !/[\p{L}\p{N}]/u.test(tokens[emFrom])) emFrom--; // « … transfrontalières ? » : le mot, pas la ponctuation seule161 const emphasis = (i: number) => tokens.length >= 3 && i >= emFrom && !truncated;162 const build = (size: number): TextBlock => {163 const lines = truncated ? fit.lines : balance(e.probe, text, displayFont(size), maxW, fit.lines.length, track(size));164 return layoutBlock(e.probe, lines, { fontOf: (em) => displayFont(size, em), size, lineHeight: 1.03, tracking: track(size), emphasis });165 };166 let block = build(fit.size);167 if (block.width > maxW) block = build(fit.size * (maxW / block.width) * 0.995);168 const size = block.size;169 const raw = spec.subtitle.trim();170 const caps = raw.length > 0 && raw.length <= 46;171 const subTrack = (px: number) => (caps ? px * 0.16 : 0);172 const sub = raw ? fitText(e.probe, caps ? raw.toLocaleUpperCase(e.lang === "fr" ? "fr-CA" : "en-US") : raw, { weight: 500, max: (caps ? 34 : 42) * u, min: 24 * u, maxWidth: maxW, maxLines: 3, letterSpacing: subTrack }) : null;173 const slh = (sub?.size ?? 0) * 1.4;174 const ruleGap = 50 * u, subGap = size * 0.34 + 34 * u;175 const blockH = ruleGap + size * 0.78 + (block.lines.length - 1) * block.lh + (sub ? subGap + sub.size * 0.75 + (sub.lines.length - 1) * slh : 0);176 const y0 = safe.t + (safe.h - blockH) * 0.46;177 const yTitle = y0 + ruleGap + size * 0.78;178 const n = block.words.length;179 const stagger = Math.min(0.085 * e.I.stagger, 0.9 / n) * e.k;180 const tSub = 0.45 + n * (stagger / e.k) * 0.8;181 return (ctx, t) => {182 // lente poussée avant : le plan n'est jamais figé183 const z = 1 + 0.028 * (t / Math.max(e.seconds, 0.1));184 ctx.translate(safe.l, y0 + blockH / 2);185 ctx.scale(z, z);186 ctx.translate(-safe.l, -(y0 + blockH / 2));187 ctx.fillStyle = INK.gold;188 ctx.fillRect(safe.l, y0, 92 * u * easeOutExpo(prog(t, 0.08 * e.k, 0.9 * e.k)), Math.max(3, 5 * u));189 const tEm = 0.3 * e.k + n * stagger + 0.6 * e.k;190 drawKinetic(ctx, block, safe.l, yTitle, {191 t, start: 0.22 * e.k, stagger, dur: 0.95 * e.k,192 color: (w) => (w.em ? goldFill(ctx, safe.l + w.x - w.w * 0.3, safe.l + w.x + w.w * 1.3, ((t - tEm) % 3.4) / 1.1) : INK.text),193 });194 if (sub) sub.lines.forEach((line, i) => rise(ctx, e, t, tSub + i * 0.1, () => {195 ctx.font = font(500, sub.size);196 ctx.letterSpacing = `${subTrack(sub.size).toFixed(2)}px`;197 ctx.fillStyle = caps ? INK.gold : INK.soft;198 ctx.textAlign = "left";199 ctx.fillText(line, safe.l, yTitle + (block.lines.length - 1) * block.lh + subGap + sub.size * 0.75 + i * slh);200 ctx.letterSpacing = "0px";201 }, { dy: 16, dur: 0.9 }));202 };203}204205// ── bullets ──────────────────────────────────────────────────────────────────206function bulletsScene(spec: Extract<MotionSpec, { type: "bullets" }>, e: Env): Draw {207 const { safe, u } = e;208 const n = spec.items.length;209 // listes longues en 16:9 : deux colonnes (corps bien plus grand qu'une seule colonne tassée)210 const cols = e.kind === "wide" && n >= 5 ? 2 : 1;211 const perCol = Math.ceil(n / cols);212 const head = header(e, spec.heading, "", n >= 5);213 const avail = safe.h - head.height;214 const colGap = 70 * u, colW = (safe.w - (cols - 1) * colGap) / cols;215 const colOf = (i: number) => Math.floor(i / perCol);216 let size = (e.kind === "wide" ? 60 : 56) * u, wrapped: string[][] = [], gap = 0, lh = 0, indent = 0;217 const colHeights = () => Array.from({ length: cols }, (_, c) => wrapped.reduce((a, l, i) => a + (colOf(i) === c ? l.length * lh + gap : 0), -gap));218 for (let gapK = 0.9; ; ) {219 e.probe.font = font(600, size * 0.62);220 indent = e.probe.measureText("00").width + size * 0.62;221 e.probe.font = font(500, size);222 wrapped = spec.items.map((it) => wrapText(e.probe, it.trim(), colW - indent - 20 * u));223 lh = size * 1.24; gap = size * gapK;224 if (Math.max(...colHeights()) <= avail || size <= 30 * u) break;225 // on resserre d'abord l'interligne entre éléments, puis on réduit le corps226 if (gapK > 0.5) gapK -= 0.1; else size *= 0.96;227 }228 // dernier recours : textes vraiment trop longs → lignes limitées, points de suspension229 e.probe.font = font(500, size);230 if (Math.max(...colHeights()) > avail) {231 const maxLines = Math.max(1, Math.floor((avail - gap * (perCol - 1)) / lh / perCol));232 wrapped = wrapped.map((l) => (l.length > maxLines ? [...l.slice(0, maxLines - 1), ellipsize(e.probe, `${l[maxLines - 1]} ${l[maxLines] ?? ""}…`, colW - indent - 20 * u)] : l));233 }234 const blocks = wrapped.map((lines) => layoutBlock(e.probe, lines, { fontOf: () => font(500, size), size, lineHeight: 1.24 }));235 const heights = wrapped.map((l) => l.length * lh);236 const total = Math.max(...colHeights());237 const y0 = safe.t + Math.max(0, (safe.h - head.height - total) * 0.44);238 const tops: number[] = [], lefts: number[] = [];239 let y = 0;240 heights.forEach((h, i) => { if (i % perCol === 0) y = y0 + head.height; tops[i] = y; lefts[i] = safe.l + colOf(i) * (colW + colGap); y += h + gap; });241 const first = spec.heading.trim() ? 0.55 : 0.25;242 const step = Math.min(1.6, Math.max(0.18, ((e.seconds - e.exitDur) * 0.74 / e.k - first) / n));243 const numSize = size * 0.62;244 return (ctx, t) => {245 head.draw(ctx, t, y0);246 // élément courant : celui dont l'entrée est la plus récente ; la plaque de mise en avant glisse de l'un à l'autre247 const cur = Math.min(n - 1, Math.max(0, Math.floor((t / e.k - first) / step + 1e-6)));248 const glide = easeInOutCubic(prog(t, (first + cur * step) * e.k, 0.5 * e.k));249 const from = Math.max(0, cur - 1);250 const px = lerp(lefts[from], lefts[cur], glide), py = lerp(tops[from], tops[cur], glide), ph = lerp(heights[from], heights[cur], glide);251 const pa = easeOutCubic(prog(t, first * e.k, 0.5 * e.k));252 const padY = Math.min(gap * 0.4, size * 0.34), padX = 26 * u;253 withAlpha(ctx, pa, () => {254 roundRect(ctx, px - padX, py - padY, colW + 2 * padX, ph + 2 * padY, 18 * u);255 ctx.fillStyle = "rgba(255,255,255,0.06)";256 ctx.fill();257 ctx.fillStyle = INK.gold;258 roundRect(ctx, px - padX, py - padY + (ph + 2 * padY) * 0.2, Math.max(3, 5 * u), (ph + 2 * padY) * 0.6, 3 * u);259 ctx.fill();260 });261 blocks.forEach((b, i) => {262 const start = (first + i * step) * e.k;263 const p = prog(t, start, 0.8 * e.k);264 if (p <= 0) return;265 // les éléments passés s'estompent légèrement266 const past = i < cur ? easeOutCubic(prog(t, (first + (i + 1) * step) * e.k, 0.5 * e.k)) : 0;267 withAlpha(ctx, lerp(1, 0.6, past), () => {268 const m = easeOutExpo(p);269 withAlpha(ctx, easeOutCubic(Math.min(1, p * 1.6)), () => {270 ctx.save();271 ctx.translate((1 - m) * -22 * u * e.I.travel, 0);272 ctx.font = font(600, numSize);273 ctx.fillStyle = INK.gold;274 ctx.textAlign = "left";275 ctx.fillText(String(i + 1).padStart(2, "0"), lefts[i], tops[i] + size * 0.9 - (size - numSize) * 0.08);276 ctx.restore();277 });278 drawKinetic(ctx, b, lefts[i] + indent, tops[i] + size * 0.9, { t, start, stagger: 0.09 * e.k, dur: 0.8 * e.k, unit: "line", color: INK.text });279 });280 });281 };282}283284// ── counter ──────────────────────────────────────────────────────────────────285function counterScene(spec: Extract<MotionSpec, { type: "counter" }>, e: Env): Draw {286 const { safe, u } = e;287 const fmt = (v: number) => formatNumber(v, spec.decimals, e.lang);288 const pre = spec.prefix.trim(), suf = spec.suffix.trim();289 const widest = [fmt(spec.to), fmt(spec.from)].sort((a, b) => b.length - a.length)[0].replace(/\d/g, "0");290 const unitK = (s: string) => (s.length <= 2 ? 0.5 : s.length <= 5 ? 0.38 : 0.27);291 const track = (px: number) => -px * 0.03;292 const measure = (size: number) => {293 e.probe.font = font(700, size);294 e.probe.letterSpacing = `${track(size).toFixed(2)}px`;295 const digitW = Math.max(...Array.from("0123456789", (d) => e.probe.measureText(d).width));296 const numW = Array.from(widest).reduce((a, ch) => a + (/\d/.test(ch) ? digitW : e.probe.measureText(ch).width), 0);297 e.probe.letterSpacing = "0px";298 const side = (s: string) => { if (!s) return 0; e.probe.font = font(600, size * unitK(s)); return e.probe.measureText(s).width + size * 0.07; };299 return { digitW, total: numW + side(pre) + side(suf), preW: side(pre), sufW: side(suf) };300 };301 let size = (e.kind === "wide" ? 310 : e.kind === "tall" ? 236 : 244) * u;302 while (measure(size).total > safe.w * 0.96 && size > 64 * u) size *= 0.95;303 const m = measure(size);304 const label = fitText(e.probe, spec.label.trim(), { weight: 500, max: (e.kind === "wide" ? 46 : 46) * u, min: 28 * u, maxWidth: safe.w * 0.86, maxLines: 3 });305 const llh = label.size * 1.3;306 const capH = size * 0.73;307 const barW = Math.min(safe.w * 0.5, 560 * u), barH = Math.max(3, 6 * u);308 const blockH = capH + 62 * u + barH + 50 * u + label.size * 0.76 + (label.lines.length - 1) * llh;309 const yNum = safe.t + (safe.h - blockH) * 0.48 + capH;310 const yBar = yNum + 62 * u;311 const cx = e.W / 2;312 const dur = Math.min(3, Math.max(0.6, (e.seconds - e.exitDur) * 0.52)) / e.I.speed;313 const start = 0.3 * e.k;314 const tEnd = start + dur;315 return (ctx, t) => {316 const lin = prog(t, start, dur);317 const p = easeOutCubic(lin);318 const done = lin >= 1;319 const value = spec.from + (spec.to - spec.from) * p;320 const text = fmt(done ? spec.to : value);321 const appearP = easeOutCubic(prog(t, 0.05 * e.k, 0.6 * e.k));322 // halo qui respire derrière le chiffre, onde à l'arrivée323 drawHalo(ctx, cx, yNum - capH * 0.45, Math.min(e.W, e.H) * 0.62, GOLD, (0.07 + 0.07 * p + 0.025 * Math.sin(t * 1.7)) * appearP);324 const pulse = prog(t, tEnd - 0.05, 1.1);325 if (pulse > 0 && pulse < 1) {326 ctx.strokeStyle = rgba(GOLD, 0.5 * (1 - pulse) ** 2);327 ctx.lineWidth = Math.max(1.5, 3 * u);328 ctx.beginPath();329 ctx.ellipse(cx, yNum - capH * 0.45, m.total * (0.5 + 0.28 * easeOutCubic(pulse)), capH * (0.9 + 0.9 * easeOutCubic(pulse)), 0, 0, Math.PI * 2);330 ctx.stroke();331 }332 // élan : le chiffre arrive avec un léger dépassement d'échelle puis « tape » à l'arrivée333 const pop = prog(t, tEnd - 0.04, 0.55);334 const scale = lerp(0.86, 1, e.I.bounce > 0 ? easeSpring(prog(t, 0.05 * e.k, 1.1 * e.k), e.I.bounce) : easeOutExpo(prog(t, 0.05 * e.k, 0.9 * e.k))) * (1 + 0.045 * Math.sin(Math.PI * pop) * (1 - pop));335 withAlpha(ctx, appearP, () => {336 ctx.save();337 ctx.translate(cx, yNum - capH * 0.45);338 ctx.scale(scale, scale);339 ctx.translate(-cx, -(yNum - capH * 0.45));340 ctx.font = font(700, size);341 ctx.letterSpacing = `${track(size).toFixed(2)}px`;342 const widths = Array.from(text, (ch) => (/\d/.test(ch) ? m.digitW : ctx.measureText(ch).width));343 const numW = widths.reduce((a, b) => a + b, 0);344 let x = cx - (numW + m.preW + m.sufW) / 2;345 const g = ctx.createLinearGradient(0, yNum - capH, 0, yNum);346 g.addColorStop(0, INK.goldHi);347 g.addColorStop(0.55, INK.gold);348 g.addColorStop(1, INK.goldLo);349 const side = (s: string, w: number) => {350 ctx.font = font(600, size * unitK(s));351 ctx.letterSpacing = "0px";352 ctx.fillStyle = INK.gold;353 ctx.textAlign = "left";354 ctx.fillText(s, x + (s === pre ? 0 : size * 0.07), yNum);355 x += w;356 };357 if (pre) side(pre, m.preW);358 ctx.font = font(700, size);359 ctx.letterSpacing = `${track(size).toFixed(2)}px`;360 ctx.fillStyle = g;361 ctx.textAlign = "center";362 // chiffres à chasse fixe (dessin cellule par cellule) : le nombre ne tremble pas pendant le décompte363 Array.from(text).forEach((ch, i) => { ctx.fillText(ch, x + widths[i] / 2 - track(size) / 2, yNum); x += widths[i]; });364 if (suf) side(suf, m.sufW);365 ctx.letterSpacing = "0px";366 ctx.restore();367 });368 // barre de progression : suit le décompte, puis un reflet la parcourt369 const bp = easeOutExpo(prog(t, 0.2 * e.k, 0.8 * e.k));370 const bx = cx - barW / 2;371 withAlpha(ctx, bp, () => {372 roundRect(ctx, bx, yBar, barW * bp, barH, barH / 2);373 ctx.fillStyle = "rgba(255,255,255,0.1)";374 ctx.fill();375 if (p > 0.004) {376 roundRect(ctx, bx, yBar, barW * p, barH, barH / 2);377 ctx.fillStyle = goldFill(ctx, bx, bx + barW, done ? ((t - tEnd) % 2.6) / 1.3 : -1);378 ctx.fill();379 drawHalo(ctx, bx + barW * p, yBar + barH / 2, 22 * u, GOLD, 0.55 * (done ? 0.45 + 0.25 * Math.sin((t - tEnd) * 3) : 1));380 }381 });382 rise(ctx, e, t, 0.4, () => {383 ctx.font = font(500, label.size);384 ctx.fillStyle = INK.soft;385 ctx.textAlign = "center";386 label.lines.forEach((line, i) => ctx.fillText(line, cx, yBar + barH + 50 * u + label.size * 0.76 + i * llh));387 }, { dy: 16 });388 };389}390391// ── bar_chart ────────────────────────────────────────────────────────────────392function barChartScene(spec: Extract<MotionSpec, { type: "bar_chart" }>, e: Env): Draw {393 const { safe, u } = e;394 const n = spec.bars.length;395 // beaucoup de barres en 16:9 : deux colonnes à la même échelle (des rangées deux fois plus hautes, donc lisibles)396 const cols = e.kind === "wide" && n >= 7 ? 2 : 1;397 const perCol = Math.ceil(n / cols);398 const head = header(e, spec.title, spec.unit, n >= 7);399 const note = sourceNote(e, spec.sourceNote);400 const values = spec.bars.map((b) => b.value);401 const dec = decimalsFor(values);402 const suffix = unitSuffix(spec.unit, e.lang);403 const lo = Math.min(0, ...values), hi = Math.max(0, ...values);404 const span = hi - lo || 1;405 const iMax = values.indexOf(Math.max(...values));406 const axisSize = 22 * u, axisH = axisSize * 1.9;407 const avail = safe.h - head.height - note.height - axisH;408 // étiquette au-dessus de la barre en formats carré et vertical, tant que les rangées sont assez hautes pour deux étages409 const stacked = e.kind !== "wide" && avail / perCol >= 84 * u;410 const rowH = Math.min(avail / perCol, (stacked ? 168 : 128) * u);411 const labelSize = Math.max(20 * u, Math.min(40 * u, rowH * (stacked ? 0.25 : 0.34)));412 const valueSize = labelSize * 1.04;413 const barH = stacked ? Math.min(rowH * 0.26, 38 * u) : Math.min(rowH * 0.46, 54 * u);414 const colGap = 90 * u, colW = (safe.w - (cols - 1) * colGap) / cols;415 e.probe.font = font(700, valueSize);416 const valueW = Math.max(...values.map((v) => e.probe.measureText(formatNumber(v, dec, e.lang) + suffix).width)) + 22 * u;417 e.probe.font = font(600, labelSize);418 const labelW = stacked ? 0 : Math.min(colW * (cols > 1 ? 0.46 : 0.36), Math.max(...spec.bars.map((b) => e.probe.measureText(b.label).width))) + 30 * u;419 const trackW = colW - labelW - (stacked ? 0 : valueW);420 const bodyH = rowH * perCol + axisH;421 const y0 = safe.t + Math.max(0, (safe.h - head.height - bodyH - note.height) * 0.4);422 const yRows = y0 + head.height;423 const ticks = niceTicks(lo, hi, e.kind === "wide" && cols === 1 ? 5 : 3).filter((v) => v >= lo - 1e-9 && v <= hi + 1e-9);424 const tdec = decimalsFor(ticks);425 const step = Math.min(0.24, Math.max(0.06, ((e.seconds - e.exitDur) * 0.4 / e.k) / n));426 const tAll = (0.5 + n * step + 1) * e.k;427 return (ctx, t) => {428 head.draw(ctx, t, y0);429 note.draw(ctx, t, yRows + bodyH + note.height - 6 * u);430 const ga = easeOutCubic(prog(t, 0.3 * e.k, 0.6 * e.k));431 for (let c = 0; c < cols; c++) {432 const left = safe.l + c * (colW + colGap), x0 = left + labelW;433 const rows = Math.min(perCol, n - c * perCol);434 // axes fins : lignes verticales aux graduations, ligne de base au zéro435 withAlpha(ctx, ga, () => {436 ctx.font = font(400, axisSize);437 ctx.textAlign = "center";438 ticks.forEach((v) => {439 const x = x0 + ((v - lo) / span) * trackW;440 ctx.fillStyle = v === 0 ? "rgba(255,255,255,0.3)" : "rgba(255,255,255,0.075)";441 ctx.fillRect(Math.round(x), yRows + rowH * rows * (1 - ga), Math.max(1, 1.5 * u), rowH * rows * ga + 8 * u);442 ctx.fillStyle = INK.dim;443 ctx.fillText(formatNumber(v, tdec, e.lang), x, yRows + rowH * rows + axisSize * 1.5);444 });445 });446 }447 spec.bars.forEach((b, i) => {448 const start = (0.5 + i * step) * e.k;449 const p = easeOutExpo(prog(t, start, 1.1 * e.k));450 const a = easeOutCubic(prog(t, start, 0.4 * e.k));451 if (a <= 0) return;452 const top = i === iMax;453 const c = Math.floor(i / perCol);454 const left = safe.l + c * (colW + colGap), right = left + colW, x0 = left + labelW;455 const zeroX = x0 + ((0 - lo) / span) * trackW;456 const rowY = yRows + (i % perCol) * rowH;457 const barY = stacked ? rowY + rowH - barH - rowH * 0.2 : rowY + (rowH - barH) / 2;458 const len = (Math.abs(b.value) / span) * trackW * p;459 const bx = b.value >= 0 ? zeroX : zeroX - len;460 withAlpha(ctx, a, () => {461 ctx.fillStyle = INK.track;462 roundRect(ctx, x0, barY, trackW, barH, 5 * u);463 ctx.fill();464 if (len > 0.5) {465 if (top) drawHalo(ctx, bx + (b.value >= 0 ? len : 0), barY + barH / 2, barH * 1.7, GOLD, 0.34 * p);466 roundRect(ctx, bx, barY, len, barH, Math.min(5 * u, len / 2));467 // le maximum est mis en avant (or, reflet récurrent) ; les autres barres restent en retrait468 ctx.fillStyle = top ? goldFill(ctx, bx, bx + Math.max(len, 1), t > tAll ? ((t - tAll) % 3) / 1.2 : -1) : "rgba(205,210,219,0.46)";469 ctx.fill();470 }471 ctx.font = font(top ? 600 : 500, labelSize);472 ctx.fillStyle = top ? INK.text : INK.soft;473 ctx.textAlign = "left";474 if (stacked) ctx.fillText(ellipsize(ctx, b.label, colW - valueW), left, barY - labelSize * 0.55);475 else ctx.fillText(ellipsize(ctx, b.label, labelW - 30 * u), left, barY + barH / 2 + labelSize * 0.36);476 ctx.font = font(700, valueSize);477 ctx.fillStyle = top ? INK.gold : INK.text;478 ctx.textAlign = "right";479 const shown = formatNumber(p >= 0.999 ? b.value : b.value * p, dec, e.lang) + suffix;480 ctx.fillText(shown, right, stacked ? barY - labelSize * 0.55 : barY + barH / 2 + valueSize * 0.36);481 });482 });483 };484}485486// ── line_chart ───────────────────────────────────────────────────────────────487function lineChartScene(spec: Extract<MotionSpec, { type: "line_chart" }>, e: Env): Draw {488 const { safe, u } = e;489 const head = header(e, spec.title, spec.unit);490 const note = sourceNote(e, spec.sourceNote);491 const ys = spec.points.map((p) => p.y);492 const ticks = niceTicks(Math.min(...ys), Math.max(...ys), e.kind === "wide" ? 4 : 5);493 const lo = ticks[0], hi = ticks[ticks.length - 1];494 const dec = Math.max(decimalsFor(ticks), 0);495 const vdec = Math.max(dec, decimalsFor(ys));496 const suffix = unitSuffix(spec.unit, e.lang);497 const axisSize = 25 * u, valSize = 40 * u;498 e.probe.font = font(400, axisSize);499 const yLabelW = Math.max(...ticks.map((v) => e.probe.measureText(formatNumber(v, dec, e.lang)).width)) + 20 * u;500 const lastLabel = formatNumber(ys[ys.length - 1], vdec, e.lang) + suffix;501 e.probe.font = font(700, valSize);502 const widestVal = Math.max(...ys.map((v) => e.probe.measureText(formatNumber(v, vdec, e.lang) + suffix).width));503 const endPad = widestVal / 2 + 12 * u;504 const n = spec.points.length;505 const plotH = Math.min(safe.h - head.height - note.height - axisSize * 2.1 - valSize * 1.6, safe.w * (e.kind === "wide" ? 0.36 : 0.86));506 const bodyH = valSize * 1.6 + plotH + axisSize * 2.1;507 const y0 = safe.t + Math.max(0, (safe.h - head.height - bodyH - note.height) * 0.4);508 const px0 = safe.l + yLabelW, px1 = safe.r - endPad;509 const py0 = y0 + head.height + valSize * 1.6, py1 = py0 + plotH;510 const X = (i: number) => px0 + (i / (n - 1)) * (px1 - px0);511 const Y = (v: number) => py1 - ((v - lo) / (hi - lo)) * (py1 - py0);512 e.probe.font = font(400, axisSize);513 const maxLabels = Math.max(2, Math.min(n, Math.floor((px1 - px0) / (Math.max(...spec.points.map((p) => e.probe.measureText(p.x).width)) + 40 * u)) + 1));514 const labelIdx = Array.from(new Set(Array.from({ length: maxLabels }, (_, k) => Math.round((k / (maxLabels - 1)) * (n - 1)))));515 const drawDur = Math.min(3, Math.max(0.7, (e.seconds - e.exitDur) * 0.5)) / e.I.speed;516 const startLine = 0.55 * e.k;517 const iMax = ys.indexOf(Math.max(...ys));518 // le maximum reçoit son repère, sauf s'il se confond avec la valeur finale (étiquetée de toute façon)519 const showMax = iMax < n - 1 && X(n - 1) - X(iMax) > widestVal * 1.15;520 const tMax = startLine + drawDur * easeInvCubic(iMax / (n - 1));521 return (ctx, t) => {522 head.draw(ctx, t, y0);523 note.draw(ctx, t, py1 + axisSize * 2.1 + note.height - 6 * u);524 const ga = easeOutCubic(prog(t, 0.25 * e.k, 0.7 * e.k));525 withAlpha(ctx, ga, () => {526 ctx.font = font(400, axisSize);527 ticks.forEach((v) => {528 ctx.fillStyle = v === lo ? "rgba(255,255,255,0.28)" : "rgba(255,255,255,0.075)";529 ctx.fillRect(px0, Math.round(Y(v)), (px1 - px0) * ga, Math.max(1, 1.5 * u));530 ctx.fillStyle = INK.dim;531 ctx.textAlign = "right";532 ctx.fillText(formatNumber(v, dec, e.lang), px0 - 16 * u, Y(v) + axisSize * 0.35);533 });534 labelIdx.forEach((i, k) => {535 ctx.textAlign = k === 0 ? "left" : k === labelIdx.length - 1 ? "right" : "center";536 ctx.fillStyle = INK.muted;537 ctx.fillText(spec.points[i].x, k === 0 ? px0 : k === labelIdx.length - 1 ? px1 : X(i), py1 + axisSize * 1.6);538 });539 });540541 const p = easeInOutCubic(prog(t, startLine, drawDur));542 if (p <= 0) return;543 const pos = p * (n - 1), full = Math.min(n - 1, Math.floor(pos)), frac = pos - full;544 const pts: [number, number][] = [];545 for (let i = 0; i <= full; i++) pts.push([X(i), Y(ys[i])]);546 let headValue = ys[full];547 if (full < n - 1 && frac > 0) { headValue = ys[full] + (ys[full + 1] - ys[full]) * frac; pts.push([X(full) + (X(full + 1) - X(full)) * frac, Y(headValue)]); }548 const [ex, ey] = pts[pts.length - 1];549 const fill = ctx.createLinearGradient(0, py0, 0, py1);550 fill.addColorStop(0, rgba(GOLD, 0.26));551 fill.addColorStop(1, rgba(GOLD, 0));552 ctx.beginPath();553 ctx.moveTo(pts[0][0], py1);554 pts.forEach(([x, y]) => ctx.lineTo(x, y));555 ctx.lineTo(ex, py1);556 ctx.closePath();557 ctx.fillStyle = fill;558 ctx.fill();559 ctx.lineJoin = "round";560 ctx.lineCap = "round";561 const stroke = (w: number, style: string) => {562 ctx.beginPath();563 pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));564 ctx.strokeStyle = style;565 ctx.lineWidth = w;566 ctx.stroke();567 };568 stroke(Math.max(8, 18 * u), rgba(GOLD, 0.1));569 stroke(Math.max(3, 6 * u), INK.gold);570 // repère du maximum571 if (showMax) {572 const mp = prog(t, tMax, 0.5 * e.k);573 if (mp > 0) {574 const mx = X(iMax), my = Y(ys[iMax]);575 withAlpha(ctx, easeOutCubic(mp), () => {576 ctx.fillStyle = "rgba(255,255,255,0.16)";577 ctx.fillRect(mx - 0.75 * u, my, Math.max(1, 1.5 * u), py1 - my);578 ctx.beginPath();579 ctx.arc(mx, my, 8 * u * easeSpring(mp, 0.4), 0, Math.PI * 2);580 ctx.fillStyle = INK.goldHi;581 ctx.fill();582 ctx.font = font(700, valSize * 0.8);583 ctx.textAlign = "center";584 ctx.fillStyle = INK.text;585 ctx.fillText(formatNumber(ys[iMax], vdec, e.lang) + suffix, mx, my - 22 * u - (1 - easeOutExpo(mp)) * 14 * u);586 });587 }588 }589 // tête de la courbe : halo pulsé + valeur courante qui s'incrémente590 const beat = 0.5 + 0.5 * Math.sin(t * 4.2);591 drawHalo(ctx, ex, ey, (26 + 10 * beat) * u, GOLD, 0.5);592 ctx.beginPath();593 ctx.arc(ex, ey, 10 * u, 0, Math.PI * 2);594 ctx.fillStyle = INK.bg;595 ctx.fill();596 ctx.strokeStyle = INK.gold;597 ctx.lineWidth = Math.max(2, 4.5 * u);598 ctx.stroke();599 const nearMax = showMax && Math.abs(ex - X(iMax)) < widestVal * 1.1;600 withAlpha(ctx, easeOutCubic(prog(t, startLine, 0.4 * e.k)) * (nearMax ? clamp01(Math.abs(ex - X(iMax)) / (widestVal * 1.1)) ** 2 : 1), () => {601 ctx.font = font(700, valSize);602 ctx.fillStyle = INK.gold;603 ctx.textAlign = "center";604 ctx.fillText(p >= 1 ? lastLabel : formatNumber(headValue, vdec, e.lang) + suffix, Math.min(Math.max(ex, px0 + widestVal / 2), safe.r - widestVal / 2 - 2 * u), Math.max(ey - 30 * u, py0 - valSize * 0.5));605 });606 };607}608/** Inverse de easeInOutCubic (instant où la tête de la courbe atteint une abscisse donnée). */609function easeInvCubic(y: number): number {610 const v = clamp01(y);611 return v < 0.5 ? Math.cbrt(v / 4) : 1 - Math.cbrt((1 - v) * 2) / 2;612}613614// ── timeline ─────────────────────────────────────────────────────────────────615function timelineScene(spec: Extract<MotionSpec, { type: "timeline" }>, e: Env): Draw {616 const { safe, u } = e;617 const n = spec.events.length;618 const head = header(e, spec.title, "", n >= 6);619 const first = 0.5;620 const step = Math.min(1.4, Math.max(0.14, ((e.seconds - e.exitDur) * 0.72 / e.k - first) / n));621 const lit = (t: number, i: number) => prog(t, (first + i * step) * e.k, 0.5 * e.k);622 const current = (t: number) => Math.min(n - 1, Math.max(0, Math.floor((t / e.k - first) / step + 1e-6)));623 const travel = (t: number) => { const c = current(t); return c + easeInOutCubic(prog(t, (first + c * step) * e.k - 0.45 * e.k, 0.45 * e.k)) - 1; };624 const node = (ctx: Ctx, t: number, i: number, x: number, y: number, k = 1) => {625 const dp = lit(t, i);626 ctx.beginPath();627 ctx.arc(x, y, 7 * u * k, 0, Math.PI * 2);628 ctx.fillStyle = INK.bg;629 ctx.fill();630 ctx.strokeStyle = "rgba(255,255,255,0.3)";631 ctx.lineWidth = Math.max(1.5, 2.5 * u);632 ctx.stroke();633 if (dp <= 0) return;634 const isCur = current(t) === i;635 if (dp < 1) { ctx.strokeStyle = rgba(GOLD, 0.7 * (1 - dp)); ctx.lineWidth = Math.max(1.5, 3 * u); ctx.beginPath(); ctx.arc(x, y, (12 + 34 * easeOutCubic(dp)) * u * k, 0, Math.PI * 2); ctx.stroke(); }636 drawHalo(ctx, x, y, (isCur ? 40 + 6 * Math.sin(t * 3.4) : 24) * u * k, GOLD, isCur ? 0.5 : 0.22);637 ctx.beginPath();638 ctx.arc(x, y, 12 * u * k * easeSpring(dp, 0.2 + e.I.bounce), 0, Math.PI * 2);639 ctx.fillStyle = INK.gold;640 ctx.fill();641 };642 const dim = (t: number, i: number) => (i < current(t) ? lerp(1, 0.68, easeOutCubic(lit(t, i + 1))) : 1);643644 if (e.kind === "wide") {645 const colW = safe.w / n;646 const dateSize = Math.min(76 * u, colW * 0.21), labelSize = Math.min(38 * u, Math.max(22 * u, colW * 0.1));647 e.probe.font = font(500, labelSize);648 const labels = spec.events.map((ev) => wrapText(e.probe, ev.label.trim(), colW * 1.7 - 24 * u).slice(0, 4));649 const lh = labelSize * 1.28;650 const stem = 44 * u;651 const blockH = (i: number) => dateSize * 0.8 + 14 * u + labels[i].length * lh;652 const upH = Math.max(0, ...spec.events.map((_, i) => (i % 2 === 0 ? blockH(i) : 0))), downH = Math.max(0, ...spec.events.map((_, i) => (i % 2 ? blockH(i) : 0)));653 const bodyH = upH + downH + 2 * (stem + 22 * u);654 const y0 = safe.t + Math.max(0, (safe.h - head.height - bodyH) * 0.45);655 const yLine = y0 + head.height + upH + stem + 22 * u;656 const cx = (i: number) => safe.l + colW * (i + 0.5);657 return (ctx, t) => {658 head.draw(ctx, t, y0);659 const lp = easeOutExpo(prog(t, 0.25 * e.k, 1 * e.k));660 ctx.fillStyle = "rgba(255,255,255,0.14)";661 ctx.fillRect(safe.l, yLine - u, safe.w * lp, Math.max(1.5, 2 * u));662 // la ligne or se trace jusqu'au jalon courant663 const tr = travel(t);664 if (tr > -1) {665 const xEnd = tr <= 0 ? lerp(safe.l, cx(0), tr + 1) : lerp(cx(Math.floor(tr)), cx(Math.min(n - 1, Math.floor(tr) + 1)), tr - Math.floor(tr));666 ctx.fillStyle = INK.gold;667 ctx.fillRect(safe.l, yLine - 1.5 * u, Math.max(0, xEnd - safe.l), Math.max(2, 3.5 * u));668 }669 spec.events.forEach((ev, i) => {670 const up = i % 2 === 0; // alternance au-dessus / au-dessous de la ligne : deux fois plus de place par étiquette671 node(ctx, t, i, cx(i), yLine);672 const dp = lit(t, i);673 if (dp <= 0) return;674 withAlpha(ctx, dim(t, i), () => {675 const sp = easeOutExpo(dp);676 ctx.fillStyle = rgba(GOLD, 0.55);677 ctx.fillRect(cx(i) - u, up ? yLine - 16 * u - stem * sp : yLine + 16 * u, Math.max(1.5, 2 * u), stem * sp);678 withAlpha(ctx, easeOutCubic(dp), () => {679 ctx.save();680 ctx.translate(0, (1 - sp) * (up ? 18 : -18) * u * e.I.travel);681 ctx.textAlign = "center";682 const y = up ? yLine - stem - 22 * u - blockH(i) : yLine + stem + 22 * u;683 ctx.font = font(700, dateSize);684 ctx.fillStyle = INK.gold;685 ctx.fillText(ellipsize(ctx, ev.date.trim(), colW * 1.7), cx(i), y + dateSize * 0.8);686 ctx.font = font(500, labelSize);687 ctx.fillStyle = INK.text;688 labels[i].forEach((line, j) => ctx.fillText(j === labels[i].length - 1 ? ellipsize(ctx, line, colW * 1.7) : line, cx(i), y + dateSize * 0.8 + 14 * u + labelSize * 0.86 + j * lh));689 ctx.restore();690 });691 });692 });693 };694 }695 // formats vertical et carré : ligne verticale à gauche, événements empilés696 const avail = safe.h - head.height;697 const rowH = Math.min(avail / n, 230 * u);698 // rangées basses (beaucoup de jalons) : date et libellé sur une même ligne699 const inline = rowH < 112 * u;700 const dateSize = inline ? Math.max(22 * u, Math.min(40 * u, rowH * 0.5)) : Math.min(54 * u, rowH * 0.3);701 const labelSize = inline ? dateSize * 0.86 : Math.min(38 * u, Math.max(24 * u, rowH * 0.2));702 const xLine = safe.l + 14 * u, xText = safe.l + 66 * u;703 e.probe.font = font(700, dateSize);704 const dateW = inline ? Math.max(...spec.events.map((ev) => e.probe.measureText(ev.date.trim()).width)) + 28 * u : 0;705 e.probe.font = font(500, labelSize);706 const maxLines = inline ? 1 : Math.max(1, Math.floor((rowH - dateSize * 1.35) / (labelSize * 1.28)));707 const labels = spec.events.map((ev) => wrapText(e.probe, ev.label.trim(), safe.r - xText - dateW).slice(0, maxLines));708 const y0 = safe.t + Math.max(0, (avail - rowH * n) * 0.45);709 const yRow = (i: number) => y0 + head.height + i * rowH;710 const yDot = (i: number) => yRow(i) + dateSize * 0.44;711 return (ctx, t) => {712 head.draw(ctx, t, y0);713 const lp = easeOutExpo(prog(t, 0.25 * e.k, 1 * e.k));714 ctx.fillStyle = "rgba(255,255,255,0.14)";715 ctx.fillRect(xLine - u, yDot(0), Math.max(1.5, 2 * u), (yDot(n - 1) - yDot(0)) * lp);716 const tr = travel(t);717 if (tr > 0) {718 ctx.fillStyle = INK.gold;719 ctx.fillRect(xLine - 1.5 * u, yDot(0), Math.max(2, 3.5 * u), lerp(yDot(Math.floor(tr)), yDot(Math.min(n - 1, Math.floor(tr) + 1)), tr - Math.floor(tr)) - yDot(0));720 }721 spec.events.forEach((ev, i) => {722 node(ctx, t, i, xLine, yDot(i), inline ? Math.min(1, rowH / (60 * u)) : 1);723 const dp = lit(t, i);724 if (dp <= 0) return;725 withAlpha(ctx, dim(t, i) * easeOutCubic(dp), () => {726 ctx.save();727 ctx.translate((1 - easeOutExpo(dp)) * -24 * u * e.I.travel, 0);728 ctx.textAlign = "left";729 ctx.font = font(700, dateSize);730 ctx.fillStyle = INK.gold;731 ctx.fillText(ellipsize(ctx, ev.date.trim(), safe.r - xText), xText, yRow(i) + dateSize * 0.8);732 ctx.font = font(500, labelSize);733 ctx.fillStyle = INK.text;734 if (inline) ctx.fillText(ellipsize(ctx, ev.label.trim(), safe.r - xText - dateW), xText + dateW, yRow(i) + dateSize * 0.8);735 else labels[i].forEach((line, j) => ctx.fillText(j === labels[i].length - 1 ? ellipsize(ctx, line, safe.r - xText) : line, xText, yRow(i) + dateSize * 0.8 + 16 * u + labelSize * 0.86 + j * labelSize * 1.28));736 ctx.restore();737 });738 });739 };740}741742// ── quote ────────────────────────────────────────────────────────────────────743function quoteScene(spec: Extract<MotionSpec, { type: "quote" }>, e: Env): Draw {744 const { safe, u } = e;745 const wide = e.kind === "wide";746 const bare = spec.text.trim().replace(/^[«"“”\s ]+|[»"“”\s ]+$/g, "");747 const mark = e.lang === "fr" ? "«" : "“";748 const maxW = safe.w * (wide ? 0.86 : 1);749 const markSize = (wide ? 300 : 260) * u;750 e.probe.font = displayFont(markSize);751 const mm = e.probe.measureText(mark);752 const markH = mm.actualBoundingBoxAscent - Math.max(0, -mm.actualBoundingBoxDescent); // hauteur d'encre du guillemet753 const markBottom = Math.max(0, -mm.actualBoundingBoxDescent);754 const attrText = spec.attribution.trim().replace(/^[—–-]\s*/, "");755 const attrSize = 30 * u;756 const attr = attrText ? fitText(e.probe, attrText.toLocaleUpperCase(e.lang === "fr" ? "fr-CA" : "en-US"), { weight: 600, max: attrSize, min: 22 * u, maxWidth: maxW - 76 * u, maxLines: 2, letterSpacing: (px) => px * 0.12 }) : null;757 const attrH = attr ? 54 * u + attr.size * 0.76 + (attr.lines.length - 1) * attr.size * 1.4 : 0;758 const availText = safe.h - markH - 40 * u - attrH;759 const track = (px: number) => -px * 0.008;760 let q = fitText(e.probe, bare, { weight: 400, fontOf: (px) => displayFont(px), max: (wide ? 124 : 100) * u, min: 40 * u, maxWidth: maxW, maxLines: wide ? 5 : 9, letterSpacing: track });761 while (q.lines.length * q.size * 1.16 > availText && q.size > 40 * u) q = fitText(e.probe, bare, { weight: 400, fontOf: (px) => displayFont(px), max: q.size * 0.94, min: 40 * u, maxWidth: maxW, maxLines: Math.max(1, Math.floor(availText / (40 * u * 1.16))), letterSpacing: track });762 const lines = q.lines.join(" ").endsWith("…") && !bare.endsWith("…") ? q.lines : balance(e.probe, bare, displayFont(q.size), maxW, q.lines.length, track(q.size));763 const block = layoutBlock(e.probe, lines, { fontOf: () => displayFont(q.size), size: q.size, lineHeight: 1.16, tracking: track(q.size) });764 const textH = q.size * 0.76 + (lines.length - 1) * block.lh;765 const blockH = markH + 40 * u + textH + attrH;766 const y0 = safe.t + (safe.h - blockH) * 0.46;767 const yText = y0 + markH + 40 * u + q.size * 0.76;768 const step = Math.min(0.2 * e.I.stagger, ((e.seconds - e.exitDur) * 0.4 / e.k) / lines.length) * e.k;769 const tAttr = 0.5 * e.k + lines.length * step + 0.25 * e.k;770 return (ctx, t) => {771 const z = 1 + 0.024 * (t / Math.max(e.seconds, 0.1));772 ctx.translate(safe.l, y0 + blockH / 2);773 ctx.scale(z, z);774 ctx.translate(-safe.l, -(y0 + blockH / 2));775 // guillemet géant : arrive avec un ressort, puis respire776 const mp = prog(t, 0.05 * e.k, 1 * e.k);777 if (mp > 0) withAlpha(ctx, easeOutCubic(Math.min(1, mp * 1.8)), () => {778 const s = lerp(0.6, 1, easeSpring(mp, 0.15 + e.I.bounce)) * (1 + 0.012 * Math.sin(t * 1.5));779 const ax = safe.l + mm.actualBoundingBoxLeft, ay = y0 + markH;780 drawHalo(ctx, ax + mm.width * 0.4, ay - markH / 2, markSize * 0.9, GOLD, 0.1 + 0.03 * Math.sin(t * 1.5));781 ctx.save();782 ctx.translate(ax, ay);783 ctx.scale(s, s);784 ctx.font = displayFont(markSize);785 ctx.fillStyle = INK.gold;786 ctx.textAlign = "left";787 ctx.fillText(mark, 0, markBottom);788 ctx.restore();789 });790 drawKinetic(ctx, block, safe.l, yText, { t, start: 0.35 * e.k, stagger: step, dur: 0.95 * e.k, unit: "line", color: INK.text });791 if (attr) {792 const ap = prog(t, tAttr, 0.8 * e.k);793 if (ap > 0) withAlpha(ctx, easeOutCubic(ap), () => {794 const yA = yText + (lines.length - 1) * block.lh + 54 * u + attr.size * 0.76;795 ctx.fillStyle = INK.gold;796 ctx.fillRect(safe.l, yA - attr.size * 0.34, 52 * u * easeOutExpo(ap), Math.max(2, 3 * u));797 ctx.font = font(600, attr.size);798 ctx.letterSpacing = `${(attr.size * 0.12).toFixed(2)}px`;799 ctx.fillStyle = INK.soft;800 ctx.textAlign = "left";801 attr.lines.forEach((line, i) => ctx.fillText(line, safe.l + 76 * u + (1 - easeOutExpo(ap)) * -14 * u, yA + i * attr.size * 1.4));802 ctx.letterSpacing = "0px";803 });804 }805 };806}807808function build(spec: MotionSpec, e: Env): Draw {809 switch (spec.type) {810 case "title": return titleScene(spec, e);811 case "bullets": return bulletsScene(spec, e);812 case "counter": return counterScene(spec, e);813 case "bar_chart": return barChartScene(spec, e);814 case "line_chart": return lineChartScene(spec, e);815 case "timeline": return timelineScene(spec, e);816 case "quote": return quoteScene(spec, e);817 default: throw new Error(`MotionSpec inconnu : ${(spec as { type: string }).type}`);818 }819}820821/** Décor par type : géométrie et point de lumière choisis pour servir la composition (la lumière chaude derrière le sujet). */822const STAGE: Record<MotionSpec["type"], { variant: BackdropVariant; focus: { x: number; y: number } }> = {823 title: { variant: "orbits", focus: { x: 0.74, y: 0.34 } },824 bullets: { variant: "beams", focus: { x: 0.2, y: 0.25 } },825 counter: { variant: "grid", focus: { x: 0.5, y: 0.42 } },826 bar_chart: { variant: "grid", focus: { x: 0.72, y: 0.3 } },827 line_chart: { variant: "grid", focus: { x: 0.6, y: 0.5 } },828 timeline: { variant: "beams", focus: { x: 0.5, y: 0.5 } },829 quote: { variant: "orbits", focus: { x: 0.24, y: 0.3 } },830};831832/** Fabrique le dessin complet d'une scène (décor + contenu + sortie) : `frame(ctx, t)`. */833function scene(spec: MotionSpec, o: MotionOptions & { fps?: number }): Draw {834 const e = makeEnv(o);835 const draw = build(spec, e);836 const stage = STAGE[spec.type];837 const backdrop = makeBackdrop({ width: o.width, height: o.height, seed: o.seed ?? hashString(spec.type), variant: stage.variant, focus: stage.focus, energy: e.I.energy, intro: Math.min(0.9, o.seconds * 0.3), fps: o.fps });838 return (ctx, t) => {839 ctx.globalAlpha = 1;840 backdrop.draw(ctx, t);841 const out = e.exitDur > 0 ? easeInCubic(prog(t, e.seconds - e.exitDur, e.exitDur)) : 0;842 ctx.save();843 ctx.globalAlpha = 1 - out;844 ctx.translate(0, -out * 16 * e.u);845 draw(ctx, t);846 ctx.restore();847 };848}849850/** Dessine une trame isolée (PNG) : aperçus, tests visuels, planches-contact. */851export async function renderMotionFrame(spec: MotionSpec, o: MotionOptions & { at: number }): Promise<Buffer> {852 const frame = scene(spec, o);853 const { canvas, ctx } = newCanvas(o.width, o.height);854 frame(ctx, o.at);855 return canvas.encode("png");856}857858/**859 * Rend une animation en vidéo intermédiaire (H.264 CRF 12, `fps` constant, piste audio silencieuse 48 kHz stéréo).860 * Paramètres facultatifs : `seed` (variante du décor), `exit` (sortie animée du contenu en fin de scène, défaut : oui).861 */862export async function renderMotion(spec: MotionSpec, o: MotionOptions & { fps: number; output: string }): Promise<void> {863 if (!(o.seconds > 0)) throw new Error("renderMotion : durée invalide");864 const frame = scene(spec, o);865 await renderCanvasVideo({ width: o.width, height: o.height, fps: o.fps, seconds: o.seconds, output: o.output, draw: (ctx, t) => frame(ctx, t) });866}867