Repository Public
1"use client";2import { createContext, useContext, useEffect, useId, useRef, useState, type ClipboardEvent, type KeyboardEvent, type ReactNode } from "react";3import { ICONS, TONES, type Icon, type Locale, type Tone } from "@/schema";4import { fill } from "@/i18n/dict";5import { IconGlyph } from "@/renderer/icons";6import { looksLikeGrid, moveItem, numberText, parseDelimited, parseNumber, removeItem, replaceItem, type FormIssue } from "./helpers";7import { S, TONE_LABEL } from "./strings";89// ── Context: interface language and the issues of the block being edited ────────────────────────────1011export interface FormContextValue { locale: Locale; issues: readonly FormIssue[] }12export const FormContext = createContext<FormContextValue>({ locale: "fr", issues: [] });13export const useLocale = (): Locale => useContext(FormContext).locale;14export const useT = () => S(useContext(FormContext).locale);15/** The problem attached to a field of the block (path as in the schema: `items.2.title`), if any. */16export function useIssue(path?: string): string | undefined {17 const { issues } = useContext(FormContext);18 return path === undefined ? undefined : issues.find((i) => i.path === path)?.message;19}2021/** Text being typed; follows the committed value whenever that one changes. */22function useDraft(value: string): [string, (s: string) => void] {23 const [text, setText] = useState(value);24 const [prev, setPrev] = useState(value);25 if (value !== prev) { setPrev(value); setText(value); }26 return [text, setText];27}2829const describedBy = (id: string, hint: unknown, error: unknown): string | undefined => [hint ? `${id}-hint` : "", error ? `${id}-err` : ""].filter(Boolean).join(" ") || undefined;3031// ── Field shell ─────────────────────────────────────────────────────────────────────────────────────3233export interface FieldProps {34 id: string; label: string; children: ReactNode;35 hint?: ReactNode; error?: string;36 /** Shows the "requis" marker next to the label. */37 required?: boolean;38 /** Keeps the label for assistive technology only (dense rows whose legend already says what the field is). */39 hideLabel?: boolean;40 className?: string;41}42/** Label, control, hint and error. The control links them with `aria-describedby` (ids `<id>-hint`, `<id>-err`). */43export function Field({ id, label, children, hint, error, required, hideLabel, className }: FieldProps) {44 const t = useT();45 return (46 <div className={`flex min-w-0 flex-col gap-1 ${className ?? ""}`}>47 <label htmlFor={id} className={hideLabel ? "sr-only" : "text-sm font-medium text-ink"}>48 {label}{required && <span className="ml-1.5 rounded bg-warn/15 px-1.5 py-0.5 text-[0.6875rem] font-semibold uppercase tracking-wide text-warn">{t.required}</span>}49 </label>50 {children}51 {hint && <p id={`${id}-hint`} className="text-xs leading-snug text-muted">{hint}</p>}52 {error && <p id={`${id}-err`} role="alert" className="text-sm leading-snug text-bad">{error}</p>}53 </div>54 );55}5657/** A titled group of fields. */58export function Group({ legend, children, hint, className }: { legend: string; children: ReactNode; hint?: ReactNode; className?: string }) {59 return (60 <fieldset className={`min-w-0 rounded-xl border border-line p-3 ${className ?? ""}`}>61 <legend className="eyebrow px-1">{legend}</legend>62 {hint && <p className="mb-2 text-xs leading-snug text-muted">{hint}</p>}63 <div className="flex min-w-0 flex-col gap-3">{children}</div>64 </fieldset>65 );66}6768export function Note({ tone = "info", children }: { tone?: "info" | "warn" | "bad"; children: ReactNode }) {69 const c = tone === "bad" ? "border-bad/40 bg-bad/10" : tone === "warn" ? "border-warn/40 bg-warn/10" : "border-line bg-raised";70 return <p role={tone === "info" ? "status" : "alert"} className={`rounded-lg border px-3 py-2 text-sm leading-snug ${c}`}>{children}</p>;71}7273// ── Text ────────────────────────────────────────────────────────────────────────────────────────────7475interface TextCommon {76 label: string; value: string | undefined;77 /** Called on blur or Enter, only when the text changed. */78 onCommit: (text: string) => void;79 /** Schema path of the field, to show its validation issue. */80 path?: string;81 /** Extra problem to show (takes precedence over the schema issue). */82 error?: string;83 maxLength?: number; required?: boolean; hint?: ReactNode; placeholder?: string; mono?: boolean; hideLabel?: boolean; className?: string;84 /** Receives the text on every keystroke (live previews). */85 onDraft?: (text: string) => void;86}8788export function TextField({ label, value, onCommit, path, error, maxLength, required, hint, placeholder, mono, hideLabel, className, onDraft }: TextCommon) {89 const id = useId();90 const [text, setText] = useDraft(value ?? "");91 const issue = useIssue(path);92 const err = error ?? issue;93 const commit = () => { if (text !== (value ?? "")) onCommit(text); };94 return (95 <Field id={id} label={label} hint={hint} error={err} required={required} hideLabel={hideLabel} className={className}>96 <input id={id} type="text" className={`field ${mono ? "font-mono" : ""}`} value={text} maxLength={maxLength} placeholder={placeholder}97 aria-required={required || undefined} aria-invalid={err ? true : undefined} aria-describedby={describedBy(id, hint, err)}98 onChange={(e) => { setText(e.target.value); onDraft?.(e.target.value); }} onBlur={commit}99 onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commit(); } }} />100 </Field>101 );102}103104export interface LongTextProps extends TextCommon {105 /** Code editing: monospace, no wrapping surprises, Tab inserts two spaces (Escape then Tab leaves the field). */106 code?: boolean;107 rows?: number;108}109/** Auto-growing textarea. Commits on blur and on Ctrl/⌘ + Enter. */110export function LongText({ label, value, onCommit, path, error, maxLength, required, hint, placeholder, mono, hideLabel, className, onDraft, code, rows = 2 }: LongTextProps) {111 const id = useId();112 const t = useT();113 const [text, setText] = useDraft(value ?? "");114 const issue = useIssue(path);115 const err = error ?? issue;116 const ref = useRef<HTMLTextAreaElement>(null);117 const escaped = useRef(false);118 useEffect(() => { const el = ref.current; if (!el) return; el.style.height = "auto"; el.style.height = `${el.scrollHeight + 2}px`; }, [text]);119 const change = (next: string) => { setText(next); onDraft?.(next); };120 const commit = () => { if (text !== (value ?? "")) onCommit(text); };121 const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {122 if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); commit(); return; }123 if (!code) return;124 if (e.key === "Escape") { escaped.current = true; return; }125 if (e.key === "Tab" && !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey && !escaped.current) {126 e.preventDefault();127 const el = e.currentTarget, start = el.selectionStart, end = el.selectionEnd;128 const next = text.slice(0, start) + " " + text.slice(end);129 if (maxLength !== undefined && next.length > maxLength) return;130 change(next);131 requestAnimationFrame(() => { el.selectionStart = el.selectionEnd = start + 2; });132 return;133 }134 escaped.current = false;135 };136 const allHint = code ? <>{hint}{hint ? " " : ""}{t.tabHint}</> : hint;137 return (138 <Field id={id} label={label} hint={allHint} error={err} required={required} hideLabel={hideLabel} className={className}>139 <textarea id={id} ref={ref} rows={code ? Math.max(rows, 6) : rows} value={text} maxLength={maxLength} placeholder={placeholder}140 className={`field resize-y leading-relaxed ${code || mono ? "font-mono" : ""} ${code ? "overflow-x-auto whitespace-pre [tab-size:2]" : ""}`}141 spellCheck={code || mono ? false : undefined} autoCapitalize={code || mono ? "off" : undefined} autoCorrect={code || mono ? "off" : undefined}142 aria-required={required || undefined} aria-invalid={err ? true : undefined} aria-describedby={describedBy(id, allHint, err)}143 onChange={(e) => change(e.target.value)} onBlur={commit} onKeyDown={onKeyDown} />144 </Field>145 );146}147148// ── Numbers ─────────────────────────────────────────────────────────────────────────────────────────149150export interface NumberFieldProps {151 label: string; value: number | undefined;152 /** `undefined` only when `optional` and the field was emptied. */153 onCommit: (n: number | undefined) => void;154 path?: string; min?: number; max?: number; integer?: boolean; optional?: boolean; hint?: ReactNode; placeholder?: string; hideLabel?: boolean; className?: string; unit?: string;155}156/** A number typed as text (decimal comma accepted). Out-of-range or unreadable input is explained and not committed. */157export function NumberField({ label, value, onCommit, path, min, max, integer, optional: isOptional, hint, placeholder, hideLabel, className, unit }: NumberFieldProps) {158 const id = useId();159 const t = useT();160 const shown = value === undefined ? "" : numberText(value);161 const [text, setText] = useDraft(shown);162 const [local, setLocal] = useState<string | null>(null);163 const issue = useIssue(path);164 const err = local ?? issue;165 const commit = () => {166 if (text.trim() === "") {167 if (!isOptional) { setLocal(t.numberRequired); return; }168 setLocal(null);169 if (value !== undefined) onCommit(undefined);170 return;171 }172 const n = parseNumber(text);173 if (n === null) { setLocal(t.numberExpected); return; }174 if (integer && !Number.isInteger(n)) { setLocal(t.integerExpected); return; }175 if ((min !== undefined && n < min) || (max !== undefined && n > max)) {176 setLocal(min !== undefined && max !== undefined ? fill(t.between, { min: numberText(min), max: numberText(max) }) : min !== undefined ? fill(t.atLeast, { min: numberText(min) }) : fill(t.atMost, { max: numberText(max ?? 0) }));177 return;178 }179 setLocal(null);180 if (n !== value) onCommit(n); else setText(shown);181 };182 return (183 <Field id={id} label={unit ? `${label} (${unit})` : label} hint={hint} error={err} hideLabel={hideLabel} className={className}>184 <input id={id} type="text" inputMode={integer && (min ?? -1) >= 0 ? "numeric" : "text"} className="field tabular-nums" value={text} placeholder={placeholder}185 aria-invalid={err ? true : undefined} aria-describedby={describedBy(id, hint, err)}186 onChange={(e) => { setText(e.target.value); setLocal(null); }} onBlur={commit}187 onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commit(); } }} />188 </Field>189 );190}191192// ── Choices ─────────────────────────────────────────────────────────────────────────────────────────193194export interface Option<T extends string | number> { value: T; label: string }195/** Options of a select from a label map, in the order of `values`. */196export const optionsOf = <T extends string>(values: readonly T[], labels: Record<T, string>): Option<T>[] => values.map((value) => ({ value, label: labels[value] }));197198export interface SelectProps<T extends string | number> { label: string; value: T; options: readonly Option<T>[]; onChange: (value: T) => void; hint?: ReactNode; path?: string; hideLabel?: boolean; className?: string; disabled?: boolean }199export function Select<T extends string | number>({ label, value, options, onChange, hint, path, hideLabel, className, disabled }: SelectProps<T>) {200 const id = useId();201 const err = useIssue(path);202 return (203 <Field id={id} label={label} hint={hint} error={err} hideLabel={hideLabel} className={className}>204 <select id={id} className="field" value={String(value)} disabled={disabled} aria-invalid={err ? true : undefined} aria-describedby={describedBy(id, hint, err)}205 onChange={(e) => { const hit = options.find((o) => String(o.value) === e.target.value); if (hit) onChange(hit.value); }}>206 {!options.some((o) => o.value === value) && <option value={String(value)}>{String(value)}</option>}207 {options.map((o) => <option key={String(o.value)} value={String(o.value)}>{o.label}</option>)}208 </select>209 </Field>210 );211}212213export function Toggle({ label, checked, onChange, hint }: { label: string; checked: boolean; onChange: (checked: boolean) => void; hint?: ReactNode }) {214 const id = useId();215 return (216 <div className="flex min-w-0 flex-col gap-1">217 <label htmlFor={id} className="flex min-h-11 cursor-pointer items-center gap-3 text-sm font-medium text-ink">218 <input id={id} type="checkbox" className="h-5 w-5 shrink-0 accent-accent" checked={checked} aria-describedby={hint ? `${id}-hint` : undefined} onChange={(e) => onChange(e.target.checked)} />219 <span>{label}</span>220 </label>221 {hint && <p id={`${id}-hint`} className="text-xs leading-snug text-muted">{hint}</p>}222 </div>223 );224}225226const RADIO_TILE = "relative flex min-h-11 cursor-pointer items-center justify-center rounded-lg border border-line bg-surface text-sm font-medium text-ink has-[:checked]:border-accent has-[:checked]:bg-accent-soft has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-accent";227228export interface SegmentedProps<T extends string | number> { legend: string; value: T; options: readonly (Option<T> & { visual?: ReactNode })[]; onChange: (value: T) => void; hint?: ReactNode }229/** A short list of exclusive choices shown side by side (native radio buttons: arrow keys work). */230export function Segmented<T extends string | number>({ legend, value, options, onChange, hint }: SegmentedProps<T>) {231 const name = useId();232 return (233 <fieldset className="min-w-0">234 <legend className="mb-1 text-sm font-medium text-ink">{legend}</legend>235 <div className="flex flex-wrap gap-1.5">236 {options.map((o) => (237 <label key={String(o.value)} className={`${RADIO_TILE} min-w-11 flex-1 flex-col gap-1 px-2 py-1.5`}>238 <input type="radio" className="sr-only" name={name} checked={o.value === value} onChange={() => onChange(o.value)} />239 {o.visual}240 <span className="text-center leading-tight">{o.label}</span>241 </label>242 ))}243 </div>244 {hint && <p className="mt-1 text-xs leading-snug text-muted">{hint}</p>}245 </fieldset>246 );247}248249/** The eight semantic tones as colour swatches, drawn with the sheet's own tokens (`--sh-t-<tone>`). */250export function TonePicker({ label, value, onChange }: { label: string; value: Tone; onChange: (tone: Tone) => void }) {251 const name = useId();252 const names = TONE_LABEL(useLocale());253 return (254 <fieldset className="min-w-0">255 <legend className="mb-1 text-sm font-medium text-ink">{label} <span className="font-normal text-muted">· {names[value]}</span></legend>256 <div className="sheet flex flex-wrap gap-1 rounded-lg border border-line p-1">257 {TONES.map((tone) => (258 <label key={tone} title={names[tone]} className="relative flex h-11 w-11 cursor-pointer items-center justify-center rounded-md has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-accent">259 <input type="radio" className="sr-only" name={name} checked={tone === value} onChange={() => onChange(tone)} />260 <span aria-hidden="true" className="h-7 w-7 rounded-full" style={{ background: `var(--sh-t-${tone})`, boxShadow: tone === value ? `0 0 0 2px var(--sh-bg), 0 0 0 4px var(--sh-t-${tone})` : `inset 0 0 0 2px var(--sh-t-${tone}-soft)` }} />261 <span className="sr-only">{names[tone]}</span>262 </label>263 ))}264 </div>265 </fieldset>266 );267}268269/** The fixed icon set as a grid of the real glyphs. Collapsed to the current choice until opened. */270export function IconPicker({ label, value, onChange }: { label: string; value: Icon | undefined; onChange: (icon: Icon | undefined) => void }) {271 const t = useT();272 const [open, setOpen] = useState(false);273 const pick = (icon: Icon | undefined) => { onChange(icon); setOpen(false); };274 return (275 <fieldset className="min-w-0">276 <legend className="mb-1 text-sm font-medium text-ink">{label}</legend>277 <button type="button" className="btn w-full !justify-start !font-medium" aria-expanded={open} onClick={() => setOpen(!open)}>278 {value ? <IconGlyph name={value} size={20} /> : null}279 <span>{value ?? t.noIcon}</span>280 <span aria-hidden="true" className="ml-auto text-faint">{open ? "▴" : "▾"}</span>281 </button>282 {open && (283 <div className="mt-1.5 grid grid-cols-[repeat(auto-fill,minmax(2.75rem,1fr))] gap-1 rounded-lg border border-line bg-surface p-1">284 <button type="button" className="col-span-full flex min-h-11 items-center justify-center rounded-md text-sm text-muted aria-pressed:bg-accent-soft" aria-pressed={value === undefined} onClick={() => pick(undefined)}>{t.noIcon}</button>285 {ICONS.map((icon) => (286 <button key={icon} type="button" title={icon} aria-label={icon} aria-pressed={icon === value} onClick={() => pick(icon)}287 className="flex h-11 items-center justify-center rounded-md text-ink aria-pressed:bg-accent-soft aria-pressed:text-accent">288 <IconGlyph name={icon} size={20} />289 </button>290 ))}291 </div>292 )}293 </fieldset>294 );295}296297/** Several choices among a list, as toggle chips. */298export function ChipSelect({ legend, options, selected, onChange, max, empty, hint }: { legend: string; options: readonly Option<string>[]; selected: readonly string[]; onChange: (next: string[]) => void; max?: number; empty?: string; hint?: ReactNode }) {299 const full = max !== undefined && selected.length >= max;300 return (301 <fieldset className="min-w-0">302 <legend className="mb-1 text-sm font-medium text-ink">{legend}</legend>303 {options.length === 0 && empty ? <p className="text-sm text-muted">{empty}</p> : (304 <div className="flex flex-wrap gap-1.5">305 {options.map((o) => {306 const on = selected.includes(o.value);307 return (308 <button key={o.value} type="button" aria-pressed={on} disabled={!on && full} title={o.label}309 onClick={() => onChange(on ? selected.filter((s) => s !== o.value) : [...selected, o.value])}310 className="inline-flex min-h-11 max-w-full items-center gap-1.5 rounded-full border border-line bg-surface px-3 text-left text-sm text-ink disabled:opacity-50 aria-pressed:border-accent aria-pressed:bg-accent-soft">311 <span aria-hidden="true">{on ? "✓" : "+"}</span><span className="truncate">{o.label}</span>312 </button>313 );314 })}315 </div>316 )}317 {hint && <p className="mt-1 text-xs leading-snug text-muted">{hint}</p>}318 </fieldset>319 );320}321322// ── Lists ───────────────────────────────────────────────────────────────────────────────────────────323324const ICON_BTN = "btn btn-ghost !min-h-11 !w-11 !shrink-0 !px-0";325326/** ▲ ▼ ✕ for one item of a list. Keyboard and touch; no drag. */327export function ItemButtons({ name, index, count, onMove, onRemove, canRemove = true }: { name: string; index: number; count: number; onMove?: (delta: -1 | 1) => void; onRemove?: () => void; canRemove?: boolean }) {328 const t = useT();329 return (330 <div className="flex shrink-0 items-center">331 {onMove && <button type="button" className={ICON_BTN} disabled={index === 0} aria-label={fill(t.moveUp, { name })} onClick={() => onMove(-1)}><span aria-hidden="true">▲</span></button>}332 {onMove && <button type="button" className={ICON_BTN} disabled={index === count - 1} aria-label={fill(t.moveDown, { name })} onClick={() => onMove(1)}><span aria-hidden="true">▼</span></button>}333 {onRemove && <button type="button" className={`${ICON_BTN} text-bad`} disabled={!canRemove} aria-label={fill(t.remove, { name })} onClick={onRemove}><span aria-hidden="true">✕</span></button>}334 </div>335 );336}337338export interface ListEditorProps<T> {339 legend: string;340 items: readonly T[];341 /** New list after an edit, an addition, a removal or a move (unless the matching handler below is given). */342 onChange: (items: T[]) => void;343 renderItem: (item: T, index: number, update: (next: T) => void) => ReactNode;344 newItem: () => T;345 /** Short name of an item for the row header and the button labels. */346 itemTitle: (item: T, index: number) => string;347 min?: number; max: number;348 /** Items shown in full, one under the other, without a header to open (short items such as a line of text). */349 compact?: boolean;350 /** Item open at first (default: the only item of a one-item list, otherwise none). */351 defaultOpen?: number;352 addLabel?: string; hint?: ReactNode;353 /** Schema path of the list, to show list-level issues. */354 path?: string;355 /** Structural edits that must touch more than this list (columns of a table, nodes of a diagram…). */356 onAdd?: () => void; onRemove?: (index: number) => void; onMove?: (index: number, delta: -1 | 1) => void;357}358359/** A list with add / remove / reorder buttons. In the default mode one item at a time is open for editing. */360export function ListEditor<T>({ legend, items, onChange, renderItem, newItem, itemTitle, min = 0, max, compact, defaultOpen, addLabel, hint, path, onAdd, onRemove, onMove }: ListEditorProps<T>) {361 const t = useT();362 const issue = useIssue(path);363 const [open, setOpen] = useState<number | null>(defaultOpen ?? (items.length === 1 ? 0 : null));364 const add = () => { if (items.length >= max) return; if (onAdd) onAdd(); else onChange([...items, newItem()]); setOpen(items.length); };365 const remove = (i: number) => { if (items.length <= min) return; if (onRemove) onRemove(i); else onChange(removeItem(items, i)); setOpen(null); };366 const move = (i: number, d: -1 | 1) => { if (onMove) onMove(i, d); else onChange(moveItem(items, i, d)); setOpen(open === i ? i + d : open === i + d ? i : open); };367 return (368 <fieldset className="min-w-0 rounded-xl border border-line p-2">369 <legend className="eyebrow px-1">{legend} <span className="font-normal normal-case tracking-normal">· {items.length}/{max}</span></legend>370 {hint && <p className="mb-2 px-1 text-xs leading-snug text-muted">{hint}</p>}371 <ol className="flex min-w-0 flex-col gap-1.5">372 {items.map((item, i) => {373 const name = itemTitle(item, i);374 const buttons = <ItemButtons name={name} index={i} count={items.length} onMove={(d) => move(i, d)} onRemove={() => remove(i)} canRemove={items.length > min} />;375 const body = renderItem(item, i, (next) => onChange(replaceItem(items, i, next)));376 if (compact) return (377 <li key={i} className="flex min-w-0 flex-wrap items-start justify-end gap-x-1 rounded-lg bg-raised/60 p-1.5">378 <div className="flex min-w-[9rem] flex-1 flex-col gap-2">{body}</div>379 {buttons}380 </li>381 );382 const isOpen = open === i;383 return (384 <li key={i} className="min-w-0 rounded-lg border border-line bg-surface">385 <div className="flex min-w-0 items-center">386 <button type="button" className="flex min-h-11 min-w-0 flex-1 items-center gap-2 px-2 text-left text-sm font-medium text-ink" aria-expanded={isOpen} onClick={() => setOpen(isOpen ? null : i)}>387 <span aria-hidden="true" className="w-3 shrink-0 text-faint">{isOpen ? "▾" : "▸"}</span>388 <span className="shrink-0 tabular-nums text-faint">{i + 1}.</span>389 <span className="truncate">{name}</span>390 </button>391 {buttons}392 </div>393 {isOpen && <div className="flex min-w-0 flex-col gap-3 border-t border-line p-2.5">{body}</div>}394 </li>395 );396 })}397 </ol>398 {issue && <p role="alert" className="mt-1.5 px-1 text-sm text-bad">{issue}</p>}399 <button type="button" className="btn btn-sm mt-2 w-full !min-h-11" disabled={items.length >= max} onClick={add}>+ {addLabel ?? t.add}</button>400 </fieldset>401 );402}403404// ── Grid ────────────────────────────────────────────────────────────────────────────────────────────405406function Cell({ value, label, numeric, maxLength, validate, onCommit, onGridPaste, onError }: { value: string; label: string; numeric?: boolean; maxLength?: number; validate?: (text: string) => string | null; onCommit: (text: string) => void; onGridPaste: (data: string[][]) => void; onError: (message: string | null) => void }) {407 const [text, setText] = useDraft(value);408 const [bad, setBad] = useState(false);409 const commit = () => {410 if (text === value) { if (bad) { setBad(false); onError(null); } return; }411 const problem = validate ? validate(text) : null;412 if (problem) { setBad(true); onError(`${label} : ${problem}`); return; }413 setBad(false); onError(null); onCommit(text);414 };415 const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {416 const clip = e.clipboardData.getData("text/plain");417 if (!looksLikeGrid(clip)) return;418 e.preventDefault();419 onGridPaste(parseDelimited(clip));420 };421 return (422 <input type="text" inputMode={numeric ? "text" : undefined} aria-label={label} aria-invalid={bad || undefined} value={text} maxLength={maxLength}423 className={`field !min-w-[5.5rem] !rounded-md !px-2 ${numeric ? "text-right tabular-nums" : ""} ${bad ? "!border-bad" : ""}`}424 onChange={(e) => setText(e.target.value)} onBlur={commit} onPaste={onPaste}425 onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commit(); } }} />426 );427}428429export interface GridEditorProps {430 legend: string;431 /** Column headers (also used in the cell labels). */432 columns: readonly string[];433 /** Rectangular rows of text. */434 rows: readonly (readonly string[])[];435 /** Header of each row; defaults to its number. */436 rowLabels?: readonly string[];437 onCell: (row: number, col: number, text: string) => void;438 /** A sentence explaining why the text cannot go in this cell, or null. Rejected cells keep the typed text and are not committed. */439 validateCell?: (text: string, row: number, col: number) => string | null;440 /** Cells pasted from a spreadsheet (tab-, semicolon- or comma-separated), starting at a cell. */441 onPaste: (row: number, col: number, data: string[][]) => void;442 onAddRow?: () => void; onRemoveRow?: (row: number) => void;443 minRows?: number; maxRows: number; numeric?: boolean; cellMaxLength?: number;444 /** Result of the last paste or import, said aloud. */445 note?: string | null; hint?: ReactNode; pageSize?: number;446}447448/** An editable grid of text cells, horizontally scrollable, paginated, with spreadsheet paste. The caller keeps it rectangular. */449export function GridEditor({ legend, columns, rows, rowLabels, onCell, validateCell, onPaste, onAddRow, onRemoveRow, minRows = 1, maxRows, numeric, cellMaxLength, note, hint, pageSize = 25 }: GridEditorProps) {450 const t = useT();451 const pasteId = useId();452 const [page, setPage] = useState(0);453 const [cellError, setCellError] = useState<string | null>(null);454 const [pasting, setPasting] = useState(false);455 const [clip, setClip] = useState("");456 const pages = Math.max(1, Math.ceil(rows.length / pageSize));457 const current = Math.min(page, pages - 1);458 const start = current * pageSize;459 const visible = rows.slice(start, start + pageSize);460 const rowName = (r: number) => rowLabels?.[r] || fill(t.rowN, { n: r + 1 });461 return (462 <fieldset className="min-w-0 rounded-xl border border-line p-2">463 <legend className="eyebrow px-1">{legend} <span className="font-normal normal-case tracking-normal">· {rows.length} × {columns.length}</span></legend>464 {hint && <p className="mb-2 px-1 text-xs leading-snug text-muted">{hint}</p>}465 <div className="max-w-full overflow-x-auto rounded-lg border border-line" tabIndex={-1}>466 <table className="border-separate border-spacing-1 text-sm">467 <thead>468 <tr>469 <th scope="col" className="sticky left-0 z-10 bg-surface px-1 text-left text-xs font-medium text-faint"><span className="sr-only">{t.row}</span></th>470 {columns.map((c, j) => <th key={j} scope="col" className="max-w-[9rem] truncate px-1 text-left text-xs font-semibold text-muted">{c || fill(t.columnN, { n: j + 1 })}</th>)}471 {onRemoveRow && <th scope="col"><span className="sr-only">{t.actions}</span></th>}472 </tr>473 </thead>474 <tbody>475 {visible.map((row, k) => {476 const r = start + k;477 return (478 <tr key={r}>479 <th scope="row" className="sticky left-0 z-10 max-w-[6rem] truncate bg-surface px-1 text-left text-xs font-medium text-faint">{rowLabels ? rowName(r) : r + 1}</th>480 {columns.map((c, j) => (481 <td key={j}>482 <Cell value={row[j] ?? ""} numeric={numeric} maxLength={cellMaxLength}483 label={`${rowName(r)}, ${c || fill(t.columnN, { n: j + 1 })}`}484 validate={validateCell ? (text) => validateCell(text, r, j) : undefined}485 onCommit={(text) => onCell(r, j, text)} onGridPaste={(data) => onPaste(r, j, data)} onError={setCellError} />486 </td>487 ))}488 {onRemoveRow && <td><button type="button" className={`${ICON_BTN} text-bad`} disabled={rows.length <= minRows} aria-label={fill(t.remove, { name: rowName(r) })} onClick={() => onRemoveRow(r)}><span aria-hidden="true">✕</span></button></td>}489 </tr>490 );491 })}492 </tbody>493 </table>494 </div>495 {pages > 1 && (496 <div className="mt-1.5 flex items-center justify-between gap-2 text-sm text-muted">497 <button type="button" className="btn btn-sm !min-h-11" disabled={current === 0} onClick={() => setPage(current - 1)}>‹ {t.previous}</button>498 <span aria-live="polite">{fill(t.rowsRange, { from: start + 1, to: start + visible.length, total: rows.length })}</span>499 <button type="button" className="btn btn-sm !min-h-11" disabled={current >= pages - 1} onClick={() => setPage(current + 1)}>{t.next} ›</button>500 </div>501 )}502 {cellError && <p role="alert" className="mt-1.5 px-1 text-sm text-bad">{cellError}</p>}503 {note && <p role="status" className="mt-1.5 px-1 text-sm text-muted">{note}</p>}504 <div className="mt-2 flex flex-wrap gap-2">505 {onAddRow && <button type="button" className="btn btn-sm !min-h-11 flex-1" disabled={rows.length >= maxRows} onClick={() => { onAddRow(); setPage(Math.floor(rows.length / pageSize)); }}>+ {t.addRow}</button>}506 <button type="button" className="btn btn-sm !min-h-11 flex-1" aria-expanded={pasting} onClick={() => setPasting(!pasting)}>{t.pasteSheet}</button>507 </div>508 {pasting && (509 <div className="mt-2 flex flex-col gap-2">510 <label htmlFor={pasteId} className="text-sm font-medium text-ink">{t.pasteLabel}</label>511 <textarea id={pasteId} rows={4} className="field font-mono !text-base" value={clip} placeholder={"a\tb\tc\n1\t2\t3"} aria-describedby={`${pasteId}-hint`} onChange={(e) => setClip(e.target.value)} />512 <p id={`${pasteId}-hint`} className="text-xs leading-snug text-muted">{t.pasteHint}</p>513 <button type="button" className="btn btn-sm btn-primary !min-h-11" disabled={clip.trim() === ""} onClick={() => { onPaste(0, 0, parseDelimited(clip)); setClip(""); setPasting(false); setPage(0); }}>{t.pasteFill}</button>514 </div>515 )}516 </fieldset>517 );518}519