/* ═══════════════════════════════════════════════════════════════ ADMIN FORM PRIMITIVES Field renders one input from a manifest entry. Repeater renders an ordered collection of them, and nests one level for content blocks and their items. Ordering is array position (the server writes sort_order from the index), so moving a row is a splice, not a number to hand-edit. Rows fold to their title line. They start folded, so a long collection (the front page's slides and paths) reads as a list rather than a wall of fields; a row just added starts open, and one the server rejected opens itself so the error can't hide. Which rows are open is a set of indices, remapped by every move, insert and removal here, so it survives a save (which replaces every row object but keeps their order). Rows can be dragged by the handle or moved with the arrow buttons; the arrows are the keyboard path and stay whether or not a pointer is in use. A row added and never filled in is dropped by the server rather than rejected, which depends on spec.blank seeding nothing the server doesn't also declare as a column default. If you give a blank row a starting value here, add the matching default: to that column in the server's admin-schema.js or the row will be saved as real input. In a repeater row, `when: { path, value }` shows a field only while another field of the row holds that value (or one of them, given an array). A field that goes hidden is cleared, so a row can't keep a value for a choice it no longer makes: a featured card switched from "record" to "link" drops its record. `when: { scope: "parent", path, value }` looks at the row this collection belongs to instead: a schedule entry shows its day and time only while the block above it is a schedule. A nested collection takes `when` the same way, and one that goes hidden is emptied: a list block turned into a paragraph drops its items. `help` and `label` may be functions of the row, for wording that depends on another field (a content block's type says what its text is). `preview` on a collection names an entry in PREVIEWS below; each open row then shows how it will look on the site, drawn by the site's own component. Every row can be duplicated (a copy lands below it, ids stripped so it saves as new) or have a blank row inserted below it, as well as appended at the end. `widget: "linkPreview"` is a URL box with a "Fetch preview" button (LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty title, blurb and image through `onPatch`. `files: true` on a link field adds "Choose a file" (FilePicker in DriveFiles.tsx): the field takes the file's Drive link, and with `previewFills` (a link card) the row's empty title and picture take the file's name and first-page preview. `filesWhen` limits it to rows that match, as `when` does for the field. `redirects: true` on a link field adds "Pick a redirect": a list of Data → Links/redirects (the `redirects` options) that fills the field with the short link's full address, /go/. `widget: "testNotice"` is a text box of email addresses with a "Send a test notice" button (TestNoticeInput below), for Site settings → Notices. `widget: "image"` is a text box with a preview and upload and library buttons beside it (ImageInput in MediaLibrary.tsx). Its `resolve` option is the media.ts helper for the field's public/ directory, so a bare filename previews from the right place. Its `folder` ("logos" for logo and icon fields) is where uploads go and the tab the library opens on. `frameFrom` names the row's video link field and adds "Frame at" (a still at a typed time, saved to thumbnails/); `frameWhen` limits it to rows that match. Two options change the box itself rather than what goes in it: prefix fixed text inside the box, left of the cursor. The value it decorates is only the part after it, so the caller joins the two. Used by composed slugs, where the prefix is a fact about another field rather than something to retype. readOnly shown, selectable, not editable. Deliberately not `disabled`: a disabled control reads as switched off and drops out of the tab order, whereas an immutable id is settled fact you still want to be able to read and copy. ═══════════════════════════════════════════════════════════════ */ import { ArrowUp, ArrowDown, CaretRight, Copy, Plus, X } from "@phosphor-icons/react"; import { useMemo, useRef, useState } from "react"; import { ApiError, post } from "../../lib/api.ts"; import ContentBlocks from "../ContentBlocks.tsx"; import { FILTER_FROM, OptionFilter, narrow } from "../OptionFilter.tsx"; import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; import { ChooseFileButton } from "./DriveFiles.tsx"; import { siteUrl } from "../../lib/site.ts"; /* Live previews a collection can name with `preview`. Each gets the row as the form holds it, which is the API's shape. */ const PREVIEWS = { // The form holds an entry's person as person_id; the renderer wants // the person, so it's looked up in the select options (a name, no // photo: the options carry no more). contentBlock: (row, options) => ( { const person = item.person_id ? options?.people?.find((p) => p.id === item.person_id) : null; return { ...item, person: person ? { id: person.id, name: person.label } : null }; }), }, ]} /> ), }; const input = "w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body "+ "outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25"; /* Same box, but lit by the real input nested inside it. */ const inputShell = "flex w-full items-center border border-muted/25 bg-surface px-3 py-2 text-sm "+ "text-body transition-colors focus-within:border-brand focus-within:ring-2 " + "focus-within:ring-brand/25"; const inputError = "border-danger focus:border-danger focus:ring-danger/20"; const shellError = "border-danger focus-within:border-danger focus-within:ring-danger/20"; /* Reads as settled fact rather than as an empty box someone forgot to fill in. */ const inputLocked = "w-full border border-muted/20 bg-tint-soft px-3 py-2 text-sm "+ "text-muted outline-none cursor-default focus:border-muted/40"; /* ── Dotted paths ────────────────────────────────────────────── */ /* What an empty color field shows in its swatch and placeholder: the field's own default (a value, or one worked out from the row), else the brand teal. */ function colorPlaceholder(field, row): string { const own = typeof field.placeholder === "function" ? field.placeholder(row) : field.placeholder; return own || "#00748a"; } export function getPath(object, path) { // An entity with no slug has no heading path either, and a missing // path should read as "no value" rather than throwing on .split. if (!path) return undefined; return path.split(".").reduce((value, key) => value?.[key], object); } export function setPath(object, path, value) { const [head, ...rest] = path.split("."); if (rest.length === 0) return { ...object, [head]: value }; return { ...object, [head]: setPath(object?.[head] ?? {}, rest.join("."), value) }; } /* ── Conditional fields ──────────────────────────────────────── */ /* `when: { path, value }` shows a field when the other field holds that value (or one of a list); `when: { path, filled: true }` when it holds anything at all. */ export function fieldShown(field, row, parent?) { if (!field.when) return true; const source = field.when.scope === "parent" ? parent : row; if (field.when.filled) return Boolean(source?.[field.when.path]); const want = Array.isArray(field.when.value) ? field.when.value : [field.when.value]; return want.includes(source?.[field.when.path]); } /* A row after an edit, with any field the edit hid cleared. "" is the engine's deliberate clear, so it saves as NULL. */ function withHiddenCleared(spec, row, parent?) { let next = row; // Two fields can share a path, each shown for a different kind of // row (a card's Description and a list item's Detail are both // `detail`); a value is only hidden when none of them is showing. const shownPaths = new Set(spec.fields.filter((f) => fieldShown(f, row, parent)).map((f) => f.path)); for (const field of spec.fields) { const value = next[field.path]; if (!shownPaths.has(field.path) && value != null && value !== "") { next = { ...next, [field.path]: "" }; } } for (const nested of spec.children ?? []) { const rows = next[nested.key]; if (!rows?.length) continue; if (!fieldShown(nested, next, parent)) { next = { ...next, [nested.key]: [] }; } else { // Its rows may have fields that follow this row (scope // "parent"), which this edit may just have hidden. const cleared = rows.map((child) => withHiddenCleared(nested, child, next)); if (cleared.some((child, i) => child !== rows[i])) next = { ...next, [nested.key]: cleared }; } } return next; } /* A copy of a row with every id removed, nested rows included, so the server inserts it as new rather than colliding with the row it was copied from. */ function withoutIds(value) { if (Array.isArray(value)) return value.map(withoutIds); if (!value || typeof value !== "object") return value; const copy = {}; for (const [key, inner] of Object.entries(value)) { if (key !== "id") copy[key] = withoutIds(inner); } return copy; } const helpText = (field, row) => (typeof field.help === "function" ? field.help(row) : field.help); /* ── Field ───────────────────────────────────────────────────── */ export function Field({ field, value, row, options, error, onChange, onPatch }: any) { const id = `f-${field.path.replace(/\./g, "-")}`; const widget = field.widget ?? "text"; const locked = Boolean(field.readOnly); // The select's options, rebuilt only when their source changes // (or, with filterBy, the row they're filtered by), not on every // keystroke elsewhere in the form. const source = field.optionsFrom ? options?.[field.optionsFrom] : field.options; const filterRow = field.filterBy ? row : null; const list: any[] | null = useMemo(() => { if (widget !== "select") return null; let all = field.optionsFrom ? (source ?? []).map((o) => [o.id, o.label, o]) : (source ?? []).map((o) => (Array.isArray(o) ? [o[0], o[1]] : [o, o])); if (field.filterBy && filterRow) { all = all.filter(([, , raw]) => !raw || field.filterBy(raw, filterRow)); } return all; }, [widget, field, source, filterRow]); // Past FILTER_FROM options, a box above the select narrows them. const [needle, setNeedle] = useState(""); const shown: any[] = list ? narrow(list, needle, ([, label]) => label, ([optionId]) => String(optionId) === String(value)) : []; // A stored value with no matching option renders as the blank // choice, which reads as "nobody set this" and saves as a // deliberate clear. It usually means the row it pointed at was // deleted, so keep it on screen and say so. const orphaned = list != null && value != null && value !== "" && !list.some(([optionId]) => String(optionId) === String(value)); // A file from the Drive library into this link field (`files`). const pickFile = (file) => { const fills = field.previewFills; const patch = { [field.path]: file.url }; if (fills && !row?.[fills.title]) patch[fills.title] = file.title; if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview; if (onPatch && !field.path.includes(".")) onPatch(patch); else onChange(file.url); }; const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row)); // The line under the field (its error, the deleted-row warning, or // its help) is read with it, and the field says when it's required // or wrong, not only the red star and border. const noteId = `${id}-note`; const hasNote = Boolean(error || (orphaned && !locked) || (helpText(field, row) && widget !== "checkbox")); const described = { "aria-describedby": hasNote ? noteId : undefined, "aria-invalid": Boolean(error || (orphaned && !locked)) || undefined, "aria-required": (field.required && !locked) || undefined, }; const common = { id, className: `${input} ${error ? inputError : ""}`, value: value ?? "", onChange: (e) => onChange(e.target.value), ...described, }; return (
{widget === "checkbox" ? ( ) : widget === "textarea" ? (