SPB Git

Repository Public

forms-lists.tsx 16.4 KB 271 lines tsx

1"use client";2import { useState } from "react";3import { blockText, newId, type BlockOf, type LeafBlock } from "@/schema";4import { fill } from "@/i18n/dict";5import { BLOCK_CATALOG, catalogEntry, newLeafBlock } from "./defaults";6import {7  comparisonAddColumn, comparisonMoveColumn, comparisonRemoveColumn, moveItem, optional, removeItem, replaceItem,8  TABLE_MAX, tableAddColumn, tableAddRow, tableMoveColumn, tablePaste, tableRemoveColumn, tableRemoveRow,9} from "./helpers";10import { GridEditor, IconPicker, ItemButtons, ListEditor, LongText, Note, Segmented, Select, TextField, Toggle, TonePicker, useLocale, useT } from "./primitives";11import { ALIGN, LEGEND_SHAPE, ORIENTATION, labelOptions } from "./strings";12import type { FormProps } from "./types";1314type Item<T extends "cards" | "steps" | "legend" | "timeline" | "accordion"> = BlockOf<T>["items"][number];1516export function CardsForm({ block, set }: FormProps<"cards">) {17  const t = useT();18  return (19    <>20      <Segmented legend={t.cardColumns} value={block.columns} onChange={(columns) => set({ ...block, columns })} options={[{ value: 2, label: "2" }, { value: 3, label: "3" }, { value: 4, label: "4" }]} />21      <ListEditor<Item<"cards">> legend={t.cards} items={block.items} min={1} max={12} path="items" addLabel={t.addCard}22        itemTitle={(c, i) => c.title || fill(t.itemN, { n: i + 1 })} newItem={() => ({ title: t.newCardTitle, text: "", tone: "neutral" })}23        onChange={(items) => set({ ...block, items })}24        renderItem={(c, i, update) => (25          <>26            <TextField label={t.title} value={c.title} path={`items.${i}.title`} maxLength={200} required onCommit={(title) => update({ ...c, title })} />27            <LongText label={t.text} value={c.text} path={`items.${i}.text`} maxLength={800} onCommit={(text) => update({ ...c, text })} />28            <TextField label={t.badge} value={c.badge} path={`items.${i}.badge`} maxLength={40} onCommit={(v) => update({ ...c, badge: optional(v) })} />29            <TonePicker label={t.tone} value={c.tone} onChange={(tone) => update({ ...c, tone })} />30            <IconPicker label={t.icon} value={c.icon} onChange={(icon) => update({ ...c, icon })} />31          </>32        )} />33    </>34  );35}3637export function StepsForm({ block, set }: FormProps<"steps">) {38  const t = useT();39  return (40    <ListEditor<Item<"steps">> legend={t.steps} items={block.items} min={1} max={12} path="items" addLabel={t.addStep}41      itemTitle={(s, i) => s.title || fill(t.itemN, { n: i + 1 })} newItem={() => ({ title: t.newStepTitle, text: "" })}42      onChange={(items) => set({ ...block, items })}43      renderItem={(s, i, update) => (44        <>45          <TextField label={t.title} value={s.title} path={`items.${i}.title`} maxLength={200} required onCommit={(title) => update({ ...s, title })} />46          <LongText label={t.text} value={s.text} path={`items.${i}.text`} maxLength={800} onCommit={(text) => update({ ...s, text })} />47          <IconPicker label={t.icon} value={s.icon} onChange={(icon) => update({ ...s, icon })} />48        </>49      )} />50  );51}5253export function LegendForm({ block, set }: FormProps<"legend">) {54  const t = useT();55  const locale = useLocale();56  return (57    <>58      <TextField label={t.title} value={block.title} path="title" maxLength={200} onCommit={(v) => set({ ...block, title: optional(v) })} />59      <ListEditor<Item<"legend">> legend={t.legendEntries} items={block.items} min={1} max={12} path="items" addLabel={t.addEntry}60        itemTitle={(e, i) => e.label || fill(t.itemN, { n: i + 1 })} newItem={() => ({ label: t.newEntryLabel, tone: "neutral", shape: "square" })}61        onChange={(items) => set({ ...block, items })}62        renderItem={(e, i, update) => (63          <>64            <TextField label={t.label} value={e.label} path={`items.${i}.label`} maxLength={200} required onCommit={(label) => update({ ...e, label })} />65            <Select label={t.shape} value={e.shape} options={labelOptions(LEGEND_SHAPE(locale))} onChange={(shape) => update({ ...e, shape })} />66            <TonePicker label={t.tone} value={e.tone} onChange={(tone) => update({ ...e, tone })} />67          </>68        )} />69    </>70  );71}7273export function TimelineForm({ block, set }: FormProps<"timeline">) {74  const t = useT();75  const locale = useLocale();76  return (77    <>78      <Segmented legend={t.orientation} value={block.orientation} options={labelOptions(ORIENTATION(locale))} onChange={(orientation) => set({ ...block, orientation })} />79      <ListEditor<Item<"timeline">> legend={t.milestones} items={block.items} min={2} max={20} path="items" addLabel={t.addMilestone}80        itemTitle={(m, i) => [m.when, m.title].filter(Boolean).join(" · ") || fill(t.itemN, { n: i + 1 })} newItem={() => ({ when: t.newMilestoneWhen, title: t.newMilestoneTitle, tone: "neutral" })}81        onChange={(items) => set({ ...block, items })}82        renderItem={(m, i, update) => (83          <>84            <TextField label={t.when} value={m.when} path={`items.${i}.when`} maxLength={60} required onCommit={(when) => update({ ...m, when })} />85            <TextField label={t.title} value={m.title} path={`items.${i}.title`} maxLength={200} required onCommit={(title) => update({ ...m, title })} />86            <LongText label={t.text} value={m.text} path={`items.${i}.text`} maxLength={600} onCommit={(v) => update({ ...m, text: optional(v) })} />87            <TonePicker label={t.tone} value={m.tone} onChange={(tone) => update({ ...m, tone })} />88          </>89        )} />90    </>91  );92}9394export function AccordionForm({ block, set }: FormProps<"accordion">) {95  const t = useT();96  return (97    <ListEditor<Item<"accordion">> legend={t.sections} items={block.items} min={1} max={12} path="items" addLabel={t.addSection}98      itemTitle={(s, i) => s.title || fill(t.itemN, { n: i + 1 })} newItem={() => ({ title: t.newSectionTitle, text: t.newSectionText })}99      onChange={(items) => set({ ...block, items })}100      renderItem={(s, i, update) => (101        <>102          <TextField label={t.title} value={s.title} path={`items.${i}.title`} maxLength={200} required onCommit={(title) => update({ ...s, title })} />103          <LongText label={t.text} value={s.text} path={`items.${i}.text`} maxLength={4000} required rows={3} onCommit={(text) => update({ ...s, text })} />104        </>105      )} />106  );107}108109type ComparisonColumn = BlockOf<"comparison">["columns"][number];110type ComparisonRow = BlockOf<"comparison">["rows"][number];111112export function ComparisonForm({ block, set }: FormProps<"comparison">) {113  const t = useT();114  return (115    <>116      <TextField label={t.caption} value={block.caption} path="caption" maxLength={300} onCommit={(v) => set({ ...block, caption: optional(v) })} />117      <ListEditor<ComparisonColumn> legend={t.comparedOptions} items={block.columns} min={2} max={4} path="columns" addLabel={t.addOption}118        itemTitle={(c, i) => c.title || fill(t.columnN, { n: i + 1 })} newItem={() => ({ title: t.newOptionTitle, tone: "neutral" })}119        onChange={(columns) => set({ ...block, columns })}120        onAdd={() => set(comparisonAddColumn(block, fill(t.optionN, { n: block.columns.length + 1 })))}121        onRemove={(i) => set(comparisonRemoveColumn(block, i))}122        onMove={(i, d) => set(comparisonMoveColumn(block, i, d))}123        renderItem={(c, i, update) => (124          <>125            <TextField label={t.title} value={c.title} path={`columns.${i}.title`} maxLength={200} required onCommit={(title) => update({ ...c, title })} />126            <TextField label={t.badge} value={c.badge} path={`columns.${i}.badge`} maxLength={40} onCommit={(v) => update({ ...c, badge: optional(v) })} />127            <TonePicker label={t.tone} value={c.tone} onChange={(tone) => update({ ...c, tone })} />128          </>129        )} />130      <ListEditor<ComparisonRow> legend={t.criteria} items={block.rows} min={1} max={16} path="rows" addLabel={t.addCriterion}131        itemTitle={(r, i) => r.label || fill(t.rowN, { n: i + 1 })} newItem={() => ({ label: t.newCriterionLabel, cells: block.columns.map(() => "") })}132        onChange={(rows) => set({ ...block, rows })}133        renderItem={(r, i, update) => (134          <>135            <TextField label={t.criterion} value={r.label} path={`rows.${i}.label`} maxLength={200} required onCommit={(label) => update({ ...r, label })} />136            {block.columns.map((c, j) => (137              <LongText key={j} label={c.title || fill(t.columnN, { n: j + 1 })} value={r.cells[j] ?? ""} path={`rows.${i}.cells.${j}`} maxLength={600} rows={1}138                onCommit={(text) => update({ ...r, cells: block.columns.map((_, k) => (k === j ? text : r.cells[k] ?? "")) })} />139            ))}140          </>141        )} />142      <LongText label={t.verdict} value={block.verdict} path="verdict" maxLength={800} onCommit={(v) => set({ ...block, verdict: optional(v) })} />143    </>144  );145}146147type Choice = BlockOf<"quiz">["choices"][number];148149export function QuizForm({ block, set }: FormProps<"quiz">) {150  const t = useT();151  const noneCorrect = !block.choices.some((c) => c.correct);152  return (153    <>154      <LongText label={t.question} value={block.question} path="question" maxLength={600} required onCommit={(question) => set({ ...block, question })} />155      <ListEditor<Choice> legend={t.choices} items={block.choices} min={2} max={6} path="choices" addLabel={t.addChoice}156        itemTitle={(c, i) => `${c.correct ? "✓ " : ""}${c.text || fill(t.itemN, { n: i + 1 })}`} newItem={() => ({ text: t.newChoiceText, correct: false })}157        onChange={(choices) => set({ ...block, choices })}158        renderItem={(c, i, update) => (159          <>160            <LongText label={t.answer} value={c.text} path={`choices.${i}.text`} maxLength={400} required rows={1} onCommit={(text) => update({ ...c, text })} />161            <Toggle label={t.correct} checked={c.correct} onChange={(correct) => update({ ...c, correct })} />162            <LongText label={t.choiceExplanation} value={c.explanation} path={`choices.${i}.explanation`} maxLength={600} rows={1} onCommit={(v) => update({ ...c, explanation: optional(v) })} />163          </>164        )} />165      {noneCorrect && <Note tone="warn">{t.quizNoCorrect}</Note>}166    </>167  );168}169170type TableColumn = BlockOf<"table">["columns"][number];171172export function TableForm({ block, set }: FormProps<"table">) {173  const t = useT();174  const locale = useLocale();175  const [note, setNote] = useState<string | null>(null);176  const columnLabel = (n: number) => fill(t.columnN, { n });177  return (178    <>179      <TextField label={t.caption} value={block.caption} path="caption" maxLength={300} onCommit={(v) => set({ ...block, caption: optional(v) })} />180      <ListEditor<TableColumn> legend={t.columns} items={block.columns} min={1} max={TABLE_MAX.cols} path="columns" addLabel={t.addColumn} compact181        itemTitle={(c, i) => c.label || columnLabel(i + 1)} newItem={() => ({ label: "", align: "left" })}182        onChange={(columns) => set({ ...block, columns })}183        onAdd={() => set(tableAddColumn(block, columnLabel(block.columns.length + 1)))}184        onRemove={(i) => set(tableRemoveColumn(block, i))}185        onMove={(i, d) => set(tableMoveColumn(block, i, d))}186        renderItem={(c, i, update) => (187          <>188            <TextField label={fill(t.columnLabelN, { n: i + 1 })} hideLabel placeholder={columnLabel(i + 1)} value={c.label} path={`columns.${i}.label`} maxLength={200} onCommit={(label) => update({ ...c, label })} />189            <Select label={fill(t.columnAlignN, { n: i + 1 })} hideLabel value={c.align} options={labelOptions(ALIGN(locale))} onChange={(align) => update({ ...c, align })} />190          </>191        )} />192      <GridEditor legend={t.rows} columns={block.columns.map((c) => c.label)} rows={block.rows} maxRows={TABLE_MAX.rows} cellMaxLength={TABLE_MAX.cell} note={note} hint={t.gridPasteHint}193        onCell={(r, c, text) => set({ ...block, rows: replaceItem(block.rows, r, replaceItem(block.rows[r] ?? [], c, text)) })}194        onAddRow={() => set(tableAddRow(block))} onRemoveRow={(r) => set(tableRemoveRow(block, r))}195        onPaste={(row, col, data) => {196          const r = tablePaste(block, { row, col }, data, columnLabel);197          setNote(r.droppedRows + r.droppedCols > 0 ? fill(t.pasteDropped, { rows: r.droppedRows, cols: r.droppedCols }) : fill(t.pasteDone, { rows: data.length }));198          set(r.block);199        }} />200      <Toggle label={t.headerColumn} hint={t.headerColumnHint} checked={block.headerColumn === true} onChange={(v) => set({ ...block, headerColumn: v || undefined })} />201    </>202  );203}204205type Tab = BlockOf<"tabs">["tabs"][number];206const LEAF_TYPES = BLOCK_CATALOG.map((e) => e.type).filter((type): type is LeafBlock["type"] => type !== "tabs");207208function TabChildren({ tab, tabIndex, update, onEdit }: { tab: Tab; tabIndex: number; update: (next: Tab) => void; onEdit: (childId: string) => void }) {209  const t = useT();210  const locale = useLocale();211  const [type, setType] = useState<LeafBlock["type"]>("paragraph");212  const full = tab.blocks.length >= 12;213  return (214    <fieldset className="min-w-0 rounded-lg border border-line p-2">215      <legend className="eyebrow px-1">{t.tabBlocks} <span className="font-normal normal-case tracking-normal">· {tab.blocks.length}/12</span></legend>216      <ol className="flex flex-col gap-1.5">217        {tab.blocks.map((child, k) => {218          const kind = catalogEntry(child.type).label[locale];219          const excerpt = blockText(child).slice(0, 60);220          const name = excerpt ? `${kind} « ${excerpt} »` : kind;221          return (222            <li key={child.id} className="flex min-w-0 flex-wrap items-center justify-end gap-x-1 rounded-lg bg-raised/60 p-1">223              <button type="button" className="flex min-h-11 min-w-[8rem] flex-1 flex-col items-start justify-center rounded-md px-2 text-left" aria-label={fill(t.editChild, { name })} onClick={() => onEdit(child.id)}>224                <span className="text-sm font-semibold text-accent">{kind} <span aria-hidden="true">›</span></span>225                {excerpt && <span className="w-full truncate text-xs text-muted">{excerpt}</span>}226              </button>227              <ItemButtons name={name} index={k} count={tab.blocks.length} canRemove={tab.blocks.length > 1}228                onMove={(d) => update({ ...tab, blocks: moveItem(tab.blocks, k, d) })} onRemove={() => update({ ...tab, blocks: removeItem(tab.blocks, k) })} />229            </li>230          );231        })}232      </ol>233      <div className="mt-2 flex flex-wrap items-end gap-2">234        <Select className="min-w-[9rem] flex-1" label={fill(t.childType, { n: tabIndex + 1 })} value={type} onChange={setType}235          options={LEAF_TYPES.map((value) => ({ value, label: catalogEntry(value).label[locale] }))} />236        <button type="button" className="btn !min-h-11" disabled={full} onClick={() => { const child = newLeafBlock(type, locale); update({ ...tab, blocks: [...tab.blocks, child] }); }}>+ {t.addBlock}</button>237      </div>238    </fieldset>239  );240}241242export function TabsForm({ block, set, env }: FormProps<"tabs">) {243  const t = useT();244  const locale = useLocale();245  const tabIndex = env.drill === null ? -1 : block.tabs.findIndex((tab) => tab.blocks.some((c) => c.id === env.drill));246  if (tabIndex >= 0) {247    const tab = block.tabs[tabIndex];248    const childIndex = tab.blocks.findIndex((c) => c.id === env.drill);249    const child = tab.blocks[childIndex];250    return (251      <div className="flex min-w-0 flex-col gap-3">252        <button type="button" className="btn w-full !justify-start" onClick={() => env.setDrill(null)}><span aria-hidden="true">‹</span> {t.backToTabs}</button>253        <p className="text-sm text-muted">{tab.label} <span aria-hidden="true">›</span> <strong className="text-ink">{catalogEntry(child.type).label[locale]}</strong></p>254        {env.renderChild(child, (next) => set({ ...block, tabs: replaceItem(block.tabs, tabIndex, { ...tab, blocks: replaceItem(tab.blocks, childIndex, next) }) }))}255      </div>256    );257  }258  return (259    <ListEditor<Tab> legend={t.tabs} items={block.tabs} min={2} max={6} path="tabs" addLabel={t.addTab} defaultOpen={0}260      itemTitle={(tab, i) => tab.label || fill(t.tabN, { n: i + 1 })}261      newItem={() => ({ id: newId("t"), label: fill(t.tabN, { n: block.tabs.length + 1 }), blocks: [newLeafBlock("paragraph", locale)] })}262      onChange={(tabs) => set({ ...block, tabs })}263      renderItem={(tab, i, update) => (264        <>265          <TextField label={t.tabLabel} value={tab.label} path={`tabs.${i}.label`} maxLength={60} required onCommit={(label) => update({ ...tab, label })} />266          <TabChildren tab={tab} tabIndex={i} update={update} onEdit={env.setDrill} />267        </>268      )} />269  );270}271
Files main
Menu

Theme