SPB Git

Repository Public

BlockForm.tsx 8.6 KB 143 lines tsx

1"use client";2import { useMemo, useState, type ReactNode } from "react";3import { BlockSchema, LeafBlockSchema, SPANS, stableStringify, type Block, type BlockType, type LeafBlock, type Locale, type Sheet } from "@/schema";4import { fill } from "@/i18n/dict";5import { catalogEntry } from "./defaults";6import { ChartForm, MatrixForm, SimulationForm } from "./forms-data";7import { AccordionForm, CardsForm, ComparisonForm, LegendForm, QuizForm, StepsForm, TableForm, TabsForm, TimelineForm } from "./forms-lists";8import { CalloutForm, CodeForm, DividerForm, EquationForm, HeadingForm, ListForm, ParagraphForm, ReferencesForm } from "./forms-text";9import { DiagramForm, ImageForm, SvgForm } from "./forms-visual";10import { optional, plainIssues, simParams, simulationIssues, type Dataset, type FormIssue } from "./helpers";11import { ChipSelect, FormContext, Group, LongText, Segmented, Toggle } from "./primitives";12import { S } from "./strings";13import type { FormEnv, FormProps } from "./types";1415export interface BlockFormProps {16  block: Block | LeafBlock;17  /** For source pickers (doc.sources) and asset pickers (doc.assets). */18  doc: Sheet;19  /** Complete next value of the block. Called on every committed edit (blur / Enter / toggle / select), only with a block that passes the schema. */20  onChange: (next: Block | LeafBlock) => void;21  /** Interface language. */22  locale: Locale;23  /** Opens the visual diagram editor (host-provided); the button is shown on diagram blocks. */24  onOpenDiagramEditor?: () => void;25  /** Lets the host add an uploaded image/dataset to doc.assets and returns its local id; without it those pickers are hidden. */26  onPickAsset?: (kind: "image" | "dataset") => Promise<string | null>;27  /** Rows of a dataset asset (for building a chart from uploaded data). */28  loadDataset?: (assetRef: string) => Promise<Dataset | null>;29}3031/** One form per block type: leaving a type out is a compile error. */32const FORMS: { [T in BlockType]: (props: FormProps<T>) => ReactNode } = {33  heading: HeadingForm, paragraph: ParagraphForm, list: ListForm, equation: EquationForm, callout: CalloutForm, table: TableForm,34  cards: CardsForm, steps: StepsForm, legend: LegendForm, diagram: DiagramForm, timeline: TimelineForm, matrix: MatrixForm,35  code: CodeForm, chart: ChartForm, svg: SvgForm, image: ImageForm, comparison: ComparisonForm, accordion: AccordionForm,36  quiz: QuizForm, simulation: SimulationForm, references: ReferencesForm, divider: DividerForm, tabs: TabsForm,37};38type AnyForm = (props: { block: Block | LeafBlock; set: (next: Block | LeafBlock) => void; env: FormEnv }) => ReactNode;3940/** Blocks whose text alternative the quality report requires. */41const VISUAL: ReadonlySet<BlockType> = new Set<BlockType>(["diagram", "chart", "matrix", "svg", "image", "simulation"]);4243export type Checked = { ok: true; block: Block | LeafBlock } | { ok: false; issues: FormIssue[] };4445/**46 * The gate every edit goes through: absent optional values are dropped, simulation sliders are brought back to the47 * ones the kind defines, then the candidate must pass the schema (LeafBlockSchema inside a tab) and, for a48 * simulation, the simulation's own checks. Pure.49 */50export function checkBlock(candidate: Block | LeafBlock, leaf: boolean, locale: Locale): Checked {51  let value = JSON.parse(JSON.stringify(candidate)) as Block | LeafBlock;52  if (value.type === "simulation" && value.config && typeof value.config === "object") value = { ...value, params: simParams(value.kind, value.config, value.params ?? {}) };53  const r = leaf ? LeafBlockSchema.safeParse(value) : BlockSchema.safeParse(value);54  if (!r.success) return { ok: false, issues: plainIssues(r.error, locale) };55  if (r.data.type === "simulation") { const issues = simulationIssues(r.data); if (issues.length > 0) return { ok: false, issues }; }56  return { ok: true, block: r.data };57}5859const SPAN_FRACTION: Record<(typeof SPANS)[number], string> = { 3: "¼", 4: "⅓", 6: "½", 8: "⅔", 12: "1" };6061function CommonSection({ block, set, doc, locale }: { block: Block | LeafBlock; set: (next: Block | LeafBlock) => void; doc: Sheet; locale: Locale }) {62  const t = S(locale);63  const visual = VISUAL.has(block.type);64  const selected = block.sourceIds ?? [];65  const known = doc.sources.map((s) => ({ value: s.id, label: `${s.title}${s.year ? ` (${s.year})` : ""}` }));66  const orphans = selected.filter((id) => !doc.sources.some((s) => s.id === id)).map((id) => ({ value: id, label: fill(t.unknownSource, { id }) }));67  const alt = (68    <LongText label={t.alt} value={block.alt} path="alt" maxLength={600} required={visual} rows={visual ? 3 : 2}69      hint={visual ? (block.alt?.trim() ? t.altHintVisual : <span className="font-medium text-warn">{t.altMissing}</span>) : t.altHint}70      onCommit={(v) => set({ ...block, alt: optional(v) })} />71  );72  return (73    <>74      {visual && <div className="rounded-xl border border-warn/40 bg-warn/5 p-3">{alt}</div>}75      <Group legend={t.blockSettings}>76        <Segmented legend={t.width} value={block.span} hint={t.widthHint} onChange={(span) => set({ ...block, span })}77          options={SPANS.map((span) => ({78            value: span, label: SPAN_FRACTION[span],79            visual: <span aria-hidden="true" className="flex h-1.5 w-full min-w-8 overflow-hidden rounded-full bg-line"><span className="h-full rounded-full bg-accent" style={{ width: `${(span / 12) * 100}%` }} /></span>,80          }))} />81        {!visual && alt}82        <ChipSelect legend={t.sources} options={[...known, ...orphans]} selected={selected} max={12} empty={t.noSources} hint={known.length > 0 ? t.sourcesHint : undefined}83          onChange={(next) => set({ ...block, sourceIds: next.length > 0 ? next : undefined })} />84        <Toggle label={t.locked} hint={t.lockedHint} checked={block.locked === true} onChange={(v) => set({ ...block, locked: v || undefined })} />85      </Group>86    </>87  );88}8990type InnerProps = BlockFormProps & { leaf: boolean };9192function Inner({ block, doc, onChange, locale, onOpenDiagramEditor, onPickAsset, loadDataset, leaf }: InnerProps) {93  const t = S(locale);94  // `draft` is what the fields show. It follows the host's block, except while it holds an edit that is not valid yet.95  const [seen, setSeen] = useState(block);96  const [draft, setDraft] = useState<Block | LeafBlock>(block);97  const [issues, setIssues] = useState<FormIssue[]>([]);98  const [drill, setDrill] = useState<string | null>(null);99  if (block !== seen) {100    setSeen(block);101    if (stableStringify(block) !== stableStringify(seen)) { setDraft(block); setIssues([]); }102  }103  const set = (next: Block | LeafBlock) => {104    const r = checkBlock(next, leaf, locale);105    // An edit that changes nothing (a number retyped with a decimal comma…) is not reported: no empty undo step.106    const unchanged = r.ok && issues.length === 0 && stableStringify(r.block) === stableStringify(draft);107    setDraft(next);108    setIssues(r.ok ? [] : r.issues);109    if (r.ok && !unchanged) onChange(r.block);110  };111  const env: FormEnv = {112    doc, locale, onOpenDiagramEditor, onPickAsset, loadDataset, drill, setDrill,113    renderChild: (child, onChild) => <Inner key={child.id} block={child} doc={doc} locale={locale} leaf onChange={(next) => { if (next.type !== "tabs") onChild(next); }} onOpenDiagramEditor={onOpenDiagramEditor} onPickAsset={onPickAsset} loadDataset={loadDataset} />,114  };115  const context = useMemo(() => ({ locale, issues }), [locale, issues]);116  const Form = FORMS[draft.type] as unknown as AnyForm;117  const drilled = draft.type === "tabs" && drill !== null && draft.tabs.some((tab) => tab.blocks.some((c) => c.id === drill));118  const entry = catalogEntry(draft.type);119  return (120    <FormContext.Provider value={context}>121      <div role="group" className="flex min-w-0 flex-col gap-4 text-ink" aria-label={fill(t.formLabel, { type: entry.label[locale] })}>122        {issues.length > 0 && (123          <div role="alert" className="rounded-xl border border-bad/40 bg-bad/10 px-3 py-2 text-sm leading-snug">124            <p className="font-semibold text-bad">{t.notSaved}</p>125            <ul className="mt-1 list-disc pl-5">{issues.slice(0, 6).map((i, k) => <li key={k}>{i.message}</li>)}</ul>126          </div>127        )}128        <Form block={draft} set={set} env={env} />129        {!drilled && <CommonSection block={draft} set={set} doc={doc} locale={locale} />}130      </div>131    </FormContext.Provider>132  );133}134135/**136 * The property form of one block. The host owns the document: this component only reports complete, schema-valid137 * next values through `onChange`. An edit that is not valid yet (a required text emptied…) stays in the form, with138 * the reason under the field, until it is fixed.139 */140export function BlockForm(props: BlockFormProps) {141  return <Inner key={props.block.id} {...props} leaf={false} />;142}143
Files main
Menu

Theme