Repository Public
1"use client";23import { Inline } from "@/renderer/inline";4import { Component, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";5import type { Locale } from "@/schema";6import { describeParams, isSimKind, paramDefs, resolveParams, SIMULATIONS, snapParam, type SimBlock, type SimDef } from "./registry";7import { decimalsOf, fmt, fmtInt } from "./ui/format";89const UI = {10 fr: {11 synthetic: "Données synthétiques — graine", analytic: "Illustration analytique", newDraw: "Nouveau tirage", resetParams: "Réinitialiser les paramètres",12 controls: "Paramètres de la simulation", play: "Lecture", pause: "Pause", prev: "Étape précédente", next: "Étape suivante", restart: "Revenir au début",13 speed: "Vitesse", step: "Étape", playback: "Animation", params: "Paramètres",14 unknown: "Simulation inconnue", failed: "Cette simulation ne peut pas être affichée", invalid: "Configuration invalide",15 },16 en: {17 synthetic: "Synthetic data — seed", analytic: "Analytic illustration", newDraw: "New draw", resetParams: "Reset parameters",18 controls: "Simulation parameters", play: "Play", pause: "Pause", prev: "Previous step", next: "Next step", restart: "Back to the start",19 speed: "Speed", step: "Step", playback: "Animation", params: "Parameters",20 unknown: "Unknown simulation", failed: "This simulation cannot be displayed", invalid: "Invalid configuration",21 },22} as const;2324const SPEEDS = [0.5, 1, 2] as const;25const BASE_STEP_MS = 1100;26const FRAME_MS = 1000 / 30;27const MAX_SEED = 2 ** 31 - 1;2829function ErrorMessage({ kind, locale, title, detail }: { kind: string; locale: Locale; title: string; detail?: string }) {30 return (31 <figure className="sim sim-error" data-sim={kind} role="group">32 <p className="sim-error-title">{title}</p>33 {detail ? <p className="sim-error-detail" lang={locale === "fr" ? "en" : undefined}>{detail}</p> : null}34 </figure>35 );36}3738/** A drawing error must never take the page down: the block is replaced by a message. */39class SimErrorBoundary extends Component<{ kind: string; locale: Locale; resetKey?: string; children: ReactNode }, { message: string | null }> {40 state: { message: string | null } = { message: null };41 static getDerivedStateFromError(error: unknown): { message: string } { return { message: error instanceof Error ? error.message : String(error) }; }42 componentDidUpdate(prev: { resetKey?: string }): void {43 // New parameters deserve a new attempt.44 if (prev.resetKey !== this.props.resetKey && this.state.message !== null) this.setState({ message: null });45 }46 render(): ReactNode {47 if (this.state.message !== null) return <ErrorMessage kind={this.props.kind} locale={this.props.locale} title={UI[this.props.locale].failed} detail={this.state.message} />;48 return this.props.children;49 }50}5152type Computed = { ok: true; model: unknown } | { ok: false; error: string };53function computeModel(def: SimDef, params: Record<string, number>, seed: number, config: SimBlock["config"], locale: Locale): Computed {54 try { return { ok: true, model: def.compute(params, seed, { ...config, locale }) }; }55 catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }56}57function stepCount(def: SimDef, model: unknown): number { return def.steps ? Math.max(1, Math.floor(def.steps(model))) : 0; }5859function Badge({ def, seed, locale }: { def: SimDef; seed: number; locale: Locale }) {60 const L = UI[locale];61 return <span className="sim-badge" data-kind={def.stochastic ? "synthetic" : "analytic"}>{def.stochastic ? `${L.synthetic} ${fmtInt(locale, seed)}` : L.analytic}</span>;62}6364function Frame({ block, def, locale, seed, children, footer, mode }: { block: SimBlock; def: SimDef; locale: Locale; seed: number; children: ReactNode; footer?: ReactNode; mode: "static" | "interactive" }) {65 return (66 <figure className="sim" data-sim={block.kind} data-mode={mode}>67 <header className="sim-head">68 <div className="sim-head-row">69 <h3 className="sim-title"><Inline text={block.title ?? def.title[locale]} /></h3>70 <Badge def={def} seed={seed} locale={locale} />71 </div>72 <p className="sim-desc"><Inline text={def.description[locale]} /></p>73 </header>74 {block.alt ? <p className="sim-sr">{block.alt}</p> : null}75 <div className="sim-picture">{children}</div>76 {footer}77 {block.caption ? <figcaption className="sim-caption"><Inline text={block.caption} /></figcaption> : null}78 </figure>79 );80}8182function StaticSimulation({ block, def, locale }: { block: SimBlock; def: SimDef; locale: Locale }) {83 const params = resolveParams(block);84 const res = computeModel(def, params, block.seed, block.config, locale);85 if (!res.ok) return <ErrorMessage kind={block.kind} locale={locale} title={UI[locale].invalid} detail={res.error} />;86 const n = stepCount(def, res.model);87 const summary = describeParams(block, locale);88 return (89 <Frame block={block} def={def} locale={locale} seed={block.seed} mode="static" footer={summary ? <p className="sim-summary">{UI[locale].params}{locale === "fr" ? " : " : ": "}{summary}</p> : null}>90 <def.View model={res.model} locale={locale} step={Math.max(0, n - 1)} idPrefix={`sim-${block.id}`} />91 </Frame>92 );93}9495const subscribeMedia = (query: string) => (cb: () => void) => {96 const mq = window.matchMedia(query);97 mq.addEventListener("change", cb);98 return () => mq.removeEventListener("change", cb);99};100const subscribeReducedMotion = subscribeMedia("(prefers-reduced-motion: reduce)");101const subscribeVisibility = (cb: () => void) => { document.addEventListener("visibilitychange", cb); return () => document.removeEventListener("visibilitychange", cb); };102103function InteractiveSimulation({ block, def, locale }: { block: SimBlock; def: SimDef; locale: Locale }) {104 const L = UI[locale];105 const defs = useMemo(() => paramDefs(block.kind, block.config), [block.kind, block.config]);106 const initial = useMemo(() => resolveParams(block), [block]);107 const [params, setParams] = useState<Record<string, number>>(initial);108 const [seed, setSeed] = useState<number>(block.seed);109 /** null = the default frame (the last one: the complete picture). */110 const [stepState, setStep] = useState<number | null>(null);111 const [playing, setPlaying] = useState(false);112 const [speed, setSpeed] = useState<(typeof SPEEDS)[number]>(1);113 const [onScreen, setOnScreen] = useState(true);114 const root = useRef<HTMLDivElement>(null);115 const autoplayed = useRef(false);116117 const reducedMotion = useSyncExternalStore(subscribeReducedMotion, () => window.matchMedia("(prefers-reduced-motion: reduce)").matches, () => false);118 const tabVisible = useSyncExternalStore(subscribeVisibility, () => !document.hidden, () => true);119120 const res = useMemo(() => computeModel(def, params, seed, block.config, locale), [def, params, seed, block.config, locale]);121 const nSteps = res.ok ? stepCount(def, res.model) : 0;122 const lastStep = Math.max(0, nSteps - 1);123 const step = Math.min(stepState ?? lastStep, lastStep);124 const stepRef = useRef(step);125 useEffect(() => { stepRef.current = step; }, [step]);126127 const start = useCallback(() => {128 if (stepRef.current >= lastStep) { stepRef.current = 0; setStep(0); }129 setPlaying(true);130 }, [lastStep]);131132 // Pause when the block leaves the screen; optionally start once when it first enters it.133 useEffect(() => {134 const el = root.current;135 if (!el || typeof IntersectionObserver === "undefined") return;136 const io = new IntersectionObserver((entries) => {137 const visible = entries.some((e) => e.isIntersecting);138 setOnScreen(visible);139 if (visible && !autoplayed.current && block.config.autoplay === true && nSteps > 1 && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {140 autoplayed.current = true;141 stepRef.current = 0; setStep(0); setPlaying(true);142 }143 }, { threshold: 0.2 });144 io.observe(el);145 return () => io.disconnect();146 }, [block.config.autoplay, nSteps]);147148 // The clock: one requestAnimationFrame loop, at most 30 ticks per second, and only state changes when a step is due.149 const running = playing && onScreen && tabVisible && nSteps > 1;150 useEffect(() => {151 if (!running) return;152 const interval = BASE_STEP_MS / speed;153 let raf = 0, last = performance.now(), acc = 0;154 const tick = (now: number) => {155 const dt = now - last;156 if (dt >= FRAME_MS) {157 last = now;158 acc += Math.min(dt, 250);159 if (acc >= interval) {160 acc = 0;161 if (stepRef.current >= lastStep) { setPlaying(false); return; }162 stepRef.current += 1;163 setStep(stepRef.current);164 if (stepRef.current >= lastStep) { setPlaying(false); return; }165 }166 }167 raf = requestAnimationFrame(tick);168 };169 raf = requestAnimationFrame(tick);170 return () => cancelAnimationFrame(raf);171 }, [running, speed, lastStep]);172173 const goTo = (s: number) => { setPlaying(false); setStep(Math.min(lastStep, Math.max(0, s))); };174 const dirty = seed !== block.seed || defs.some((d) => params[d.key] !== initial[d.key]);175 const reset = () => { setParams(initial); setSeed(block.seed); setStep(null); setPlaying(false); };176177 const hasControls = nSteps > 1 || defs.length > 0 || def.stochastic;178 const controls = !hasControls ? null : (179 <div className="sim-controls">180 {nSteps > 1 ? (181 <div className="sim-playback" role="group" aria-label={L.playback}>182 <button type="button" className="sim-btn sim-btn-primary" onClick={() => (playing ? setPlaying(false) : start())} aria-pressed={playing}>{playing ? L.pause : L.play}</button>183 <button type="button" className="sim-btn sim-btn-icon" onClick={() => goTo(0)} aria-label={L.restart} title={L.restart}><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M5 4v12M16 4l-8 6 8 6z" /></svg></button>184 <button type="button" className="sim-btn sim-btn-icon" onClick={() => goTo(step - 1)} disabled={step <= 0} aria-label={L.prev} title={L.prev}><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M13 4l-7 6 7 6z" /></svg></button>185 <button type="button" className="sim-btn sim-btn-icon" onClick={() => goTo(step + 1)} disabled={step >= lastStep} aria-label={L.next} title={L.next}><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M7 4l7 6-7 6z" /></svg></button>186 <label className="sim-scrub">187 <span className="sim-scrub-label">{L.step} {fmtInt(locale, step + 1)} / {fmtInt(locale, nSteps)}</span>188 <input type="range" min={0} max={lastStep} step={1} value={step} onChange={(e) => goTo(Number(e.target.value))} />189 </label>190 <button type="button" className="sim-btn" onClick={() => setSpeed(SPEEDS[(SPEEDS.indexOf(speed) + 1) % SPEEDS.length])} aria-label={`${L.speed} ${fmt(locale, speed, 1)}×`}>{fmt(locale, speed, 1)}×</button>191 </div>192 ) : null}193 {defs.length ? (194 <div className="sim-sliders" role="group" aria-label={L.controls}>195 {defs.map((d) => {196 const id = `sim-${block.id}-${d.key}`;197 const value = params[d.key] ?? d.default;198 const text = `${fmt(locale, value, decimalsOf(d.step))}${d.unit ? ` ${d.unit}` : ""}`;199 return (200 <div key={d.key} className="sim-slider">201 <label htmlFor={id}><span><Inline text={d.label[locale]} /></span><output htmlFor={id}>{text}</output></label>202 <input id={id} type="range" min={d.min} max={d.max} step={d.step} value={value} aria-valuetext={text}203 onChange={(e) => { const v = snapParam(d, Number(e.target.value)); setParams((p) => ({ ...p, [d.key]: v })); }} />204 </div>205 );206 })}207 </div>208 ) : null}209 <div className="sim-actions">210 {def.stochastic ? <button type="button" className="sim-btn" onClick={() => setSeed((s) => (s >= MAX_SEED ? 1 : s + 1))}>{L.newDraw}</button> : null}211 {defs.length || def.stochastic ? <button type="button" className="sim-btn" onClick={reset} disabled={!dirty}>{L.resetParams}</button> : null}212 </div>213 </div>214 );215216 return (217 <div ref={root} className="sim-root" data-reduced-motion={reducedMotion || undefined} data-playing={playing || undefined}>218 <Frame block={block} def={def} locale={locale} seed={seed} mode="interactive" footer={controls}>219 {res.ok220 ? <SimErrorBoundary resetKey={`${seed}:${JSON.stringify(params)}`} kind={block.kind} locale={locale}><def.View model={res.model} locale={locale} step={step} idPrefix={`sim-${block.id}`} /></SimErrorBoundary>221 : <div className="sim-error" role="alert"><p className="sim-error-title">{L.invalid}</p><p className="sim-error-detail">{res.error}</p></div>}222 </Frame>223 </div>224 );225}226227/**228 * Interactive simulation. The server render and the first paint are the static default state (document parameters229 * and seed, last animation frame); the block then becomes interactive. `staticOnly` renders only the picture230 * and a one-line summary of the parameter values (exports, print, previews).231 */232export function SimulationBlock({ block, locale, staticOnly }: { block: SimBlock; locale: Locale; staticOnly?: boolean }) {233 const L = UI[locale] ?? UI.fr;234 const loc: Locale = locale === "en" ? "en" : "fr";235 if (!block || !isSimKind(block.kind)) return <ErrorMessage kind={String(block?.kind)} locale={loc} title={L.unknown} detail={String(block?.kind)} />;236 const def = SIMULATIONS[block.kind];237 const safe: SimBlock = { ...block, params: block.params ?? {}, config: block.config ?? {}, seed: Number.isInteger(block.seed) ? block.seed : 1 };238 return (239 <SimErrorBoundary kind={block.kind} locale={loc}>240 {staticOnly ? <StaticSimulation block={safe} def={def} locale={loc} /> : <InteractiveSimulation key={JSON.stringify([safe.kind, safe.params, safe.seed, safe.config])} block={safe} def={def} locale={loc} />}241 </SimErrorBoundary>242 );243}244