import { Badge, Button, Checkbox, Input, InputArea, Link, Select, Switch, Text, } from "@cloudflare/kumo"; import type { FieldDefinition, ReferenceField, ReferenceSubField, SubFieldDefinition, } from "@cloudhal/core-contracts"; import { FIELD_LIMITS, fieldHelp, optionLabel } from "@cloudhal/core-ts/fields"; import { type ReactNode, useEffect, useId, useState } from "react"; import { DateTimeField, type DateTimeFieldLabels, type DateTimeValue } from "./DateTimeField.tsx"; import { hasValue, instantOf, referenceIds } from "./entry-fields-model.ts"; import { wallClockOf, zonedToInstant } from "./zoned-time.ts"; /** A field or a repeater's sub-field: what one control edits. */ export type AnyFieldDefinition = FieldDefinition | SubFieldDefinition; /** The controls' own words; the fields' words come from their definitions (`labels`). */ export interface FieldControlLabels { /** The marker of a `requiredToPublish` field: "Needed to publish". */ neededToPublish: string; /** Under a non-localized field of a translation: "From the original (English)". */ fromOriginal: string; /** The link to the original next to it: "Open the original". */ openOriginal: string; /** Under an empty localized field whose control has no placeholder: "The original: {value}". */ originalValue: (text: string) => string; yes: string; no: string; /** A select's empty choice: "No value". */ noValue: string; /** Removes a date or a date and time: "Clear". */ clear: string; /** What an image of the original is called in a fallback line: "The original's image". */ originalImage: string; /** The date and time controls' words (`DateTimeField`). */ date: DateTimeFieldLabels; /** Under a value a running type change has not converted yet (shown read-only). */ beingChanged: string; } /** What the host renders for a rich text field (Studio: the lazy markdown body editor). */ export interface FieldRichTextSlot { def: AnyFieldDefinition; label: string; description: ReactNode; error: string | undefined; value: string; onChange: (value: string) => void; readOnly: boolean; placeholder: string | undefined; } /** What the host renders for an image field (Studio: the media picker); the value is an asset id. */ export interface FieldImageSlot { def: AnyFieldDefinition; label: string; description: ReactNode; error: string | undefined; value: string | undefined; onChange: (assetId: string | undefined) => void; readOnly: boolean; } /** * What the host renders for a reference (RFC-0045 §5; Studio: `ReferenceList` and `EntryPicker` * around the picker route), inside the block's `fieldset`, which carries the label, the * description and the error. Values are translation group ids, in order. */ export interface FieldReferenceSlot { def: ReferenceField | ReferenceSubField; /** The value's path under `fields`: `venue`, or `speakers/2/person` in a repeater item. */ path: string; label: string; description: ReactNode; error: string | undefined; value: readonly string[]; /** A list of targets (`multiple`), or one. */ multiple: boolean; /** At most this many targets (1 unless `multiple`). */ max: number; onChange: (ids: readonly string[]) => void; readOnly: boolean; /** * An empty localized field of a translation: the original's targets. The form words them under * the control through `referenceTitle`; the host loads them so it can. */ fallback: readonly string[] | undefined; } /** Everything a control needs besides its own field. */ export interface FieldControlContext { /** The Studio language (labels, numbers, dates) and the site's default (label fallback). */ locale: string; defaultLocale: string; /** The zone a new date and time is entered in (the site's), and how a zone reads. */ timeZone: string; zoneLabel: (timeZone: string) => string; labels: FieldControlLabels; renderRichText?: ((slot: FieldRichTextSlot) => ReactNode) | undefined; renderImage?: ((slot: FieldImageSlot) => ReactNode) | undefined; renderReference?: ((slot: FieldReferenceSlot) => ReactNode) | undefined; } export interface FieldControlProps { def: AnyFieldDefinition; /** The value's path under `fields` (`venue`, `speakers/2/person`). */ path: string; label: string; description: ReactNode; error: string | undefined; value: unknown; onChange: (v: unknown) => void; readOnly: boolean; /** The original's value as text, for an empty localized field of a translation. */ placeholder?: string | undefined; /** The original's value itself, for controls that show it their own way (references). */ fallbackValue?: unknown; /** Show the stored value read-only, as it is: a value a running type change has not converted. */ asStored?: boolean | undefined; context: FieldControlContext; } type Ctl = FieldControlProps; const str = (v: unknown) => (typeof v === "string" ? v : ""); function TextControl({ def, label, description, error, value, onChange, readOnly, placeholder, }: Ctl) { const common = { className: "w-full", label, description, error, value: str(value), placeholder, disabled: readOnly, onValueChange: onChange, }; if (def.type === "text" && def.multiline) return ; return ( ); } function NumberControl(c: Ctl) { const { def, label, description, error, value, onChange, readOnly, placeholder } = c; const integer = def.type === "number" && def.integer === true; return ( onChange(raw.trim() === "" ? undefined : Number.isFinite(Number(raw)) ? Number(raw) : raw) } /> ); } function BooleanControl({ label, description, value, onChange, readOnly }: Ctl) { return (
onChange(on || undefined)} /> {description && ( {description} )}
); } function SelectControl(c: Ctl) { const { def, label, description, error, value, onChange, readOnly, placeholder, context } = c; if (def.type !== "select") return null; const words = (v: string) => optionLabel(def, v, context.locale, context.defaultLocale); if ("multiple" in def && def.multiple) { const chosen = Array.isArray(value) ? value.map(String) : []; return ( o.value)} onValueChange={(next: string[]) => onChange(def.options.map((o) => o.value).filter((v) => next.includes(v))) } > {def.options.map((o) => ( ))} ); } return ( ); } /** A stored value read-only, as JSON: a reference without a host picker, or a value of no known shape. */ function StoredValueControl({ label, description, error, value }: Ctl) { return ( ); } /** RFC-0045: a reference through the host's picker; one id is stored bare, several as a list. */ function ReferenceControl(c: Ctl) { const about = useId(); const { def } = c; if (def.type !== "reference" || !c.context.renderReference) return StoredValueControl(c); const multiple = "multiple" in def && def.multiple === true; const max = multiple ? ("maxItems" in def ? def.maxItems : undefined) : 1; const fallback = referenceIds(c.fallbackValue); const slot: FieldReferenceSlot = { def, path: c.path, label: c.label, description: c.description, error: c.error, value: referenceIds(c.value), multiple, max: max ?? FIELD_LIMITS.listItems, onChange: (ids) => c.onChange(multiple ? [...ids] : ids[0]), readOnly: c.readOnly, fallback: fallback.length ? fallback : undefined, }; return (
{/* Kumo's own label style (`Field`, `Checkbox.Group`). */} {c.label} {c.context.renderReference(slot)} {(c.description || c.error) && ( {c.description && ( {c.description} )} {c.error && ( {c.error} )} )}
); } const CONTROLS: Record ReactNode> = { text: TextControl, url: TextControl, richText: RichTextControl, number: NumberControl, boolean: BooleanControl, date: DateControl, datetime: DateControl, image: ImageControl, select: SelectControl, reference: ReferenceControl, // A repeater renders through `RepeaterField` (EntryFieldsForm); never as a sub-field. repeater: StoredValueControl, }; /** Placeholders only fit controls that show text; the rest say it under the control. */ export const HAS_PLACEHOLDER: ReadonlySet = new Set(["text", "url", "number", "richText"]); /** What a description says besides the field's own help. */ export interface DescribeExtra { /** A limit in words ("Up to 80 characters."), after the help. */ hint?: string | undefined; /** The original's value in words, for a control without a placeholder. */ fallback?: string | undefined; /** The value is the original's: "From the original · Open the original". */ inherited?: { href: string } | undefined; /** One more line, such as a shared list's "Not translated" note. */ note?: string | undefined; } /** A field's description: "Needed to publish", help, limits, and where a translation's value comes from. */ export function describeField( def: AnyFieldDefinition, context: Pick, extra: DescribeExtra = {}, ): ReactNode { const { labels } = context; const help = fieldHelp(def, context.locale, context.defaultLocale); const required = def.type !== "boolean" && def.requiredToPublish === true; const words = [help, extra.hint, extra.note].filter(Boolean).join(" "); const fallback = extra.fallback && !HAS_PLACEHOLDER.has(def.type) ? labels.originalValue(extra.fallback) : ""; if (!required && !words && !extra.inherited && !fallback) return undefined; return ( {required && ( {labels.neededToPublish} )} {words && {words}} {fallback && {fallback}} {extra.inherited && ( {labels.fromOriginal} · {labels.openOriginal} )} ); } /** * One typed value's Kumo control (RFC-0041 §7, RFC-0045 §5): text (`Input`, `InputArea` when * multiline), rich text (the host's markdown editor, else a markdown `InputArea`), number, boolean * (`Switch`), date and date-time (`DateTimeField`), URL, image (the host's media picker), select * (`Select`, a `Checkbox` group when multiple) and reference (the host's picker, else the stored * ids read-only). `EntryFieldsForm` uses it for fields, `RepeaterField` items for sub-fields. */ export function FieldControl(props: FieldControlProps) { const Control = props.asStored ? StoredValueControl : CONTROLS[props.def.type]; return ; }