@bettercms-ai/kit 3.1.14 → 3.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -289,6 +289,14 @@ function MultiSelectInput({ field, value, onChange, readOnly, id }) {
289
289
  else if (!full) onChange([...list, o]);
290
290
  };
291
291
  const label = (val) => options.find((o) => o.value === val)?.label ?? val;
292
+ const onBackspace = (e) => {
293
+ if (e.key !== "Backspace") return;
294
+ e.stopPropagation();
295
+ if (readOnly || !list.length) return;
296
+ e.preventDefault();
297
+ onChange(list.slice(0, -1));
298
+ if (e.target.matches("[aria-label^='Remove ']") && id) document.getElementById(id)?.focus();
299
+ };
292
300
  const withLimit = (body) => full && !readOnly ? /* @__PURE__ */ jsxs("div", {
293
301
  className: "flex flex-col gap-1",
294
302
  children: [body, /* @__PURE__ */ jsx(LimitLine, { max })]
@@ -319,6 +327,7 @@ function MultiSelectInput({ field, value, onChange, readOnly, id }) {
319
327
  id: readOnly ? id : void 0,
320
328
  role: readOnly ? "group" : void 0,
321
329
  "aria-label": readOnly ? field.title : void 0,
330
+ onKeyDown: onBackspace,
322
331
  className: "flex min-h-8 flex-wrap items-center gap-1 rounded-kit-md border border-kit-line-strong bg-kit-field-bg p-1 transition-colors hover:border-kit-line-strong",
323
332
  children: [list.map((o) => /* @__PURE__ */ jsxs("span", {
324
333
  className: "inline-flex h-6 items-center gap-1 rounded-kit-md border border-kit-line bg-kit-control-bg pl-2 pr-1 text-kit-sm text-kit-fg shadow-kit-xs",
@@ -346,6 +355,7 @@ function MultiSelectInput({ field, value, onChange, readOnly, id }) {
346
355
  children: [/* @__PURE__ */ jsx("div", {
347
356
  role: "group",
348
357
  "aria-label": field.title,
358
+ onKeyDown: onBackspace,
349
359
  children: options.map((o) => {
350
360
  const on = list.includes(o.value);
351
361
  const blocked = !on && full;
@@ -1 +1 @@
1
- {"version":3,"file":"choice.js","names":[],"sources":["../../src/controls/choice.tsx"],"sourcesContent":["/**\n * CHOICE — boolean · select · multiselect · tags (V2 HEAD 9829bf1 kit/controls/choice.tsx, DESIGN 8.10–8.12).\n * Rule (production): few options → segmented, many → dropdown, many values → checkboxes, on/off → switch card.\n * D46: `layout: \"segmented\"` is a request, not a promise. With 4+ options, or labels that would wrap or truncate\n * in a 340px inspector (`fitsSegmented`), it renders the dropdown instead, so every schema follows the rule.\n *\n * Values are the ones production stores, untouched by any adapter (schema.ts plans them AS_IS): boolean, the option's\n * string, a string[] of option values, a string[] of tags. Tags are written the way the backend judges them\n * (tagsValueProblem: trimmed, case-insensitively unique, at most TAG_VALUE_MAX_LENGTH characters), and a tag the\n * control will not add says why under the box instead of vanishing.\n *\n * Option icons are all or none per list (the schema adapter's rule): a list draws icons only when every option names an\n * icon that can be drawn, so labels stay aligned and no option gets a stand-in glyph. The host's glyphs come first\n * (KitServices.IconGlyph, the BetterCMS set the site renders: every stored option icon is one of its names); with no\n * host renderer, the kit's own drawn icons.\n */\nimport * as React from \"react\";\nimport { IconCheck, IconPlus, IconX } from \"@tabler/icons-react\";\nimport { Checkbox, Segmented, Switch } from \"../ui/controls\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"../ui/overlay\";\nimport { Select } from \"../ui/select\";\nimport { fitsSegmented } from \"../ui/choice-switch\";\nimport { shortcutHintsOn } from \"../ui/shortcut-hint\";\nimport { cn } from \"../lib/cn\";\nimport { KitIcon, iconKey } from \"../lib/icons\";\nimport type { Option } from \"../schema/types\";\nimport { useKitEnv, useKitServices, type KitServices } from \"../context\";\nimport { dockIconOf } from \"../adapters/icons\";\nimport type { ControlProps } from \"../types\";\nimport { TAG_VALUE_MAX_LENGTH } from \"../adapters/prod-types\";\nimport { UnknownValueNote } from \"./unknown-value\";\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\nconst opts = (o?: Option[]) => o ?? [];\n\n/**\n * Icons for a list: every option's icon when all of them resolve, otherwise none (never a fallback glyph). `Glyph` is\n * the host's renderer (KitServices.IconGlyph): it draws every BetterCMS icon name (the option's kit name read back\n * through dockIconOf); without it, or when a name is not in that set, the kit's own drawn icons.\n */\nexport function optionIcons(options: Option[], className?: string, Glyph?: KitServices[\"IconGlyph\"]): (React.ReactNode | undefined)[] {\n if (options.length === 0) return [];\n const dock = options.map((o) => dockIconOf(o.icon));\n // a block box, as the kit's own <svg> is under preflight: an inline glyph would sit on a line box and grow the row\n if (Glyph && dock.every((n) => n !== undefined)) return dock.map((n) => <Glyph name={n!} className={cn(\"flex\", className)} />);\n const all = options.every((o) => iconKey(o.icon) !== undefined);\n return options.map((o) => (all ? <KitIcon name={o.icon} className={className} /> : undefined));\n}\n\n/** The limit sentence (DESIGN 8.12), shared by multiselect and tags. */\nfunction LimitLine({ max }: { max: number }) {\n return <span className=\"px-0.5 text-kit-xs text-kit-fg-3\">That's the limit of {max}. Remove one to add another.</span>;\n}\n\n/**\n * Roving focus for a radiogroup of buttons (WAI-ARIA radio group, as Segmented does): Tab lands on the selected option\n * (or the first), arrows move and select, Home / End jump.\n */\nfunction useRadioKeys(values: string[], current: string, onPick: (v: string) => void, readOnly?: boolean) {\n const focusable = values.includes(current) ? current : values[0];\n const onKeyDown = (e: React.KeyboardEvent, i: number) => {\n if (readOnly || !values.length) return;\n const n = values.length;\n const next =\n e.key === \"ArrowRight\" || e.key === \"ArrowDown\"\n ? (i + 1) % n\n : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\"\n ? (i - 1 + n) % n\n : e.key === \"Home\"\n ? 0\n : e.key === \"End\"\n ? n - 1\n : -1;\n if (next < 0) return;\n e.preventDefault();\n onPick(values[next]);\n const group = (e.currentTarget as HTMLElement).closest(\"[role=radiogroup]\");\n group?.querySelector<HTMLElement>(`[data-choice-value=\"${CSS.escape(values[next])}\"]`)?.focus();\n };\n return { tabIndexOf: (v: string) => (v === focusable ? 0 : -1), onKeyDown };\n}\n\n/**\n * Adds or removes one id of the control's own in aria-describedby, leaving the ids FieldShell wires (help, issue)\n * in place (as ScaleSlider does).\n */\nexport function useOwnDescription(ref: React.RefObject<HTMLElement | null>, ownId: string | null) {\n const last = React.useRef<string | null>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const ids = (el.getAttribute(\"aria-describedby\") ?? \"\").split(\" \").filter((t) => t && t !== last.current && t !== ownId);\n if (ownId) ids.push(ownId);\n if (ids.length) el.setAttribute(\"aria-describedby\", ids.join(\" \"));\n else el.removeAttribute(\"aria-describedby\");\n last.current = ownId;\n });\n}\n\n/** Boolean switch (used inside the switch card the shell draws). Commits immediately. */\nexport function BooleanControl({ field, value, onChange, readOnly, id }: ControlProps) {\n if (field.layout === \"checkbox\")\n return <Checkbox id={id} checked={Boolean(value)} disabled={readOnly} onCheckedChange={(c) => onChange(c === true)} aria-label={field.title} nativeButton render={<button type=\"button\" />} />;\n /* V2's switch is a native <button role=\"switch\"> (Radix); Base UI draws a <span> unless asked for the button */\n return <Switch id={id} checked={Boolean(value)} disabled={readOnly} onCheckedChange={(c) => onChange(c)} aria-label={field.title} nativeButton render={<button type=\"button\" />} />;\n}\n\n/**\n * A stored value none of the options names any more (renamed or removed) is kept and flagged under the control, with\n * change-to and remove (H4). @see UnknownValueNote\n */\nexport function SelectControl(props: ControlProps) {\n const options = opts(props.field.options);\n const v = str(props.value);\n if (v === \"\" || options.length === 0 || options.some((o) => o.value === v)) return <SelectInput {...props} />;\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <SelectInput {...props} />\n <UnknownValueNote\n items={[{ key: v, label: `“${v}”`, options: options.map((o) => ({ value: o.value, label: o.label })) }]}\n onRemap={(_, to) => props.onChange(to)}\n onRemove={() => props.onChange(null)}\n readOnly={props.readOnly}\n />\n </div>\n );\n}\n\nfunction SelectInput({ field, value, onChange, readOnly, id }: ControlProps) {\n const { variant } = useKitEnv();\n const { IconGlyph } = useKitServices();\n const options = opts(field.options);\n const v = str(value);\n const fits = fitsSegmented(options.map((o) => o.label));\n const layout = field.layout ?? (fits ? \"segmented\" : \"dropdown\");\n const pick = (n: string) => {\n if (!readOnly && n !== v) onChange(n);\n };\n const keys = useRadioKeys(\n options.map((o) => o.value),\n v,\n pick,\n readOnly,\n );\n\n if (layout === \"segmented\" && fits) {\n const icons = optionIcons(options, \"size-3.5\", IconGlyph);\n return (\n <Segmented\n aria-label={field.title}\n value={v}\n onChange={pick}\n items={options.map((o, i) => ({ value: o.value, label: o.label, icon: icons[i], disabled: readOnly }))}\n className=\"w-full [&>button]:min-w-0 [&>button]:flex-1\"\n />\n );\n }\n if (layout === \"radio\")\n return (\n <div role=\"radiogroup\" id={id} aria-label={field.title} className=\"flex flex-col gap-0.5\">\n {options.map((o, i) => (\n <button\n key={o.value}\n type=\"button\"\n role=\"radio\"\n data-choice-value={o.value}\n aria-checked={o.value === v}\n tabIndex={keys.tabIndexOf(o.value)}\n disabled={readOnly}\n onClick={() => pick(o.value)}\n onKeyDown={(e) => keys.onKeyDown(e, i)}\n className=\"flex items-start gap-2.5 rounded-kit-md px-1.5 py-1.5 text-left hover:bg-kit-hover\"\n >\n <span className={cn(\"mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border transition-colors\", o.value === v ? \"border-kit-accent\" : \"border-kit-line-strong\")}>\n {o.value === v ? <span className=\"size-2 rounded-full bg-kit-accent\" /> : null}\n </span>\n <span className=\"min-w-0\">\n <span className=\"block text-kit-sm text-kit-fg\">{o.label}</span>\n {o.description ? <span className=\"block text-kit-xs text-kit-fg-3\">{o.description}</span> : null}\n </span>\n </button>\n ))}\n </div>\n );\n if (layout === \"cards\" || layout === \"grid\") {\n /* V2 draws the icon itself as the button's first child (no wrapper), coloured by the selected state */\n const iconsOn = optionIcons(options, \"size-4 text-kit-fg\", IconGlyph);\n const iconsOff = optionIcons(options, \"size-4 text-kit-fg-3\", IconGlyph);\n return (\n <div role=\"radiogroup\" id={id} aria-label={field.title} className={cn(\"grid gap-1.5\", variant === \"document\" ? \"grid-cols-3\" : \"grid-cols-2\")}>\n {options.map((o, i) => {\n const on = o.value === v;\n return (\n <button\n key={o.value}\n type=\"button\"\n role=\"radio\"\n data-choice-value={o.value}\n aria-checked={on}\n tabIndex={keys.tabIndexOf(o.value)}\n disabled={readOnly}\n onClick={() => pick(o.value)}\n onKeyDown={(e) => keys.onKeyDown(e, i)}\n className={cn(\n \"relative flex flex-col items-start gap-1.5 rounded-kit-lg border p-2.5 text-left transition-[border-color,box-shadow] duration-150\",\n on ? \"border-[var(--kit-emphasis-line)] bg-kit-control-bg shadow-kit-xs\" : \"border-kit-line hover:border-kit-line-strong\",\n )}\n >\n {(on ? iconsOn : iconsOff)[i] ?? null}\n <span className=\"text-kit-sm font-medium text-kit-fg\">{o.label}</span>\n {o.description ? <span className=\"text-kit-xs leading-4 text-kit-fg-3\">{o.description}</span> : null}\n {on ? <IconCheck aria-hidden className=\"absolute right-2 top-2 size-3.5 text-kit-fg\" stroke={2} /> : null}\n </button>\n );\n })}\n </div>\n );\n }\n const icons = optionIcons(options, undefined, IconGlyph);\n return (\n <Select\n id={id}\n aria-label={field.title}\n size={variant === \"document\" ? \"lg\" : \"md\"}\n value={v || undefined}\n disabled={readOnly}\n onValueChange={pick}\n placeholder={field.placeholder ?? \"Select…\"}\n options={options.map((o, i) => ({ value: o.value, label: o.label, description: o.description, icon: icons[i] }))}\n />\n );\n}\n\n/** As `SelectControl`: each stored choice no option names any more is kept and flagged, with change-to and remove. */\nexport function MultiSelectControl(props: ControlProps) {\n const list = Array.isArray(props.value) ? (props.value as unknown[]).filter((x): x is string => typeof x === \"string\") : [];\n const options = opts(props.field.options);\n const unknown = options.length ? list.filter((x) => !options.some((o) => o.value === x)) : [];\n if (unknown.length === 0) return <MultiSelectInput {...props} />;\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <MultiSelectInput {...props} />\n <UnknownValueNote\n items={unknown.map((x) => ({ key: x, label: `“${x}”`, options: options.filter((o) => !list.includes(o.value)).map((o) => ({ value: o.value, label: o.label })) }))}\n onRemap={(from, to) => props.onChange(list.map((x) => (x === from ? to : x)))}\n onRemove={(from) => props.onChange(list.filter((x) => x !== from))}\n readOnly={props.readOnly}\n />\n </div>\n );\n}\n\nfunction MultiSelectInput({ field, value, onChange, readOnly, id }: ControlProps) {\n const list = Array.isArray(value) ? (value as unknown[]).filter((x): x is string => typeof x === \"string\") : [];\n const options = opts(field.options);\n const max = field.validation?.max;\n const full = max != null && list.length >= max;\n const toggle = (o: string) => {\n if (readOnly) return;\n if (list.includes(o)) onChange(list.filter((x) => x !== o));\n else if (!full) onChange([...list, o]);\n };\n const label = (val: string) => options.find((o) => o.value === val)?.label ?? val;\n /* V2 draws the control bare; the limit line (ours: say why the next pick is refused) wraps it only while it shows */\n const withLimit = (body: React.ReactElement) =>\n full && !readOnly ? (\n <div className=\"flex flex-col gap-1\">\n {body}\n <LimitLine max={max!} />\n </div>\n ) : (\n body\n );\n if (field.layout === \"checkbox\" || field.layout === \"list\")\n return withLimit(\n <>\n <div id={id} role=\"group\" aria-label={field.title} className=\"flex flex-col gap-0.5\">\n {options.map((o) => {\n const on = list.includes(o.value);\n return (\n <label key={o.value} className={cn(\"flex cursor-pointer items-center gap-2.5 rounded-kit-md px-1.5 py-1.5 hover:bg-kit-hover\", !on && full && \"cursor-not-allowed hover:bg-transparent\")}>\n <Checkbox checked={on} disabled={readOnly || (!on && full)} onCheckedChange={() => toggle(o.value)} nativeButton render={<button type=\"button\" />} />\n <span className=\"text-kit-sm text-kit-fg\">{o.label}</span>\n </label>\n );\n })}\n </div>\n </>,\n );\n return withLimit(\n <>\n <Popover>\n {/* read-only there is no trigger to carry the field id, so the chip row is the named group */}\n <div\n id={readOnly ? id : undefined}\n role={readOnly ? \"group\" : undefined}\n aria-label={readOnly ? field.title : undefined}\n className=\"flex min-h-8 flex-wrap items-center gap-1 rounded-kit-md border border-kit-line-strong bg-kit-field-bg p-1 transition-colors hover:border-kit-line-strong\"\n >\n {list.map((o) => (\n <span key={o} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md border border-kit-line bg-kit-control-bg pl-2 pr-1 text-kit-sm text-kit-fg shadow-kit-xs\">\n {label(o)}\n {readOnly ? null : (\n <button type=\"button\" aria-label={`Remove ${label(o)}`} onClick={() => toggle(o)} className=\"flex rounded-kit-md p-0.5 text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconX className=\"size-3\" stroke={1.5} />\n </button>\n )}\n </span>\n ))}\n {readOnly ? null : (\n <PopoverTrigger id={id} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md px-1.5 text-kit-sm text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconPlus aria-hidden className=\"size-3.5\" stroke={1.5} />\n {list.length ? \"Add\" : field.placeholder ?? \"Choose…\"}\n </PopoverTrigger>\n )}\n </div>\n <PopoverContent className=\"w-60 p-1\">\n <div role=\"group\" aria-label={field.title}>\n {options.map((o) => {\n const on = list.includes(o.value);\n const blocked = !on && full;\n return (\n <button\n key={o.value}\n type=\"button\"\n role=\"checkbox\"\n aria-checked={on}\n disabled={blocked}\n onClick={() => toggle(o.value)}\n className={cn(\"flex h-8 w-full items-center gap-2 rounded-kit-md px-2 text-left text-kit-sm hover:bg-kit-hover\", blocked && \"opacity-40 hover:bg-transparent\")}\n >\n <span className={cn(\"flex size-4 items-center justify-center rounded-kit-md border\", on ? \"border-kit-accent bg-kit-accent text-kit-accent-on\" : \"border-kit-line-strong\")}>\n {on ? <IconCheck aria-hidden className=\"size-3\" stroke={3} /> : null}\n </span>\n {o.label}\n </button>\n );\n })}\n </div>\n {full ? <div className=\"px-2 pb-1 pt-1.5\"><LimitLine max={max!} /></div> : null}\n </PopoverContent>\n </Popover>\n </>,\n );\n}\n\n/** Why a typed tag is not added, or null when it is (the backend's own checks, said in words). */\nexport function tagRefusal(tag: string, list: string[]): string | null {\n if (Array.from(tag).length > TAG_VALUE_MAX_LENGTH) return `A tag can be up to ${TAG_VALUE_MAX_LENGTH} characters.`;\n const folded = tag.toLowerCase();\n const twin = list.find((t) => t.trim().toLowerCase() === folded);\n if (twin !== undefined) return `\"${twin}\" is already a tag.`;\n return null;\n}\n\n/** Chip input. Says so at its limit, and says why a tag was not added, instead of silently dropping it. */\nexport function TagsControl({ field, value, onChange, readOnly, id, onBlur }: ControlProps) {\n const list = Array.isArray(value) ? (value as unknown[]).map((x) => str(x)) : [];\n const [draft, setDraft] = React.useState(\"\");\n const [refusal, setRefusal] = React.useState<string | null>(null);\n const reasonId = React.useId();\n const inputRef = React.useRef<HTMLInputElement>(null);\n useOwnDescription(inputRef, refusal ? reasonId : null);\n const max = field.validation?.max;\n const full = max != null && list.length >= max;\n const add = () => {\n const t = draft.trim().replace(/,$/, \"\").trim();\n if (!t || full) {\n setDraft(\"\");\n setRefusal(null);\n return;\n }\n const why = tagRefusal(t, list);\n if (why) {\n // keep the text so it can be fixed; the reason reads under the box\n setRefusal(why);\n return;\n }\n onChange([...list, t]);\n setDraft(\"\");\n setRefusal(null);\n };\n return (\n <div className=\"flex flex-col gap-1\">\n <div className=\"flex min-h-8 flex-wrap items-center gap-1 rounded-kit-md border border-kit-line-strong bg-kit-field-bg p-1 transition-colors focus-within:border-kit-line-strong focus-within:bg-kit-field-bg hover:border-kit-line-strong\">\n {list.map((t, i) => (\n <span key={`${t}-${i}`} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md bg-kit-selected pl-2 pr-1 text-kit-sm text-kit-fg\">\n {t}\n {readOnly ? null : (\n <button type=\"button\" aria-label={`Remove ${t}`} onClick={() => onChange(list.filter((_, j) => j !== i))} className=\"flex rounded-kit-md p-0.5 text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconX className=\"size-3\" stroke={1.5} />\n </button>\n )}\n </span>\n ))}\n {readOnly ? null : (\n <input\n ref={inputRef}\n id={id}\n value={draft}\n disabled={full}\n onChange={(e) => {\n setDraft(e.target.value);\n if (refusal) setRefusal(null);\n }}\n onBlur={() => {\n add();\n onBlur?.();\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \",\") {\n e.preventDefault();\n add();\n } else if (e.key === \"Backspace\" && !draft && list.length) onChange(list.slice(0, -1));\n }}\n placeholder={full ? \"\" : list.length ? \"Add…\" : field.placeholder ?? (shortcutHintsOn() ? \"Type and press Enter\" : \"Add…\")}\n className=\"h-6 min-w-20 flex-1 bg-transparent px-1.5 text-kit-sm text-kit-fg outline-none placeholder:text-kit-fg-3\"\n />\n )}\n </div>\n {refusal && !readOnly ? (\n <span id={reasonId} role=\"status\" aria-live=\"polite\" className=\"px-0.5 text-kit-xs text-kit-fg-3\">\n {refusal}\n </span>\n ) : null}\n {full && !readOnly ? <LimitLine max={max!} /> : null}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAM,OAAO,MAAgB,OAAO,MAAM,WAAW,IAAI,KAAK,OAAO,KAAK,OAAO,CAAC;AAClF,IAAM,QAAQ,MAAiB,KAAK,CAAC;;;;;;AAOrC,SAAgB,YAAY,SAAmB,WAAoB,OAAmE;CACpI,IAAI,QAAQ,WAAW,GAAG,OAAO,CAAC;CAClC,MAAM,OAAO,QAAQ,KAAK,MAAM,WAAW,EAAE,IAAI,CAAC;CAElD,IAAI,SAAS,KAAK,OAAO,MAAM,MAAM,KAAA,CAAS,GAAG,OAAO,KAAK,KAAK,MAAM,oBAAC,OAAD;EAAO,MAAM;EAAI,WAAW,GAAG,QAAQ,SAAS;CAAI,CAAA,CAAC;CAC7H,MAAM,MAAM,QAAQ,OAAO,MAAM,QAAQ,EAAE,IAAI,MAAM,KAAA,CAAS;CAC9D,OAAO,QAAQ,KAAK,MAAO,MAAM,oBAAC,SAAD;EAAS,MAAM,EAAE;EAAiB;CAAY,CAAA,IAAI,KAAA,CAAU;AAC/F;;AAGA,SAAS,UAAU,EAAE,OAAwB;CAC3C,OAAO,qBAAC,QAAD;EAAM,WAAU;EAAhB,UAAA;GAAmD;GAAqB;GAAI;EAAkC;;AACvH;;;;;AAMA,SAAS,aAAa,QAAkB,SAAiB,QAA6B,UAAo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H,UAAA,oBAAC,OAAD;OAAO,WAAU;OAAS,QAAQ;MAAM,CAAA;KAClC,CAAA,CAEN;IAPK,GAAA,GAAG,EAAE,GAAG,GAOb,CACP,GACA,WAAW,OACV,oBAAC,SAAD;KACE,KAAK;KACD;KACJ,OAAO;KACP,UAAU;KACV,WAAW,MAAM;MACf,SAAS,EAAE,OAAO,KAAK;MACvB,IAAI,SAAS,WAAW,IAAI;KAC9B;KACA,cAAc;MACZ,IAAI;MACJ,SAAS;KACX;KACA,YAAY,MAAM;MAChB,IAAI,EAAE,QAAQ,WAAW,EAAE,QAAQ,KAAK;OACtC,EAAE,eAAe;OACjB,IAAI;MACN,OAAO,IAAI,EAAE,QAAQ,eAAe,CAAC,SAAS,KAAK,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC;KACvF;KACA,aAAa,OAAO,KAAK,KAAK,SAAS,SAAS,MAAM,gBAAgB,gBAAgB,IAAI,yBAAyB;KACnH,WAAU;IACX,CAAA,CAEA;;GACJ,WAAW,CAAC,WACX,oBAAC,QAAD;IAAM,IAAI;IAAU,MAAK;IAAS,aAAU;IAAS,WAAU;IAC5D,UAAA;GACG,CAAA,IACJ;GACH,QAAQ,CAAC,WAAW,oBAAC,WAAD,EAAgB,IAAO,CAAA,IAAI;EAC7C;;AAET"}
1
+ {"version":3,"file":"choice.js","names":[],"sources":["../../src/controls/choice.tsx"],"sourcesContent":["/**\n * CHOICE — boolean · select · multiselect · tags (V2 HEAD 9829bf1 kit/controls/choice.tsx, DESIGN 8.10–8.12).\n * Rule (production): few options → segmented, many → dropdown, many values → checkboxes, on/off → switch card.\n * D46: `layout: \"segmented\"` is a request, not a promise. With 4+ options, or labels that would wrap or truncate\n * in a 340px inspector (`fitsSegmented`), it renders the dropdown instead, so every schema follows the rule.\n *\n * Values are the ones production stores, untouched by any adapter (schema.ts plans them AS_IS): boolean, the option's\n * string, a string[] of option values, a string[] of tags. Tags are written the way the backend judges them\n * (tagsValueProblem: trimmed, case-insensitively unique, at most TAG_VALUE_MAX_LENGTH characters), and a tag the\n * control will not add says why under the box instead of vanishing.\n *\n * Option icons are all or none per list (the schema adapter's rule): a list draws icons only when every option names an\n * icon that can be drawn, so labels stay aligned and no option gets a stand-in glyph. The host's glyphs come first\n * (KitServices.IconGlyph, the BetterCMS set the site renders: every stored option icon is one of its names); with no\n * host renderer, the kit's own drawn icons.\n */\nimport * as React from \"react\";\nimport { IconCheck, IconPlus, IconX } from \"@tabler/icons-react\";\nimport { Checkbox, Segmented, Switch } from \"../ui/controls\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"../ui/overlay\";\nimport { Select } from \"../ui/select\";\nimport { fitsSegmented } from \"../ui/choice-switch\";\nimport { shortcutHintsOn } from \"../ui/shortcut-hint\";\nimport { cn } from \"../lib/cn\";\nimport { KitIcon, iconKey } from \"../lib/icons\";\nimport type { Option } from \"../schema/types\";\nimport { useKitEnv, useKitServices, type KitServices } from \"../context\";\nimport { dockIconOf } from \"../adapters/icons\";\nimport type { ControlProps } from \"../types\";\nimport { TAG_VALUE_MAX_LENGTH } from \"../adapters/prod-types\";\nimport { UnknownValueNote } from \"./unknown-value\";\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\nconst opts = (o?: Option[]) => o ?? [];\n\n/**\n * Icons for a list: every option's icon when all of them resolve, otherwise none (never a fallback glyph). `Glyph` is\n * the host's renderer (KitServices.IconGlyph): it draws every BetterCMS icon name (the option's kit name read back\n * through dockIconOf); without it, or when a name is not in that set, the kit's own drawn icons.\n */\nexport function optionIcons(options: Option[], className?: string, Glyph?: KitServices[\"IconGlyph\"]): (React.ReactNode | undefined)[] {\n if (options.length === 0) return [];\n const dock = options.map((o) => dockIconOf(o.icon));\n // a block box, as the kit's own <svg> is under preflight: an inline glyph would sit on a line box and grow the row\n if (Glyph && dock.every((n) => n !== undefined)) return dock.map((n) => <Glyph name={n!} className={cn(\"flex\", className)} />);\n const all = options.every((o) => iconKey(o.icon) !== undefined);\n return options.map((o) => (all ? <KitIcon name={o.icon} className={className} /> : undefined));\n}\n\n/** The limit sentence (DESIGN 8.12), shared by multiselect and tags. */\nfunction LimitLine({ max }: { max: number }) {\n return <span className=\"px-0.5 text-kit-xs text-kit-fg-3\">That's the limit of {max}. Remove one to add another.</span>;\n}\n\n/**\n * Roving focus for a radiogroup of buttons (WAI-ARIA radio group, as Segmented does): Tab lands on the selected option\n * (or the first), arrows move and select, Home / End jump.\n */\nfunction useRadioKeys(values: string[], current: string, onPick: (v: string) => void, readOnly?: boolean) {\n const focusable = values.includes(current) ? current : values[0];\n const onKeyDown = (e: React.KeyboardEvent, i: number) => {\n if (readOnly || !values.length) return;\n const n = values.length;\n const next =\n e.key === \"ArrowRight\" || e.key === \"ArrowDown\"\n ? (i + 1) % n\n : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\"\n ? (i - 1 + n) % n\n : e.key === \"Home\"\n ? 0\n : e.key === \"End\"\n ? n - 1\n : -1;\n if (next < 0) return;\n e.preventDefault();\n onPick(values[next]);\n const group = (e.currentTarget as HTMLElement).closest(\"[role=radiogroup]\");\n group?.querySelector<HTMLElement>(`[data-choice-value=\"${CSS.escape(values[next])}\"]`)?.focus();\n };\n return { tabIndexOf: (v: string) => (v === focusable ? 0 : -1), onKeyDown };\n}\n\n/**\n * Adds or removes one id of the control's own in aria-describedby, leaving the ids FieldShell wires (help, issue)\n * in place (as ScaleSlider does).\n */\nexport function useOwnDescription(ref: React.RefObject<HTMLElement | null>, ownId: string | null) {\n const last = React.useRef<string | null>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const ids = (el.getAttribute(\"aria-describedby\") ?? \"\").split(\" \").filter((t) => t && t !== last.current && t !== ownId);\n if (ownId) ids.push(ownId);\n if (ids.length) el.setAttribute(\"aria-describedby\", ids.join(\" \"));\n else el.removeAttribute(\"aria-describedby\");\n last.current = ownId;\n });\n}\n\n/** Boolean switch (used inside the switch card the shell draws). Commits immediately. */\nexport function BooleanControl({ field, value, onChange, readOnly, id }: ControlProps) {\n if (field.layout === \"checkbox\")\n return <Checkbox id={id} checked={Boolean(value)} disabled={readOnly} onCheckedChange={(c) => onChange(c === true)} aria-label={field.title} nativeButton render={<button type=\"button\" />} />;\n /* V2's switch is a native <button role=\"switch\"> (Radix); Base UI draws a <span> unless asked for the button */\n return <Switch id={id} checked={Boolean(value)} disabled={readOnly} onCheckedChange={(c) => onChange(c)} aria-label={field.title} nativeButton render={<button type=\"button\" />} />;\n}\n\n/**\n * A stored value none of the options names any more (renamed or removed) is kept and flagged under the control, with\n * change-to and remove (H4). @see UnknownValueNote\n */\nexport function SelectControl(props: ControlProps) {\n const options = opts(props.field.options);\n const v = str(props.value);\n if (v === \"\" || options.length === 0 || options.some((o) => o.value === v)) return <SelectInput {...props} />;\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <SelectInput {...props} />\n <UnknownValueNote\n items={[{ key: v, label: `“${v}”`, options: options.map((o) => ({ value: o.value, label: o.label })) }]}\n onRemap={(_, to) => props.onChange(to)}\n onRemove={() => props.onChange(null)}\n readOnly={props.readOnly}\n />\n </div>\n );\n}\n\nfunction SelectInput({ field, value, onChange, readOnly, id }: ControlProps) {\n const { variant } = useKitEnv();\n const { IconGlyph } = useKitServices();\n const options = opts(field.options);\n const v = str(value);\n const fits = fitsSegmented(options.map((o) => o.label));\n const layout = field.layout ?? (fits ? \"segmented\" : \"dropdown\");\n const pick = (n: string) => {\n if (!readOnly && n !== v) onChange(n);\n };\n const keys = useRadioKeys(\n options.map((o) => o.value),\n v,\n pick,\n readOnly,\n );\n\n if (layout === \"segmented\" && fits) {\n const icons = optionIcons(options, \"size-3.5\", IconGlyph);\n return (\n <Segmented\n aria-label={field.title}\n value={v}\n onChange={pick}\n items={options.map((o, i) => ({ value: o.value, label: o.label, icon: icons[i], disabled: readOnly }))}\n className=\"w-full [&>button]:min-w-0 [&>button]:flex-1\"\n />\n );\n }\n if (layout === \"radio\")\n return (\n <div role=\"radiogroup\" id={id} aria-label={field.title} className=\"flex flex-col gap-0.5\">\n {options.map((o, i) => (\n <button\n key={o.value}\n type=\"button\"\n role=\"radio\"\n data-choice-value={o.value}\n aria-checked={o.value === v}\n tabIndex={keys.tabIndexOf(o.value)}\n disabled={readOnly}\n onClick={() => pick(o.value)}\n onKeyDown={(e) => keys.onKeyDown(e, i)}\n className=\"flex items-start gap-2.5 rounded-kit-md px-1.5 py-1.5 text-left hover:bg-kit-hover\"\n >\n <span className={cn(\"mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border transition-colors\", o.value === v ? \"border-kit-accent\" : \"border-kit-line-strong\")}>\n {o.value === v ? <span className=\"size-2 rounded-full bg-kit-accent\" /> : null}\n </span>\n <span className=\"min-w-0\">\n <span className=\"block text-kit-sm text-kit-fg\">{o.label}</span>\n {o.description ? <span className=\"block text-kit-xs text-kit-fg-3\">{o.description}</span> : null}\n </span>\n </button>\n ))}\n </div>\n );\n if (layout === \"cards\" || layout === \"grid\") {\n /* V2 draws the icon itself as the button's first child (no wrapper), coloured by the selected state */\n const iconsOn = optionIcons(options, \"size-4 text-kit-fg\", IconGlyph);\n const iconsOff = optionIcons(options, \"size-4 text-kit-fg-3\", IconGlyph);\n return (\n <div role=\"radiogroup\" id={id} aria-label={field.title} className={cn(\"grid gap-1.5\", variant === \"document\" ? \"grid-cols-3\" : \"grid-cols-2\")}>\n {options.map((o, i) => {\n const on = o.value === v;\n return (\n <button\n key={o.value}\n type=\"button\"\n role=\"radio\"\n data-choice-value={o.value}\n aria-checked={on}\n tabIndex={keys.tabIndexOf(o.value)}\n disabled={readOnly}\n onClick={() => pick(o.value)}\n onKeyDown={(e) => keys.onKeyDown(e, i)}\n className={cn(\n \"relative flex flex-col items-start gap-1.5 rounded-kit-lg border p-2.5 text-left transition-[border-color,box-shadow] duration-150\",\n on ? \"border-[var(--kit-emphasis-line)] bg-kit-control-bg shadow-kit-xs\" : \"border-kit-line hover:border-kit-line-strong\",\n )}\n >\n {(on ? iconsOn : iconsOff)[i] ?? null}\n <span className=\"text-kit-sm font-medium text-kit-fg\">{o.label}</span>\n {o.description ? <span className=\"text-kit-xs leading-4 text-kit-fg-3\">{o.description}</span> : null}\n {on ? <IconCheck aria-hidden className=\"absolute right-2 top-2 size-3.5 text-kit-fg\" stroke={2} /> : null}\n </button>\n );\n })}\n </div>\n );\n }\n const icons = optionIcons(options, undefined, IconGlyph);\n return (\n <Select\n id={id}\n aria-label={field.title}\n size={variant === \"document\" ? \"lg\" : \"md\"}\n value={v || undefined}\n disabled={readOnly}\n onValueChange={pick}\n placeholder={field.placeholder ?? \"Select…\"}\n options={options.map((o, i) => ({ value: o.value, label: o.label, description: o.description, icon: icons[i] }))}\n />\n );\n}\n\n/** As `SelectControl`: each stored choice no option names any more is kept and flagged, with change-to and remove. */\nexport function MultiSelectControl(props: ControlProps) {\n const list = Array.isArray(props.value) ? (props.value as unknown[]).filter((x): x is string => typeof x === \"string\") : [];\n const options = opts(props.field.options);\n const unknown = options.length ? list.filter((x) => !options.some((o) => o.value === x)) : [];\n if (unknown.length === 0) return <MultiSelectInput {...props} />;\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <MultiSelectInput {...props} />\n <UnknownValueNote\n items={unknown.map((x) => ({ key: x, label: `“${x}”`, options: options.filter((o) => !list.includes(o.value)).map((o) => ({ value: o.value, label: o.label })) }))}\n onRemap={(from, to) => props.onChange(list.map((x) => (x === from ? to : x)))}\n onRemove={(from) => props.onChange(list.filter((x) => x !== from))}\n readOnly={props.readOnly}\n />\n </div>\n );\n}\n\nfunction MultiSelectInput({ field, value, onChange, readOnly, id }: ControlProps) {\n const list = Array.isArray(value) ? (value as unknown[]).filter((x): x is string => typeof x === \"string\") : [];\n const options = opts(field.options);\n const max = field.validation?.max;\n const full = max != null && list.length >= max;\n const toggle = (o: string) => {\n if (readOnly) return;\n if (list.includes(o)) onChange(list.filter((x) => x !== o));\n else if (!full) onChange([...list, o]);\n };\n const label = (val: string) => options.find((o) => o.value === val)?.label ?? val;\n /* DK-010: Backspace on the chip row, the Add button or the open list removes the last chip (as the tags control\n does) and never reaches the host, whose own Backspace deletes the selected section. Focus goes to the Add button,\n since the chip that had it may be the one removed. */\n const onBackspace = (e: React.KeyboardEvent) => {\n if (e.key !== \"Backspace\") return;\n e.stopPropagation();\n if (readOnly || !list.length) return;\n e.preventDefault();\n onChange(list.slice(0, -1));\n if ((e.target as HTMLElement).matches(\"[aria-label^='Remove ']\") && id) document.getElementById(id)?.focus();\n };\n /* V2 draws the control bare; the limit line (ours: say why the next pick is refused) wraps it only while it shows */\n const withLimit = (body: React.ReactElement) =>\n full && !readOnly ? (\n <div className=\"flex flex-col gap-1\">\n {body}\n <LimitLine max={max!} />\n </div>\n ) : (\n body\n );\n if (field.layout === \"checkbox\" || field.layout === \"list\")\n return withLimit(\n <>\n <div id={id} role=\"group\" aria-label={field.title} className=\"flex flex-col gap-0.5\">\n {options.map((o) => {\n const on = list.includes(o.value);\n return (\n <label key={o.value} className={cn(\"flex cursor-pointer items-center gap-2.5 rounded-kit-md px-1.5 py-1.5 hover:bg-kit-hover\", !on && full && \"cursor-not-allowed hover:bg-transparent\")}>\n <Checkbox checked={on} disabled={readOnly || (!on && full)} onCheckedChange={() => toggle(o.value)} nativeButton render={<button type=\"button\" />} />\n <span className=\"text-kit-sm text-kit-fg\">{o.label}</span>\n </label>\n );\n })}\n </div>\n </>,\n );\n return withLimit(\n <>\n <Popover>\n {/* read-only there is no trigger to carry the field id, so the chip row is the named group */}\n <div\n id={readOnly ? id : undefined}\n role={readOnly ? \"group\" : undefined}\n aria-label={readOnly ? field.title : undefined}\n onKeyDown={onBackspace}\n className=\"flex min-h-8 flex-wrap items-center gap-1 rounded-kit-md border border-kit-line-strong bg-kit-field-bg p-1 transition-colors hover:border-kit-line-strong\"\n >\n {list.map((o) => (\n <span key={o} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md border border-kit-line bg-kit-control-bg pl-2 pr-1 text-kit-sm text-kit-fg shadow-kit-xs\">\n {label(o)}\n {readOnly ? null : (\n <button type=\"button\" aria-label={`Remove ${label(o)}`} onClick={() => toggle(o)} className=\"flex rounded-kit-md p-0.5 text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconX className=\"size-3\" stroke={1.5} />\n </button>\n )}\n </span>\n ))}\n {readOnly ? null : (\n <PopoverTrigger id={id} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md px-1.5 text-kit-sm text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconPlus aria-hidden className=\"size-3.5\" stroke={1.5} />\n {list.length ? \"Add\" : field.placeholder ?? \"Choose…\"}\n </PopoverTrigger>\n )}\n </div>\n <PopoverContent className=\"w-60 p-1\">\n <div role=\"group\" aria-label={field.title} onKeyDown={onBackspace}>\n {options.map((o) => {\n const on = list.includes(o.value);\n const blocked = !on && full;\n return (\n <button\n key={o.value}\n type=\"button\"\n role=\"checkbox\"\n aria-checked={on}\n disabled={blocked}\n onClick={() => toggle(o.value)}\n className={cn(\"flex h-8 w-full items-center gap-2 rounded-kit-md px-2 text-left text-kit-sm hover:bg-kit-hover\", blocked && \"opacity-40 hover:bg-transparent\")}\n >\n <span className={cn(\"flex size-4 items-center justify-center rounded-kit-md border\", on ? \"border-kit-accent bg-kit-accent text-kit-accent-on\" : \"border-kit-line-strong\")}>\n {on ? <IconCheck aria-hidden className=\"size-3\" stroke={3} /> : null}\n </span>\n {o.label}\n </button>\n );\n })}\n </div>\n {full ? <div className=\"px-2 pb-1 pt-1.5\"><LimitLine max={max!} /></div> : null}\n </PopoverContent>\n </Popover>\n </>,\n );\n}\n\n/** Why a typed tag is not added, or null when it is (the backend's own checks, said in words). */\nexport function tagRefusal(tag: string, list: string[]): string | null {\n if (Array.from(tag).length > TAG_VALUE_MAX_LENGTH) return `A tag can be up to ${TAG_VALUE_MAX_LENGTH} characters.`;\n const folded = tag.toLowerCase();\n const twin = list.find((t) => t.trim().toLowerCase() === folded);\n if (twin !== undefined) return `\"${twin}\" is already a tag.`;\n return null;\n}\n\n/** Chip input. Says so at its limit, and says why a tag was not added, instead of silently dropping it. */\nexport function TagsControl({ field, value, onChange, readOnly, id, onBlur }: ControlProps) {\n const list = Array.isArray(value) ? (value as unknown[]).map((x) => str(x)) : [];\n const [draft, setDraft] = React.useState(\"\");\n const [refusal, setRefusal] = React.useState<string | null>(null);\n const reasonId = React.useId();\n const inputRef = React.useRef<HTMLInputElement>(null);\n useOwnDescription(inputRef, refusal ? reasonId : null);\n const max = field.validation?.max;\n const full = max != null && list.length >= max;\n const add = () => {\n const t = draft.trim().replace(/,$/, \"\").trim();\n if (!t || full) {\n setDraft(\"\");\n setRefusal(null);\n return;\n }\n const why = tagRefusal(t, list);\n if (why) {\n // keep the text so it can be fixed; the reason reads under the box\n setRefusal(why);\n return;\n }\n onChange([...list, t]);\n setDraft(\"\");\n setRefusal(null);\n };\n return (\n <div className=\"flex flex-col gap-1\">\n <div className=\"flex min-h-8 flex-wrap items-center gap-1 rounded-kit-md border border-kit-line-strong bg-kit-field-bg p-1 transition-colors focus-within:border-kit-line-strong focus-within:bg-kit-field-bg hover:border-kit-line-strong\">\n {list.map((t, i) => (\n <span key={`${t}-${i}`} className=\"inline-flex h-6 items-center gap-1 rounded-kit-md bg-kit-selected pl-2 pr-1 text-kit-sm text-kit-fg\">\n {t}\n {readOnly ? null : (\n <button type=\"button\" aria-label={`Remove ${t}`} onClick={() => onChange(list.filter((_, j) => j !== i))} className=\"flex rounded-kit-md p-0.5 text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconX className=\"size-3\" stroke={1.5} />\n </button>\n )}\n </span>\n ))}\n {readOnly ? null : (\n <input\n ref={inputRef}\n id={id}\n value={draft}\n disabled={full}\n onChange={(e) => {\n setDraft(e.target.value);\n if (refusal) setRefusal(null);\n }}\n onBlur={() => {\n add();\n onBlur?.();\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \",\") {\n e.preventDefault();\n add();\n } else if (e.key === \"Backspace\" && !draft && list.length) onChange(list.slice(0, -1));\n }}\n placeholder={full ? \"\" : list.length ? \"Add…\" : field.placeholder ?? (shortcutHintsOn() ? \"Type and press Enter\" : \"Add…\")}\n className=\"h-6 min-w-20 flex-1 bg-transparent px-1.5 text-kit-sm text-kit-fg outline-none placeholder:text-kit-fg-3\"\n />\n )}\n </div>\n {refusal && !readOnly ? (\n <span id={reasonId} role=\"status\" aria-live=\"polite\" className=\"px-0.5 text-kit-xs text-kit-fg-3\">\n {refusal}\n </span>\n ) : null}\n {full && !readOnly ? <LimitLine max={max!} /> : null}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAM,OAAO,MAAgB,OAAO,MAAM,WAAW,IAAI,KAAK,OAAO,KAAK,OAAO,CAAC;AAClF,IAAM,QAAQ,MAAiB,KAAK,CAAC;;;;;;AAOrC,SAAgB,YAAY,SAAmB,WAAoB,OAAmE;CACpI,IAAI,QAAQ,WAAW,GAAG,OAAO,CAAC;CAClC,MAAM,OAAO,QAAQ,KAAK,MAAM,WAAW,EAAE,IAAI,CAAC;CAElD,IAAI,SAAS,KAAK,OAAO,MAAM,MAAM,KAAA,CAAS,GAAG,OAAO,KAAK,KAAK,MAAM,oBAAC,OAAD;EAAO,MAAM;EAAI,WAAW,GAAG,QAAQ,SAAS;CAAI,CAAA,CAAC;CAC7H,MAAM,MAAM,QAAQ,OAAO,MAAM,QAAQ,EAAE,IAAI,MAAM,KAAA,CAAS;CAC9D,OAAO,QAAQ,KAAK,MAAO,MAAM,oBAAC,SAAD;EAAS,MAAM,EAAE;EAAiB;CAAY,CAAA,IAAI,KAAA,CAAU;AAC/F;;AAGA,SAAS,UAAU,EAAE,OAAwB;CAC3C,OAAO,qBAAC,QAAD;EAAM,WAAU;EAAhB,UAAA;GAAmD;GAAqB;GAAI;EAAkC;;AACvH;;;;;AAMA,SAAS,aAAa,QAAkB,SAAiB,QAA6B,UAAoB;CACxG,MAAM,YAAY,O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AAK,WAAU;EAAf,UAAA;GACE,qBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACG,KAAK,KAAK,GAAG,MACZ,qBAAC,QAAD;KAAwB,WAAU;KAAlC,UAAA,CACG,GACA,WAAW,OACV,oBAAC,UAAD;MAAQ,MAAK;MAAS,cAAY,UAAU;MAAK,eAAe,SAAS,KAAK,QAAQ,GAAG,MAAM,MAAM,CAAC,CAAC;MAAG,WAAU;MAClH,UAAA,oBAAC,OAAD;OAAO,WAAU;OAAS,QAAQ;MAAM,CAAA;KAClC,CAAA,CAEN;IAPK,GAAA,GAAG,EAAE,GAAG,GAOb,CACP,GACA,WAAW,OACV,oBAAC,SAAD;KACE,KAAK;KACD;KACJ,OAAO;KACP,UAAU;KACV,WAAW,MAAM;MACf,SAAS,EAAE,OAAO,KAAK;MACvB,IAAI,SAAS,WAAW,IAAI;KAC9B;KACA,cAAc;MACZ,IAAI;MACJ,SAAS;KACX;KACA,YAAY,MAAM;MAChB,IAAI,EAAE,QAAQ,WAAW,EAAE,QAAQ,KAAK;OACtC,EAAE,eAAe;OACjB,IAAI;MACN,OAAO,IAAI,EAAE,QAAQ,eAAe,CAAC,SAAS,KAAK,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC;KACvF;KACA,aAAa,OAAO,KAAK,KAAK,SAAS,SAAS,MAAM,gBAAgB,gBAAgB,IAAI,yBAAyB;KACnH,WAAU;IACX,CAAA,CAEA;;GACJ,WAAW,CAAC,WACX,oBAAC,QAAD;IAAM,IAAI;IAAU,MAAK;IAAS,aAAU;IAAS,WAAU;IAC5D,UAAA;GACG,CAAA,IACJ;GACH,QAAQ,CAAC,WAAW,oBAAC,WAAD,EAAgB,IAAO,CAAA,IAAI;EAC7C;;AAET"}
@@ -42,9 +42,33 @@ function inline(node, inCode = false) {
42
42
  default: return kids();
43
43
  }
44
44
  }
45
- function list(el) {
46
- if (el.querySelector("ul ul, ul ol, ol ol, ol ul, li > p + p")) return null;
47
- return Array.from(el.children).filter((li) => li.tagName === "LI").map((li, i) => (el.tagName === "OL" ? `${i + 1}. ` : "- ") + inline(li).trim().replace(/ {2}\n/g, " ")).join("\n");
45
+ var isList = (n) => n.nodeType === 1 && /^(UL|OL)$/.test(n.tagName);
46
+ /**
47
+ * A list as Markdown lines. A list nested in an item is written under it, indented by the width of the item's marker
48
+ * (RT-035), so the level survives the trip. Null (kept as markup) for what Markdown cannot say: an item of several
49
+ * paragraphs, or text after an item's nested list.
50
+ */
51
+ function list(el, pad = "") {
52
+ if (el.querySelector("li > p + p")) return null;
53
+ const lines = [];
54
+ let n = 0;
55
+ for (const li of Array.from(el.children)) {
56
+ if (li.tagName !== "LI") continue;
57
+ const marker = el.tagName === "OL" ? `${++n}. ` : "- ";
58
+ const kids = Array.from(li.childNodes);
59
+ const at = kids.findIndex(isList);
60
+ const own = at < 0 ? kids : kids.slice(0, at);
61
+ const rest = at < 0 ? [] : kids.slice(at);
62
+ if (rest.some((k) => !isList(k) && (k.textContent ?? "").trim())) return null;
63
+ lines.push(pad + marker + own.map((k) => inline(k)).join("").trim().replace(/ {2}\n/g, " "));
64
+ for (const k of rest) {
65
+ if (!isList(k)) continue;
66
+ const inner = list(k, pad + " ".repeat(marker.length));
67
+ if (inner === null) return null;
68
+ lines.push(inner);
69
+ }
70
+ }
71
+ return lines.join("\n");
48
72
  }
49
73
  function htmlToMarkdown(html) {
50
74
  const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
@@ -109,6 +133,26 @@ var RE = {
109
133
  ul: /^\s*[-*+]\s+(.*)$/,
110
134
  ol: /^\s*\d+[.)]\s+(.*)$/
111
135
  };
136
+ /**
137
+ * A run of list lines as lists. A line indented two or more spaces past an item is that item's nested list (RT-035),
138
+ * and a shallower line closes it; a line of the other kind at the same level starts a new list, as it always did.
139
+ */
140
+ function listHtml(items) {
141
+ let html = "";
142
+ for (let i = 0; i < items.length;) {
143
+ const { ordered, indent } = items[i];
144
+ const tag = ordered ? "ol" : "ul";
145
+ html += `<${tag}>`;
146
+ while (i < items.length && items[i].ordered === ordered) {
147
+ const item = items[i++];
148
+ const kids = [];
149
+ while (i < items.length && items[i].indent >= indent + 2) kids.push(items[i++]);
150
+ html += `<li>${inlineMd(item.text)}${kids.length ? listHtml(kids) : ""}</li>`;
151
+ }
152
+ html += `</${tag}>`;
153
+ }
154
+ return html;
155
+ }
112
156
  var startsBlock = (l) => RE.fence.test(l) || RE.heading.test(l) || RE.hr.test(l) || RE.quote.test(l) || RE.ul.test(l) || RE.ol.test(l) || RAW_BLOCK.test(l.trim());
113
157
  /** Throws on Markdown it cannot read (e.g. an unclosed code fence). */
114
158
  function markdownToHtml(md) {
@@ -160,11 +204,17 @@ function markdownToHtml(md) {
160
204
  continue;
161
205
  }
162
206
  if (RE.ul.test(line) || RE.ol.test(line)) {
163
- const ordered = !RE.ul.test(line);
164
- const re = ordered ? RE.ol : RE.ul;
165
207
  const items = [];
166
- while (i < lines.length && re.test(lines[i])) items.push(`<li>${inlineMd(lines[i++].match(re)[1])}</li>`);
167
- out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`);
208
+ while (i < lines.length && (RE.ul.test(lines[i]) || RE.ol.test(lines[i]))) {
209
+ const l = lines[i++];
210
+ const ordered = !RE.ul.test(l);
211
+ items.push({
212
+ indent: l.match(/^\s*/)[0].replace(/\t/g, " ").length,
213
+ ordered,
214
+ text: l.match(ordered ? RE.ol : RE.ul)[1]
215
+ });
216
+ }
217
+ out.push(listHtml(items));
168
218
  continue;
169
219
  }
170
220
  const para = [];
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.js","names":[],"sources":["../../../src/controls/rich-text/markdown.ts"],"sourcesContent":["/**\n * RICH TEXT · a small HTML ⇄ Markdown converter for the field's Markdown mode and for pasting (V2 HEAD\n * controls/rich-text/markdown.ts). Covers headings, bold/italic/strike/underline, inline code, links, images, lists,\n * quotes, code blocks, rules and paragraphs. Anything else is kept as one line of raw HTML, which the reverse direction\n * passes through untouched (and the field's own rules then decide whether it may stay).\n */\nimport { esc, escAttr, sanitize } from \"./dom\";\n\n/* ── HTML → Markdown ───────────────────────────────────────────────── */\nconst escText = (s: string) => s.replace(/([\\\\`*[\\]~])/g, \"\\\\$1\");\n\nfunction inline(node: Node, inCode = false): string {\n if (node.nodeType === 3) {\n const t = (node.textContent ?? \"\").replace(/ /g, \" \");\n return inCode ? t : escText(t.replace(/\\s+/g, \" \"));\n }\n if (node.nodeType !== 1) return \"\";\n const el = node as HTMLElement;\n const kids = () => Array.from(el.childNodes).map((c) => inline(c, inCode)).join(\"\");\n const wrap = (mark: string) => {\n const inner = kids();\n if (!inner.trim()) return inner;\n const lead = inner.match(/^\\s*/)![0];\n const trail = inner.match(/\\s*$/)![0];\n return `${lead}${mark}${inner.trim()}${mark}${trail}`;\n };\n switch (el.tagName) {\n case \"STRONG\":\n case \"B\":\n return wrap(\"**\");\n case \"EM\":\n case \"I\":\n return wrap(\"_\");\n case \"S\":\n case \"STRIKE\":\n case \"DEL\":\n return wrap(\"~~\");\n case \"U\":\n return `<u>${kids()}</u>`;\n // footnote markers are written elsewhere; a plain x² / x₂ stays inline HTML, which Markdown allows\n case \"SUP\":\n return el.matches(\"[data-footnote]\") || el.querySelector(\":scope > a[href*='-fn-']\") ? kids() : `<sup>${kids()}</sup>`;\n case \"SUB\":\n return `<sub>${kids()}</sub>`;\n case \"CODE\":\n return \"`\" + (el.textContent ?? \"\").replace(/`/g, \"\") + \"`\";\n case \"BR\":\n return \" \\n\";\n case \"IMG\":\n return `![${el.getAttribute(\"alt\") ?? \"\"}](${el.getAttribute(\"src\") ?? \"\"})`;\n case \"A\":\n // a link that carries more than its address (opens in a new tab) keeps its markup, so Markdown mode drops nothing\n if (el.hasAttribute(\"target\")) return el.outerHTML;\n return `[${kids()}](${el.getAttribute(\"href\") ?? \"\"})`;\n default:\n return kids();\n }\n}\n\nfunction list(el: HTMLElement): string | null {\n if (el.querySelector(\"ul ul, ul ol, ol ol, ol ul, li > p + p\")) return null;\n return Array.from(el.children)\n .filter((li) => li.tagName === \"LI\")\n .map((li, i) => (el.tagName === \"OL\" ? `${i + 1}. ` : \"- \") + inline(li).trim().replace(/ {2}\\n/g, \" \"))\n .join(\"\\n\");\n}\n\nexport function htmlToMarkdown(html: string): string {\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n const out: string[] = [];\n for (const node of Array.from(doc.body.childNodes)) {\n if (node.nodeType === 3) {\n const t = inline(node).trim();\n if (t) out.push(t);\n continue;\n }\n if (node.nodeType !== 1) continue;\n const el = node as HTMLElement;\n const tag = el.tagName;\n const raw = () => out.push(el.outerHTML.replace(/\\n+/g, \" \"));\n if (/^H[1-6]$/.test(tag)) out.push(`${\"#\".repeat(Number(tag[1]))} ${inline(el).trim()}`);\n else if (tag === \"P\") {\n const s = inline(el).trim().replace(/^([#>]|\\d+\\.|[-+] |-{3})/, \"\\\\$1\");\n if (s) out.push(s);\n } else if (tag === \"UL\" || tag === \"OL\") {\n const l = list(el);\n if (l === null) raw();\n else out.push(l);\n } else if (tag === \"BLOCKQUOTE\") {\n const paras = el.querySelector(\"p,div\") ? Array.from(el.children).map((c) => inline(c).trim()) : [inline(el).trim()];\n out.push(paras.filter(Boolean).map((p) => p.split(\"\\n\").map((l) => `> ${l}`).join(\"\\n\")).join(\"\\n>\\n\"));\n } else if (tag === \"PRE\") out.push(\"```\\n\" + (el.textContent ?? \"\").replace(/\\n$/, \"\") + \"\\n```\");\n else if (tag === \"HR\") out.push(\"---\");\n else if (tag === \"FIGURE\" && el.querySelector(\":scope > img\")) {\n const img = el.querySelector(\"img\")!;\n const cap = el.querySelector(\"figcaption\")?.textContent?.trim();\n out.push(`![${img.getAttribute(\"alt\") ?? \"\"}](${img.getAttribute(\"src\") ?? \"\"}${cap ? ` \"${cap.replace(/\"/g, \"'\")}\"` : \"\"})`);\n } else raw();\n }\n return out.join(\"\\n\\n\") + (out.length ? \"\\n\" : \"\");\n}\n\n/* ── Markdown → HTML ───────────────────────────────────────────────── */\nconst safeHref = (h: string) => (/^\\s*(javascript|vbscript|data:text)/i.test(h) ? \"#\" : h);\n\nexport function inlineMd(src: string): string {\n const slots: string[] = [];\n const hold = (html: string) => `\\u0000${slots.push(html) - 1}\\u0000`;\n let s = src.replace(/\\\\([\\\\`*_[\\]~#>+\\-.!])/g, (_, c: string) => hold(esc(c)));\n s = s.replace(/`([^`]+)`/g, (_, c: string) => hold(`<code>${esc(c)}</code>`));\n s = s.replace(/<a [^>]*>.*?<\\/a>/g, (m) => hold(m));\n s = esc(s);\n s = s.replace(/&lt;(\\/?)u&gt;/g, \"<$1u>\");\n s = s.replace(/!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g, (_, a: string, u: string) => hold(`<img src=\"${escAttr(safeHref(u))}\" alt=\"${escAttr(a)}\">`));\n s = s.replace(/\\[([^\\]]+)\\]\\(([^)\\s]+)\\)/g, (_, t: string, u: string) => `<a href=\"${escAttr(safeHref(u))}\">${t}</a>`);\n s = s.replace(/\\*\\*([^*]+?)\\*\\*/g, \"<strong>$1</strong>\");\n s = s.replace(/__([^_]+?)__/g, \"<strong>$1</strong>\");\n s = s.replace(/(^|[^\\w*])\\*([^*\\s][^*]*?)\\*(?!\\*)/g, \"$1<em>$2</em>\");\n s = s.replace(/(^|[^\\w])_([^_\\s][^_]*?)_(?!\\w)/g, \"$1<em>$2</em>\");\n s = s.replace(/~~([^~]+?)~~/g, \"<s>$1</s>\");\n s = s.replace(/ {2,}\\n/g, \"<br>\").replace(/\\n/g, \" \");\n return s.replace(/\\u0000(\\d+)\\u0000/g, (_, i: string) => slots[Number(i)]);\n}\n\nconst RAW_BLOCK = /^<\\/?(div|table|figure|details|ul|ol|p|h[1-6]|blockquote|pre|hr|section|aside)\\b/i;\nconst RE = {\n fence: /^\\s*```/,\n heading: /^(#{1,6})\\s+(.*?)\\s*#*\\s*$/,\n hr: /^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$/,\n image: /^!\\[([^\\]]*)\\]\\(([^)\\s]+)(?:\\s+\"([^\"]*)\")?\\)\\s*$/,\n quote: /^\\s*>/,\n ul: /^\\s*[-*+]\\s+(.*)$/,\n ol: /^\\s*\\d+[.)]\\s+(.*)$/,\n};\nconst startsBlock = (l: string) => RE.fence.test(l) || RE.heading.test(l) || RE.hr.test(l) || RE.quote.test(l) || RE.ul.test(l) || RE.ol.test(l) || RAW_BLOCK.test(l.trim());\n\n/** Throws on Markdown it cannot read (e.g. an unclosed code fence). */\nexport function markdownToHtml(md: string): string {\n const lines = md.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n if (!line.trim()) {\n i++;\n continue;\n }\n if (RE.fence.test(line)) {\n const code: string[] = [];\n i++;\n while (i < lines.length && !RE.fence.test(lines[i])) code.push(lines[i++]);\n if (i >= lines.length) throw new Error(\"Unclosed code block\");\n i++;\n out.push(`<pre>${esc(code.join(\"\\n\"))}</pre>`);\n continue;\n }\n if (RAW_BLOCK.test(line.trim())) {\n const raw: string[] = [];\n while (i < lines.length && lines[i].trim()) raw.push(lines[i++]);\n out.push(raw.join(\" \"));\n continue;\n }\n let m = line.match(RE.heading);\n if (m) {\n out.push(`<h${m[1].length}>${inlineMd(m[2])}</h${m[1].length}>`);\n i++;\n continue;\n }\n if (RE.hr.test(line)) {\n out.push(\"<hr>\");\n i++;\n continue;\n }\n m = line.match(RE.image);\n if (m) {\n // an image keeps no caption in production rich text: a title becomes the line under it, never dropped\n out.push(`<figure><img src=\"${escAttr(safeHref(m[2]))}\" alt=\"${escAttr(m[1])}\"></figure>${m[3] ? `<p>${esc(m[3])}</p>` : \"\"}`);\n i++;\n continue;\n }\n if (RE.quote.test(line)) {\n const q: string[] = [];\n while (i < lines.length && RE.quote.test(lines[i])) q.push(lines[i++].replace(/^\\s*> ?/, \"\"));\n out.push(`<blockquote>${q.join(\"\\n\").split(/\\n\\s*\\n/).map(inlineMd).join(\"<br><br>\")}</blockquote>`);\n continue;\n }\n if (RE.ul.test(line) || RE.ol.test(line)) {\n const ordered = !RE.ul.test(line);\n const re = ordered ? RE.ol : RE.ul;\n const items: string[] = [];\n while (i < lines.length && re.test(lines[i])) items.push(`<li>${inlineMd(lines[i++].match(re)![1])}</li>`);\n out.push(ordered ? `<ol>${items.join(\"\")}</ol>` : `<ul>${items.join(\"\")}</ul>`);\n continue;\n }\n const para: string[] = [];\n while (i < lines.length && lines[i].trim() && (para.length === 0 || !startsBlock(lines[i]))) para.push(lines[i++]);\n out.push(`<p>${inlineMd(para.join(\"\\n\"))}</p>`);\n }\n return sanitize(out.join(\"\"));\n}\n\n/** Does pasted plain text look like Markdown worth converting into blocks? */\nexport const looksLikeMarkdown = (t: string) => /\\n\\s*\\n/.test(t) || /^(#{1,6}\\s|[-*+]\\s|\\d+[.)]\\s|>\\s|```|---)/m.test(t) || /\\*\\*[^*]+\\*\\*|\\[[^\\]]+\\]\\([^)]+\\)/.test(t);\n"],"mappings":";;;;;;;;AASA,IAAM,WAAW,MAAc,EAAE,QAAQ,iBAAiB,MAAM;AAEhE,SAAS,OAAO,MAAY,SAAS,OAAe;CAClD,IAAI,KAAK,aAAa,GAAG;EACvB,MAAM,KAAK,KAAK,eAAe,GAAA,CAAI,QAAQ,MAAM,GAAG;EACpD,OAAO,SAAS,IAAI,QAAQ,EAAE,QAAQ,QAAQ,GAAG,CAAC;CACpD;CACA,IAAI,KAAK,aAAa,GAAG,OAAO;CAChC,MAAM,KAAK;CACX,MAAM,aAAa,MAAM,KAAK,GAAG,UAAU,CAAC,CAAC,KAAK,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,EAAE;CAClF,MAAM,QAAQ,SAAiB;EAC7B,MAAM,QAAQ,KAAK;EACnB,IAAI,CAAC,MAAM,KAAK,GAAG,OAAO;EAC1B,MAAM,OAAO,MAAM,MAAM,MAAM,CAAC,CAAE;EAClC,MAAM,QAAQ,MAAM,MAAM,MAAM,CAAC,CAAE;EACnC,OAA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,CAAC,MAAM,EAAE,CAAC,CAAE,EAAE,EAAE,MAAM;GACzG,IAAI,KAAK,UAAU,OAAO,MAAM,KAAK,EAAE,EAAE,SAAS,OAAO,MAAM,KAAK,EAAE,EAAE,MAAM;GAC9E;EACF;EACA,MAAM,OAAiB,CAAC;EACxB,OAAO,IAAI,MAAM,UAAU,MAAM,EAAE,CAAC,KAAK,MAAM,KAAK,WAAW,KAAK,CAAC,YAAY,MAAM,EAAE,IAAI,KAAK,KAAK,MAAM,IAAI;EACjH,IAAI,KAAK,MAAM,SAAS,KAAK,KAAK,IAAI,CAAC,EAAE,KAAK;CAChD;CACA,OAAO,SAAS,IAAI,KAAK,EAAE,CAAC;AAC9B;;AAGA,IAAa,qBAAqB,MAAc,UAAU,KAAK,CAAC,KAAK,6CAA6C,KAAK,CAAC,KAAK,oCAAoC,KAAK,CAAC"}
1
+ {"version":3,"file":"markdown.js","names":[],"sources":["../../../src/controls/rich-text/markdown.ts"],"sourcesContent":["/**\n * RICH TEXT · a small HTML ⇄ Markdown converter for the field's Markdown mode and for pasting (V2 HEAD\n * controls/rich-text/markdown.ts). Covers headings, bold/italic/strike/underline, inline code, links, images, lists,\n * quotes, code blocks, rules and paragraphs. Anything else is kept as one line of raw HTML, which the reverse direction\n * passes through untouched (and the field's own rules then decide whether it may stay).\n */\nimport { esc, escAttr, sanitize } from \"./dom\";\n\n/* ── HTML → Markdown ───────────────────────────────────────────────── */\nconst escText = (s: string) => s.replace(/([\\\\`*[\\]~])/g, \"\\\\$1\");\n\nfunction inline(node: Node, inCode = false): string {\n if (node.nodeType === 3) {\n const t = (node.textContent ?? \"\").replace(/ /g, \" \");\n return inCode ? t : escText(t.replace(/\\s+/g, \" \"));\n }\n if (node.nodeType !== 1) return \"\";\n const el = node as HTMLElement;\n const kids = () => Array.from(el.childNodes).map((c) => inline(c, inCode)).join(\"\");\n const wrap = (mark: string) => {\n const inner = kids();\n if (!inner.trim()) return inner;\n const lead = inner.match(/^\\s*/)![0];\n const trail = inner.match(/\\s*$/)![0];\n return `${lead}${mark}${inner.trim()}${mark}${trail}`;\n };\n switch (el.tagName) {\n case \"STRONG\":\n case \"B\":\n return wrap(\"**\");\n case \"EM\":\n case \"I\":\n return wrap(\"_\");\n case \"S\":\n case \"STRIKE\":\n case \"DEL\":\n return wrap(\"~~\");\n case \"U\":\n return `<u>${kids()}</u>`;\n // footnote markers are written elsewhere; a plain x² / x₂ stays inline HTML, which Markdown allows\n case \"SUP\":\n return el.matches(\"[data-footnote]\") || el.querySelector(\":scope > a[href*='-fn-']\") ? kids() : `<sup>${kids()}</sup>`;\n case \"SUB\":\n return `<sub>${kids()}</sub>`;\n case \"CODE\":\n return \"`\" + (el.textContent ?? \"\").replace(/`/g, \"\") + \"`\";\n case \"BR\":\n return \" \\n\";\n case \"IMG\":\n return `![${el.getAttribute(\"alt\") ?? \"\"}](${el.getAttribute(\"src\") ?? \"\"})`;\n case \"A\":\n // a link that carries more than its address (opens in a new tab) keeps its markup, so Markdown mode drops nothing\n if (el.hasAttribute(\"target\")) return el.outerHTML;\n return `[${kids()}](${el.getAttribute(\"href\") ?? \"\"})`;\n default:\n return kids();\n }\n}\n\nconst isList = (n: Node) => n.nodeType === 1 && /^(UL|OL)$/.test((n as HTMLElement).tagName);\n\n/**\n * A list as Markdown lines. A list nested in an item is written under it, indented by the width of the item's marker\n * (RT-035), so the level survives the trip. Null (kept as markup) for what Markdown cannot say: an item of several\n * paragraphs, or text after an item's nested list.\n */\nfunction list(el: HTMLElement, pad = \"\"): string | null {\n if (el.querySelector(\"li > p + p\")) return null;\n const lines: string[] = [];\n let n = 0;\n for (const li of Array.from(el.children)) {\n if (li.tagName !== \"LI\") continue;\n const marker = el.tagName === \"OL\" ? `${++n}. ` : \"- \";\n const kids = Array.from(li.childNodes);\n const at = kids.findIndex(isList);\n const own = at < 0 ? kids : kids.slice(0, at);\n const rest = at < 0 ? [] : kids.slice(at);\n if (rest.some((k) => !isList(k) && (k.textContent ?? \"\").trim())) return null;\n lines.push(pad + marker + own.map((k) => inline(k)).join(\"\").trim().replace(/ {2}\\n/g, \" \"));\n for (const k of rest) {\n if (!isList(k)) continue;\n const inner = list(k as HTMLElement, pad + \" \".repeat(marker.length));\n if (inner === null) return null;\n lines.push(inner);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function htmlToMarkdown(html: string): string {\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n const out: string[] = [];\n for (const node of Array.from(doc.body.childNodes)) {\n if (node.nodeType === 3) {\n const t = inline(node).trim();\n if (t) out.push(t);\n continue;\n }\n if (node.nodeType !== 1) continue;\n const el = node as HTMLElement;\n const tag = el.tagName;\n const raw = () => out.push(el.outerHTML.replace(/\\n+/g, \" \"));\n if (/^H[1-6]$/.test(tag)) out.push(`${\"#\".repeat(Number(tag[1]))} ${inline(el).trim()}`);\n else if (tag === \"P\") {\n const s = inline(el).trim().replace(/^([#>]|\\d+\\.|[-+] |-{3})/, \"\\\\$1\");\n if (s) out.push(s);\n } else if (tag === \"UL\" || tag === \"OL\") {\n const l = list(el);\n if (l === null) raw();\n else out.push(l);\n } else if (tag === \"BLOCKQUOTE\") {\n const paras = el.querySelector(\"p,div\") ? Array.from(el.children).map((c) => inline(c).trim()) : [inline(el).trim()];\n out.push(paras.filter(Boolean).map((p) => p.split(\"\\n\").map((l) => `> ${l}`).join(\"\\n\")).join(\"\\n>\\n\"));\n } else if (tag === \"PRE\") out.push(\"```\\n\" + (el.textContent ?? \"\").replace(/\\n$/, \"\") + \"\\n```\");\n else if (tag === \"HR\") out.push(\"---\");\n else if (tag === \"FIGURE\" && el.querySelector(\":scope > img\")) {\n const img = el.querySelector(\"img\")!;\n const cap = el.querySelector(\"figcaption\")?.textContent?.trim();\n out.push(`![${img.getAttribute(\"alt\") ?? \"\"}](${img.getAttribute(\"src\") ?? \"\"}${cap ? ` \"${cap.replace(/\"/g, \"'\")}\"` : \"\"})`);\n } else raw();\n }\n return out.join(\"\\n\\n\") + (out.length ? \"\\n\" : \"\");\n}\n\n/* ── Markdown → HTML ───────────────────────────────────────────────── */\nconst safeHref = (h: string) => (/^\\s*(javascript|vbscript|data:text)/i.test(h) ? \"#\" : h);\n\nexport function inlineMd(src: string): string {\n const slots: string[] = [];\n const hold = (html: string) => `\\u0000${slots.push(html) - 1}\\u0000`;\n let s = src.replace(/\\\\([\\\\`*_[\\]~#>+\\-.!])/g, (_, c: string) => hold(esc(c)));\n s = s.replace(/`([^`]+)`/g, (_, c: string) => hold(`<code>${esc(c)}</code>`));\n s = s.replace(/<a [^>]*>.*?<\\/a>/g, (m) => hold(m));\n s = esc(s);\n s = s.replace(/&lt;(\\/?)u&gt;/g, \"<$1u>\");\n s = s.replace(/!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g, (_, a: string, u: string) => hold(`<img src=\"${escAttr(safeHref(u))}\" alt=\"${escAttr(a)}\">`));\n s = s.replace(/\\[([^\\]]+)\\]\\(([^)\\s]+)\\)/g, (_, t: string, u: string) => `<a href=\"${escAttr(safeHref(u))}\">${t}</a>`);\n s = s.replace(/\\*\\*([^*]+?)\\*\\*/g, \"<strong>$1</strong>\");\n s = s.replace(/__([^_]+?)__/g, \"<strong>$1</strong>\");\n s = s.replace(/(^|[^\\w*])\\*([^*\\s][^*]*?)\\*(?!\\*)/g, \"$1<em>$2</em>\");\n s = s.replace(/(^|[^\\w])_([^_\\s][^_]*?)_(?!\\w)/g, \"$1<em>$2</em>\");\n s = s.replace(/~~([^~]+?)~~/g, \"<s>$1</s>\");\n s = s.replace(/ {2,}\\n/g, \"<br>\").replace(/\\n/g, \" \");\n return s.replace(/\\u0000(\\d+)\\u0000/g, (_, i: string) => slots[Number(i)]);\n}\n\nconst RAW_BLOCK = /^<\\/?(div|table|figure|details|ul|ol|p|h[1-6]|blockquote|pre|hr|section|aside)\\b/i;\nconst RE = {\n fence: /^\\s*```/,\n heading: /^(#{1,6})\\s+(.*?)\\s*#*\\s*$/,\n hr: /^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$/,\n image: /^!\\[([^\\]]*)\\]\\(([^)\\s]+)(?:\\s+\"([^\"]*)\")?\\)\\s*$/,\n quote: /^\\s*>/,\n ul: /^\\s*[-*+]\\s+(.*)$/,\n ol: /^\\s*\\d+[.)]\\s+(.*)$/,\n};\ntype ListLine = { indent: number; ordered: boolean; text: string };\n/**\n * A run of list lines as lists. A line indented two or more spaces past an item is that item's nested list (RT-035),\n * and a shallower line closes it; a line of the other kind at the same level starts a new list, as it always did.\n */\nfunction listHtml(items: ListLine[]): string {\n let html = \"\";\n for (let i = 0; i < items.length; ) {\n const { ordered, indent } = items[i];\n const tag = ordered ? \"ol\" : \"ul\";\n html += `<${tag}>`;\n while (i < items.length && items[i].ordered === ordered) {\n const item = items[i++];\n const kids: ListLine[] = [];\n while (i < items.length && items[i].indent >= indent + 2) kids.push(items[i++]);\n html += `<li>${inlineMd(item.text)}${kids.length ? listHtml(kids) : \"\"}</li>`;\n }\n html += `</${tag}>`;\n }\n return html;\n}\nconst startsBlock =(l: string) => RE.fence.test(l) || RE.heading.test(l) || RE.hr.test(l) || RE.quote.test(l) || RE.ul.test(l) || RE.ol.test(l) || RAW_BLOCK.test(l.trim());\n\n/** Throws on Markdown it cannot read (e.g. an unclosed code fence). */\nexport function markdownToHtml(md: string): string {\n const lines = md.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n if (!line.trim()) {\n i++;\n continue;\n }\n if (RE.fence.test(line)) {\n const code: string[] = [];\n i++;\n while (i < lines.length && !RE.fence.test(lines[i])) code.push(lines[i++]);\n if (i >= lines.length) throw new Error(\"Unclosed code block\");\n i++;\n out.push(`<pre>${esc(code.join(\"\\n\"))}</pre>`);\n continue;\n }\n if (RAW_BLOCK.test(line.trim())) {\n const raw: string[] = [];\n while (i < lines.length && lines[i].trim()) raw.push(lines[i++]);\n out.push(raw.join(\" \"));\n continue;\n }\n let m = line.match(RE.heading);\n if (m) {\n out.push(`<h${m[1].length}>${inlineMd(m[2])}</h${m[1].length}>`);\n i++;\n continue;\n }\n if (RE.hr.test(line)) {\n out.push(\"<hr>\");\n i++;\n continue;\n }\n m = line.match(RE.image);\n if (m) {\n // an image keeps no caption in production rich text: a title becomes the line under it, never dropped\n out.push(`<figure><img src=\"${escAttr(safeHref(m[2]))}\" alt=\"${escAttr(m[1])}\"></figure>${m[3] ? `<p>${esc(m[3])}</p>` : \"\"}`);\n i++;\n continue;\n }\n if (RE.quote.test(line)) {\n const q: string[] = [];\n while (i < lines.length && RE.quote.test(lines[i])) q.push(lines[i++].replace(/^\\s*> ?/, \"\"));\n out.push(`<blockquote>${q.join(\"\\n\").split(/\\n\\s*\\n/).map(inlineMd).join(\"<br><br>\")}</blockquote>`);\n continue;\n }\n if (RE.ul.test(line) || RE.ol.test(line)) {\n const items: ListLine[] = [];\n while (i < lines.length && (RE.ul.test(lines[i]) || RE.ol.test(lines[i]))) {\n const l = lines[i++];\n const ordered = !RE.ul.test(l);\n items.push({ indent: l.match(/^\\s*/)![0].replace(/\\t/g, \" \").length, ordered, text: l.match(ordered ? RE.ol : RE.ul)![1] });\n }\n out.push(listHtml(items));\n continue;\n }\n const para: string[] = [];\n while (i < lines.length && lines[i].trim() && (para.length === 0 || !startsBlock(lines[i]))) para.push(lines[i++]);\n out.push(`<p>${inlineMd(para.join(\"\\n\"))}</p>`);\n }\n return sanitize(out.join(\"\"));\n}\n\n/** Does pasted plain text look like Markdown worth converting into blocks? */\nexport const looksLikeMarkdown = (t: string) => /\\n\\s*\\n/.test(t) || /^(#{1,6}\\s|[-*+]\\s|\\d+[.)]\\s|>\\s|```|---)/m.test(t) || /\\*\\*[^*]+\\*\\*|\\[[^\\]]+\\]\\([^)]+\\)/.test(t);\n"],"mappings":";;;;;;;;AASA,IAAM,WAAW,MAAc,EAAE,QAAQ,iBAAiB,MAAM;AAEhE,SAAS,OAAO,MAAY,SAAS,OAAe;CAClD,IAAI,KAAK,aAAa,GAAG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AM,EAAE,GAAG,EAAE,KAAK,MAAM,IAAI,CAAC,QAAQ,WAAW,EAAE,CAAC;GAC5F,IAAI,KAAK,eAAe,EAAE,KAAK,IAAI,CAAC,CAAC,MAAM,SAAS,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,KAAK,UAAU,EAAE,cAAc;GACnG;EACF;EACA,IAAI,GAAG,GAAG,KAAK,IAAI,KAAK,GAAG,GAAG,KAAK,IAAI,GAAG;GACxC,MAAM,QAAoB,CAAC;GAC3B,OAAO,IAAI,MAAM,WAAW,GAAG,GAAG,KAAK,MAAM,EAAE,KAAK,GAAG,GAAG,KAAK,MAAM,EAAE,IAAI;IACzE,MAAM,IAAI,MAAM;IAChB,MAAM,UAAU,CAAC,GAAG,GAAG,KAAK,CAAC;IAC7B,MAAM,KAAK;KAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,CAAE,EAAE,CAAC,QAAQ,OAAO,MAAM,CAAC,CAAC;KAAQ;KAAS,MAAM,EAAE,MAAM,UAAU,GAAG,KAAK,GAAG,EAAE,CAAC,CAAE;IAAG,CAAC;GAC/H;GACA,IAAI,KAAK,SAAS,KAAK,CAAC;GACxB;EACF;EACA,MAAM,OAAiB,CAAC;EACxB,OAAO,IAAI,MAAM,UAAU,MAAM,EAAE,CAAC,KAAK,MAAM,KAAK,WAAW,KAAK,CAAC,YAAY,MAAM,EAAE,IAAI,KAAK,KAAK,MAAM,IAAI;EACjH,IAAI,KAAK,MAAM,SAAS,KAAK,KAAK,IAAI,CAAC,EAAE,KAAK;CAChD;CACA,OAAO,SAAS,IAAI,KAAK,EAAE,CAAC;AAC9B;;AAGA,IAAa,qBAAqB,MAAc,UAAU,KAAK,CAAC,KAAK,6CAA6C,KAAK,CAAC,KAAK,oCAAoC,KAAK,CAAC"}
@@ -438,7 +438,11 @@ function SchemaForm({ schema: schemaIn, value, onChange, path: controlledPath, d
438
438
  value: ROWS_HOST,
439
439
  children: /* @__PURE__ */ jsxs("div", {
440
440
  ref: root,
441
- onKeyDown: nav.onKeyDown,
441
+ onKeyDown: (e) => {
442
+ nav.onKeyDown(e);
443
+ const t = e.target;
444
+ if ((e.key === "Backspace" || e.key === "Delete") && !e.metaKey && !e.ctrlKey && !e.altKey && !(t.matches("input,textarea,select") || t.isContentEditable)) e.stopPropagation();
445
+ },
442
446
  className: cn("flex min-h-0 min-w-0 flex-col", ownScroll && "h-full", className),
443
447
  "data-kit-form": schema.name,
444
448
  children: [
@@ -1 +1 @@
1
- {"version":3,"file":"schema-form.js","names":[],"sources":["../../src/engine/schema-form.tsx"],"sourcesContent":["/**\n * <SchemaForm> — the BetterCMS Block Kit form engine (V2 HEAD 9829bf1 kit/engine/schema-form.tsx). One schema in, one\n * value out; renders through the shared field chrome; owns validation visibility, per-field undo + history (coalesced\n * 900ms, 50 steps), the published baseline (changed dots, Reset to published) and the navigation path.\n *\n * <SchemaForm schema={faq} value={v} onChange={setV} variant=\"panel\" />\n *\n * `path` is controllable so a canvas can sync selection <-> breadcrumb both ways. Frames (root, drilled object, array\n * item, slot block, button, history) come from lib/frames `resolveFrames`; the drill-in stage, crumbs and keys\n * (Esc / Alt+Up/Down) from frame.tsx and breadcrumb.tsx; the layout of each frame from grouping.tsx through field-list.\n *\n * The host provides the kit scope (`data-kit-scope`) around the form; the form never declares one of its own, so a\n * dark host scope is never reset to light inside it.\n */\nimport * as React from \"react\";\nimport { cn } from \"../lib/cn\";\nimport type { Condition, FieldPath, FieldSchema, TypeSchema } from \"../schema/types\";\nimport { DEFAULT_ENV, fieldAccessOf, FormProvider, KitEnvProvider, useForm, useKitEnv, visibleSchema, type FormApi, type HistoryEntry, type KitEnv, type KitPeer, type Swatch } from \"../context\";\nimport { resolveFrames } from \"../lib/frames\";\nimport { getIn, isObj, keyStartsWith, pathEq, pathKey, same, setIn } from \"../lib/path\";\nimport { condCtx, failingRules, isHidden } from \"../lib/schema\";\nimport { collectIssues, type KitIssue, type UniquePeers } from \"../lib/validate\";\nimport { RowsHostContext } from \"./array\";\nimport { crumbSignature, FrameCrumbs, framesToCrumbs, type KitCrumb } from \"./breadcrumb\";\nimport { FieldList, type FieldListProps } from \"./field-list\";\nimport { FrameSlotsProvider, FrameStage, useFrameNavigation, type FrameSlots } from \"./frame\";\nimport { FieldList as GroupedFieldList, FieldSection } from \"./grouping\";\nimport { KitField, NestedForm } from \"./kit-field\";\nimport { TableFrame } from \"../controls/table/table\";\nimport { ButtonScreen } from \"../controls/button\";\n\nexport interface SchemaFormProps {\n schema: TypeSchema;\n value: Record<string, unknown>;\n onChange: (value: Record<string, unknown>) => void;\n /** controlled navigation path ([] = root). Omit for uncontrolled. */\n path?: FieldPath;\n defaultPath?: FieldPath;\n onPathChange?: (path: FieldPath) => void;\n /** \"panel\" = 320–420px inspector; \"document\" = the wide document editor column */\n variant?: \"panel\" | \"document\";\n /** resolve a block type (slot children) to its schema */\n resolveSchema?: (blockType: string) => TypeSchema | undefined;\n /** blocks offered by \"+ Add block\" (filtered by each slot's allow list) */\n blockLibrary?: TypeSchema[];\n /** the published version: enables changed dots and \"Reset to published\" */\n published?: Record<string, unknown>;\n /**\n * Component instance (CPO D28): values come from `from` unless a top-level key is in `overridden`. Overridden fields\n * get an accent dot + \"Reset\"; inherited ones read muted. `onReset(key)` drops one override.\n */\n inherited?: { from: string; overridden: string[]; onReset: (key: string) => void };\n /** pathKey → teammates in that field (\"items.1.answer\") */\n presence?: Record<string, KitPeer | KitPeer[]>;\n /** pathKey → open comment threads */\n comments?: Record<string, number>;\n /** host comment system. When set, the field comment chip opens the host's popover/panel instead of the kit's. */\n onComment?: KitEnv[\"onComment\"];\n /** \"Open {title}\" on a reference: the host opens the referenced entry (e.g. a stacked panel) */\n onOpenReference?: KitEnv[\"onOpenReference\"];\n /** D61: the host's Review changes markers (while its History panel is open) */\n review?: KitEnv[\"review\"];\n /** D61 field ⋯ › History: the host opens its History panel on this field (see `KitEnv.onFieldHistory`). Keep it stable. */\n onFieldHistory?: KitEnv[\"onFieldHistory\"];\n /** the whole form is read-only for the lens (fields with their own `access.edit` still follow `env.can`) */\n readOnly?: boolean;\n /** validate everything now (after a publish attempt) */\n showErrors?: boolean;\n /** document identity + site context */\n env?: {\n docId?: string;\n docTitle?: string;\n urlPrefix?: string;\n isPublished?: boolean;\n /** the slug is the document's address (KitEnv.slugIsAddress) */\n slugIsAddress?: boolean;\n palette?: Swatch[];\n syncedFrom?: string;\n /** D58: the host's access check (`useCan` at the host). Omitted → allow-all (staff tools, demos). */\n can?: KitEnv[\"can\"];\n /** CPO D39: \"tooltip\" moves help lines behind the ⓘ (dense hosts) */\n helpDisplay?: KitEnv[\"helpDisplay\"];\n /** \"quiet\" field chrome for meta-forms (see `KitEnv.fieldChrome`) */\n fieldChrome?: KitEnv[\"fieldChrome\"];\n /** the host's own controls by path key (see `KitEnv.controls`); keep it stable */\n controls?: KitEnv[\"controls\"];\n /** the host's chip summary for collapsed fieldsets (see `KitEnv.sectionSummary`); keep it stable */\n sectionSummary?: KitEnv[\"sectionSummary\"];\n };\n /**\n * Issues the host computes itself (a live check the schema can't express), merged with the form's own. A host issue on a\n * path the form already flags is dropped; `live` ones show while typing; `fix` adds one action after the message.\n */\n extraIssues?: KitIssue[];\n /** Root fields with `validation.unique`: the values the model's other records hold (V2). Absent: not checked. Keep it stable. */\n uniquePeers?: UniquePeers;\n /** The host's access check (V2 `KitEnv.can`), the same as `env.can`; `env.can` wins when both are set. */\n can?: KitEnv[\"can\"];\n /**\n * D70 (V2 `KitEnv.hiddenLine`): keep the fields that would leave the form in place as the host's line instead. `why`\n * says what hid it: \"rule\" (its condition doesn't hold for the current value) or \"access\" (the lens can't `view` it);\n * `failed` holds the rules that don't hold (\"Badge is not Sale\"), [] for access.\n * The schema preview draws its dashed \"Hidden for Editor\" / \"Hidden: …\" lines with it. Absent: hidden fields leave the\n * form, as in every editor. Keep it stable (a new function re-renders the form).\n */\n hiddenLine?: (field: FieldSchema, path: FieldPath, why: HiddenWhy, failed: Condition[]) => React.ReactNode;\n /** own scroll container (default: panel yes, document no) */\n scroll?: boolean;\n /** rendered above the breadcrumb (e.g. a block header) */\n header?: React.ReactNode;\n /** label of the root crumb (defaults to schema.title) */\n rootLabel?: string;\n /**\n * Host-owned trail (CPO D38): the form stops rendering its own breadcrumb and reports the drill-in crumbs\n * instead, so a host with its own path header shows ONE breadcrumb. Navigate with `onPathChange`. Called in a\n * layout effect, so the host header never lags a frame.\n */\n onCrumbs?: (crumbs: KitCrumb[]) => void;\n onIssuesChange?: (issues: KitIssue[]) => void;\n /** imperative navigation for hosts (e.g. a dialog's Escape: go up one level before closing) */\n navRef?: React.Ref<{ back: () => boolean }>;\n className?: string;\n}\n\nexport const COALESCE_MS = 900;\nexport const UNDO_STEPS = 50;\nconst HISTORY_ENTRIES = 30;\n\n/* The frame pieces other lanes own, handed to frame.tsx (which never imports them directly). ButtonScreen (link\n control) and TableFrame (table control) arrive with the controls lanes; until then the header title reads the\n button's label the way V2's `normLink(v).label` does.\n The getters read the imports at render, not at module evaluation: kit-field → array / field-list → schema-form →\n kit-field is a cycle, and an eager read would hit the TDZ the day one of them becomes a const or memo(). */\nconst buttonLabel = (v: unknown) => ({ label: isObj(v) && typeof v.label === \"string\" ? v.label : undefined });\nconst FRAME_SLOTS: FrameSlots = {\n get FieldList() {\n return FieldList;\n },\n get FieldSection() {\n return FieldSection;\n },\n get TableFrame() {\n return TableFrame;\n },\n get ButtonScreen() {\n return ButtonScreen;\n },\n normLink: buttonLabel,\n};\nconst ROWS_HOST = {\n get NestedForm() {\n return NestedForm;\n },\n};\n\n/* ── archived fields leave every form ───────────────────────────────── */\n/** Drop archived fields at every depth (V2 registry: \"What a form renders: archived fields left out (their values stay\n * stored)\"). Same object back when nothing is archived, so a form with none renders exactly as before. */\nfunction liveFields(fields: FieldSchema[]): FieldSchema[] {\n let changed = false;\n const out: FieldSchema[] = [];\n for (const f of fields) {\n if (f.archived) {\n changed = true;\n continue;\n }\n let g = f;\n if (f.fields) {\n const n = liveFields(f.fields);\n if (n !== f.fields) g = { ...g, fields: n };\n }\n if (Array.isArray(f.of)) {\n const n = liveFields(f.of);\n if (n !== f.of) g = { ...g, of: n };\n }\n if (f.slotSettings) {\n const n = liveFields(f.slotSettings);\n if (n !== f.slotSettings) g = { ...g, slotSettings: n };\n }\n if (g !== f) changed = true;\n out.push(g);\n }\n return changed ? out : fields;\n}\nfunction liveSchema(schema: TypeSchema): TypeSchema {\n const fields = liveFields(schema.fields);\n return fields === schema.fields ? schema : { ...schema, fields };\n}\n\n/* ── hiddenLine: hidden fields kept in place as the host's line ──────── */\nexport type HiddenWhy = \"rule\" | \"access\";\nconst GHOST = \"__ghost\";\ntype Ghost = { why: HiddenWhy; field: FieldSchema; failed: Condition[] };\ntype GhostField = FieldSchema & { [GHOST]?: Ghost };\nconst HiddenLineCtx = React.createContext<SchemaFormProps[\"hiddenLine\"]>(undefined);\n\n/** A stand-in that keeps a hidden field's place: no value rules, no condition, nothing to validate or drill into. */\nfunction ghostOf(f: FieldSchema, why: HiddenWhy, failed: Condition[] = []): GhostField {\n return { name: f.name, title: f.title, type: f.type === \"object\" || f.type === \"array\" || f.type === \"slot\" ? \"string\" : f.type, fieldset: f.fieldset, group: f.group, readOnly: true, [GHOST]: { why, field: f, failed } };\n}\n\n/** `visibleSchema`, except that a field the lens can't view stays as a ghost (top level and inside objects). */\nfunction lensGhosts(schema: TypeSchema, can: KitEnv[\"can\"]): TypeSchema {\n const walk = (fields: FieldSchema[]): FieldSchema[] =>\n fields.map((f) => {\n const a = fieldAccessOf(f);\n if (a?.view && !can(a.view)) return ghostOf(f, \"access\");\n return f.type === \"object\" && f.fields ? { ...f, fields: walk(f.fields) } : f;\n });\n return { ...schema, fields: walk(schema.fields) };\n}\n\n/** The frame's field list with condition-hidden fields kept as ghosts, every ghost drawn by the host's line. */\nfunction GhostFieldList(props: FieldListProps) {\n const form = useForm()!;\n const line = React.useContext(HiddenLineCtx)!;\n const raw = form.getAt(props.basePath);\n const parent = isObj(raw) ? raw : {};\n const cc = condCtx(form, props.basePath);\n const fields = props.fields.map((f) => ((f as GhostField)[GHOST] || f.hidden === true || !isHidden(f, parent, cc) ? f : ghostOf(f, \"rule\", failingRules(f, parent, cc))));\n return (\n <GroupedFieldList\n {...props}\n fields={fields}\n renderField={(f, path, p) => {\n const g = (f as GhostField)[GHOST];\n return g ? (\n <div data-field-key={pathKey(path)} data-ghost={g.why}>\n {line(g.field, path, g.why, g.failed)}\n </div>\n ) : (\n <KitField field={f} path={path} parent={p} />\n );\n }}\n />\n );\n}\nconst GHOST_SLOTS: FrameSlots = {\n get FieldList() {\n return GhostFieldList;\n },\n get FieldSection() {\n return FieldSection;\n },\n get TableFrame() {\n return TableFrame;\n },\n get ButtonScreen() {\n return ButtonScreen;\n },\n normLink: buttonLabel,\n};\n\nexport function SchemaForm({\n schema: schemaIn,\n value,\n onChange,\n path: controlledPath,\n defaultPath,\n onPathChange,\n variant = \"panel\",\n resolveSchema: resolveIn,\n blockLibrary,\n published,\n inherited,\n presence,\n comments,\n onComment,\n onOpenReference,\n review,\n onFieldHistory,\n readOnly,\n showErrors = false,\n env: envIn,\n scroll,\n header,\n rootLabel,\n onCrumbs,\n onIssuesChange,\n navRef,\n className,\n can: canIn,\n hiddenLine,\n extraIssues,\n uniquePeers,\n}: SchemaFormProps) {\n const outerCan = useKitEnv().can;\n const can = envIn?.can ?? canIn ?? outerCan; // a nested form (dialog object, article block) inherits its host form's check\n /* D58: fields the lens can't view are dropped from the schema here, once: not rendered, not validated (with\n `hiddenLine`, they stay as ghosts: a place and a line, still nothing to validate) */\n const schema = React.useMemo(() => {\n const live = liveSchema(schemaIn);\n return hiddenLine ? lensGhosts(live, can) : visibleSchema(live, can);\n }, [schemaIn, can, hiddenLine]);\n const resolveSchema = React.useMemo(\n () =>\n resolveIn\n ? (t: string) => {\n const s = resolveIn(t);\n return s && visibleSchema(liveSchema(s), can);\n }\n : undefined,\n [resolveIn, can],\n );\n const docId = envIn?.docId ?? schema.name;\n const ownScroll = scroll ?? variant === \"panel\";\n\n /* value + baseline */\n const valueRef = React.useRef(value);\n valueRef.current = value;\n const [baseline, setBaseline] = React.useState(value);\n const stacks = React.useRef(new Map<string, { path: FieldPath; values: unknown[]; at: number }>());\n const log = React.useRef(new Map<string, HistoryEntry[]>());\n const memory = React.useRef(new Map<string, unknown>());\n const [aiKeys, setAiKeys] = React.useState<Set<string>>(() => new Set());\n const [touched, setTouched] = React.useState<Set<string>>(() => new Set());\n const editing = React.useRef(new Set<string>());\n const [, bump] = React.useReducer((x: number) => x + 1, 0);\n React.useEffect(() => {\n setBaseline(valueRef.current);\n stacks.current.clear();\n log.current.clear();\n memory.current.clear();\n setTouched(new Set());\n setAiKeys(new Set());\n }, [docId]);\n\n /* navigation */\n const [innerPath, setInnerPath] = React.useState<FieldPath>(defaultPath ?? []);\n const rawPath = controlledPath ?? innerPath;\n const { frames, path } = React.useMemo(() => resolveFrames(schema, value, rawPath, resolveSchema), [schema, value, rawPath, resolveSchema]);\n const navigate = React.useCallback(\n (p: FieldPath) => {\n if (controlledPath === undefined) setInnerPath(p);\n onPathChange?.(p);\n },\n [controlledPath, onPathChange],\n );\n /* a path that no longer resolves (a removed item, a hidden field) settles on the deepest frame that does */\n React.useEffect(() => {\n if (!pathEq(path, rawPath)) navigate(path);\n }, [path, rawPath, navigate]);\n /* V2: a new document starts at its root (an uncontrolled path never carries the last document's drill or history).\n Skips the mount run so `defaultPath` survives. */\n const lastDoc = React.useRef(docId);\n React.useEffect(() => {\n if (lastDoc.current === docId) return;\n lastDoc.current = docId;\n if (controlledPath === undefined) setInnerPath([]);\n }, [docId]); // eslint-disable-line react-hooks/exhaustive-deps\n\n /* writes */\n const setAt = React.useCallback<FormApi[\"setAt\"]>(\n (p, v, opts) => {\n const prev = getIn(valueRef.current, p);\n if (same(prev, v)) return;\n const key = pathKey(p);\n if (opts?.record !== false) {\n const now = Date.now();\n const st = stacks.current.get(key) ?? { path: p, values: [], at: 0 };\n if (!st.values.length || now - st.at > COALESCE_MS) st.values = [...st.values, prev].slice(-UNDO_STEPS);\n st.at = now;\n stacks.current.set(key, st);\n const h = log.current.get(key) ?? [];\n const entry: HistoryEntry = { value: v, at: now, by: \"You\", label: opts?.label };\n log.current.set(key, h.length && now - h[0].at < COALESCE_MS && !opts?.label ? [entry, ...h.slice(1)] : [entry, ...h].slice(0, HISTORY_ENTRIES));\n editing.current.add(key);\n }\n const next = setIn(valueRef.current, p, v);\n valueRef.current = next;\n onChange(next);\n },\n [onChange],\n );\n\n /* validation */\n const issueList = React.useMemo(() => {\n // the variant the form draws: the value's own, else the schema's first (as condCtx reads it for rendering)\n const variant = typeof value._variant === \"string\" ? value._variant : schema.variants?.[0]?.id;\n const own = collectIssues(schema.fields, value, [], resolveSchema, [], { root: value, variant }, uniquePeers);\n return extraIssues?.length ? [...own, ...extraIssues.filter((x) => !own.some((o) => o.key === x.key))] : own;\n }, [schema, value, resolveSchema, extraIssues, uniquePeers]);\n const issues = React.useMemo(() => new Map(issueList.map((i) => [i.key, i])), [issueList]);\n React.useEffect(() => onIssuesChange?.(issueList), [issueList, onIssuesChange]);\n const isVisible = React.useCallback(\n (i: KitIssue) => showErrors || !!i.live || touched.has(i.key) || (i.kind === \"rule\" && !editing.current.has(i.key)),\n [showErrors, touched],\n );\n\n const api: FormApi = {\n schema,\n value,\n setAt,\n getAt: (p) => getIn(value, p),\n baselineAt: (p) => getIn(baseline, p),\n publishedAt: (p) => getIn(published, p),\n hasPublished: !!published,\n inherited: inherited ? { from: inherited.from, isOverridden: (k) => inherited.overridden.includes(k), reset: inherited.onReset } : undefined,\n path,\n navigate,\n canNavigate: true,\n resolveSchema,\n blockLibrary,\n issues,\n visibleIssue: (k) => {\n const i = issues.get(k);\n return i && isVisible(i) ? i : undefined;\n },\n rollup: (prefix) => {\n const pk = pathKey(prefix);\n let errors = 0;\n let warnings = 0;\n for (const i of issueList) if (keyStartsWith(i.key, pk) && isVisible(i)) i.level === \"error\" ? errors++ : warnings++;\n return { errors, warnings };\n },\n touch: (k) => {\n editing.current.delete(k);\n if (!touched.has(k)) setTouched((s) => new Set(s).add(k));\n },\n showAllErrors: showErrors,\n canUndo: (k) => !!stacks.current.get(k)?.values.length,\n undo: (k) => {\n const st = stacks.current.get(k);\n if (!st?.values.length) return;\n const prev = st.values[st.values.length - 1];\n st.values = st.values.slice(0, -1);\n st.at = 0;\n const next = setIn(valueRef.current, st.path, prev);\n valueRef.current = next;\n onChange(next);\n bump();\n },\n history: (k) => log.current.get(k) ?? [],\n aiKeys,\n markAi: (k, on) =>\n setAiKeys((s) => {\n const n = new Set(s);\n if (on) n.add(k);\n else n.delete(k);\n return n;\n }),\n memory: memory.current,\n };\n\n const normPresence = React.useMemo(() => {\n const out: Record<string, KitPeer[]> = {};\n for (const [k, v] of Object.entries(presence ?? {})) out[k] = Array.isArray(v) ? v : [v];\n return out;\n }, [presence]);\n const env: KitEnv = React.useMemo(\n () => ({\n ...DEFAULT_ENV,\n variant,\n docId,\n docTitle: envIn?.docTitle,\n urlPrefix: envIn?.urlPrefix,\n /* a published copy proves \"live\"; its absence proves nothing (the dock has none), so it stays unknown */\n isPublished: envIn?.isPublished ?? (published ? true : undefined),\n slugIsAddress: envIn?.slugIsAddress,\n palette: envIn?.palette ?? DEFAULT_ENV.palette,\n readOnly: !!readOnly,\n can,\n presence: normPresence,\n comments: comments ?? {},\n onComment,\n onOpenReference,\n syncedFrom: envIn?.syncedFrom,\n helpDisplay: envIn?.helpDisplay,\n review,\n onFieldHistory,\n fieldChrome: envIn?.fieldChrome,\n controls: envIn?.controls,\n sectionSummary: envIn?.sectionSummary,\n }),\n [variant, docId, envIn?.docTitle, envIn?.urlPrefix, envIn?.isPublished, envIn?.slugIsAddress, envIn?.palette, envIn?.syncedFrom, envIn?.helpDisplay, envIn?.fieldChrome, envIn?.controls, envIn?.sectionSummary, published, readOnly, can, normPresence, comments, onComment, onOpenReference, review, onFieldHistory],\n );\n\n React.useImperativeHandle(\n navRef,\n () => ({\n back: () => {\n if (frames.length < 2) return false;\n navigate(frames[frames.length - 2].path);\n return true;\n },\n }),\n [frames, navigate],\n );\n\n /* drill-in stage: direction-aware slide, scroll memory, focus on the entering frame, Esc / Alt+Up/Down */\n const root = React.useRef<HTMLDivElement>(null);\n const scroller = React.useRef<HTMLDivElement>(null);\n const nav = useFrameNavigation({ frames, navigate, root, scroller });\n\n const crumbs = framesToCrumbs(frames, schema, api.rollup, rootLabel);\n const crumbSig = crumbSignature(crumbs);\n const onCrumbsRef = React.useRef(onCrumbs);\n onCrumbsRef.current = onCrumbs;\n React.useLayoutEffect(() => {\n onCrumbsRef.current?.(crumbs);\n }, [crumbSig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const syncedNote = envIn?.syncedFrom ? (\n <p className=\"mb-5 flex items-start gap-2 rounded-kit-lg bg-kit-info-soft px-3 py-2 text-kit-xs text-kit-info-fg\">\n <span className=\"mt-0.5 size-1.5 shrink-0 rounded-full bg-kit-info\" aria-hidden />\n <span>\n Synced from <span className=\"font-medium\">{envIn.syncedFrom}</span>. Changes here apply on every page that uses it.\n </span>\n </p>\n ) : null;\n const body = <FrameStage review={!!review} frames={frames} frameKey={nav.frameKey} dir={nav.dir} rootLabel={rootLabel ?? schema.title} variant={variant} before={syncedNote} />;\n\n return (\n <KitEnvProvider value={env}>\n <FormProvider value={api}>\n <HiddenLineCtx.Provider value={hiddenLine}>\n <FrameSlotsProvider value={hiddenLine ? GHOST_SLOTS : FRAME_SLOTS}>\n <RowsHostContext.Provider value={ROWS_HOST}>\n <div ref={root} onKeyDown={nav.onKeyDown} className={cn(\"flex min-h-0 min-w-0 flex-col\", ownScroll && \"h-full\", className)} data-kit-form={schema.name}>\n {header}\n {onCrumbs ? null : <FrameCrumbs crumbs={crumbs} onNavigate={navigate} variant={variant} />}\n {ownScroll ? (\n <div ref={scroller} className=\"@container min-h-0 flex-1 overflow-y-auto overscroll-contain\">\n {body}\n </div>\n ) : (\n <div className=\"@container\">{body}</div>\n )}\n </div>\n </RowsHostContext.Provider>\n </FrameSlotsProvider>\n </H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CAAC;EAAgB;EAAQ,UAAU,IAAI;EAAU,KAAK,IAAI;EAAK,WAAW,aAAa,OAAO;EAAgB;EAAS,QAAQ;CAAa,CAAA;CAE9K,OACE,oBAAC,gBAAD;EAAgB,OAAO;EACrB,UAAA,oBAAC,cAAD;GAAc,OAAO;GACnB,UAAA,oBAAC,cAAc,UAAf;IAAwB,OAAO;IAC/B,UAAA,oBAAC,oBAAD;KAAoB,OAAO,aAAa,cAAc;KACpD,UAAA,oBAAC,gBAAgB,UAAjB;MAA0B,OAAO;MAC/B,UAAA,qBAAC,OAAD;OAAK,KAAK;OAAM,WAAW,IAAI;OAAW,WAAW,GAAG,iCAAiC,aAAa,UAAU,SAAS;OAAG,iBAAe,OAAO;OAAlJ,UAAA;QACG;QACA,WAAW,OAAO,oBAAC,aAAD;SAAqB;SAAQ,YAAY;SAAmB;QAAU,CAAA;QACxF,YACC,oBAAC,OAAD;SAAK,KAAK;SAAU,WAAU;SAC3B,UAAA;QACE,CAAA,IAEL,oBAAC,OAAD;SAAK,WAAU;SAAc,UAAA;QAAU,CAAA;OAEtC;;KACmB,CAAA;IACR,CAAA;GACI,CAAA;EACZ,CAAA;CACA,CAAA;AAEpB"}
1
+ {"version":3,"file":"schema-form.js","names":[],"sources":["../../src/engine/schema-form.tsx"],"sourcesContent":["/**\n * <SchemaForm> — the BetterCMS Block Kit form engine (V2 HEAD 9829bf1 kit/engine/schema-form.tsx). One schema in, one\n * value out; renders through the shared field chrome; owns validation visibility, per-field undo + history (coalesced\n * 900ms, 50 steps), the published baseline (changed dots, Reset to published) and the navigation path.\n *\n * <SchemaForm schema={faq} value={v} onChange={setV} variant=\"panel\" />\n *\n * `path` is controllable so a canvas can sync selection <-> breadcrumb both ways. Frames (root, drilled object, array\n * item, slot block, button, history) come from lib/frames `resolveFrames`; the drill-in stage, crumbs and keys\n * (Esc / Alt+Up/Down) from frame.tsx and breadcrumb.tsx; the layout of each frame from grouping.tsx through field-list.\n *\n * The host provides the kit scope (`data-kit-scope`) around the form; the form never declares one of its own, so a\n * dark host scope is never reset to light inside it.\n */\nimport * as React from \"react\";\nimport { cn } from \"../lib/cn\";\nimport type { Condition, FieldPath, FieldSchema, TypeSchema } from \"../schema/types\";\nimport { DEFAULT_ENV, fieldAccessOf, FormProvider, KitEnvProvider, useForm, useKitEnv, visibleSchema, type FormApi, type HistoryEntry, type KitEnv, type KitPeer, type Swatch } from \"../context\";\nimport { resolveFrames } from \"../lib/frames\";\nimport { getIn, isObj, keyStartsWith, pathEq, pathKey, same, setIn } from \"../lib/path\";\nimport { condCtx, failingRules, isHidden } from \"../lib/schema\";\nimport { collectIssues, type KitIssue, type UniquePeers } from \"../lib/validate\";\nimport { RowsHostContext } from \"./array\";\nimport { crumbSignature, FrameCrumbs, framesToCrumbs, type KitCrumb } from \"./breadcrumb\";\nimport { FieldList, type FieldListProps } from \"./field-list\";\nimport { FrameSlotsProvider, FrameStage, useFrameNavigation, type FrameSlots } from \"./frame\";\nimport { FieldList as GroupedFieldList, FieldSection } from \"./grouping\";\nimport { KitField, NestedForm } from \"./kit-field\";\nimport { TableFrame } from \"../controls/table/table\";\nimport { ButtonScreen } from \"../controls/button\";\n\nexport interface SchemaFormProps {\n schema: TypeSchema;\n value: Record<string, unknown>;\n onChange: (value: Record<string, unknown>) => void;\n /** controlled navigation path ([] = root). Omit for uncontrolled. */\n path?: FieldPath;\n defaultPath?: FieldPath;\n onPathChange?: (path: FieldPath) => void;\n /** \"panel\" = 320–420px inspector; \"document\" = the wide document editor column */\n variant?: \"panel\" | \"document\";\n /** resolve a block type (slot children) to its schema */\n resolveSchema?: (blockType: string) => TypeSchema | undefined;\n /** blocks offered by \"+ Add block\" (filtered by each slot's allow list) */\n blockLibrary?: TypeSchema[];\n /** the published version: enables changed dots and \"Reset to published\" */\n published?: Record<string, unknown>;\n /**\n * Component instance (CPO D28): values come from `from` unless a top-level key is in `overridden`. Overridden fields\n * get an accent dot + \"Reset\"; inherited ones read muted. `onReset(key)` drops one override.\n */\n inherited?: { from: string; overridden: string[]; onReset: (key: string) => void };\n /** pathKey → teammates in that field (\"items.1.answer\") */\n presence?: Record<string, KitPeer | KitPeer[]>;\n /** pathKey → open comment threads */\n comments?: Record<string, number>;\n /** host comment system. When set, the field comment chip opens the host's popover/panel instead of the kit's. */\n onComment?: KitEnv[\"onComment\"];\n /** \"Open {title}\" on a reference: the host opens the referenced entry (e.g. a stacked panel) */\n onOpenReference?: KitEnv[\"onOpenReference\"];\n /** D61: the host's Review changes markers (while its History panel is open) */\n review?: KitEnv[\"review\"];\n /** D61 field ⋯ › History: the host opens its History panel on this field (see `KitEnv.onFieldHistory`). Keep it stable. */\n onFieldHistory?: KitEnv[\"onFieldHistory\"];\n /** the whole form is read-only for the lens (fields with their own `access.edit` still follow `env.can`) */\n readOnly?: boolean;\n /** validate everything now (after a publish attempt) */\n showErrors?: boolean;\n /** document identity + site context */\n env?: {\n docId?: string;\n docTitle?: string;\n urlPrefix?: string;\n isPublished?: boolean;\n /** the slug is the document's address (KitEnv.slugIsAddress) */\n slugIsAddress?: boolean;\n palette?: Swatch[];\n syncedFrom?: string;\n /** D58: the host's access check (`useCan` at the host). Omitted → allow-all (staff tools, demos). */\n can?: KitEnv[\"can\"];\n /** CPO D39: \"tooltip\" moves help lines behind the ⓘ (dense hosts) */\n helpDisplay?: KitEnv[\"helpDisplay\"];\n /** \"quiet\" field chrome for meta-forms (see `KitEnv.fieldChrome`) */\n fieldChrome?: KitEnv[\"fieldChrome\"];\n /** the host's own controls by path key (see `KitEnv.controls`); keep it stable */\n controls?: KitEnv[\"controls\"];\n /** the host's chip summary for collapsed fieldsets (see `KitEnv.sectionSummary`); keep it stable */\n sectionSummary?: KitEnv[\"sectionSummary\"];\n };\n /**\n * Issues the host computes itself (a live check the schema can't express), merged with the form's own. A host issue on a\n * path the form already flags is dropped; `live` ones show while typing; `fix` adds one action after the message.\n */\n extraIssues?: KitIssue[];\n /** Root fields with `validation.unique`: the values the model's other records hold (V2). Absent: not checked. Keep it stable. */\n uniquePeers?: UniquePeers;\n /** The host's access check (V2 `KitEnv.can`), the same as `env.can`; `env.can` wins when both are set. */\n can?: KitEnv[\"can\"];\n /**\n * D70 (V2 `KitEnv.hiddenLine`): keep the fields that would leave the form in place as the host's line instead. `why`\n * says what hid it: \"rule\" (its condition doesn't hold for the current value) or \"access\" (the lens can't `view` it);\n * `failed` holds the rules that don't hold (\"Badge is not Sale\"), [] for access.\n * The schema preview draws its dashed \"Hidden for Editor\" / \"Hidden: …\" lines with it. Absent: hidden fields leave the\n * form, as in every editor. Keep it stable (a new function re-renders the form).\n */\n hiddenLine?: (field: FieldSchema, path: FieldPath, why: HiddenWhy, failed: Condition[]) => React.ReactNode;\n /** own scroll container (default: panel yes, document no) */\n scroll?: boolean;\n /** rendered above the breadcrumb (e.g. a block header) */\n header?: React.ReactNode;\n /** label of the root crumb (defaults to schema.title) */\n rootLabel?: string;\n /**\n * Host-owned trail (CPO D38): the form stops rendering its own breadcrumb and reports the drill-in crumbs\n * instead, so a host with its own path header shows ONE breadcrumb. Navigate with `onPathChange`. Called in a\n * layout effect, so the host header never lags a frame.\n */\n onCrumbs?: (crumbs: KitCrumb[]) => void;\n onIssuesChange?: (issues: KitIssue[]) => void;\n /** imperative navigation for hosts (e.g. a dialog's Escape: go up one level before closing) */\n navRef?: React.Ref<{ back: () => boolean }>;\n className?: string;\n}\n\nexport const COALESCE_MS = 900;\nexport const UNDO_STEPS = 50;\nconst HISTORY_ENTRIES = 30;\n\n/* The frame pieces other lanes own, handed to frame.tsx (which never imports them directly). ButtonScreen (link\n control) and TableFrame (table control) arrive with the controls lanes; until then the header title reads the\n button's label the way V2's `normLink(v).label` does.\n The getters read the imports at render, not at module evaluation: kit-field → array / field-list → schema-form →\n kit-field is a cycle, and an eager read would hit the TDZ the day one of them becomes a const or memo(). */\nconst buttonLabel = (v: unknown) => ({ label: isObj(v) && typeof v.label === \"string\" ? v.label : undefined });\nconst FRAME_SLOTS: FrameSlots = {\n get FieldList() {\n return FieldList;\n },\n get FieldSection() {\n return FieldSection;\n },\n get TableFrame() {\n return TableFrame;\n },\n get ButtonScreen() {\n return ButtonScreen;\n },\n normLink: buttonLabel,\n};\nconst ROWS_HOST = {\n get NestedForm() {\n return NestedForm;\n },\n};\n\n/* ── archived fields leave every form ───────────────────────────────── */\n/** Drop archived fields at every depth (V2 registry: \"What a form renders: archived fields left out (their values stay\n * stored)\"). Same object back when nothing is archived, so a form with none renders exactly as before. */\nfunction liveFields(fields: FieldSchema[]): FieldSchema[] {\n let changed = false;\n const out: FieldSchema[] = [];\n for (const f of fields) {\n if (f.archived) {\n changed = true;\n continue;\n }\n let g = f;\n if (f.fields) {\n const n = liveFields(f.fields);\n if (n !== f.fields) g = { ...g, fields: n };\n }\n if (Array.isArray(f.of)) {\n const n = liveFields(f.of);\n if (n !== f.of) g = { ...g, of: n };\n }\n if (f.slotSettings) {\n const n = liveFields(f.slotSettings);\n if (n !== f.slotSettings) g = { ...g, slotSettings: n };\n }\n if (g !== f) changed = true;\n out.push(g);\n }\n return changed ? out : fields;\n}\nfunction liveSchema(schema: TypeSchema): TypeSchema {\n const fields = liveFields(schema.fields);\n return fields === schema.fields ? schema : { ...schema, fields };\n}\n\n/* ── hiddenLine: hidden fields kept in place as the host's line ──────── */\nexport type HiddenWhy = \"rule\" | \"access\";\nconst GHOST = \"__ghost\";\ntype Ghost = { why: HiddenWhy; field: FieldSchema; failed: Condition[] };\ntype GhostField = FieldSchema & { [GHOST]?: Ghost };\nconst HiddenLineCtx = React.createContext<SchemaFormProps[\"hiddenLine\"]>(undefined);\n\n/** A stand-in that keeps a hidden field's place: no value rules, no condition, nothing to validate or drill into. */\nfunction ghostOf(f: FieldSchema, why: HiddenWhy, failed: Condition[] = []): GhostField {\n return { name: f.name, title: f.title, type: f.type === \"object\" || f.type === \"array\" || f.type === \"slot\" ? \"string\" : f.type, fieldset: f.fieldset, group: f.group, readOnly: true, [GHOST]: { why, field: f, failed } };\n}\n\n/** `visibleSchema`, except that a field the lens can't view stays as a ghost (top level and inside objects). */\nfunction lensGhosts(schema: TypeSchema, can: KitEnv[\"can\"]): TypeSchema {\n const walk = (fields: FieldSchema[]): FieldSchema[] =>\n fields.map((f) => {\n const a = fieldAccessOf(f);\n if (a?.view && !can(a.view)) return ghostOf(f, \"access\");\n return f.type === \"object\" && f.fields ? { ...f, fields: walk(f.fields) } : f;\n });\n return { ...schema, fields: walk(schema.fields) };\n}\n\n/** The frame's field list with condition-hidden fields kept as ghosts, every ghost drawn by the host's line. */\nfunction GhostFieldList(props: FieldListProps) {\n const form = useForm()!;\n const line = React.useContext(HiddenLineCtx)!;\n const raw = form.getAt(props.basePath);\n const parent = isObj(raw) ? raw : {};\n const cc = condCtx(form, props.basePath);\n const fields = props.fields.map((f) => ((f as GhostField)[GHOST] || f.hidden === true || !isHidden(f, parent, cc) ? f : ghostOf(f, \"rule\", failingRules(f, parent, cc))));\n return (\n <GroupedFieldList\n {...props}\n fields={fields}\n renderField={(f, path, p) => {\n const g = (f as GhostField)[GHOST];\n return g ? (\n <div data-field-key={pathKey(path)} data-ghost={g.why}>\n {line(g.field, path, g.why, g.failed)}\n </div>\n ) : (\n <KitField field={f} path={path} parent={p} />\n );\n }}\n />\n );\n}\nconst GHOST_SLOTS: FrameSlots = {\n get FieldList() {\n return GhostFieldList;\n },\n get FieldSection() {\n return FieldSection;\n },\n get TableFrame() {\n return TableFrame;\n },\n get ButtonScreen() {\n return ButtonScreen;\n },\n normLink: buttonLabel,\n};\n\nexport function SchemaForm({\n schema: schemaIn,\n value,\n onChange,\n path: controlledPath,\n defaultPath,\n onPathChange,\n variant = \"panel\",\n resolveSchema: resolveIn,\n blockLibrary,\n published,\n inherited,\n presence,\n comments,\n onComment,\n onOpenReference,\n review,\n onFieldHistory,\n readOnly,\n showErrors = false,\n env: envIn,\n scroll,\n header,\n rootLabel,\n onCrumbs,\n onIssuesChange,\n navRef,\n className,\n can: canIn,\n hiddenLine,\n extraIssues,\n uniquePeers,\n}: SchemaFormProps) {\n const outerCan = useKitEnv().can;\n const can = envIn?.can ?? canIn ?? outerCan; // a nested form (dialog object, article block) inherits its host form's check\n /* D58: fields the lens can't view are dropped from the schema here, once: not rendered, not validated (with\n `hiddenLine`, they stay as ghosts: a place and a line, still nothing to validate) */\n const schema = React.useMemo(() => {\n const live = liveSchema(schemaIn);\n return hiddenLine ? lensGhosts(live, can) : visibleSchema(live, can);\n }, [schemaIn, can, hiddenLine]);\n const resolveSchema = React.useMemo(\n () =>\n resolveIn\n ? (t: string) => {\n const s = resolveIn(t);\n return s && visibleSchema(liveSchema(s), can);\n }\n : undefined,\n [resolveIn, can],\n );\n const docId = envIn?.docId ?? schema.name;\n const ownScroll = scroll ?? variant === \"panel\";\n\n /* value + baseline */\n const valueRef = React.useRef(value);\n valueRef.current = value;\n const [baseline, setBaseline] = React.useState(value);\n const stacks = React.useRef(new Map<string, { path: FieldPath; values: unknown[]; at: number }>());\n const log = React.useRef(new Map<string, HistoryEntry[]>());\n const memory = React.useRef(new Map<string, unknown>());\n const [aiKeys, setAiKeys] = React.useState<Set<string>>(() => new Set());\n const [touched, setTouched] = React.useState<Set<string>>(() => new Set());\n const editing = React.useRef(new Set<string>());\n const [, bump] = React.useReducer((x: number) => x + 1, 0);\n React.useEffect(() => {\n setBaseline(valueRef.current);\n stacks.current.clear();\n log.current.clear();\n memory.current.clear();\n setTouched(new Set());\n setAiKeys(new Set());\n }, [docId]);\n\n /* navigation */\n const [innerPath, setInnerPath] = React.useState<FieldPath>(defaultPath ?? []);\n const rawPath = controlledPath ?? innerPath;\n const { frames, path } = React.useMemo(() => resolveFrames(schema, value, rawPath, resolveSchema), [schema, value, rawPath, resolveSchema]);\n const navigate = React.useCallback(\n (p: FieldPath) => {\n if (controlledPath === undefined) setInnerPath(p);\n onPathChange?.(p);\n },\n [controlledPath, onPathChange],\n );\n /* a path that no longer resolves (a removed item, a hidden field) settles on the deepest frame that does */\n React.useEffect(() => {\n if (!pathEq(path, rawPath)) navigate(path);\n }, [path, rawPath, navigate]);\n /* V2: a new document starts at its root (an uncontrolled path never carries the last document's drill or history).\n Skips the mount run so `defaultPath` survives. */\n const lastDoc = React.useRef(docId);\n React.useEffect(() => {\n if (lastDoc.current === docId) return;\n lastDoc.current = docId;\n if (controlledPath === undefined) setInnerPath([]);\n }, [docId]); // eslint-disable-line react-hooks/exhaustive-deps\n\n /* writes */\n const setAt = React.useCallback<FormApi[\"setAt\"]>(\n (p, v, opts) => {\n const prev = getIn(valueRef.current, p);\n if (same(prev, v)) return;\n const key = pathKey(p);\n if (opts?.record !== false) {\n const now = Date.now();\n const st = stacks.current.get(key) ?? { path: p, values: [], at: 0 };\n if (!st.values.length || now - st.at > COALESCE_MS) st.values = [...st.values, prev].slice(-UNDO_STEPS);\n st.at = now;\n stacks.current.set(key, st);\n const h = log.current.get(key) ?? [];\n const entry: HistoryEntry = { value: v, at: now, by: \"You\", label: opts?.label };\n log.current.set(key, h.length && now - h[0].at < COALESCE_MS && !opts?.label ? [entry, ...h.slice(1)] : [entry, ...h].slice(0, HISTORY_ENTRIES));\n editing.current.add(key);\n }\n const next = setIn(valueRef.current, p, v);\n valueRef.current = next;\n onChange(next);\n },\n [onChange],\n );\n\n /* validation */\n const issueList = React.useMemo(() => {\n // the variant the form draws: the value's own, else the schema's first (as condCtx reads it for rendering)\n const variant = typeof value._variant === \"string\" ? value._variant : schema.variants?.[0]?.id;\n const own = collectIssues(schema.fields, value, [], resolveSchema, [], { root: value, variant }, uniquePeers);\n return extraIssues?.length ? [...own, ...extraIssues.filter((x) => !own.some((o) => o.key === x.key))] : own;\n }, [schema, value, resolveSchema, extraIssues, uniquePeers]);\n const issues = React.useMemo(() => new Map(issueList.map((i) => [i.key, i])), [issueList]);\n React.useEffect(() => onIssuesChange?.(issueList), [issueList, onIssuesChange]);\n const isVisible = React.useCallback(\n (i: KitIssue) => showErrors || !!i.live || touched.has(i.key) || (i.kind === \"rule\" && !editing.current.has(i.key)),\n [showErrors, touched],\n );\n\n const api: FormApi = {\n schema,\n value,\n setAt,\n getAt: (p) => getIn(value, p),\n baselineAt: (p) => getIn(baseline, p),\n publishedAt: (p) => getIn(published, p),\n hasPublished: !!published,\n inherited: inherited ? { from: inherited.from, isOverridden: (k) => inherited.overridden.includes(k), reset: inherited.onReset } : undefined,\n path,\n navigate,\n canNavigate: true,\n resolveSchema,\n blockLibrary,\n issues,\n visibleIssue: (k) => {\n const i = issues.get(k);\n return i && isVisible(i) ? i : undefined;\n },\n rollup: (prefix) => {\n const pk = pathKey(prefix);\n let errors = 0;\n let warnings = 0;\n for (const i of issueList) if (keyStartsWith(i.key, pk) && isVisible(i)) i.level === \"error\" ? errors++ : warnings++;\n return { errors, warnings };\n },\n touch: (k) => {\n editing.current.delete(k);\n if (!touched.has(k)) setTouched((s) => new Set(s).add(k));\n },\n showAllErrors: showErrors,\n canUndo: (k) => !!stacks.current.get(k)?.values.length,\n undo: (k) => {\n const st = stacks.current.get(k);\n if (!st?.values.length) return;\n const prev = st.values[st.values.length - 1];\n st.values = st.values.slice(0, -1);\n st.at = 0;\n const next = setIn(valueRef.current, st.path, prev);\n valueRef.current = next;\n onChange(next);\n bump();\n },\n history: (k) => log.current.get(k) ?? [],\n aiKeys,\n markAi: (k, on) =>\n setAiKeys((s) => {\n const n = new Set(s);\n if (on) n.add(k);\n else n.delete(k);\n return n;\n }),\n memory: memory.current,\n };\n\n const normPresence = React.useMemo(() => {\n const out: Record<string, KitPeer[]> = {};\n for (const [k, v] of Object.entries(presence ?? {})) out[k] = Array.isArray(v) ? v : [v];\n return out;\n }, [presence]);\n const env: KitEnv = React.useMemo(\n () => ({\n ...DEFAULT_ENV,\n variant,\n docId,\n docTitle: envIn?.docTitle,\n urlPrefix: envIn?.urlPrefix,\n /* a published copy proves \"live\"; its absence proves nothing (the dock has none), so it stays unknown */\n isPublished: envIn?.isPublished ?? (published ? true : undefined),\n slugIsAddress: envIn?.slugIsAddress,\n palette: envIn?.palette ?? DEFAULT_ENV.palette,\n readOnly: !!readOnly,\n can,\n presence: normPresence,\n comments: comments ?? {},\n onComment,\n onOpenReference,\n syncedFrom: envIn?.syncedFrom,\n helpDisplay: envIn?.helpDisplay,\n review,\n onFieldHistory,\n fieldChrome: envIn?.fieldChrome,\n controls: envIn?.controls,\n sectionSummary: envIn?.sectionSummary,\n }),\n [variant, docId, envIn?.docTitle, envIn?.urlPrefix, envIn?.isPublished, envIn?.slugIsAddress, envIn?.palette, envIn?.syncedFrom, envIn?.helpDisplay, envIn?.fieldChrome, envIn?.controls, envIn?.sectionSummary, published, readOnly, can, normPresence, comments, onComment, onOpenReference, review, onFieldHistory],\n );\n\n React.useImperativeHandle(\n navRef,\n () => ({\n back: () => {\n if (frames.length < 2) return false;\n navigate(frames[frames.length - 2].path);\n return true;\n },\n }),\n [frames, navigate],\n );\n\n /* drill-in stage: direction-aware slide, scroll memory, focus on the entering frame, Esc / Alt+Up/Down */\n const root = React.useRef<HTMLDivElement>(null);\n const scroller = React.useRef<HTMLDivElement>(null);\n const nav = useFrameNavigation({ frames, navigate, root, scroller });\n\n const crumbs = framesToCrumbs(frames, schema, api.rollup, rootLabel);\n const crumbSig = crumbSignature(crumbs);\n const onCrumbsRef = React.useRef(onCrumbs);\n onCrumbsRef.current = onCrumbs;\n React.useLayoutEffect(() => {\n onCrumbsRef.current?.(crumbs);\n }, [crumbSig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const syncedNote = envIn?.syncedFrom ? (\n <p className=\"mb-5 flex items-start gap-2 rounded-kit-lg bg-kit-info-soft px-3 py-2 text-kit-xs text-kit-info-fg\">\n <span className=\"mt-0.5 size-1.5 shrink-0 rounded-full bg-kit-info\" aria-hidden />\n <span>\n Synced from <span className=\"font-medium\">{envIn.syncedFrom}</span>. Changes here apply on every page that uses it.\n </span>\n </p>\n ) : null;\n const body = <FrameStage review={!!review} frames={frames} frameKey={nav.frameKey} dir={nav.dir} rootLabel={rootLabel ?? schema.title} variant={variant} before={syncedNote} />;\n\n return (\n <KitEnvProvider value={env}>\n <FormProvider value={api}>\n <HiddenLineCtx.Provider value={hiddenLine}>\n <FrameSlotsProvider value={hiddenLine ? GHOST_SLOTS : FRAME_SLOTS}>\n <RowsHostContext.Provider value={ROWS_HOST}>\n <div\n ref={root}\n onKeyDown={(e) => {\n nav.onKeyDown(e);\n // DK-010: Backspace / Delete pressed on a control that is not a text box (a button, chip, switch, option)\n // ends here. A host that deletes its selection on those keys must never hear them from inside the form.\n const t = e.target as HTMLElement;\n if ((e.key === \"Backspace\" || e.key === \"Delete\") && !e.metaKey && !e.ctrlKey && !e.altKey && !(t.matches(\"input,textarea,select\") || t.isContentEditable)) e.stopPropagation();\n }}\n className={cn(\"flex min-h-0 min-w-0 flex-col\", ownScroll && \"h-full\", className)} data-kit-form={schema.name}>\n {header}\n {onCrumbs ? null : <FrameCrumbs crumbs={crumbs} onNavigate={navigate} variant={variant} />}\n {ownScroll ? (\n <div ref={scroller} className=\"@container min-h-0 flex-1 overflow-y-auto overscroll-contain\">\n {body}\n </div>\n ) : (\n <div className=\"@container\">{body}</div>\n )}\n </div>\n </RowsHostContext.Provider>\n </FrameSlotsProvider>\n </HiddenLineCtx.Provider>\n </FormProvider>\n </KitEnvProvider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,IAAa,cAAc;AAC3B,IAAa,aAAa;AAC1B,IAAM,kBAAkB;AAOxB,IAAM,eAAe,OAAgB,EAAE,OAAO,MAAM,CAAC,KAAK,OAAO,EAAE,UAAU,WAAW,EAAE,QAAQ,KAAA,EAAU;AAC5G,IAAM,cAA0B;CAC9B,IAAI,YAAY;EACd,OAAO;CACT;CACA,IAAI,eAAe;EACjB,OAAO;CACT;CACA,IAAI,aAAa;EACf,OAAO;CACT;CACA,IAAI,eAAe;EACjB,OAAO;CACT;CACA,UAAU;AACZ;AACA,IAAM,YAAY,EAChB,IAAI,aAAa;CACf,OAAO;AACT,EACF;;;AAKA,SAAS,WAAW,QAAsC;CACxD,IAAI,UAAU;CACd,MAA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