Repository Public
1"use client";2import { useId, useState } from "react";3import { SIM_KINDS, type BlockOf } from "@/schema";4import { fill } from "@/i18n/dict";5import { paramDefs, SIMULATIONS, snapParam, type ParamDef } from "@/sim/registry";6import {7 CHART_MAX_POINTS, CHART_MAX_SERIES, convertPointsX, datasetToSeries, gridToPoints, MATRIX_MAX, matrixAddColumn, matrixAddRow, matrixMoveColumn, matrixMoveRow,8 matrixPaste, matrixRemoveColumn, matrixRemoveRow, numberText, optional, parseNumber, pasteCells, pointsToGrid, rectangular, removeItem, replaceItem, rowToPoint,9 seriesTone, simWithConfig, simWithKind, type ChartPoint, type ChartSeries, type Dataset,10} from "./helpers";11import { ChipSelect, GridEditor, Group, ListEditor, LongText, Note, NumberField, Segmented, Select, TextField, Toggle, TonePicker, useIssue, useLocale, useT } from "./primitives";12import { sliderBoundFields, SIM_CONFIG, type ConfigField } from "./sim-config";13import { AXIS_SCALE, AXIS_TYPE, CHART_KIND, DATA_KIND, DATA_KIND_HELP, MATRIX_SCALE, labelOptions } from "./strings";14import type { FormEnv, FormProps } from "./types";1516type Chart = BlockOf<"chart">;17type DataKindValue = Chart["dataKind"];1819/** Nature of the numbers, with one line on what each choice commits the author to. */20function DataKindField({ value, onChange }: { value: DataKindValue; onChange: (v: DataKindValue) => void }) {21 const t = useT();22 const locale = useLocale();23 const names = DATA_KIND(locale), help = DATA_KIND_HELP(locale);24 return (25 <Select label={t.dataKind} value={value} options={labelOptions(names)} onChange={onChange}26 hint={labelOptions(help).map((o) => <span key={o.value} className={`block ${o.value === value ? "font-medium text-ink" : ""}`}>{names[o.value]} : {o.label}</span>)} />27 );28}2930// ── Chart ───────────────────────────────────────────────────────────────────────────────────────────3132function AxisFields<A extends Chart["y"]>({ axis, path, onChange }: { axis: A; path: "x" | "y"; onChange: (next: A) => void }) {33 const t = useT();34 const locale = useLocale();35 return (36 <>37 <TextField label={t.axisLabel} value={axis.label} path={`${path}.label`} maxLength={200} required onCommit={(label) => onChange({ ...axis, label })} />38 <TextField label={t.unit} value={axis.unit} path={`${path}.unit`} maxLength={40} onCommit={(v) => onChange({ ...axis, unit: optional(v) })} />39 <Select label={t.axisScale} value={axis.scale} options={labelOptions(AXIS_SCALE(locale))} onChange={(scale) => onChange({ ...axis, scale })} />40 <div className="grid grid-cols-2 gap-2">41 <NumberField label={t.axisMin} value={axis.min} path={`${path}.min`} optional placeholder={t.auto} onCommit={(min) => onChange({ ...axis, min })} />42 <NumberField label={t.axisMax} value={axis.max} path={`${path}.max`} optional placeholder={t.auto} onCommit={(max) => onChange({ ...axis, max })} />43 </div>44 </>45 );46}4748function PointsGrid({ points, xType, onChange }: { points: readonly ChartPoint[]; xType: "number" | "category"; onChange: (points: ChartPoint[]) => void }) {49 const t = useT();50 const [note, setNote] = useState<string | null>(null);51 const rows = pointsToGrid(points);52 return (53 <GridEditor legend={t.points} columns={["x", "y", t.pointLo, t.pointHi]} rows={rows} minRows={1} maxRows={CHART_MAX_POINTS} numeric={xType === "number"} cellMaxLength={60} note={note} hint={t.pointsHint}54 validateCell={(text, _r, c) => {55 if (c === 0 && xType === "category") return null;56 if (c >= 2 && text.trim() === "") return null;57 return parseNumber(text) === null ? t.numberExpected : null;58 }}59 onCell={(r, c, text) => { const p = rowToPoint(replaceItem(rows[r] ?? [], c, text), xType); if (p) onChange(replaceItem(points, r, p)); }}60 onAddRow={() => {61 const last = points[points.length - 1];62 onChange([...points, { x: xType === "number" ? (typeof last?.x === "number" ? last.x + 1 : points.length) : "", y: last?.y ?? 0 }]);63 }}64 onRemoveRow={(r) => { if (points.length > 1) onChange(removeItem(points, r)); }}65 onPaste={(row, col, data) => {66 const pasted = pasteCells(rows, { row, col }, data, { maxRows: Number.MAX_SAFE_INTEGER, maxCols: 4, maxCell: 60 });67 const r = gridToPoints(pasted.grid, xType);68 if (r.points.length === 0) { setNote(t.pasteNothing); return; }69 setNote(fill(t.pointsPasted, { n: r.points.length, skipped: r.skipped, dropped: r.dropped }));70 onChange(r.points);71 }} />72 );73}7475type Annotation = NonNullable<Chart["annotations"]>[number];7677function DatasetImport({ block, set, env }: { block: Chart; set: (next: Chart) => void; env: FormEnv }) {78 const t = useT();79 const { onPickAsset, loadDataset } = env;80 const [busy, setBusy] = useState(false);81 const [loaded, setLoaded] = useState<{ ref: string; data: Dataset } | null>(null);82 const [xCol, setXCol] = useState(0);83 const [yCols, setYCols] = useState<string[]>([]);84 const [message, setMessage] = useState<{ tone: "info" | "bad"; text: string } | null>(null);85 if (!onPickAsset || !loadDataset) return null;86 const open = async (pick: boolean) => {87 setBusy(true); setMessage(null);88 try {89 const ref = pick ? await onPickAsset("dataset") : block.datasetRef ?? null;90 if (!ref) return;91 const data = await loadDataset(ref);92 if (!data || data.columns.length === 0) { setLoaded(null); setMessage({ tone: "bad", text: t.datasetUnreadable }); return; }93 setLoaded({ ref, data });94 setXCol(0);95 setYCols(data.columns.map((c, i) => ({ c, i })).filter(({ c, i }) => c.type === "number" && i !== 0).slice(0, 1).map(({ i }) => String(i)));96 } catch { setMessage({ tone: "bad", text: t.datasetUnreadable }); }97 finally { setBusy(false); }98 };99 const apply = () => {100 if (!loaded) return;101 const r = datasetToSeries(loaded.data, xCol, yCols.map(Number));102 if (r.series.length === 0) { setMessage({ tone: "bad", text: t.datasetNoRows }); return; }103 set({ ...block, datasetRef: loaded.ref, x: { ...block.x, type: r.xType, scale: r.xType === "category" ? "linear" : block.x.scale, label: block.x.label || loaded.data.columns[xCol]?.name.slice(0, 200) || "x" }, series: r.series });104 const kept = r.series[0]?.points.length ?? 0;105 setMessage({ tone: "info", text: [fill(t.datasetDone, { kept, total: r.total }), r.dropped > 0 ? fill(t.datasetDropped, { dropped: r.dropped, max: CHART_MAX_POINTS }) : "", r.unreadable > 0 ? fill(t.datasetSkipped, { n: r.unreadable }) : ""].filter(Boolean).join(" ") });106 setLoaded(null);107 };108 const columnOptions = loaded?.data.columns.map((c, i) => ({ value: String(i), label: `${c.name || fill(t.columnN, { n: i + 1 })} (${c.type === "number" ? t.typeNumber : t.typeText})` })) ?? [];109 return (110 <Group legend={t.dataset} hint={t.datasetHint}>111 {block.datasetRef && <p className="break-all text-sm text-muted">{fill(t.datasetLinked, { ref: block.datasetRef })}</p>}112 <div className="flex flex-wrap gap-2">113 <button type="button" className="btn flex-1" disabled={busy} onClick={() => void open(true)}>{t.importDataset}</button>114 {block.datasetRef && <button type="button" className="btn flex-1" disabled={busy} onClick={() => void open(false)}>{t.datasetColumns}</button>}115 {block.datasetRef && <button type="button" className="btn btn-danger flex-1" onClick={() => { set({ ...block, datasetRef: undefined }); setLoaded(null); }}>{t.datasetUnlink}</button>}116 </div>117 {loaded && (118 <>119 <Select label={t.datasetX} value={String(xCol)} options={columnOptions} onChange={(v) => { setXCol(Number(v)); setYCols(yCols.filter((y) => y !== v)); }} />120 <ChipSelect legend={t.datasetY} options={columnOptions.filter((o) => o.value !== String(xCol) && loaded.data.columns[Number(o.value)]?.type === "number")} selected={yCols} onChange={setYCols} max={CHART_MAX_SERIES} empty={t.datasetNoNumeric} />121 <p className="text-xs text-muted">{fill(t.datasetRows, { n: loaded.data.rows.length, max: CHART_MAX_POINTS })}</p>122 <button type="button" className="btn btn-primary" disabled={yCols.length === 0} onClick={apply}>{t.datasetApply}</button>123 </>124 )}125 {message && <Note tone={message.tone}>{message.text}</Note>}126 </Group>127 );128}129130export function ChartForm({ block, set, env }: FormProps<"chart">) {131 const t = useT();132 const locale = useLocale();133 const xType = block.x.type;134 const annotations = block.annotations ?? [];135 const setXType = (type: "number" | "category") => set({136 ...block,137 x: { ...block.x, type, scale: type === "category" ? "linear" : block.x.scale },138 series: block.series.map((s) => ({ ...s, points: convertPointsX(s.points, type) })),139 annotations: block.annotations?.map((a) => (a.x === undefined ? a : { ...a, x: type === "category" ? String(a.x) : typeof a.x === "number" ? a.x : parseNumber(a.x) ?? 0 })),140 });141 return (142 <>143 <Select label={t.chartKind} value={block.kind} options={labelOptions(CHART_KIND(locale))} onChange={(kind) => set({ ...block, kind })} />144 <TextField label={t.title} value={block.title} path="title" maxLength={200} onCommit={(v) => set({ ...block, title: optional(v) })} />145 <LongText label={t.caption} value={block.caption} path="caption" maxLength={400} onCommit={(v) => set({ ...block, caption: optional(v) })} />146 <DataKindField value={block.dataKind} onChange={(dataKind) => set({ ...block, dataKind })} />147 {block.dataKind === "empirical" && (block.sourceIds ?? []).length === 0 && <Note tone="warn">{t.empiricalNeedsSource}</Note>}148 <Group legend={t.xAxis}>149 <Select label={t.axisType} value={xType} options={labelOptions(AXIS_TYPE(locale))} onChange={setXType} hint={t.axisTypeHint} />150 <AxisFields axis={block.x} path="x" onChange={(x) => set({ ...block, x })} />151 </Group>152 <Group legend={t.yAxis}>153 <AxisFields axis={block.y} path="y" onChange={(y) => set({ ...block, y })} />154 </Group>155 <DatasetImport block={block} set={set} env={env} />156 <ListEditor<ChartSeries> legend={t.series} items={block.series} min={1} max={CHART_MAX_SERIES} path="series" addLabel={t.addSeries}157 itemTitle={(s, i) => `${s.name || fill(t.seriesN, { n: i + 1 })} (${s.points.length})`}158 newItem={() => ({ name: fill(t.seriesN, { n: block.series.length + 1 }), tone: seriesTone(block.series.length), points: (block.series[0]?.points ?? [{ x: xType === "number" ? 0 : "A", y: 0 }]).map((p) => ({ x: p.x, y: 0 })) })}159 onChange={(series) => set({ ...block, series })}160 renderItem={(s, i, update) => (161 <>162 <TextField label={t.seriesName} value={s.name} path={`series.${i}.name`} maxLength={200} required onCommit={(name) => update({ ...s, name })} />163 <TonePicker label={t.tone} value={s.tone} onChange={(tone) => update({ ...s, tone })} />164 <PointsGrid points={s.points} xType={xType} onChange={(points) => update({ ...s, points })} />165 </>166 )} />167 <ListEditor<Annotation> legend={t.annotations} items={annotations} max={8} path="annotations" addLabel={t.addAnnotation} hint={t.annotationsHint}168 itemTitle={(a, i) => a.label || fill(t.itemN, { n: i + 1 })} newItem={() => ({ label: t.newAnnotationLabel })}169 onChange={(next) => set({ ...block, annotations: next.length > 0 ? next : undefined })}170 renderItem={(a, i, update) => (171 <>172 <TextField label={t.label} value={a.label} path={`annotations.${i}.label`} maxLength={120} required onCommit={(label) => update({ ...a, label })} />173 {xType === "number"174 ? <NumberField label={t.annotationX} value={typeof a.x === "number" ? a.x : undefined} path={`annotations.${i}.x`} optional onCommit={(x) => update({ ...a, x })} />175 : <TextField label={t.annotationX} value={a.x === undefined ? "" : String(a.x)} path={`annotations.${i}.x`} maxLength={60} onCommit={(v) => update({ ...a, x: optional(v) })} />}176 <NumberField label={t.annotationY} value={a.y} path={`annotations.${i}.y`} optional onCommit={(y) => update({ ...a, y })} />177 </>178 )} />179 </>180 );181}182183// ── Matrix ──────────────────────────────────────────────────────────────────────────────────────────184185export function MatrixForm({ block, set }: FormProps<"matrix">) {186 const t = useT();187 const locale = useLocale();188 const [note, setNote] = useState<string | null>(null);189 const values = rectangular(block.values, block.colLabels.length, 0, block.rowLabels.length);190 const rowLabel = (n: number) => fill(t.matrixRowN, { n });191 const colLabel = (n: number) => fill(t.matrixColN, { n });192 return (193 <>194 <TextField label={t.title} value={block.title} path="title" maxLength={200} onCommit={(v) => set({ ...block, title: optional(v) })} />195 <LongText label={t.caption} value={block.caption} path="caption" maxLength={400} onCommit={(v) => set({ ...block, caption: optional(v) })} />196 <DataKindField value={block.dataKind} onChange={(dataKind) => set({ ...block, dataKind })} />197 {block.dataKind === "empirical" && (block.sourceIds ?? []).length === 0 && <Note tone="warn">{t.empiricalNeedsSource}</Note>}198 <ListEditor<string> legend={t.rowLabels} items={block.rowLabels} min={1} max={MATRIX_MAX} compact path="rowLabels" addLabel={t.addRow}199 itemTitle={(l, i) => l || rowLabel(i + 1)} newItem={() => ""}200 onChange={(rowLabels) => set({ ...block, rowLabels })}201 onAdd={() => set(matrixAddRow(block, rowLabel(block.rowLabels.length + 1)))} onRemove={(i) => set(matrixRemoveRow(block, i))} onMove={(i, d) => set(matrixMoveRow(block, i, d))}202 renderItem={(l, i, update) => <TextField label={fill(t.rowLabelN, { n: i + 1 })} hideLabel value={l} path={`rowLabels.${i}`} maxLength={60} onCommit={update} />} />203 <ListEditor<string> legend={t.colLabels} items={block.colLabels} min={1} max={MATRIX_MAX} compact path="colLabels" addLabel={t.addColumn}204 itemTitle={(l, i) => l || colLabel(i + 1)} newItem={() => ""}205 onChange={(colLabels) => set({ ...block, colLabels })}206 onAdd={() => set(matrixAddColumn(block, colLabel(block.colLabels.length + 1)))} onRemove={(i) => set(matrixRemoveColumn(block, i))} onMove={(i, d) => set(matrixMoveColumn(block, i, d))}207 renderItem={(l, i, update) => <TextField label={fill(t.colLabelN, { n: i + 1 })} hideLabel value={l} path={`colLabels.${i}`} maxLength={60} onCommit={update} />} />208 <GridEditor legend={t.values} columns={block.colLabels.map((l, j) => l || colLabel(j + 1))} rowLabels={block.rowLabels.map((l, i) => l || rowLabel(i + 1))} rows={values.map((r) => r.map(numberText))}209 maxRows={MATRIX_MAX} numeric note={note} hint={t.matrixPasteHint}210 validateCell={(text) => (parseNumber(text) === null ? t.numberExpected : null)}211 onCell={(r, c, text) => { const n = parseNumber(text); if (n !== null) set({ ...block, values: replaceItem(values, r, replaceItem(values[r] ?? [], c, n)) }); }}212 onPaste={(row, col, data) => {213 const r = matrixPaste({ ...block, values }, { row, col }, data, rowLabel, colLabel);214 setNote([fill(t.pasteDone, { rows: data.length }), r.droppedRows + r.droppedCols > 0 ? fill(t.pasteDropped, { rows: r.droppedRows, cols: r.droppedCols }) : "", r.invalid > 0 ? fill(t.pasteInvalid, { n: r.invalid }) : ""].filter(Boolean).join(" "));215 set(r.block);216 }} />217 <Select label={t.matrixScale} value={block.scale} options={labelOptions(MATRIX_SCALE(locale))} onChange={(scale) => set({ ...block, scale })} />218 <Toggle label={t.showValues} checked={block.showValues} onChange={(showValues) => set({ ...block, showValues })} />219 <Segmented legend={t.decimals} value={block.decimals} onChange={(decimals) => set({ ...block, decimals })} options={[0, 1, 2, 3, 4].map((value) => ({ value, label: String(value) }))} />220 </>221 );222}223224// ── Simulation ──────────────────────────────────────────────────────────────────────────────────────225226type Sim = BlockOf<"simulation">;227type ConfigValue = Sim["config"][string];228229function ParamSlider({ def, value, onCommit }: { def: ParamDef; value: number; onCommit: (value: number) => void }) {230 const id = useId();231 const locale = useLocale();232 const [live, setLive] = useState(value);233 const [prev, setPrev] = useState(value);234 if (value !== prev) { setPrev(value); setLive(value); }235 const commit = () => { if (live !== value) onCommit(live); };236 const label = def.unit ? `${def.label[locale]} (${def.unit})` : def.label[locale];237 return (238 <fieldset className="min-w-0">239 <legend className="text-sm font-medium text-ink">{label}</legend>240 <div className="flex items-center gap-2">241 <input id={id} type="range" className="min-h-11 min-w-0 flex-1 accent-accent" aria-label={label} min={def.min} max={def.max} step={def.step} value={live}242 onChange={(e) => setLive(Number(e.target.value))} onPointerUp={commit} onTouchEnd={commit} onKeyUp={commit} onBlur={commit} />243 <NumberField className="w-24 shrink-0" label={label} hideLabel value={live} min={def.min} max={def.max} onCommit={(n) => { if (n !== undefined) onCommit(snapParam(def, n)); }} />244 </div>245 <p className="text-xs tabular-nums text-muted">{numberText(def.min)} … {numberText(def.max)}</p>246 </fieldset>247 );248}249250function ConfigControl({ field, value, onChange }: { field: ConfigField; value: ConfigValue | undefined; onChange: (value: ConfigValue | undefined) => void }) {251 const locale = useLocale();252 const path = `config.${field.key}`;253 const issue = useIssue(path);254 const label = field.label[locale], hint = field.hint?.[locale];255 switch (field.kind) {256 case "select": {257 const options = field.options.map((o) => ({ value: String(o.value), label: o.label[locale] }));258 const current = field.options.find((o) => String(o.value) === String(value)) ?? field.options[0];259 return <Select label={label} hint={hint} path={path} value={String(current?.value ?? "")} options={options} onChange={(v) => onChange(field.options.find((o) => String(o.value) === v)?.value)} />;260 }261 case "text": return <TextField label={label} hint={hint} path={path} mono={field.mono} required={field.required} maxLength={field.maxLength} placeholder={field.placeholder} value={typeof value === "string" ? value : ""} onCommit={(v) => onChange(v.trim() === "" ? undefined : v)} />;262 case "number": return <NumberField label={label} hint={issue ? undefined : hint} path={path} optional min={field.min} max={field.max} integer={field.integer} placeholder={field.placeholder} value={typeof value === "number" ? value : undefined} onCommit={onChange} />;263 case "boolean": return <Toggle label={label} hint={hint} checked={value === true} onChange={(v) => onChange(v ? true : undefined)} />;264 }265}266267export function SimulationForm({ block, set }: FormProps<"simulation">) {268 const t = useT();269 const locale = useLocale();270 const def = SIMULATIONS[block.kind];271 const defs = paramDefs(block.kind, block.config);272 const configIssue = useIssue("config");273 const setConfig = (key: string, value: ConfigValue | undefined) => {274 const config = { ...block.config };275 if (value === undefined) delete config[key]; else config[key] = value;276 set(simWithConfig(block, config));277 };278 const fields = [...SIM_CONFIG[block.kind], ...sliderBoundFields(block.kind, block.config)];279 const animated = def.steps !== undefined;280 return (281 <>282 <Select label={t.simKind} value={block.kind} options={SIM_KINDS.map((value) => ({ value, label: SIMULATIONS[value].title[locale] }))} hint={def.description[locale]}283 onChange={(kind) => {284 if (kind === block.kind) return;285 const next = simWithKind(block, kind);286 // A title still at the default of the previous kind follows the new one; a title the author wrote stays.287 set(block.title === undefined || block.title === def.title.fr || block.title === def.title.en ? { ...next, title: SIMULATIONS[kind].title[locale] } : next);288 }} />289 <Note>{t.simKindNote}</Note>290 <TextField label={t.title} value={block.title} path="title" maxLength={200} onCommit={(v) => set({ ...block, title: optional(v) })} />291 <LongText label={t.caption} value={block.caption} path="caption" maxLength={400} onCommit={(v) => set({ ...block, caption: optional(v) })} />292 <NumberField label={t.seed} value={block.seed} path="seed" min={0} max={2 ** 31 - 1} integer hint={def.stochastic ? t.seedHint : t.seedUnused} onCommit={(seed) => { if (seed !== undefined) set({ ...block, seed }); }} />293 {(fields.length > 0 || animated) && (294 <Group legend={t.simOptions}>295 {fields.map((f) => <ConfigControl key={f.key} field={f} value={block.config[f.key]} onChange={(v) => setConfig(f.key, v)} />)}296 {animated && <Toggle label={t.autoplay} hint={t.autoplayHint} checked={block.config.autoplay === true} onChange={(v) => setConfig("autoplay", v ? true : undefined)} />}297 {configIssue && <p role="alert" className="text-sm text-bad">{configIssue}</p>}298 </Group>299 )}300 <Group legend={t.simParams} hint={t.simParamsHint}>301 {defs.length === 0 && <p className="text-sm text-muted">{t.simNoParams}</p>}302 {defs.map((d) => <ParamSlider key={d.key} def={d} value={snapParam(d, block.params[d.key] ?? d.default)} onCommit={(v) => set({ ...block, params: { ...block.params, [d.key]: v } })} />)}303 </Group>304 </>305 );306}307