{"$schema":"https:\/\/ui.particle.academy\/schema\/registry-item.json","name":"template-builder","type":"registry:ui","title":"TemplateBuilder","description":"Build a quote template from blocks: a letterhead, field chips from the host list, line items repeated with a page each, a required totals block, and an exact preview drawn by fine-print on this server.","package":"fancy-template-ui","dependencies":["@particle-academy\/react-fancy","@particle-academy\/fancy-doc-commons","@particle-academy\/fancy-template"],"registryDependencies":[],"files":[{"path":"components\/fancy\/template-builder\/TemplateBuilder.tsx","content":"import { useCallback, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { Button, Callout, ResizablePanels, Tabs, type PdfPageSource } from \"@particle-academy\/react-fancy\";\nimport type { Proposal } from \"@particle-academy\/fancy-doc-commons\";\nimport { BuilderContext, type BuilderContextValue, type FieldOption } from \".\/context\";\nimport { BlockList } from \".\/BlockList\";\nimport { BlockSettings } from \".\/BlockSettings\";\nimport { PageSettings } from \".\/PageSettings\";\nimport { PendingChanges } from \".\/PendingChanges\";\nimport { TemplatePreview, type PreviewMode } from \".\/TemplatePreview\";\nimport { sampleData } from \".\/samples\";\nimport { ITEM_ALIAS, compile } from \".\/core\/compile\";\nimport { openTemplate } from \".\/core\/open\";\nimport { applyOp, checkOp, invertOp } from \".\/core\/ops\";\nimport type { BlockKind, BuilderOp, EditorState, FieldDef, JsonObject, ListDef, Problem, RepeatProps, TemplateEnvelope } from \".\/core\/types\";\n\n\/** One builder mutation, for presence, undo and coaching layers. *\/\nexport interface TemplateActivity {\n  surface: string;\n  type: \"op\" | \"accept\" | \"reject\" | \"undo\" | \"redo\" | \"resolve-drift\";\n  op?: BuilderOp;\n  proposalId?: string;\n  actor: { kind: \"human\" | \"agent\"; id?: string; name?: string };\n  ts: number;\n}\n\nexport interface TemplateBuilderProps {\n  \/** The fancy-template envelope. `undefined` starts an empty template. *\/\n  value: TemplateEnvelope | Record<string, unknown> | undefined;\n  \/** Always the full next envelope, compiled. *\/\n  onChange(template: TemplateEnvelope): void;\n  fields?: FieldDef[];\n  lists?: ListDef[];\n  kinds?: BlockKind[];\n  pickImage?: BuilderContextValue[\"pickImage\"];\n  renderPreview?: (template: TemplateEnvelope, data: JsonObject) => Promise<PdfPageSource>;\n  renderDraft?: (document: JsonObject) => ReactNode;\n  \/** A real record to preview with; else each field's sample. *\/\n  previewData?: JsonObject;\n  previewMode?: PreviewMode;\n  onPreviewModeChange?: (mode: PreviewMode) => void;\n  \/** Staged agent edits (from the `tpl_*` bridge). Only a person accepts them. *\/\n  pending?: readonly Proposal<BuilderOp>[];\n  \/** Called after the builder applied an accepted proposal and emitted onChange. *\/\n  onAccept?: (proposal: Proposal<BuilderOp>) => void;\n  \/**\n   * Whether Accept applies the op here. @default true. Pass `false` when the\n   * proposals come from `registerTemplateBridge`: call `bridge.confirm(p.id)` in\n   * `onAccept`, and the bridge writes through its adapter, so it lands once.\n   *\/\n  applyOnAccept?: boolean;\n  onReject?: (proposal: Proposal<BuilderOp>) => void;\n  onActivity?: (activity: TemplateActivity) => void;\n  \/** Controlled selection (the selected block id). *\/\n  selected?: string | null;\n  onSelectedChange?: (id: string | null) => void;\n  readOnly?: boolean;\n  \/** Stable surface id, on the root as `data-ftb-builder` and on every activity. *\/\n  surfaceId?: string;\n  className?: string;\n}\n\nconst EMPTY_TEMPLATE = { fancyTemplate: 1, writer: \"fine-print\", variables: {}, document: { blocks: [] } };\n\n\/**\n * The document builder: block list, settings, preview. Controlled: `value` is\n * one fancy-template envelope and every change emits the next one, compiled.\n *\/\nexport function TemplateBuilder({\n  value,\n  onChange,\n  fields = [],\n  lists = [],\n  kinds = [],\n  pickImage,\n  renderPreview,\n  renderDraft,\n  previewData,\n  previewMode,\n  onPreviewModeChange,\n  pending = [],\n  onAccept,\n  applyOnAccept = true,\n  onReject,\n  onActivity,\n  selected: selectedProp,\n  onSelectedChange,\n  readOnly = false,\n  surfaceId = \"template-builder\",\n  className,\n}: TemplateBuilderProps) {\n  const ctx = useMemo(() => ({ kinds, fields, lists }), [kinds, fields, lists]);\n  const opened = useMemo(() => openTemplate(value ?? EMPTY_TEMPLATE, ctx), [value, ctx]);\n  const [driftChoice, setDriftChoice] = useState<null | \"builder\" | \"document\">(null);\n  const drifting = opened.drift && driftChoice === null;\n  const state: EditorState = opened.drift && driftChoice === \"document\" && opened.fromDocument ? opened.fromDocument : opened.state;\n  const compiled = useMemo(() => compile(state, ctx), [state, ctx]);\n\n  const [selectedLocal, setSelectedLocal] = useState<string | null>(null);\n  const selected = selectedProp !== undefined ? selectedProp : selectedLocal;\n  const select = useCallback(\n    (id: string | null) => {\n      setSelectedLocal(id);\n      onSelectedChange?.(id);\n    },\n    [onSelectedChange],\n  );\n\n  const undo = useRef<BuilderOp[][]>([]);\n  const redo = useRef<BuilderOp[][]>([]);\n  const [, bump] = useState(0);\n\n  const emit = useCallback(\n    (next: EditorState) => onChange(compile(next, ctx).template),\n    [onChange, ctx],\n  );\n\n  const activity = useCallback(\n    (a: Omit<TemplateActivity, \"surface\" | \"ts\" | \"actor\"> & { actor?: TemplateActivity[\"actor\"] }) =>\n      onActivity?.({ surface: surfaceId, ts: Date.now(), actor: a.actor ?? { kind: \"human\" }, ...a }),\n    [onActivity, surfaceId],\n  );\n\n  const run = useCallback(\n    (op: BuilderOp, record = true): string | null => {\n      if (readOnly) return \"The builder is read-only.\";\n      if (drifting) return \"Choose which version to keep first.\";\n      const reason = checkOp(state, op, kinds);\n      if (reason) return reason;\n      const inverse = invertOp(state, op);\n      const next = applyOp(state, op, kinds);\n      if (record) {\n        undo.current.push(inverse);\n        redo.current = [];\n        bump((n) => n + 1);\n      }\n      emit(next);\n      return null;\n    },\n    [readOnly, drifting, state, kinds, emit],\n  );\n\n  const dispatch = useCallback(\n    (op: BuilderOp) => {\n      const reason = run(op);\n      if (!reason) activity({ type: \"op\", op });\n      return reason;\n    },\n    [run, activity],\n  );\n\n  const replay = (from: typeof undo, to: typeof undo, type: \"undo\" | \"redo\") => {\n    const ops = from.current.pop();\n    if (!ops) return;\n    let s = state;\n    const back: BuilderOp[] = [];\n    for (const op of ops) {\n      back.unshift(...invertOp(s, op));\n      s = applyOp(s, op, kinds);\n    }\n    to.current.push(back);\n    bump((n) => n + 1);\n    emit(s);\n    activity({ type });\n  };\n\n  const fieldOptions = useCallback(\n    (nodeId: string | null): FieldOption[] => {\n      const out: FieldOption[] = fields.map((f) => ({ token: f.token, label: f.label, group: \"Fields\", type: f.type }));\n      const node = nodeId ? state.tree.nodes[nodeId] : undefined;\n      const group = node?.type === \"repeat\" ? node : node?.parent ? state.tree.nodes[node.parent] : undefined;\n      if (group?.type === \"repeat\") {\n        const list = lists.find((l) => l.token === (group.props as unknown as RepeatProps).list);\n        if (list) {\n          out.unshift(\n            ...list.itemFields.map((f) => ({ token: `${ITEM_ALIAS}.${f.token}`, label: `${list.label}: ${f.label}`, group: \"Each item\", type: f.type })),\n          );\n        }\n      }\n      return out;\n    },\n    [fields, lists, state],\n  );\n\n  const labelOf = useCallback(\n    (token: string) => {\n      const f = fields.find((x) => x.token === token);\n      if (f) return f.label;\n      if (token.startsWith(`${ITEM_ALIAS}.`)) {\n        const rel = token.slice(ITEM_ALIAS.length + 1);\n        for (const l of lists) {\n          const it = l.itemFields.find((x) => x.token === rel);\n          if (it) return `${l.label}: ${it.label}`;\n        }\n      }\n      return lists.find((l) => l.token === token)?.label ?? token;\n    },\n    [fields, lists],\n  );\n\n  const problemsByNode = useMemo(() => {\n    const m = new Map<string, Problem[]>();\n    for (const p of compiled.problems) if (p.node) m.set(p.node, [...(m.get(p.node) ?? []), p]);\n    return m;\n  }, [compiled.problems]);\n  const looseProblems = compiled.problems.filter((p) => !p.node);\n\n  const contextValue: BuilderContextValue = {\n    state,\n    dispatch,\n    kinds,\n    fields,\n    lists,\n    fieldOptions,\n    labelOf,\n    problemsFor: (id) => problemsByNode.get(id) ?? [],\n    selected,\n    select,\n    readOnly: readOnly || drifting,\n    pickImage,\n  };\n\n  const data = useMemo(() => previewData ?? sampleData(fields, lists), [previewData, fields, lists]);\n\n  return (\n    <BuilderContext.Provider value={contextValue}>\n      <div className={className} data-ftb-builder={surfaceId} data-read-only={readOnly ? \"\" : undefined}>\n        {drifting && (\n          <Callout color=\"amber\" className=\"mb-3\" data-ftb-drift=\"\">\n            <div className=\"flex flex-col gap-2\">\n              <span>\n                This template&apos;s document was changed outside the builder after it was last saved, so the two no longer match. Choose which to keep.\n              <\/span>\n              <div className=\"flex gap-2\">\n                <Button\n                  type=\"button\"\n                  size=\"sm\"\n                  data-ftb-drift-keep=\"document\"\n                  onClick={() => {\n                    setDriftChoice(\"document\");\n                    if (opened.fromDocument) emit(opened.fromDocument);\n                    activity({ type: \"resolve-drift\" });\n                  }}\n                >\n                  Keep the document\n                <\/Button>\n                <Button\n                  type=\"button\"\n                  size=\"sm\"\n                  variant=\"ghost\"\n                  data-ftb-drift-keep=\"builder\"\n                  onClick={() => {\n                    setDriftChoice(\"builder\");\n                    emit(opened.state);\n                    activity({ type: \"resolve-drift\" });\n                  }}\n                >\n                  Keep the builder&apos;s version\n                <\/Button>\n              <\/div>\n            <\/div>\n          <\/Callout>\n        )}\n        {opened.notices\n          .filter((n) => !n.startsWith(\"The document was edited\"))\n          .map((n) => (\n            <Callout key={n} color=\"blue\" className=\"mb-3\" data-ftb-notice=\"\">\n              {n}\n            <\/Callout>\n          ))}\n        {looseProblems.length > 0 && (\n          <Callout color=\"red\" className=\"mb-3\" data-ftb-problems=\"\">\n            {looseProblems.map((p) => p.message).join(\" \")}\n          <\/Callout>\n        )}\n        <div className=\"mb-2 flex gap-2\">\n          <Button type=\"button\" size=\"xs\" variant=\"ghost\" icon=\"undo-2\" disabled={readOnly || undo.current.length === 0} data-ftb-undo=\"\" onClick={() => replay(undo, redo, \"undo\")}>\n            Undo\n          <\/Button>\n          <Button type=\"button\" size=\"xs\" variant=\"ghost\" icon=\"redo-2\" disabled={readOnly || redo.current.length === 0} data-ftb-redo=\"\" onClick={() => replay(redo, undo, \"redo\")}>\n            Redo\n          <\/Button>\n        <\/div>\n        <PendingChanges\n          className=\"mb-3\"\n          pending={pending}\n          onAccept={(p) => {\n            if (applyOnAccept) {\n              const reason = run(p.op);\n              if (reason) return;\n            }\n            activity({ type: \"accept\", op: p.op, proposalId: p.id, actor: p.actor ?? { kind: \"agent\" } });\n            onAccept?.(p);\n          }}\n          onReject={(p) => {\n            activity({ type: \"reject\", op: p.op, proposalId: p.id });\n            onReject?.(p);\n          }}\n        \/>\n        <ResizablePanels defaultValue={30} min={20} max={50} label=\"Resize the block list\">\n          <BlockList className=\"p-1\" \/>\n          <ResizablePanels defaultValue={50} min={25} max={75} label=\"Resize the settings\">\n            <div className=\"p-1\">\n              <Tabs defaultTab=\"block\">\n                <Tabs.List>\n                  <Tabs.Tab value=\"block\">Block<\/Tabs.Tab>\n                  <Tabs.Tab value=\"page\">Page<\/Tabs.Tab>\n                <\/Tabs.List>\n                <Tabs.Panels>\n                  <Tabs.Panel value=\"block\">\n                    <BlockSettings \/>\n                  <\/Tabs.Panel>\n                  <Tabs.Panel value=\"page\">\n                    <PageSettings \/>\n                  <\/Tabs.Panel>\n                <\/Tabs.Panels>\n              <\/Tabs>\n            <\/div>\n            <TemplatePreview\n              className=\"m-1\"\n              template={compiled.template}\n              data={data}\n              renderPreview={renderPreview}\n              renderDraft={renderDraft}\n              mode={previewMode}\n              onModeChange={onPreviewModeChange}\n            \/>\n          <\/ResizablePanels>\n        <\/ResizablePanels>\n      <\/div>\n    <\/BuilderContext.Provider>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/TemplateBuilder.tsx"},{"path":"components\/fancy\/template-builder\/context.ts","content":"import { createContext, useContext } from \"react\";\nimport type { BlockKind, BuilderOp, EditorState, FieldDef, ListDef, Problem } from \".\/core\/types\";\n\nexport interface FieldOption {\n  token: string;\n  label: string;\n  \/** \"Item\" fields inside a repeat, else the host's own. *\/\n  group: string;\n  type?: FieldDef[\"type\"];\n}\n\nexport interface BuilderContextValue {\n  state: EditorState;\n  \/** Apply one op. Returns the refusal reason, or null when it applied. *\/\n  dispatch(op: BuilderOp): string | null;\n  kinds: readonly BlockKind[];\n  fields: readonly FieldDef[];\n  lists: readonly ListDef[];\n  \/** Field options for a block (item fields included inside a repeat). *\/\n  fieldOptions(nodeId: string | null): FieldOption[];\n  labelOf(token: string): string;\n  problemsFor(nodeId: string): Problem[];\n  selected: string | null;\n  select(id: string | null): void;\n  readOnly: boolean;\n  pickImage?: () => Promise<{ dataUrl: string; widthPx?: number; heightPx?: number; name?: string } | null>;\n}\n\nexport const BuilderContext = createContext<BuilderContextValue | null>(null);\n\nexport function useBuilder(): BuilderContextValue {\n  const ctx = useContext(BuilderContext);\n  if (!ctx) throw new Error(\"fancy-template-ui parts must be rendered inside <TemplateBuilder> (or a BuilderContext provider).\");\n  return ctx;\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/context.ts"},{"path":"components\/fancy\/template-builder\/BlockList.tsx","content":"import { useState } from \"react\";\nimport { Badge, Button, Callout, Card, Dropdown, ReorderableGrid, Text } from \"@particle-academy\/react-fancy\";\nimport { childrenOf } from \"@particle-academy\/fancy-doc-commons\";\nimport { useBuilder } from \".\/context\";\nimport { hostBlock, hostType, kindOf, makeNode, orderAt } from \".\/core\/model\";\nimport { checkOp } from \".\/core\/ops\";\nimport type { BuilderNode, HeadingProps, RepeatProps, TextProps } from \".\/core\/types\";\n\nexport const BUILTIN_LABELS: Record<string, string> = {\n  heading: \"Heading\",\n  text: \"Text\",\n  image: \"Image\",\n  table: \"Table\",\n  divider: \"Divider\",\n  spacer: \"Spacer\",\n  pageBreak: \"Page break\",\n  repeat: \"Repeating section\",\n  raw: \"Kept as written\",\n};\n\n\/** Default props for a new built-in block. *\/\nexport function defaultsFor(type: string): Record<string, unknown> {\n  switch (type) {\n    case \"heading\":\n      return { level: 2, runs: [{ text: \"Heading\" }] };\n    case \"text\":\n      return { paras: [{ type: \"paragraph\", runs: [{ text: \"\" }] }] };\n    case \"image\":\n      return { widthPx: 160 };\n    case \"table\":\n      return { header: true, rows: [[[{ text: \"Item\" }], [{ text: \"Amount\" }]], [[{ text: \"\" }], [{ text: \"\" }]]] };\n    case \"divider\":\n      return {};\n    case \"spacer\":\n      return { height: 18 };\n    case \"repeat\":\n      return { list: \"\", pageEach: false };\n    default:\n      return {};\n  }\n}\n\nfunction summary(node: BuilderNode, labelOf: (t: string) => string): string {\n  const runsText = (runs: Array<{ text?: string; field?: string }>) =>\n    runs.map((r) => (r.field !== undefined ? `[${labelOf(r.field)}]` : r.text ?? \"\")).join(\"\").slice(0, 60);\n  switch (node.type) {\n    case \"heading\":\n      return runsText((node.props as unknown as HeadingProps).runs ?? []);\n    case \"text\": {\n      const first = (node.props as unknown as TextProps).paras?.[0];\n      if (!first) return \"\";\n      return runsText(first.type === \"list\" ? first.items[0] ?? [] : first.runs);\n    }\n    case \"repeat\": {\n      const p = node.props as unknown as RepeatProps;\n      return p.list ? `per ${labelOf(p.list)}${p.pageEach ? \", a page each\" : \"\"}` : \"no list chosen\";\n    }\n    default:\n      return \"\";\n  }\n}\n\ninterface AddMenuProps {\n  parent: string | null;\n}\n\nfunction AddMenu({ parent }: AddMenuProps) {\n  const { state, dispatch, kinds, readOnly, select } = useBuilder();\n  const [refusal, setRefusal] = useState<string | null>(null);\n  const builtins = [\"heading\", \"text\", \"image\", \"table\", \"divider\", \"spacer\", \"pageBreak\", ...(parent === null ? [\"repeat\"] : [])];\n  const add = (type: string) => {\n    const kind = type.startsWith(\"host:\") ? kinds.find((k) => hostType(k.kind) === type) : undefined;\n    const block = kind ? hostBlock(kind) : { type, props: defaultsFor(type) };\n    const node = makeNode(state, block, { parent });\n    const reason = dispatch({ t: \"insert\", node });\n    setRefusal(reason);\n    if (!reason) select(node.id);\n  };\n  const isAvailable = (type: string) => {\n    const probe = makeNode(state, { type, props: {} }, { parent });\n    return checkOp(state, { t: \"insert\", node: probe }, kinds) === null;\n  };\n  return (\n    <div data-ftb-add-menu={parent ?? \"root\"}>\n      <Dropdown>\n        <Dropdown.Trigger>\n          <Button type=\"button\" size=\"sm\" icon=\"plus\" disabled={readOnly} data-ftb-add-trigger={parent ?? \"root\"}>\n            {parent ? \"Add to section\" : \"Add block\"}\n          <\/Button>\n        <\/Dropdown.Trigger>\n        <Dropdown.Items>\n          {builtins.map((t) => (\n            <Dropdown.Item key={t} onClick={() => add(t)}>\n              <span data-ftb-add={t}>{BUILTIN_LABELS[t]}<\/span>\n            <\/Dropdown.Item>\n          ))}\n          {kinds\n            .filter((k) => isAvailable(hostType(k.kind)))\n            .map((k) => (\n              <Dropdown.Item key={k.kind} onClick={() => add(hostType(k.kind))}>\n                <span data-ftb-add={hostType(k.kind)}>{k.label}<\/span>\n              <\/Dropdown.Item>\n            ))}\n        <\/Dropdown.Items>\n      <\/Dropdown>\n      {refusal && (\n        <Callout color=\"amber\" className=\"mt-2\" data-ftb-refusal=\"\">\n          {refusal}\n        <\/Callout>\n      )}\n    <\/div>\n  );\n}\n\nfunction BlockRow({ node, handleProps }: { node: BuilderNode; handleProps?: Record<string, string> }) {\n  const builder = useBuilder();\n  const { state, dispatch, kinds, selected, select, labelOf, problemsFor, readOnly } = builder;\n  const kind = kindOf(node, kinds);\n  const label = kind?.label ?? (node.type.startsWith(\"host:\") ? `${node.type.slice(5)} (not registered)` : BUILTIN_LABELS[node.type] ?? node.type);\n  const removal = checkOp(state, { t: \"remove\", id: node.id }, kinds);\n  const problems = problemsFor(node.id);\n  const isSelected = selected === node.id;\n  const [refusal, setRefusal] = useState<string | null>(null);\n  return (\n    <Card\n      variant={isSelected ? \"elevated\" : \"outlined\"}\n      padding=\"sm\"\n      highlight={isSelected}\n      data-ftb-block={node.id}\n      data-ftb-type={node.type}\n      data-selected={isSelected ? \"\" : undefined}\n    >\n      <div className=\"flex items-center gap-2\">\n        <span {...handleProps} className=\"cursor-grab select-none px-1 text-[color:var(--fancy-text-muted,var(--color-zinc-500))]\" aria-hidden=\"true\">\n          \u22ee\u22ee\n        <\/span>\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"min-w-0 flex-1 justify-start text-left\"\n          data-ftb-select={node.id}\n          onClick={() => select(node.id)}\n        >\n          <span className=\"font-medium\">{label}<\/span>\n          <Text as=\"span\" size=\"xs\" color=\"muted\" className=\"ml-2 truncate\">\n            {summary(node, labelOf)}\n          <\/Text>\n        <\/Button>\n        {kind?.required === \"once\" && <Badge size=\"sm\" color=\"blue\">Required<\/Badge>}\n        {node.type === \"raw\" && <Badge size=\"sm\" color=\"zinc\">Read-only<\/Badge>}\n        {problems.length > 0 && (\n          <Badge size=\"sm\" color=\"red\" data-ftb-problem={node.id} title={problems.map((p) => p.message).join(\"\\n\")}>\n            {problems.length} problem{problems.length > 1 ? \"s\" : \"\"}\n          <\/Badge>\n        )}\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          icon=\"trash-2\"\n          aria-label={`Remove ${label}`}\n          title={removal ?? `Remove ${label}`}\n          disabled={readOnly || removal !== null}\n          data-ftb-remove={node.id}\n          onClick={() => {\n            const reason = dispatch({ t: \"remove\", id: node.id });\n            setRefusal(reason);\n            if (!reason && isSelected) select(null);\n          }}\n        \/>\n      <\/div>\n      {refusal && <Callout color=\"amber\" className=\"mt-2\">{refusal}<\/Callout>}\n      {node.type === \"repeat\" && (\n        <div className=\"mt-2 border-l-2 border-[color:var(--fancy-border,var(--color-zinc-200))] pl-3 dark:border-[color:var(--fancy-border-dark,var(--color-zinc-700))]\">\n          <BlockGrid parent={node.id} \/>\n          <div className=\"mt-2\">\n            <AddMenu parent={node.id} \/>\n          <\/div>\n        <\/div>\n      )}\n    <\/Card>\n  );\n}\n\n\/** The single id whose removal makes the two orders equal: the block that moved. *\/\nexport function movedId(before: string[], after: string[]): string | null {\n  if (before.length !== after.length || before.join(\"\\u0000\") === after.join(\"\\u0000\")) return null;\n  for (const id of before) {\n    const a = before.filter((x) => x !== id).join(\"\\u0000\");\n    const b = after.filter((x) => x !== id).join(\"\\u0000\");\n    if (a === b) return id;\n  }\n  return null;\n}\n\nfunction BlockGrid({ parent }: { parent: string | null }) {\n  const { state, dispatch, readOnly, labelOf } = useBuilder();\n  const nodes = childrenOf(state.tree, parent);\n  if (nodes.length === 0) {\n    return (\n      <Text size=\"sm\" color=\"muted\" data-ftb-empty={parent ?? \"root\"}>\n        {parent ? \"Nothing repeats yet. Add the blocks each item gets.\" : \"No blocks yet.\"}\n      <\/Text>\n    );\n  }\n  return (\n    <ReorderableGrid\n      columns={1}\n      gap=\"sm\"\n      items={nodes}\n      value={nodes.map((n) => n.id)}\n      disabled={readOnly}\n      label={parent ? \"Blocks in this section\" : \"Blocks\"}\n      getItemLabel={(n) => `${BUILTIN_LABELS[n.type] ?? n.type} ${summary(n, labelOf)}`.trim()}\n      data-ftb-list={parent ?? \"root\"}\n      onReorder={(ids) => {\n        \/\/ One move op for the block whose position changed.\n        const moved = movedId(nodes.map((n) => n.id), ids);\n        if (!moved) return;\n        const target = ids.indexOf(moved);\n        dispatch({ t: \"move\", id: moved, parent, order: orderAt(state, parent, target, moved) });\n      }}\n      renderItem={(n, s) => <BlockRow node={n} handleProps={s.handleProps as Record<string, string> | undefined} \/>}\n    \/>\n  );\n}\n\nexport interface BlockListProps {\n  className?: string;\n}\n\n\/** The block list: add, drag (pointer or keyboard) to reorder, remove. *\/\nexport function BlockList({ className }: BlockListProps) {\n  return (\n    <div className={className} data-ftb-block-list=\"\">\n      <BlockGrid parent={null} \/>\n      <div className=\"mt-3\">\n        <AddMenu parent={null} \/>\n      <\/div>\n    <\/div>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/BlockList.tsx"},{"path":"components\/fancy\/template-builder\/BlockSettings.tsx","content":"import { useCallback, type ComponentType, type ReactNode } from \"react\";\nimport { Button, Callout, Card, ColorPicker, Input, NumberField, Select, Switch, Text } from \"@particle-academy\/react-fancy\";\nimport { useBuilder, type FieldOption } from \".\/context\";\nimport { RichTextField } from \".\/RichTextField\";\nimport { htmlToParas, htmlToRuns, parasToHtml, runsToHtml } from \".\/runs-html\";\nimport { BUILTIN_LABELS } from \".\/BlockList\";\nimport { kindOf } from \".\/core\/model\";\nimport type { BlockStyle, BuilderNode, DividerProps, FieldDef, HeadingProps, ImageProps, JsonObject, RepeatProps, RichRun, SpacerProps, TableProps, TextProps } from \".\/core\/types\";\n\nconst ALIGN_OPTIONS = [\n  { value: \"\", label: \"Default\" },\n  { value: \"left\", label: \"Left\" },\n  { value: \"center\", label: \"Centre\" },\n  { value: \"right\", label: \"Right\" },\n  { value: \"justify\", label: \"Justify\" },\n];\n\nfunction num(v: number | null): number | undefined {\n  return v === null || Number.isNaN(v) ? undefined : v;\n}\n\nfunction StyleControls({ node, allowed }: { node: BuilderNode; allowed: Array<keyof BlockStyle> }) {\n  const { dispatch, readOnly } = useBuilder();\n  const s = node.style ?? {};\n  const set = (patch: BlockStyle) => dispatch({ t: \"set_style\", id: node.id, patch });\n  if (allowed.length === 0) return null;\n  return (\n    <div className=\"grid grid-cols-2 gap-3\" data-ftb-style={node.id}>\n      {allowed.includes(\"align\") && (\n        <Select\n          label=\"Alignment\"\n          list={ALIGN_OPTIONS}\n          value={s.align ?? \"\"}\n          disabled={readOnly}\n          data-ftb-style-align=\"\"\n          onValueChange={(v) => set({ align: (v || undefined) as BlockStyle[\"align\"] })}\n        \/>\n      )}\n      {allowed.includes(\"size\") && (\n        <NumberField label=\"Size (pt)\" min={4} max={96} step={0.5} value={s.size ?? null} disabled={readOnly} onValueChange={(v) => set({ size: num(v) })} \/>\n      )}\n      {allowed.includes(\"color\") && (\n        <div className=\"flex items-end gap-2\">\n          <ColorPicker\n            label=\"Colour\"\n            value={s.color && s.color !== \"accent\" ? s.color : \"\"}\n            disabled={readOnly}\n            onChange={(c) => set({ color: c || undefined })}\n          \/>\n          <Button type=\"button\" size=\"xs\" variant=\"ghost\" disabled={readOnly} onClick={() => set({ color: \"accent\" })}>\n            Use accent\n          <\/Button>\n        <\/div>\n      )}\n      {allowed.includes(\"spaceBefore\") && (\n        <NumberField label=\"Space before (pt)\" min={0} max={200} value={s.spaceBefore ?? null} disabled={readOnly} onValueChange={(v) => set({ spaceBefore: num(v) })} \/>\n      )}\n      {allowed.includes(\"spaceAfter\") && (\n        <NumberField label=\"Space after (pt)\" min={0} max={200} value={s.spaceAfter ?? null} disabled={readOnly} onValueChange={(v) => set({ spaceAfter: num(v) })} \/>\n      )}\n    <\/div>\n  );\n}\n\nconst ALL_STYLE: Array<keyof BlockStyle> = [\"align\", \"size\", \"color\", \"spaceBefore\", \"spaceAfter\"];\n\nfunction useRunsCanon() {\n  const { labelOf } = useBuilder();\n  const paraCanon = useCallback((html: string) => parasToHtml(htmlToParas(html), labelOf), [labelOf]);\n  const runCanon = useCallback((html: string) => runsToHtml(htmlToRuns(html), labelOf), [labelOf]);\n  return { paraCanon, runCanon };\n}\n\nfunction textFields(options: FieldOption[]): FieldOption[] {\n  return options.filter((o) => o.type !== \"image\");\n}\n\nfunction HeadingSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, fieldOptions, labelOf, readOnly } = useBuilder();\n  const { runCanon } = useRunsCanon();\n  const p = node.props as unknown as HeadingProps;\n  return (\n    <>\n      <Select\n        label=\"Level\"\n        list={[1, 2, 3, 4, 5, 6].map((l) => ({ value: String(l), label: `Heading ${l}` }))}\n        value={String(p.level)}\n        disabled={readOnly}\n        onValueChange={(v) => dispatch({ t: \"set_props\", id: node.id, patch: { level: Number(v) } })}\n      \/>\n      <RichTextField\n        handle={`${node.id}:runs`}\n        html={runsToHtml(p.runs ?? [], labelOf)}\n        canonical={runCanon}\n        options={textFields(fieldOptions(node.id))}\n        disabled={readOnly}\n        maxHeight={90}\n        onHtmlChange={(html) => dispatch({ t: \"set_props\", id: node.id, patch: { runs: htmlToRuns(html) } })}\n      \/>\n    <\/>\n  );\n}\n\nfunction TextSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, fieldOptions, labelOf, readOnly } = useBuilder();\n  const { paraCanon } = useRunsCanon();\n  const p = node.props as unknown as TextProps;\n  return (\n    <RichTextField\n      handle={`${node.id}:paras`}\n      html={parasToHtml(p.paras ?? [], labelOf)}\n      canonical={paraCanon}\n      options={textFields(fieldOptions(node.id))}\n      lists\n      disabled={readOnly}\n      placeholder=\"Write here. Use Insert field for data.\"\n      onHtmlChange={(html) => dispatch({ t: \"set_props\", id: node.id, patch: { paras: htmlToParas(html) } })}\n    \/>\n  );\n}\n\nfunction ImageSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, fieldOptions, readOnly, pickImage } = useBuilder();\n  const p = node.props as unknown as ImageProps;\n  const images = fieldOptions(node.id).filter((o) => o.type === \"image\");\n  const set = (patch: Partial<ImageProps>) => dispatch({ t: \"set_props\", id: node.id, patch: patch as Record<string, unknown> });\n  return (\n    <>\n      <div className=\"flex flex-wrap items-end gap-2\">\n        {pickImage && (\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            icon=\"image\"\n            disabled={readOnly}\n            data-ftb-pick-image={node.id}\n            onClick={async () => {\n              const picked = await pickImage();\n              if (!picked) return;\n              if (!\/^data:image\\\/(png|jpe?g);base64,\/.test(picked.dataUrl)) return;\n              set({ src: picked.dataUrl, field: undefined, widthPx: picked.widthPx ?? p.widthPx, heightPx: picked.heightPx, name: picked.name });\n            }}\n          >\n            {p.src ? \"Replace picture\" : \"Choose picture\"}\n          <\/Button>\n        )}\n        {images.length > 0 && (\n          <Select\n            label=\"Or from data\"\n            placeholder=\"A fixed picture\"\n            list={[{ value: \"\", label: \"A fixed picture\" }, ...images.map((o) => ({ value: o.token, label: o.label }))]}\n            value={p.field ?? \"\"}\n            disabled={readOnly}\n            onValueChange={(v) => set(v ? { field: v, src: undefined } : { field: undefined })}\n          \/>\n        )}\n      <\/div>\n      {p.name && !p.field && <Text size=\"xs\" color=\"muted\">{p.name}<\/Text>}\n      <div className=\"grid grid-cols-2 gap-3\">\n        <NumberField label=\"Width (px)\" min={1} max={2000} value={p.widthPx ?? null} disabled={readOnly} onValueChange={(v) => set({ widthPx: num(v) })} \/>\n        <NumberField label=\"Height (px)\" min={1} max={2000} value={p.heightPx ?? null} disabled={readOnly} onValueChange={(v) => set({ heightPx: num(v) })} \/>\n      <\/div>\n      <Input label=\"Alt text\" value={p.alt ?? \"\"} disabled={readOnly} onValueChange={(v) => set({ alt: v || undefined })} \/>\n      <Text size=\"xs\" color=\"muted\">PNG or JPEG. Images are placed at the left; the writer has no image alignment.<\/Text>\n    <\/>\n  );\n}\n\nfunction TableSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, fieldOptions, labelOf, readOnly } = useBuilder();\n  const { runCanon } = useRunsCanon();\n  const p = node.props as unknown as TableProps;\n  const rows = p.rows ?? [];\n  const cols = Math.max(1, ...rows.map((r) => r.length));\n  const set = (patch: Partial<TableProps>) => dispatch({ t: \"set_props\", id: node.id, patch: patch as Record<string, unknown> });\n  const setCell = (r: number, c: number, runs: RichRun[]) => set({ rows: rows.map((row, i) => (i === r ? row.map((cell, j) => (j === c ? runs : cell)) : row)) });\n  const options = textFields(fieldOptions(node.id));\n  return (\n    <>\n      <Switch label=\"First row is a header\" checked={!!p.header} disabled={readOnly} onCheckedChange={(v) => set({ header: v })} \/>\n      <div className=\"flex flex-col gap-2\" data-ftb-table={node.id}>\n        {rows.map((row, r) => (\n          <div key={r} className=\"grid gap-2\" style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}>\n            {row.map((cell, c) => (\n              <RichTextField\n                key={c}\n                handle={`${node.id}:cell:${r}:${c}`}\n                html={runsToHtml(cell, labelOf)}\n                canonical={runCanon}\n                options={options}\n                disabled={readOnly}\n                maxHeight={80}\n                onHtmlChange={(html) => setCell(r, c, htmlToRuns(html))}\n              \/>\n            ))}\n          <\/div>\n        ))}\n      <\/div>\n      <div className=\"flex flex-wrap gap-2\">\n        <Button type=\"button\" size=\"xs\" disabled={readOnly} data-ftb-table-add-row={node.id} onClick={() => set({ rows: [...rows, Array.from({ length: cols }, () => [])] })}>Add row<\/Button>\n        <Button type=\"button\" size=\"xs\" disabled={readOnly || rows.length <= 1} onClick={() => set({ rows: rows.slice(0, -1) })}>Remove last row<\/Button>\n        <Button type=\"button\" size=\"xs\" disabled={readOnly} data-ftb-table-add-col={node.id} onClick={() => set({ rows: rows.map((row) => [...row, []]), widths: undefined })}>Add column<\/Button>\n        <Button type=\"button\" size=\"xs\" disabled={readOnly || cols <= 1} onClick={() => set({ rows: rows.map((row) => row.slice(0, -1)), widths: undefined })}>Remove last column<\/Button>\n      <\/div>\n    <\/>\n  );\n}\n\nfunction DividerSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, readOnly } = useBuilder();\n  const p = node.props as unknown as DividerProps;\n  const set = (patch: Partial<DividerProps>) => dispatch({ t: \"set_props\", id: node.id, patch: patch as Record<string, unknown> });\n  return (\n    <div className=\"grid grid-cols-2 gap-3\">\n      <NumberField label=\"Weight (pt)\" min={0.25} max={12} step={0.25} value={p.weight ?? 0.75} disabled={readOnly} onValueChange={(v) => set({ weight: num(v) })} \/>\n      <ColorPicker label=\"Colour (default: accent)\" value={p.color ?? \"\"} disabled={readOnly} onChange={(c) => set({ color: c || undefined })} \/>\n    <\/div>\n  );\n}\n\nfunction SpacerSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, readOnly } = useBuilder();\n  const p = node.props as unknown as SpacerProps;\n  return (\n    <NumberField label=\"Height (pt)\" min={0} max={400} value={p.height} disabled={readOnly} onValueChange={(v) => dispatch({ t: \"set_props\", id: node.id, patch: { height: num(v) ?? 0 } })} \/>\n  );\n}\n\nfunction RepeatSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, lists, readOnly } = useBuilder();\n  const p = node.props as unknown as RepeatProps;\n  return (\n    <>\n      <Select\n        label=\"Repeat for each\"\n        placeholder=\"Choose a list\"\n        list={lists.map((l) => ({ value: l.token, label: l.label }))}\n        value={p.list}\n        disabled={readOnly}\n        data-ftb-repeat-list={node.id}\n        onValueChange={(v) => dispatch({ t: \"set_props\", id: node.id, patch: { list: v } })}\n      \/>\n      <Switch\n        label=\"Start each item on a new page\"\n        checked={p.pageEach}\n        disabled={readOnly}\n        data-ftb-repeat-page-each={node.id}\n        onCheckedChange={(v) => dispatch({ t: \"set_props\", id: node.id, patch: { pageEach: v } })}\n      \/>\n      <Text size=\"xs\" color=\"muted\">Inside this section, Insert field also offers each item&apos;s fields.<\/Text>\n    <\/>\n  );\n}\n\n\/** Props a host kind's Settings component receives. *\/\nexport interface KindSettingsProps<P extends JsonObject = JsonObject> {\n  value: P;\n  onChange(props: P): void;\n  fields: FieldDef[];\n  disabled?: boolean;\n}\n\nfunction HostSettings({ node }: { node: BuilderNode }) {\n  const { dispatch, kinds, fields, readOnly } = useBuilder();\n  const kind = kindOf(node, kinds);\n  if (!kind) {\n    return (\n      <Callout color=\"amber\">\n        This block&apos;s kind is not registered here, so it is locked. It keeps its settings and prints exactly as it was last saved.\n      <\/Callout>\n    );\n  }\n  const Settings = kind.Settings as ComponentType<KindSettingsProps> | undefined;\n  return (\n    <div data-ftb-settings={kind.kind}>\n      {Settings ? (\n        <Settings\n          value={node.props as JsonObject}\n          fields={[...fields]}\n          disabled={readOnly}\n          onChange={(next) => {\n            \/\/ Replace the props whole: keys the panel dropped are cleared.\n            const patch: Record<string, unknown> = { ...next };\n            for (const k of Object.keys(node.props)) if (!Object.hasOwn(next, k)) patch[k] = undefined;\n            dispatch({ t: \"set_props\", id: node.id, patch });\n          }}\n        \/>\n      ) : (\n        <Text size=\"sm\" color=\"muted\">{kind.label} has no settings.<\/Text>\n      )}\n    <\/div>\n  );\n}\n\nexport interface BlockSettingsProps {\n  className?: string;\n}\n\n\/** Settings for the selected block, wrapped in a react-fancy Card. *\/\nexport function BlockSettings({ className }: BlockSettingsProps) {\n  const { state, selected, kinds, problemsFor } = useBuilder();\n  const node = selected ? state.tree.nodes[selected] : undefined;\n  if (!node) {\n    return (\n      <Card className={className} padding=\"md\" data-ftb-settings-empty=\"\">\n        <Text size=\"sm\" color=\"muted\">Select a block to change it.<\/Text>\n      <\/Card>\n    );\n  }\n  const kind = kindOf(node, kinds);\n  const label = kind?.label ?? BUILTIN_LABELS[node.type] ?? node.type;\n  const problems = problemsFor(node.id);\n  let body: ReactNode = null;\n  let style: Array<keyof BlockStyle> = [];\n  switch (node.type) {\n    case \"heading\":\n      body = <HeadingSettings node={node} \/>;\n      style = ALL_STYLE;\n      break;\n    case \"text\":\n      body = <TextSettings node={node} \/>;\n      style = ALL_STYLE;\n      break;\n    case \"image\":\n      body = <ImageSettings node={node} \/>;\n      break;\n    case \"table\":\n      body = <TableSettings node={node} \/>;\n      style = [\"size\", \"color\"];\n      break;\n    case \"divider\":\n      body = <DividerSettings node={node} \/>;\n      style = [\"spaceBefore\", \"spaceAfter\"];\n      break;\n    case \"spacer\":\n      body = <SpacerSettings node={node} \/>;\n      break;\n    case \"pageBreak\":\n      body = <Text size=\"sm\" color=\"muted\">Everything after this starts on a new page.<\/Text>;\n      break;\n    case \"repeat\":\n      body = <RepeatSettings node={node} \/>;\n      break;\n    case \"raw\":\n      body = (\n        <Callout color=\"zinc\">\n          This part of the template was written outside the builder and has no matching block. It is kept exactly as written and prints unchanged.\n        <\/Callout>\n      );\n      break;\n    default:\n      body = <HostSettings node={node} \/>;\n      style = kind?.styleable ?? [];\n  }\n  return (\n    <Card className={className} padding=\"md\" data-ftb-block-settings={node.id}>\n      <Card.Header>\n        <span className=\"font-semibold\">{label}<\/span>\n      <\/Card.Header>\n      <Card.Body>\n        <div className=\"flex flex-col gap-3\">\n          {problems.map((p, i) => (\n            <Callout key={i} color=\"red\" data-ftb-problem-detail={node.id}>\n              {p.message}\n            <\/Callout>\n          ))}\n          {body}\n          <StyleControls node={node} allowed={style} \/>\n        <\/div>\n      <\/Card.Body>\n    <\/Card>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/BlockSettings.tsx"},{"path":"components\/fancy\/template-builder\/PageSettings.tsx","content":"import { useCallback } from \"react\";\nimport { Card, ColorPicker, NumberField, Select, Switch, Text } from \"@particle-academy\/react-fancy\";\nimport { useBuilder, type FieldOption } from \".\/context\";\nimport { RichTextField } from \".\/RichTextField\";\nimport { bandToHtml, htmlToBand, PAGE_TOKEN, PAGES_TOKEN } from \".\/runs-html\";\nimport type { Band, Page } from \".\/core\/types\";\n\nconst PAGE_LABELS = { page: \"Page number\", pages: \"Page count\" };\nconst PAGE_CHIPS: FieldOption[] = [\n  { token: PAGE_TOKEN, label: PAGE_LABELS.page, group: \"Page\" },\n  { token: PAGES_TOKEN, label: PAGE_LABELS.pages, group: \"Page\" },\n];\n\ntype BandKey = \"header\" | \"footer\" | \"firstHeader\" | \"firstFooter\";\n\nfunction BandEditor({ which, title }: { which: BandKey; title: string }) {\n  const { state, dispatch, fieldOptions, labelOf, readOnly } = useBuilder();\n  const band = state.page[which] ?? {};\n  const options = fieldOptions(null).filter((o) => o.type !== \"image\");\n  const canon = useCallback(\n    (html: string) => bandToHtml(htmlToBand(html), labelOf, PAGE_LABELS),\n    [labelOf],\n  );\n  const setSlot = (slot: keyof Band, html: string) => {\n    const next: Band = { ...band, [slot]: htmlToBand(html) };\n    for (const k of [\"left\", \"center\", \"right\"] as const) if (!next[k]) delete next[k];\n    dispatch({ t: \"set_page\", patch: { [which]: Object.keys(next).length ? next : undefined } });\n  };\n  return (\n    <div data-ftb-band={which}>\n      <Text size=\"sm\" weight=\"medium\">{title}<\/Text>\n      <div className=\"mt-1 grid grid-cols-3 gap-2\">\n        {([\"left\", \"center\", \"right\"] as const).map((slot) => (\n          <RichTextField\n            key={slot}\n            handle={`band:${which}:${slot}`}\n            html={bandToHtml(band[slot], labelOf, PAGE_LABELS)}\n            canonical={canon}\n            options={options}\n            extra={PAGE_CHIPS}\n            disabled={readOnly}\n            maxHeight={60}\n            placeholder={slot === \"left\" ? \"Left\" : slot === \"center\" ? \"Centre\" : \"Right\"}\n            onHtmlChange={(html) => setSlot(slot, html)}\n          \/>\n        ))}\n      <\/div>\n    <\/div>\n  );\n}\n\nexport interface PageSettingsProps {\n  className?: string;\n}\n\n\/** Paper, margins, accent colour, and the header and footer bands (a letterhead). *\/\nexport function PageSettings({ className }: PageSettingsProps) {\n  const { state, dispatch, readOnly } = useBuilder();\n  const page = state.page;\n  const set = (patch: Partial<Page>) => dispatch({ t: \"set_page\", patch });\n  const firstDifferent = page.firstHeader !== undefined || page.firstFooter !== undefined;\n  return (\n    <Card className={className} padding=\"md\" data-ftb-page=\"\">\n      <Card.Header>\n        <span className=\"font-semibold\">Page<\/span>\n      <\/Card.Header>\n      <Card.Body>\n        <div className=\"flex flex-col gap-3\">\n          <div className=\"grid grid-cols-2 gap-3\">\n            <Select\n              label=\"Paper\"\n              list={[\n                { value: \"letter\", label: \"Letter\" },\n                { value: \"a4\", label: \"A4\" },\n                { value: \"legal\", label: \"Legal\" },\n              ]}\n              value={page.size}\n              disabled={readOnly}\n              data-ftb-page-size=\"\"\n              onValueChange={(v) => set({ size: v as Page[\"size\"] })}\n            \/>\n            <Select\n              label=\"Orientation\"\n              list={[\n                { value: \"portrait\", label: \"Portrait\" },\n                { value: \"landscape\", label: \"Landscape\" },\n              ]}\n              value={page.orientation}\n              disabled={readOnly}\n              onValueChange={(v) => set({ orientation: v as Page[\"orientation\"] })}\n            \/>\n          <\/div>\n          <div className=\"grid grid-cols-4 gap-2\">\n            {([\"top\", \"right\", \"bottom\", \"left\"] as const).map((side) => (\n              <NumberField\n                key={side}\n                label={`${side[0]!.toUpperCase()}${side.slice(1)} (pt)`}\n                min={0}\n                max={300}\n                value={page.margins[side]}\n                disabled={readOnly}\n                onValueChange={(v) => set({ margins: { ...page.margins, [side]: v ?? 0 } })}\n              \/>\n            ))}\n          <\/div>\n          <ColorPicker label=\"Accent colour\" value={page.accent} disabled={readOnly} onChange={(c) => \/^#[0-9A-Fa-f]{6}$\/.test(c) && set({ accent: c })} \/>\n          <BandEditor which=\"header\" title=\"Header\" \/>\n          <BandEditor which=\"footer\" title=\"Footer\" \/>\n          <Switch\n            label=\"Different first page\"\n            checked={firstDifferent}\n            disabled={readOnly}\n            onCheckedChange={(on) =>\n              set(on ? { firstHeader: page.header ?? {}, firstFooter: page.footer ?? {} } : { firstHeader: undefined, firstFooter: undefined })\n            }\n          \/>\n          {firstDifferent && (\n            <>\n              <BandEditor which=\"firstHeader\" title=\"First page header\" \/>\n              <BandEditor which=\"firstFooter\" title=\"First page footer\" \/>\n            <\/>\n          )}\n        <\/div>\n      <\/Card.Body>\n    <\/Card>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/PageSettings.tsx"},{"path":"components\/fancy\/template-builder\/PendingChanges.tsx","content":"import { Badge, Button, Card, Text } from \"@particle-academy\/react-fancy\";\nimport type { Proposal } from \"@particle-academy\/fancy-doc-commons\";\nimport { useBuilder } from \".\/context\";\nimport { checkOp } from \".\/core\/ops\";\nimport type { BuilderOp } from \".\/core\/types\";\n\nexport interface PendingChangesProps {\n  pending: readonly Proposal<BuilderOp>[];\n  onAccept(proposal: Proposal<BuilderOp>): void;\n  onReject(proposal: Proposal<BuilderOp>): void;\n  className?: string;\n}\n\nfunction describe(op: BuilderOp): string {\n  switch (op.t) {\n    case \"insert\":\n      return `Add a ${op.node.type.replace(\/^host:\/, \"\")} block`;\n    case \"remove\":\n      return \"Remove a block\";\n    case \"move\":\n      return \"Move a block\";\n    case \"set_props\":\n      return `Change a block (${Object.keys(op.patch).join(\", \")})`;\n    case \"set_style\":\n      return `Restyle a block (${Object.keys(op.patch).join(\", \")})`;\n    case \"set_page\":\n      return `Change the page (${Object.keys(op.patch).join(\", \")})`;\n  }\n}\n\n\/**\n * Agent edits waiting for a person. Only a person accepts: nothing here is\n * reachable by the bridge, which stages and never confirms.\n *\/\nexport function PendingChanges({ pending, onAccept, onReject, className }: PendingChangesProps) {\n  const { state, kinds, readOnly } = useBuilder();\n  if (pending.length === 0) return null;\n  return (\n    <Card className={className} padding=\"md\" data-ftb-pending-list=\"\">\n      <Card.Header>\n        <span className=\"font-semibold\">Suggested changes<\/span> <Badge size=\"sm\" color=\"blue\">{pending.length}<\/Badge>\n      <\/Card.Header>\n      <Card.Body>\n        <ul className=\"flex flex-col gap-2\">\n          {pending.map((p) => {\n            const blocked = checkOp(state, p.op, kinds);\n            return (\n              <li key={p.id} data-ftb-pending={p.id} className=\"flex flex-wrap items-center gap-2\">\n                <div className=\"min-w-0 flex-1\">\n                  <Text size=\"sm\">{p.label ?? describe(p.op)}<\/Text>\n                  {p.actor?.name && <Text size=\"xs\" color=\"muted\">from {p.actor.name}<\/Text>}\n                  {blocked && <Text size=\"xs\" color=\"danger\">{blocked}<\/Text>}\n                <\/div>\n                <Button type=\"button\" size=\"xs\" color=\"green\" disabled={readOnly || blocked !== null} data-ftb-accept={p.id} onClick={() => onAccept(p)}>\n                  Accept\n                <\/Button>\n                <Button type=\"button\" size=\"xs\" variant=\"ghost\" data-ftb-reject={p.id} onClick={() => onReject(p)}>\n                  Reject\n                <\/Button>\n              <\/li>\n            );\n          })}\n        <\/ul>\n      <\/Card.Body>\n    <\/Card>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/PendingChanges.tsx"},{"path":"components\/fancy\/template-builder\/TemplatePreview.tsx","content":"import { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { Badge, Callout, Card, PdfViewer, Tabs, Text, type PdfPageSource } from \"@particle-academy\/react-fancy\";\nimport { render, validateData } from \"@particle-academy\/fancy-template\";\nimport type { JsonObject, TemplateEnvelope } from \".\/core\/types\";\n\nexport type PreviewMode = \"exact\" | \"draft\";\n\nexport interface TemplatePreviewProps {\n  template: TemplateEnvelope;\n  data: JsonObject;\n  \/**\n   * EXACT mode: the host renders with `Template::render` + fine-print\n   * `Agent::toBytes()` and serves page images (fine-print's `PageImages`).\n   * Those pages ARE fine-print's, so the preview is page for page.\n   *\/\n  renderPreview?: (template: TemplateEnvelope, data: JsonObject) => Promise<PdfPageSource>;\n  \/**\n   * DRAFT mode: draws the rendered document in the browser, e.g. last-word-ui's\n   * `<DocViewer document={doc} \/>`. Fast, but its page breaks may differ.\n   *\/\n  renderDraft?: (document: JsonObject) => ReactNode;\n  mode?: PreviewMode;\n  defaultMode?: PreviewMode;\n  onModeChange?: (mode: PreviewMode) => void;\n  \/** Debounce before asking the host for exact pages. @default 600 *\/\n  debounceMs?: number;\n  className?: string;\n}\n\n\/** The paged preview: exact (host pages) by default when available, draft labelled as approximate. *\/\nexport function TemplatePreview({\n  template,\n  data,\n  renderPreview,\n  renderDraft,\n  mode: modeProp,\n  defaultMode,\n  onModeChange,\n  debounceMs = 600,\n  className,\n}: TemplatePreviewProps) {\n  const available: PreviewMode[] = [...(renderPreview ? ([\"exact\"] as const) : []), ...(renderDraft ? ([\"draft\"] as const) : [])];\n  const [modeLocal, setModeLocal] = useState<PreviewMode>(defaultMode ?? available[0] ?? \"exact\");\n  const mode = modeProp ?? (available.includes(modeLocal) ? modeLocal : available[0] ?? \"exact\");\n  const setMode = (m: PreviewMode) => {\n    setModeLocal(m);\n    onModeChange?.(m);\n  };\n\n  const dataErrors = useMemo(() => validateData(template, data), [template, data]);\n  const draft = useMemo(() => {\n    if (mode !== \"draft\" || dataErrors.length) return null;\n    try {\n      return { doc: render(template, data) as JsonObject, error: null as string | null };\n    } catch (e) {\n      return { doc: null, error: (e as Error).message };\n    }\n  }, [mode, template, data, dataErrors]);\n\n  \/\/ Exact: debounce, keep the previous pages until new ones arrive.\n  const [pages, setPages] = useState<PdfPageSource | null>(null);\n  const [exactError, setExactError] = useState<string | null>(null);\n  const [busy, setBusy] = useState(false);\n  const seq = useRef(0);\n  useEffect(() => {\n    if (mode !== \"exact\" || !renderPreview || dataErrors.length) return;\n    const mine = ++seq.current;\n    const timer = setTimeout(() => {\n      setBusy(true);\n      renderPreview(template, data).then(\n        (src) => {\n          if (mine !== seq.current) return;\n          setPages(src);\n          setExactError(null);\n          setBusy(false);\n        },\n        (e: unknown) => {\n          if (mine !== seq.current) return;\n          setExactError(e instanceof Error ? e.message : String(e));\n          setBusy(false);\n        },\n      );\n    }, debounceMs);\n    return () => clearTimeout(timer);\n  }, [mode, renderPreview, template, data, dataErrors, debounceMs]);\n\n  let body: ReactNode;\n  if (available.length === 0) {\n    body = <Text size=\"sm\" color=\"muted\">No preview: the host supplies neither renderPreview nor renderDraft.<\/Text>;\n  } else if (dataErrors.length) {\n    body = (\n      <Callout color=\"amber\" data-ftb-preview-data-errors=\"\">\n        The preview data does not fit the template: {dataErrors.map((e) => `${e.code} at ${e.path || \"(root)\"}`).join(\", \")}.\n      <\/Callout>\n    );\n  } else if (mode === \"exact\") {\n    body = (\n      <>\n        {exactError && <Callout color=\"red\" data-ftb-preview-error=\"\">{exactError}<\/Callout>}\n        {pages ? <PdfViewer pages={pages} \/> : <Text size=\"sm\" color=\"muted\">Rendering the pages...<\/Text>}\n      <\/>\n    );\n  } else {\n    body = draft?.error ? (\n      <Callout color=\"red\" data-ftb-preview-error=\"\">{draft.error}<\/Callout>\n    ) : draft?.doc && renderDraft ? (\n      renderDraft(draft.doc)\n    ) : null;\n  }\n\n  return (\n    <Card className={className} padding=\"md\" data-ftb-preview=\"\" data-mode={mode} data-busy={busy ? \"\" : undefined}>\n      <Card.Header>\n        <div className=\"flex items-center gap-2\">\n          <span className=\"font-semibold\">Preview<\/span>\n          {available.length > 1 ? (\n            <Tabs activeTab={mode} onTabChange={(t) => setMode(t as PreviewMode)}>\n              <Tabs.List>\n                <Tabs.Tab value=\"exact\">Exact<\/Tabs.Tab>\n                <Tabs.Tab value=\"draft\">Draft view<\/Tabs.Tab>\n              <\/Tabs.List>\n            <\/Tabs>\n          ) : null}\n          {mode === \"draft\" && (\n            <Badge size=\"sm\" color=\"amber\" data-ftb-draft-warning=\"\">\n              Draft view: page breaks may differ\n            <\/Badge>\n          )}\n        <\/div>\n      <\/Card.Header>\n      <Card.Body>{body}<\/Card.Body>\n    <\/Card>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/TemplatePreview.tsx"},{"path":"components\/fancy\/template-builder\/samples.ts","content":"import { isSafePath } from \".\/core\/safe\";\nimport type { FieldDef, Json, JsonObject, ListDef } from \".\/core\/types\";\n\n\/** A 1x1 PNG (the same bytes the goldens validate through fine-print), the stand-in for an image field with no sample. *\/\nexport const PLACEHOLDER_PNG =\n  \"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\";\n\nfunction stand(def: FieldDef): Json {\n  if (def.sample !== undefined) return def.sample;\n  switch (def.type) {\n    case \"image\":\n      return PLACEHOLDER_PNG;\n    case \"number\":\n    case \"integer\":\n      return 0;\n    case \"boolean\":\n      return true;\n    case \"date\":\n      return \"2026-01-01\";\n    default:\n      return `[${def.label}]`;\n  }\n}\n\nfunction setPath(target: JsonObject, path: string, value: Json): void {\n  \/\/ Refuses __proto__, constructor and prototype in any segment (CodeQL\n  \/\/ js\/prototype-polluting-assignment): a field token is the host's data.\n  if (!isSafePath(path)) return;\n  const segs = path.split(\".\");\n  let cur = target;\n  for (let i = 0; i < segs.length - 1; i++) {\n    const s = segs[i]!;\n    \/\/ Checked again at the assignment itself, so the guard is visible where\n    \/\/ the write happens (isSafePath above already refuses these).\n    if (s === \"__proto__\" || s === \"constructor\" || s === \"prototype\") return;\n    if (!Object.hasOwn(cur, s) || typeof cur[s] !== \"object\" || cur[s] === null || Array.isArray(cur[s])) cur[s] = {};\n    cur = cur[s] as JsonObject;\n  }\n  const last = segs[segs.length - 1]!;\n  if (last === \"__proto__\" || last === \"constructor\" || last === \"prototype\") return;\n  cur[last] = value;\n}\n\n\/** Preview data built from every field's and list's sample (plan section 7.4). *\/\nexport function sampleData(fields: readonly FieldDef[], lists: readonly ListDef[]): JsonObject {\n  const data: JsonObject = {};\n  for (const f of fields) setPath(data, f.token, stand(f));\n  for (const l of lists) {\n    if (l.sample) {\n      setPath(data, l.token, l.sample);\n      continue;\n    }\n    const item: JsonObject = {};\n    for (const f of l.itemFields) setPath(item, f.token, stand(f));\n    setPath(data, l.token, [item, { ...item }]);\n  }\n  return data;\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/samples.ts"},{"path":"components\/fancy\/template-builder\/core\/compile.ts","content":"\/**\n * Source model to fancy-template envelope (plan section 5.3). `document` is\n * regenerated from the tree on every change, so a server never needs the\n * builder to render; `editor` carries the tree so the builder can reopen it.\n *\n * Field tokens are written only where the fine-print profile allows them: run\n * text, band slots, image `src` (a whole token) and `alt`. Literal `{{` typed by\n * a person is escaped, so text a person types never becomes a token.\n *\/\nimport { inspect } from \"@particle-academy\/fancy-template\";\nimport { childrenOf, roots } from \"@particle-academy\/fancy-doc-commons\";\nimport { HOST_PREFIX, kindOf } from \".\/model\";\nimport { validateSchema } from \".\/schema\";\nimport { isSafePath, setOwn } from \".\/safe\";\nimport type {\n  Band,\n  BandPart,\n  BlockKind,\n  BlockStyle,\n  BuilderNode,\n  CompileContext,\n  DividerProps,\n  EditorState,\n  FieldDef,\n  HeadingProps,\n  ImageProps,\n  Json,\n  JsonObject,\n  ListDef,\n  Page,\n  Problem,\n  RepeatProps,\n  RichRun,\n  SpacerProps,\n  TableProps,\n  TemplateEnvelope,\n  TextProps,\n} from \".\/types\";\n\nexport const ITEM_ALIAS = \"item\";\n\nexport function fieldToken(token: string): string {\n  return `{{ ${token} }}`;\n}\n\n\/** Literal text: every `{{` becomes the string-literal token that renders it. *\/\nexport function escapeText(text: string): string {\n  return text.replace(\/\\{\\{\/g, '{{ \"{{\" }}');\n}\n\nexport interface CompileResult {\n  template: TemplateEnvelope;\n  problems: Problem[];\n}\n\ninterface Scope {\n  \/** The repeat's list, when compiling inside one. *\/\n  list?: ListDef;\n}\n\nclass Compiler {\n  readonly problems: Problem[] = [];\n  \/** Host fields used, by token. *\/\n  readonly usedFields = new Map<string, FieldDef>();\n  \/** Lists used, by token, with the item fields used. *\/\n  readonly usedLists = new Map<string, { list: ListDef; items: Map<string, FieldDef> }>();\n  private readonly fields: Map<string, FieldDef>;\n  private readonly lists: Map<string, ListDef>;\n  private readonly declared: JsonObject;\n  readonly caches = new Map<string, Json[]>();\n\n  constructor(\n    private readonly state: EditorState,\n    private readonly ctx: CompileContext,\n  ) {\n    \/\/ A token that is not a plain dotted name (or names a prototype key) is\n    \/\/ never offered, so it can never reach a declaration path.\n    this.fields = new Map((ctx.fields ?? []).filter((f) => isSafePath(f.token)).map((f) => [f.token, f]));\n    this.lists = new Map(\n      (ctx.lists ?? [])\n        .filter((l) => isSafePath(l.token) && !l.token.includes(\".\"))\n        .map((l) => [l.token, { ...l, itemFields: l.itemFields.filter((f) => isSafePath(f.token)) }]),\n    );\n    this.declared = state.variables ?? {};\n  }\n\n  get accent(): string {\n    return this.state.page.accent;\n  }\n\n  private color(c: string | undefined): string | undefined {\n    return c === \"accent\" ? this.accent : c;\n  }\n\n  \/** The token text for a field chip, or null (with a problem) when it is not offered. *\/\n  token(field: string, scope: Scope, node?: string): string | null {\n    if (!isSafePath(field)) {\n      this.problems.push({ code: \"FIELD_UNKNOWN\", message: `\"${field}\" is not a field name.`, ...(node ? { node } : {}) });\n      return null;\n    }\n    if (scope.list && field.startsWith(`${ITEM_ALIAS}.`)) {\n      const rel = field.slice(ITEM_ALIAS.length + 1);\n      const def = scope.list.itemFields.find((f) => f.token === rel);\n      if (def) {\n        this.usedLists.get(scope.list.token)!.items.set(rel, def);\n        return fieldToken(field);\n      }\n    }\n    const def = this.fields.get(field);\n    if (def) {\n      this.usedFields.set(field, def);\n      return fieldToken(field);\n    }\n    if (this.isDeclared(field)) return fieldToken(field);\n    this.problems.push({ code: \"FIELD_UNKNOWN\", message: `The field \"${field}\" is not one the host offers.`, ...(node ? { node } : {}) });\n    return null;\n  }\n\n  \/** A path the kept (imported) declarations already cover. *\/\n  private isDeclared(path: string): boolean {\n    if (!isSafePath(path)) return false;\n    const [head, ...rest] = path.split(\".\");\n    if (!Object.hasOwn(this.declared, head!)) return false;\n    let decl = this.declared[head!] as JsonObject | undefined;\n    for (const seg of rest) {\n      if (!decl || decl.type !== \"object\") return false;\n      const props = decl.properties as JsonObject | undefined;\n      decl = props && Object.hasOwn(props, seg) ? (props[seg] as JsonObject) : undefined;\n    }\n    return decl !== undefined;\n  }\n\n  runs(runs: RichRun[], style: BlockStyle | undefined, scope: Scope, node: string, defaultColor?: string): JsonObject[] {\n    const out: JsonObject[] = [];\n    const color = this.color(style?.color) ?? defaultColor;\n    for (const r of runs) {\n      let text: string;\n      if (r.field !== undefined) {\n        const t = this.token(r.field, scope, node);\n        if (t === null) continue;\n        text = t;\n      } else {\n        text = escapeText(r.text ?? \"\");\n      }\n      const run: JsonObject = { text };\n      if (r.bold) run.bold = true;\n      if (r.italic) run.italic = true;\n      if (r.underline) run.underline = true;\n      if (style?.size !== undefined) run.size = style.size;\n      if (color !== undefined) run.color = color;\n      out.push(run);\n    }\n    return out;\n  }\n\n  private paraStyle(block: JsonObject, style: BlockStyle | undefined): JsonObject {\n    if (style?.align) block.align = style.align;\n    if (style?.spaceBefore !== undefined) block.spaceBefore = style.spaceBefore;\n    if (style?.spaceAfter !== undefined) block.spaceAfter = style.spaceAfter;\n    return block;\n  }\n\n  block(node: BuilderNode, scope: Scope): Json[] {\n    const p = node.props;\n    const style = node.style;\n    switch (node.type) {\n      case \"heading\": {\n        const h = p as unknown as HeadingProps;\n        const b: JsonObject = { type: \"heading\", level: h.level };\n        this.paraStyle(b, style);\n        b.runs = this.runs(h.runs ?? [], style, scope, node.id, this.accent);\n        return [b];\n      }\n      case \"text\": {\n        const t = p as unknown as TextProps;\n        return (t.paras ?? []).map((para) => {\n          if (para.type === \"list\") {\n            const b: JsonObject = { type: \"list\" };\n            if (para.ordered) b.ordered = true;\n            b.items = para.items.map((item) => ({ runs: this.runs(item, style, scope, node.id) }));\n            return b;\n          }\n          const b: JsonObject = { type: \"paragraph\" };\n          this.paraStyle(b, style);\n          b.runs = this.runs(para.runs, style, scope, node.id);\n          return b;\n        });\n      }\n      case \"image\": {\n        const im = p as unknown as ImageProps;\n        let src: string | null = null;\n        if (im.field) src = this.token(im.field, scope, node.id);\n        else if (im.src) src = im.src;\n        if (src === null) {\n          if (!im.field) this.problems.push({ code: \"IMAGE_EMPTY\", message: \"This image has no picture yet.\", node: node.id });\n          return [];\n        }\n        const b: JsonObject = { type: \"image\", src };\n        if (im.widthPx !== undefined) b.widthPx = im.widthPx;\n        if (im.heightPx !== undefined) b.heightPx = im.heightPx;\n        if (im.alt !== undefined) b.alt = escapeText(im.alt);\n        return [b];\n      }\n      case \"table\": {\n        const t = p as unknown as TableProps;\n        const b: JsonObject = { type: \"table\" };\n        if (t.widths && t.widths.length) b.widths = t.widths;\n        b.rows = (t.rows ?? []).map((row, r) => {\n          const out: JsonObject = {};\n          if (r === 0 && t.header) out.header = true;\n          out.cells = row.map((cell) => ({\n            blocks: [{ type: \"paragraph\", runs: this.runs(cell, style, scope, node.id) }],\n          }));\n          return out;\n        });\n        return [b];\n      }\n      case \"divider\": {\n        const d = p as unknown as DividerProps;\n        return [\n          {\n            type: \"paragraph\",\n            runs: [],\n            spaceBefore: style?.spaceBefore ?? 0,\n            spaceAfter: style?.spaceAfter ?? 8,\n            borders: { bottom: { style: \"single\", width: d.weight ?? 0.75, color: this.color(d.color) ?? this.accent } },\n          },\n        ];\n      }\n      case \"spacer\": {\n        const sp = p as unknown as SpacerProps;\n        return [{ type: \"paragraph\", runs: [], spaceBefore: 0, spaceAfter: sp.height }];\n      }\n      case \"pageBreak\":\n        return [{ type: \"pageBreak\" }];\n      case \"raw\":\n        return [structuredClone((p as { block: Json }).block)];\n      case \"repeat\":\n        return this.repeat(node);\n      default:\n        if (node.type.startsWith(HOST_PREFIX)) return this.host(node, scope);\n        this.problems.push({ code: \"KIND_UNKNOWN\", message: `Unknown block type \"${node.type}\".`, node: node.id });\n        return [];\n    }\n  }\n\n  \/** A list from the host, else one synthesised from a kept (imported) array declaration. *\/\n  private listFor(token: string): ListDef | undefined {\n    const host = this.lists.get(token);\n    if (host) return host;\n    const decl = Object.hasOwn(this.declared, token) ? (this.declared[token] as JsonObject) : undefined;\n    const items = decl?.type === \"array\" ? (decl.items as JsonObject | undefined) : undefined;\n    if (!items || items.type !== \"object\") return undefined;\n    const props = (items.properties ?? {}) as JsonObject;\n    const list: ListDef = {\n      label: token,\n      token,\n      itemFields: Object.keys(props).map((k) => ({ label: k, token: k })),\n    };\n    this.keptLists.add(token);\n    return list;\n  }\n\n  \/** Lists whose declaration was kept from an import, so it is never rewritten. *\/\n  readonly keptLists = new Set<string>();\n\n  private repeat(node: BuilderNode): Json[] {\n    const rp = node.props as unknown as RepeatProps;\n    const list = this.listFor(rp.list);\n    if (!list) {\n      this.problems.push({ code: \"LIST_UNKNOWN\", message: `The list \"${rp.list}\" is not one the host offers.`, node: node.id });\n      return [];\n    }\n    if (!this.usedLists.has(list.token)) this.usedLists.set(list.token, { list, items: new Map() });\n    const value: Json[] = [];\n    if (rp.pageEach) value.push({ $if: \"!$first\", type: \"pageBreak\" });\n    for (const child of childrenOf(this.state.tree, node.id)) value.push(...this.block(child, { list }));\n    return [{ $each: list.token, $as: ITEM_ALIAS, $spread: true, $value: value }];\n  }\n\n  private host(node: BuilderNode, scope: Scope): Json[] {\n    const kind = kindOf(node, this.ctx.kinds);\n    const cached = node.cache ?? [];\n    if (!kind) {\n      this.problems.push({\n        code: \"KIND_UNKNOWN\",\n        message: `\"${node.type.slice(HOST_PREFIX.length)}\" is not registered here. It is kept, locked, exactly as last compiled.`,\n        node: node.id,\n      });\n      return structuredClone(cached);\n    }\n    const errors = validateSchema(node.props, kind.schema);\n    if (errors.length > 0) {\n      this.problems.push({ code: \"KIND_PROPS\", message: `${kind.label}: ${errors[0]}`, node: node.id });\n      return structuredClone(cached);\n    }\n    let out: Json[];\n    try {\n      out = kind.render(node.props as JsonObject, {\n        page: this.state.page,\n        accent: this.accent,\n        fieldToken: (t: string) => this.token(t, scope, node.id) ?? \"\",\n      });\n      if (!Array.isArray(out)) throw new Error(\"render must return an array of blocks\");\n      out = JSON.parse(JSON.stringify(out)) as Json[];\n    } catch (e) {\n      this.problems.push({ code: \"KIND_RENDER\", message: `${kind.label}: ${(e as Error).message}`, node: node.id });\n      return structuredClone(cached);\n    }\n    this.caches.set(node.id, out);\n    return out;\n  }\n\n  bandSlot(parts: BandPart[] | undefined): string | undefined {\n    if (!parts || parts.length === 0) return undefined;\n    let s = \"\";\n    for (const part of parts) {\n      if (\"field\" in part) s += this.token(part.field, {}) ?? \"\";\n      else if (\"page\" in part) s += part.page === \"pages\" ? \"{pages}\" : \"{page}\";\n      else s += escapeText(part.text);\n    }\n    return s === \"\" ? undefined : s;\n  }\n\n  band(b: Band | undefined): JsonObject | undefined {\n    if (!b) return undefined;\n    const out: JsonObject = {};\n    for (const slot of [\"left\", \"center\", \"right\"] as const) {\n      const v = this.bandSlot(b[slot]);\n      if (v !== undefined) out[slot] = v;\n    }\n    return Object.keys(out).length ? out : undefined;\n  }\n\n  page(page: Page): JsonObject {\n    const implicit = new Set(page.implicit ?? []);\n    const out: JsonObject = {};\n    if (!implicit.has(\"size\")) out.size = page.size;\n    if (!implicit.has(\"orientation\")) out.orientation = page.orientation;\n    if (!implicit.has(\"margins\")) out.margins = { ...page.margins };\n    for (const key of [\"header\", \"footer\", \"firstHeader\", \"firstFooter\"] as const) {\n      const b = this.band(page[key]);\n      if (b) out[key] = b;\n    }\n    return { ...out, ...(page.extra ?? {}) };\n  }\n\n  variables(): JsonObject {\n    const out: JsonObject = structuredClone(this.state.variables ?? {});\n    for (const [token, def] of this.usedFields) {\n      const path = token.split(\".\");\n      let target = out;\n      for (let i = 0; i < path.length - 1; i++) {\n        const seg = path[i]!;\n        let decl = Object.hasOwn(target, seg) ? (target[seg] as JsonObject) : undefined;\n        if (!decl || decl.type !== \"object\") {\n          if (decl) {\n            this.problems.push({ code: \"VARIABLE_CONFLICT\", message: `\"${seg}\" is both a field and a group of fields.` });\n          }\n          decl = { type: \"object\", required: true, properties: {} };\n          target[seg] = decl;\n        }\n        target = decl.properties as JsonObject;\n      }\n      target[path[path.length - 1]!] = declaration(def);\n    }\n    for (const [token, { list, items }] of this.usedLists) {\n      if (this.keptLists.has(token)) continue;\n      const properties: JsonObject = {};\n      for (const [rel, def] of items) properties[rel] = declaration(def);\n      const decl: JsonObject = { type: \"array\", required: true, description: list.label };\n      if (list.sample !== undefined) decl.example = list.sample as Json;\n      if (list.maxItems !== undefined) decl.maxItems = list.maxItems;\n      decl.items = { type: \"object\", properties };\n      out[token] = decl;\n    }\n    return out;\n  }\n}\n\nfunction declaration(def: FieldDef): JsonObject {\n  const type = def.type ?? \"string\";\n  const required = def.required ?? true;\n  const d: JsonObject = { type, required };\n  if (def.label) d.description = def.description ?? def.label;\n  if (def.maxLength !== undefined) d.maxLength = def.maxLength;\n  if (def.sample !== undefined) d.example = def.sample;\n  \/\/ An absent optional string renders as empty rather than failing the render.\n  if (!required && type === \"string\") d.default = \"\";\n  return d;\n}\n\n\/** Compile the source model to a fancy-template envelope, with every problem found. *\/\nexport function compile(state: EditorState, ctx: CompileContext = {}): CompileResult {\n  const c = new Compiler(state, ctx);\n  const blocks: Json[] = [];\n  const owners: Array<{ id: string; children?: string[] }> = [];\n  for (const node of roots(state.tree)) {\n    const out = c.block(node, {});\n    const children = node.type === \"repeat\" ? childrenOf(state.tree, node.id).map((n) => n.id) : undefined;\n    for (const b of out) {\n      blocks.push(b);\n      owners.push(children ? { id: node.id, children } : { id: node.id });\n    }\n  }\n  const page = c.page(state.page);\n  const variables = c.variables();\n\n  \/\/ Document: keep the imported key order; page and blocks sit where they were.\n  const document: JsonObject = {};\n  const extra = state.docExtra ?? {};\n  let placedPage = false;\n  let placedBlocks = false;\n  for (const [k, v] of Object.entries(extra)) {\n    if (k === \"page\") {\n      if (Object.keys(page).length) document.page = page;\n      placedPage = true;\n    } else if (k === \"blocks\") {\n      document.blocks = blocks;\n      placedBlocks = true;\n    } else {\n      setOwn(document, k, v);\n    }\n  }\n  if (!placedPage && Object.keys(page).length) document.page = page;\n  if (!placedBlocks) {\n    if (placedPage) document.blocks = blocks;\n    else {\n      \/\/ Page before blocks when neither was placed by an imported order.\n      delete document.blocks;\n      document.blocks = blocks;\n    }\n  }\n\n  \/\/ The editor source, with each host block's last good output cached on it.\n  const nodes = { ...state.tree.nodes };\n  for (const [id, cache] of c.caches) nodes[id] = { ...nodes[id]!, cache };\n  const editor: EditorState = { ...state, tree: { nodes } };\n\n  const template: TemplateEnvelope = { fancyTemplate: 1, writer: \"fine-print\", variables } as TemplateEnvelope;\n  if (state.description !== undefined) template.description = state.description;\n  template.editor = editor;\n  template.document = document;\n\n  \/\/ The backstop: everything the builder writes must pass inspect.\n  const problems = [...c.problems];\n  for (const issue of inspect(template).issues) {\n    const m = \/^\\\/document\\\/blocks\\\/(\\d+)(?:\\\/\\$value\\\/(\\d+))?\/.exec(issue.path);\n    let node: string | undefined;\n    if (m) {\n      const owner = owners[Number(m[1])];\n      node = owner?.id;\n      if (owner?.children && m[2] !== undefined) {\n        \/\/ $value[0] is the guarded page break when the group has a page each.\n        const group = state.tree.nodes[owner.id]!.props as unknown as RepeatProps;\n        const idx = Number(m[2]) - (group.pageEach ? 1 : 0);\n        node = owner.children[idx] ?? owner.id;\n      }\n    }\n    problems.push({ code: \"TEMPLATE\", message: `${issue.code} at ${issue.path}`, path: issue.path, ...(node ? { node } : {}) });\n  }\n  return { template, problems };\n}\n\nexport type { BlockKind };\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/compile.ts"},{"path":"components\/fancy\/template-builder\/core\/open.ts","content":"\/**\n * Opening a template (plan section 5.2).\n *\n * - With an `editor` key: the builder's own source. If `document` was edited\n *   outside the builder since, `drift` is true and BOTH versions are returned;\n *   the caller asks the person. Never silently picks one.\n * - Without one (hand- or agent-written): `document` is imported into built-in\n *   blocks. A block is mapped only when compiling the mapped block reproduces it\n *   EXACTLY; anything else becomes a read-only raw block holding it verbatim, so\n *   opening and saving never loses or changes data.\n *\/\nimport { compile, escapeText, ITEM_ALIAS } from \".\/compile\";\nimport { setOwn } from \".\/safe\";\nimport { addBlock, defaultPage, emptyState, ensureRequired, groupBlocks, orderedBlocks, type NewBlock } from \".\/model\";\nimport type {\n  Band,\n  BandPart,\n  BlockStyle,\n  CompileContext,\n  EditorState,\n  Json,\n  JsonObject,\n  Page,\n  RichRun,\n  TextPara,\n} from \".\/types\";\n\nexport interface OpenResult {\n  \/** The state to edit: the builder's source when present, else the import. *\/\n  state: EditorState;\n  \/** True when `document` no longer matches what `editor` compiles to. *\/\n  drift: boolean;\n  \/** On drift: the document imported as a state, for \"keep the document\". *\/\n  fromDocument?: EditorState;\n  \/** Things the person should be told (a required block was added, ...). *\/\n  notices: string[];\n}\n\nfunction isObj(v: unknown): v is JsonObject {\n  return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n\/** Canonical JSON with sorted keys: equality of content, not of key order. *\/\nfunction canonical(v: unknown): string {\n  if (Array.isArray(v)) return `[${v.map(canonical).join(\",\")}]`;\n  if (isObj(v)) {\n    return `{${Object.keys(v)\n      .sort()\n      .map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)\n      .join(\",\")}}`;\n  }\n  return JSON.stringify(v);\n}\n\nconst WHOLE_TOKEN = \/^\\{\\{ ([A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*) \\}\\}$\/;\nconst ESCAPED_OPEN = '{{ \"{{\" }}';\n\nfunction unescapeText(s: string): string | null {\n  const plain = s.split(ESCAPED_OPEN).join(\"\\u0000\");\n  if (plain.includes(\"{{\")) return null;\n  return plain.split(\"\\u0000\").join(\"{{\");\n}\n\n\/** Runs back to rich runs, lifting a uniform size\/colour into the style. Null when not representable. *\/\nfunction richRuns(runs: unknown, style: BlockStyle): RichRun[] | null {\n  if (!Array.isArray(runs)) return null;\n  const out: RichRun[] = [];\n  let size: number | undefined;\n  let color: string | undefined;\n  runs.forEach((r, i) => {\n    if (!isObj(r) || typeof r.text !== \"string\") throw new Skip();\n    for (const k of Object.keys(r)) if (![\"text\", \"bold\", \"italic\", \"underline\", \"size\", \"color\"].includes(k)) throw new Skip();\n    if (i === 0) {\n      size = r.size as number | undefined;\n      color = r.color as string | undefined;\n    } else if (r.size !== size || r.color !== color) throw new Skip();\n    const m = WHOLE_TOKEN.exec(r.text);\n    const rr: RichRun = {};\n    if (m) rr.field = m[1];\n    else {\n      const t = unescapeText(r.text);\n      if (t === null) throw new Skip();\n      rr.text = t;\n    }\n    if (r.bold === true) rr.bold = true;\n    if (r.italic === true) rr.italic = true;\n    if (r.underline === true) rr.underline = true;\n    out.push(rr);\n  });\n  if (size !== undefined) style.size = size;\n  if (color !== undefined) style.color = color;\n  return out;\n}\n\nclass Skip extends Error {}\n\nfunction paraStyle(b: JsonObject, style: BlockStyle): void {\n  if (typeof b.align === \"string\") style.align = b.align as BlockStyle[\"align\"];\n  if (typeof b.spaceBefore === \"number\") style.spaceBefore = b.spaceBefore;\n  if (typeof b.spaceAfter === \"number\") style.spaceAfter = b.spaceAfter;\n}\n\n\/** Candidate built-in blocks for one document block, most specific first. *\/\nfunction candidates(b: JsonObject, accent: string): NewBlock[] {\n  const out: NewBlock[] = [];\n  const attempt = (fn: () => NewBlock | null) => {\n    try {\n      const c = fn();\n      if (c) out.push(c);\n    } catch (e) {\n      if (!(e instanceof Skip)) throw e;\n    }\n  };\n  switch (b.type) {\n    case \"heading\":\n      attempt(() => {\n        const style: BlockStyle = {};\n        paraStyle(b, style);\n        const runs = richRuns(b.runs, style)!;\n        if (style.color === accent) delete style.color;\n        return { type: \"heading\", props: { level: b.level, runs }, style };\n      });\n      break;\n    case \"paragraph\": {\n      const runs = b.runs as unknown[];\n      const borders = b.borders as JsonObject | undefined;\n      if (Array.isArray(runs) && runs.length === 0 && isObj(borders) && isObj(borders.bottom)) {\n        attempt(() => {\n          const bottom = borders.bottom as JsonObject;\n          const props: JsonObject = {};\n          if (bottom.width !== 0.75) props.weight = bottom.width as number;\n          if (bottom.color !== accent) props.color = bottom.color as string;\n          const style: BlockStyle = {};\n          if (b.spaceBefore !== 0) style.spaceBefore = b.spaceBefore as number;\n          if (b.spaceAfter !== 8) style.spaceAfter = b.spaceAfter as number;\n          return { type: \"divider\", props, style };\n        });\n      }\n      if (Array.isArray(runs) && runs.length === 0 && typeof b.spaceAfter === \"number\") {\n        attempt(() => ({ type: \"spacer\", props: { height: b.spaceAfter } }));\n      }\n      attempt(() => {\n        const style: BlockStyle = {};\n        paraStyle(b, style);\n        const rr = richRuns(b.runs, style)!;\n        return { type: \"text\", props: { paras: [{ type: \"paragraph\", runs: rr }] }, style };\n      });\n      break;\n    }\n    case \"list\":\n      attempt(() => {\n        const style: BlockStyle = {};\n        const items = (b.items as unknown[]).map((it) => {\n          if (!isObj(it) || it.children !== undefined) throw new Skip();\n          return richRuns(it.runs, style)!;\n        });\n        const para: TextPara = { type: \"list\", items };\n        if (b.ordered === true) para.ordered = true;\n        return { type: \"text\", props: { paras: [para] }, style };\n      });\n      break;\n    case \"image\":\n      attempt(() => {\n        const props: JsonObject = {};\n        const m = typeof b.src === \"string\" ? WHOLE_TOKEN.exec(b.src) : null;\n        if (m) props.field = m[1]!;\n        else props.src = b.src as string;\n        if (b.widthPx !== undefined) props.widthPx = b.widthPx as number;\n        if (b.heightPx !== undefined) props.heightPx = b.heightPx as number;\n        if (typeof b.alt === \"string\") {\n          const alt = unescapeText(b.alt);\n          if (alt === null) throw new Skip();\n          props.alt = alt;\n        }\n        return { type: \"image\", props };\n      });\n      break;\n    case \"table\":\n      attempt(() => {\n        const style: BlockStyle = {};\n        const rows = (b.rows as unknown[]).map((row) => {\n          if (!isObj(row)) throw new Skip();\n          return (row.cells as unknown[]).map((cell) => {\n            if (!isObj(cell) || !Array.isArray(cell.blocks) || cell.blocks.length !== 1) throw new Skip();\n            const p = cell.blocks[0];\n            if (!isObj(p) || p.type !== \"paragraph\") throw new Skip();\n            return richRuns(p.runs, style)!;\n          });\n        });\n        const first = (b.rows as JsonObject[])[0];\n        const props: JsonObject = { header: first?.header === true, rows: rows as unknown as Json };\n        if (Array.isArray(b.widths)) props.widths = b.widths;\n        return { type: \"table\", props, style };\n      });\n      break;\n    case \"pageBreak\":\n      out.push({ type: \"pageBreak\", props: {} });\n      break;\n  }\n  return out;\n}\n\nfunction compileOne(state: EditorState, block: NewBlock, ctx: CompileContext): unknown[] {\n  const s = addBlock({ ...state, tree: { nodes: {} } }, block);\n  return compile(s, ctx).template.document.blocks as unknown[];\n}\n\n\/** Map one top-level document block onto the state. *\/\nfunction importBlock(state: EditorState, b: unknown, ctx: CompileContext, parent: string | null): EditorState {\n  if (isObj(b) && parent === null && b.$spread === true && b.$as === ITEM_ALIAS && typeof b.$each === \"string\" && Array.isArray(b.$value)) {\n    const value = [...b.$value];\n    let pageEach = false;\n    const first = value[0];\n    if (isObj(first) && first.type === \"pageBreak\" && first.$if === \"!$first\" && Object.keys(first).length === 2) {\n      pageEach = true;\n      value.shift();\n    }\n    let s = addBlock(state, { type: \"repeat\", props: { list: b.$each, pageEach } });\n    const group = orderedBlocks(s).at(-1)!.id;\n    for (const child of value) s = importBlock(s, child, ctx, group);\n    \/\/ Keep the group only if it compiles back exactly; else the whole thing is raw.\n    const probe: EditorState = { ...s, tree: { nodes: {} } };\n    let p2 = addBlock(probe, { type: \"repeat\", props: { list: b.$each, pageEach } });\n    const gid = orderedBlocks(p2)[0]!.id;\n    for (const child of groupBlocks(s, group)) p2 = addBlock(p2, { type: child.type, props: child.props, style: child.style }, { parent: gid });\n    if (canonical(compile(p2, ctx).template.document.blocks) === canonical([b])) return s;\n    return addBlock(state, { type: \"raw\", props: { block: b } }, { parent });\n  }\n  if (isObj(b) && !Object.keys(b).some((k) => k.startsWith(\"$\"))) {\n    for (const c of candidates(b, state.page.accent)) {\n      if (canonical(compileOne(state, c, ctx)) === canonical([b])) {\n        const style = c.style && Object.keys(c.style).length ? c.style : undefined;\n        return addBlock(state, { type: c.type, props: c.props, ...(style ? { style } : {}) }, { parent });\n      }\n    }\n  }\n  return addBlock(state, { type: \"raw\", props: { block: b as Json } }, { parent });\n}\n\nfunction bandParts(s: unknown): BandPart[] | null {\n  if (typeof s !== \"string\") return null;\n  const parts: BandPart[] = [];\n  const re = \/\\{\\{ ([A-Za-z_][A-Za-z0-9_.]*) \\}\\}|\\{(page|pages)\\}\/g;\n  let last = 0;\n  for (let m = re.exec(s); m; m = re.exec(s)) {\n    if (m.index > last) parts.push({ text: s.slice(last, m.index) });\n    if (m[1]) parts.push({ field: m[1] });\n    else parts.push({ page: m[2] as \"page\" | \"pages\" });\n    last = m.index + m[0].length;\n  }\n  if (last < s.length) parts.push({ text: s.slice(last) });\n  for (const p of parts) if (\"text\" in p && (p.text.includes(\"{{\") || escapeText(p.text) !== p.text)) return null;\n  return parts;\n}\n\nfunction importPage(raw: unknown, state: EditorState, ctx: CompileContext): Page {\n  const page: Page = defaultPage();\n  if (!isObj(raw)) {\n    page.implicit = [\"size\", \"orientation\", \"margins\"];\n    return page;\n  }\n  const implicit: Page[\"implicit\"] = [];\n  const extra: JsonObject = {};\n  for (const [k, v] of Object.entries(raw)) {\n    if (k === \"size\" && (v === \"letter\" || v === \"a4\" || v === \"legal\")) page.size = v;\n    else if (k === \"orientation\" && (v === \"portrait\" || v === \"landscape\")) page.orientation = v;\n    else if (\n      k === \"margins\" && isObj(v) &&\n      [\"top\", \"right\", \"bottom\", \"left\"].every((s) => typeof v[s] === \"number\") && Object.keys(v).length === 4\n    ) page.margins = v as Page[\"margins\"];\n    else if ([\"header\", \"footer\", \"firstHeader\", \"firstFooter\"].includes(k) && isObj(v)) {\n      const band: Band = {};\n      let ok = Object.keys(v).every((s) => [\"left\", \"center\", \"right\"].includes(s));\n      for (const slot of [\"left\", \"center\", \"right\"] as const) {\n        if (v[slot] === undefined) continue;\n        const parts = bandParts(v[slot]);\n        if (!parts) ok = false;\n        else band[slot] = parts;\n      }\n      if (ok) page[k as \"header\"] = band;\n      else setOwn(extra, k, v);\n    } else setOwn(extra, k, v);\n  }\n  for (const k of [\"size\", \"orientation\", \"margins\"] as const) if (!Object.hasOwn(raw, k)) implicit.push(k);\n  if (implicit.length) page.implicit = implicit;\n  if (Object.keys(extra).length) page.extra = extra;\n  \/\/ Exactness check: if the mapped page does not compile back to the same\n  \/\/ bytes (key order included), keep the whole page as written.\n  const probe = compile({ ...state, tree: { nodes: {} }, page }, ctx).template.document.page;\n  if (JSON.stringify(probe ?? {}) === JSON.stringify(raw)) return page;\n  return { ...page, implicit: [\"size\", \"orientation\", \"margins\"], extra: structuredClone(raw), header: undefined, footer: undefined, firstHeader: undefined, firstFooter: undefined };\n}\n\n\/** Import a template's `document` into a fresh state. *\/\nexport function importDocument(template: unknown, ctx: CompileContext = {}): EditorState {\n  const t = isObj(template) ? template : {};\n  const doc = isObj(t.document) ? t.document : {};\n  let s = emptyState();\n  if (isObj(t.variables) && Object.keys(t.variables).length) s.variables = structuredClone(t.variables);\n  if (typeof t.description === \"string\") s.description = t.description;\n  const docExtra: JsonObject = {};\n  for (const [k, v] of Object.entries(doc)) setOwn(docExtra, k, k === \"page\" || k === \"blocks\" ? null : structuredClone(v));\n  if (Object.keys(docExtra).some((k) => k !== \"page\" && k !== \"blocks\") || Object.keys(docExtra)[0] === \"blocks\") s.docExtra = docExtra;\n  \/\/ Imported field tokens may name variables the host list does not, so\n  \/\/ compile against the kept declarations as well (see Compiler.isDeclared).\n  s.page = importPage(doc.page, s, ctx);\n  for (const b of Array.isArray(doc.blocks) ? doc.blocks : []) s = importBlock(s, b, ctx, null);\n  return s;\n}\n\nfunction isEditor(v: unknown): v is EditorState {\n  return isObj(v) && v.kind === \"fancy-template-ui\" && v.version === 1 && isObj(v.tree) && isObj((v.tree as JsonObject).nodes) && isObj(v.page);\n}\n\n\/** Open a template for editing. See the module comment. *\/\nexport function openTemplate(template: unknown, ctx: CompileContext = {}): OpenResult {\n  const t = isObj(template) ? template : {};\n  const notices: string[] = [];\n  let state: EditorState;\n  let drift = false;\n  let fromDocument: EditorState | undefined;\n\n  if (isEditor(t.editor)) {\n    state = structuredClone(t.editor) as EditorState;\n    const recompiled = compile(state, ctx).template.document;\n    if (canonical(recompiled) !== canonical(t.document)) {\n      drift = true;\n      fromDocument = importDocument(template, ctx);\n      notices.push(\"The document was edited outside the builder since it was last saved. Choose which version to keep.\");\n    }\n  } else {\n    state = importDocument(template, ctx);\n  }\n\n  const ensured = ensureRequired(state, ctx.kinds);\n  state = ensured.state;\n  for (const label of ensured.added) notices.push(`${label} is required, so it was added at the end.`);\n  if (fromDocument) fromDocument = ensureRequired(fromDocument, ctx.kinds).state;\n  return { state, drift, ...(fromDocument ? { fromDocument } : {}), notices };\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/open.ts"},{"path":"components\/fancy\/template-builder\/core\/ops.ts","content":"\/**\n * Every mutation is one op (plan section 10, phase 1): the doc-commons tree ops\n * plus `set_style` and `set_page`. `checkOp` names why an op is refused;\n * `applyOp` refuses (returns the SAME state) whatever `checkOp` refuses, so the\n * UI, the bridge and a server all enforce one rule set.\n *\/\nimport { treeReducer } from \"@particle-academy\/fancy-doc-commons\";\nimport { BUILTIN_TYPES, type BlockKind, type BlockStyle, type BuilderNode, type BuilderOp, type EditorState, type Page } from \".\/types\";\nimport { HOST_PREFIX, hostType, isHost, kindOf } from \".\/model\";\nimport { isForbiddenKey } from \".\/safe\";\n\n\/** The only keys a style patch may set (an agent's JSON reaches here through the bridge). *\/\nconst STYLE_KEYS = new Set([\"align\", \"size\", \"color\", \"spaceBefore\", \"spaceAfter\"]);\n\/** The only keys a page patch may set. *\/\nconst PAGE_KEYS = new Set([\"size\", \"orientation\", \"margins\", \"accent\", \"header\", \"footer\", \"firstHeader\", \"firstFooter\"]);\n\nconst tree = treeReducer<BuilderNode>();\nconst KNOWN = new Set<string>([...BUILTIN_TYPES, \"repeat\"]);\n\nfunction label(node: BuilderNode, kinds: readonly BlockKind[] | undefined): string {\n  return kindOf(node, kinds)?.label ?? node.type;\n}\n\nfunction placementProblem(state: EditorState, node: BuilderNode, parent: string | null, kinds: readonly BlockKind[] | undefined): string | null {\n  if (parent === null) return null;\n  const group = state.tree.nodes[parent];\n  if (!group) return `No block ${parent}.`;\n  if (group.type !== \"repeat\") return \"Blocks can only be placed at the top level or inside a repeat.\";\n  if (node.type === \"repeat\") return \"A repeat cannot hold a repeat.\";\n  const kind = kindOf(node, kinds);\n  if (kind && kind.allowInRepeat === false) return `${kind.label} is not allowed in a repeat: its output must appear exactly once.`;\n  return null;\n}\n\n\/** Why `op` cannot apply, or null when it can. *\/\nexport function checkOp(state: EditorState, op: BuilderOp, kinds?: readonly BlockKind[]): string | null {\n  switch (op.t) {\n    case \"insert\": {\n      const n = op.node;\n      if (state.tree.nodes[n.id]) return `A block with id ${n.id} already exists.`;\n      if (n.type === \"raw\") return \"Raw blocks come only from opening a template; they cannot be added.\";\n      if (!KNOWN.has(n.type) && !n.type.startsWith(HOST_PREFIX)) return `Unknown block type \"${n.type}\".`;\n      if (isHost(n)) {\n        const kind = kindOf(n, kinds);\n        if (!kind) return `Unknown block kind \"${n.type.slice(HOST_PREFIX.length)}\".`;\n        if (kind.required === \"once\" && Object.values(state.tree.nodes).some((x) => x.type === hostType(kind.kind))) {\n          return `${kind.label} is required exactly once and is already in the template.`;\n        }\n      }\n      return placementProblem(state, n, n.parent, kinds);\n    }\n    case \"remove\": {\n      const n = state.tree.nodes[op.id];\n      if (!n) return `No block ${op.id}.`;\n      if (kindOf(n, kinds)?.required === \"once\") return `${label(n, kinds)} is required: it can be moved and styled, never removed.`;\n      if (n.type === \"repeat\") {\n        for (const child of Object.values(state.tree.nodes)) {\n          if (child.parent === n.id && kindOf(child, kinds)?.required === \"once\") {\n            return `This repeat holds ${label(child, kinds)}, which is required. Move it out first.`;\n          }\n        }\n      }\n      return null;\n    }\n    case \"move\": {\n      const n = state.tree.nodes[op.id];\n      if (!n) return `No block ${op.id}.`;\n      return placementProblem(state, n, op.parent, kinds);\n    }\n    case \"set_props\": {\n      const n = state.tree.nodes[op.id];\n      if (!n) return `No block ${op.id}.`;\n      if (n.type === \"raw\") return \"This block was kept exactly as imported and is read-only.\";\n      return null;\n    }\n    case \"set_style\": {\n      const n = state.tree.nodes[op.id];\n      if (!n) return `No block ${op.id}.`;\n      if (n.type === \"raw\") return \"This block was kept exactly as imported and is read-only.\";\n      return null;\n    }\n    case \"set_page\":\n      return null;\n  }\n}\n\nfunction mergeStyle(prev: BlockStyle | undefined, patch: BlockStyle): BlockStyle | undefined {\n  const next: Record<string, unknown> = { ...(prev ?? {}) };\n  for (const [k, v] of Object.entries(patch)) {\n    if (!STYLE_KEYS.has(k)) continue;\n    if (v === undefined) delete next[k];\n    else next[k] = v;\n  }\n  return Object.keys(next).length ? (next as BlockStyle) : undefined;\n}\n\nfunction mergePage(prev: Page, patch: Partial<Page>): Page {\n  const next = { ...prev } as Page & Record<string, unknown>;\n  let extra = prev.extra ? { ...prev.extra } : undefined;\n  let implicit = prev.implicit ? [...prev.implicit] : undefined;\n  for (const [k, v] of Object.entries(patch)) {\n    if (k === \"extra\" || k === \"implicit\") continue;\n    if (!PAGE_KEYS.has(k) || isForbiddenKey(k)) continue;\n    if (v === undefined) delete next[k];\n    else next[k] = v;\n    \/\/ Editing a key the builder imported but did not own hands it to the builder.\n    if (extra && Object.hasOwn(extra, k)) delete extra[k];\n    if (implicit) implicit = implicit.filter((x) => x !== k);\n  }\n  if (Object.hasOwn(patch, \"extra\")) extra = patch.extra;\n  if (Object.hasOwn(patch, \"implicit\")) implicit = patch.implicit;\n  if (extra && Object.keys(extra).length) next.extra = extra;\n  else delete next.extra;\n  if (implicit && implicit.length) next.implicit = implicit;\n  else delete next.implicit;\n  return next;\n}\n\n\/** Apply one op. A refused op returns the same state object. *\/\nexport function applyOp(state: EditorState, op: BuilderOp, kinds?: readonly BlockKind[]): EditorState {\n  if (checkOp(state, op, kinds) !== null) return state;\n  switch (op.t) {\n    case \"set_style\": {\n      const n = state.tree.nodes[op.id]!;\n      const style = mergeStyle(n.style, op.patch);\n      const next: BuilderNode = { ...n };\n      if (style) next.style = style;\n      else delete next.style;\n      return { ...state, tree: { nodes: { ...state.tree.nodes, [op.id]: next } } };\n    }\n    case \"set_page\":\n      return { ...state, page: mergePage(state.page, op.patch) };\n    default:\n      return { ...state, tree: tree.reduce(state.tree, op) };\n  }\n}\n\n\/** The ops that undo `op`, computed against the state BEFORE it applies. *\/\nexport function invertOp(state: EditorState, op: BuilderOp): BuilderOp[] {\n  switch (op.t) {\n    case \"set_style\": {\n      const n = state.tree.nodes[op.id];\n      if (!n) return [];\n      const prev: BlockStyle = {};\n      for (const k of Object.keys(op.patch) as Array<keyof BlockStyle>) {\n        (prev as Record<string, unknown>)[k] = n.style?.[k];\n      }\n      return [{ t: \"set_style\", id: op.id, patch: prev }];\n    }\n    case \"set_page\": {\n      const prev: Partial<Page> = {};\n      for (const k of Object.keys(op.patch) as Array<keyof Page>) {\n        (prev as Record<string, unknown>)[k] = state.page[k];\n      }\n      prev.extra = state.page.extra;\n      prev.implicit = state.page.implicit;\n      return [{ t: \"set_page\", patch: prev }];\n    }\n    default:\n      return tree.invert(state.tree, op) as BuilderOp[];\n  }\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/ops.ts"},{"path":"components\/fancy\/template-builder\/core\/types.ts","content":"\/**\n * The builder's source model (plan section 5.1). React-free and JSON all the way\n * down, so a server, a bridge and the UI share one shape.\n *\/\nimport type { DocNode, DocTree } from \"@particle-academy\/fancy-doc-commons\";\n\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json };\nexport type JsonObject = { [key: string]: Json };\n\n\/** A field the host offers. `token` is a dotted path (`customer.name`). *\/\nexport interface FieldDef {\n  label: string;\n  token: string;\n  \/** Shown in the draft preview and declared as the variable's `example`. *\/\n  sample?: Json;\n  \/** fancy-template variable type. @default \"string\" *\/\n  type?: \"string\" | \"number\" | \"integer\" | \"boolean\" | \"date\" | \"image\";\n  \/** @default true *\/\n  required?: boolean;\n  maxLength?: number;\n  description?: string;\n}\n\n\/** A list the host offers for a repeating section. Item field tokens are relative (`title`). *\/\nexport interface ListDef {\n  label: string;\n  token: string;\n  itemFields: FieldDef[];\n  sample?: JsonObject[];\n  maxItems?: number;\n}\n\nexport type Align = \"left\" | \"center\" | \"right\" | \"justify\";\n\n\/** Per-block style (plan section 5.1). `color` may be `\"accent\"`: the page accent. *\/\nexport interface BlockStyle {\n  align?: Align;\n  size?: number;\n  color?: string;\n  spaceBefore?: number;\n  spaceAfter?: number;\n}\n\n\/** A run of rich text: literal text, or a field chip. Never both. *\/\nexport interface RichRun {\n  text?: string;\n  field?: string;\n  bold?: boolean;\n  italic?: boolean;\n  underline?: boolean;\n}\n\nexport type TextPara =\n  | { type: \"paragraph\"; runs: RichRun[] }\n  | { type: \"list\"; ordered?: boolean; items: RichRun[][] };\n\nexport interface HeadingProps { level: number; runs: RichRun[] }\nexport interface TextProps { paras: TextPara[] }\nexport interface ImageProps { src?: string; field?: string; widthPx?: number; heightPx?: number; alt?: string; name?: string }\n\/** `rows[r][c]` is one cell's runs. v1 cells hold one paragraph (plan section 13 fallback). *\/\nexport interface TableProps { header?: boolean; widths?: number[]; rows: RichRun[][][] }\nexport interface DividerProps { color?: string; weight?: number }\nexport interface SpacerProps { height: number }\nexport interface RepeatProps { list: string; pageEach: boolean }\n\/** A block the importer could not map, kept byte-for-byte. Read-only in the UI. *\/\nexport interface RawProps { block: Json }\n\nexport const BUILTIN_TYPES = [\"heading\", \"text\", \"image\", \"table\", \"divider\", \"spacer\", \"pageBreak\"] as const;\nexport type BuiltinType = (typeof BUILTIN_TYPES)[number];\n\nexport interface BuilderNode extends DocNode<Record<string, unknown>> {\n  style?: BlockStyle;\n  \/**\n   * A host block's last good compiled output. Written by `compile`, so a template\n   * reopened without the kind registered still renders exactly as it did.\n   *\/\n  cache?: Json[];\n}\n\nexport type BuilderTree = DocTree<BuilderNode>;\n\n\/** One part of a band slot: text, a field chip, or a page-number chip. *\/\nexport type BandPart = { text: string } | { field: string } | { page: \"page\" | \"pages\" };\n\nexport interface Band {\n  left?: BandPart[];\n  center?: BandPart[];\n  right?: BandPart[];\n}\n\nexport interface Page {\n  size: \"letter\" | \"a4\" | \"legal\";\n  orientation: \"portrait\" | \"landscape\";\n  margins: { top: number; right: number; bottom: number; left: number };\n  \/** `#RRGGBB`. The model has no document accent, so it compiles into run colours. *\/\n  accent: string;\n  header?: Band;\n  footer?: Band;\n  firstHeader?: Band;\n  firstFooter?: Band;\n  \/** Page keys the builder does not edit (background, border), kept as written. *\/\n  extra?: JsonObject;\n  \/**\n   * Keys an imported page did not write, so compile leaves them out and the\n   * document stays byte-identical. Editing a key takes it off this list.\n   *\/\n  implicit?: Array<\"size\" | \"orientation\" | \"margins\">;\n}\n\n\/** What the builder stores under the envelope's `editor` key. *\/\nexport interface EditorState {\n  kind: \"fancy-template-ui\";\n  version: 1;\n  tree: BuilderTree;\n  page: Page;\n  \/** Document keys the builder does not edit (title, defaultFont, meta), kept as written. *\/\n  docExtra?: JsonObject;\n  \/** Declarations kept from an imported template (what its raw blocks read). *\/\n  variables?: JsonObject;\n  \/** The envelope's `description`, kept as written. *\/\n  description?: string;\n}\n\nexport interface KindRenderContext {\n  page: Page;\n  accent: string;\n  fieldToken(token: string): string;\n}\n\n\/** A JSON Schema subset: type, properties, required, items, enum, bounds, pattern. *\/\nexport type JsonSchema = { [key: string]: Json };\n\n\/** A host block kind (plan section 6). *\/\nexport interface BlockKind<P extends JsonObject = JsonObject> {\n  \/** Namespaced: `\/^[a-z0-9-]+:[a-z0-9-]+$\/`, e.g. `fancy-sign:signature`. *\/\n  kind: string;\n  label: string;\n  \/** A react-fancy Icon name. *\/\n  icon?: string;\n  schema: JsonSchema;\n  defaults: P;\n  \/** `\"once\"`: exactly once. Never removable, never added twice; movable and styleable. *\/\n  required?: \"once\";\n  \/** @default true. `false` for anything whose output must be unique, like signing fields. *\/\n  allowInRepeat?: boolean;\n  \/** Which style controls the settings panel offers. @default none *\/\n  styleable?: Array<keyof BlockStyle>;\n  \/** Pure and synchronous. Returns last-word \/ fine-print blocks. *\/\n  render(props: P, ctx: KindRenderContext): Json[];\n  \/** The settings panel. Typed loosely here so `.\/core` stays React-free. *\/\n  Settings?: unknown;\n}\n\nexport interface Problem {\n  code: \"FIELD_UNKNOWN\" | \"KIND_UNKNOWN\" | \"KIND_PROPS\" | \"KIND_RENDER\" | \"IMAGE_EMPTY\" | \"VARIABLE_CONFLICT\" | \"LIST_UNKNOWN\" | \"TEMPLATE\";\n  message: string;\n  \/** The node the problem belongs to, when there is one. *\/\n  node?: string;\n  \/** A JSON Pointer into the template, for `TEMPLATE` problems from `inspect`. *\/\n  path?: string;\n}\n\nexport interface CompileContext {\n  kinds?: readonly BlockKind[];\n  fields?: readonly FieldDef[];\n  lists?: readonly ListDef[];\n}\n\nexport type BuilderOp =\n  | { t: \"insert\"; node: BuilderNode }\n  | { t: \"remove\"; id: string }\n  | { t: \"move\"; id: string; parent: string | null; order: string }\n  | { t: \"set_props\"; id: string; patch: Record<string, unknown> }\n  | { t: \"set_style\"; id: string; patch: BlockStyle }\n  | { t: \"set_page\"; patch: Partial<Page> };\n\n\/** A compiled envelope. Typed loosely on purpose: it is plain JSON for a writer. *\/\n\/\/ eslint-disable-next-line @typescript-eslint\/no-explicit-any\nexport type TemplateEnvelope = { fancyTemplate: 1; writer: \"fine-print\"; variables: Record<string, any>; editor: EditorState; document: Record<string, any> } & Record<string, any>;\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/types.ts"},{"path":"components\/fancy\/template-builder\/core\/model.ts","content":"\/**\n * Creating and reading the source model: the empty state, node factories,\n * ordered walks, and the host-kind registry helpers.\n *\/\nimport { appendOrder, childrenOf, fractionalKey, roots } from \"@particle-academy\/fancy-doc-commons\";\nimport { validateSchema } from \".\/schema\";\nimport type { BlockKind, BlockStyle, BuilderNode, EditorState, JsonObject, Page } from \".\/types\";\n\nexport const DEFAULT_ACCENT = \"#1F4E79\";\nexport const HOST_PREFIX = \"host:\";\nconst KIND_NAME = \/^[a-z0-9-]+:[a-z0-9-]+$\/;\n\nexport function defaultPage(): Page {\n  return {\n    size: \"letter\",\n    orientation: \"portrait\",\n    margins: { top: 72, right: 72, bottom: 72, left: 72 },\n    accent: DEFAULT_ACCENT,\n  };\n}\n\nexport function emptyState(): EditorState {\n  return { kind: \"fancy-template-ui\", version: 1, tree: { nodes: {} }, page: defaultPage() };\n}\n\nlet counter = 0;\n\/** A fresh node id. Unique within a session; ids only need to be unique per template. *\/\nexport function newId(): string {\n  counter = (counter + 1) % 1679616;\n  return `b_${Date.now().toString(36)}${counter.toString(36).padStart(4, \"0\")}${Math.random().toString(36).slice(2, 6)}`;\n}\n\n\/** Validate and return a host block kind. Throws on a malformed one: a host bug, caught at startup. *\/\nexport function defineKind<P extends JsonObject>(kind: BlockKind<P>): BlockKind<P> {\n  if (!KIND_NAME.test(kind.kind)) {\n    throw new Error(`Block kind \"${kind.kind}\" must be namespaced, like \"acme:totals\" (\/^[a-z0-9-]+:[a-z0-9-]+$\/).`);\n  }\n  if (typeof kind.render !== \"function\") throw new Error(`Block kind \"${kind.kind}\" has no render function.`);\n  const errors = validateSchema(kind.defaults, kind.schema);\n  if (errors.length > 0) throw new Error(`Block kind \"${kind.kind}\": its defaults fail its own schema (${errors[0]}).`);\n  return kind;\n}\n\nexport function hostType(kind: string): string {\n  return `${HOST_PREFIX}${kind}`;\n}\n\n\/** The kind a node belongs to, or undefined for built-ins and unknown kinds. *\/\nexport function kindOf(node: BuilderNode, kinds: readonly BlockKind[] | undefined): BlockKind | undefined {\n  if (!node.type.startsWith(HOST_PREFIX)) return undefined;\n  const name = node.type.slice(HOST_PREFIX.length);\n  return kinds?.find((k) => k.kind === name);\n}\n\nexport function isHost(node: BuilderNode): boolean {\n  return node.type.startsWith(HOST_PREFIX);\n}\n\n\/** Top-level blocks and groups, in order. *\/\nexport function orderedBlocks(state: EditorState): BuilderNode[] {\n  return roots(state.tree);\n}\n\n\/** A group's blocks, in order. *\/\nexport function groupBlocks(state: EditorState, groupId: string): BuilderNode[] {\n  return childrenOf(state.tree, groupId);\n}\n\nexport interface NewBlock {\n  type: string;\n  props: Record<string, unknown>;\n  style?: BlockStyle;\n}\n\nexport interface Placement {\n  \/** A repeat group's id, or null\/undefined for the top level. *\/\n  parent?: string | null;\n  \/** Insert at this index among the parent's children. @default the end *\/\n  index?: number;\n}\n\n\/** An order key for position `index` among `parent`'s children. *\/\nexport function orderAt(state: EditorState, parent: string | null, index: number | undefined, excludeId?: string): string {\n  const sibs = childrenOf(state.tree, parent).filter((n) => n.id !== excludeId);\n  if (index === undefined || index >= sibs.length) {\n    return sibs.length ? fractionalKey(sibs[sibs.length - 1]!.order, null) : appendOrder(state.tree, parent);\n  }\n  const i = Math.max(0, index);\n  const before = i > 0 ? sibs[i - 1]!.order : null;\n  return fractionalKey(before, sibs[i]!.order);\n}\n\nexport function makeNode(state: EditorState, block: NewBlock, at: Placement = {}): BuilderNode {\n  const parent = at.parent ?? null;\n  const node: BuilderNode = { id: newId(), type: block.type, parent, order: orderAt(state, parent, at.index), props: block.props };\n  if (block.style && Object.keys(block.style).length > 0) node.style = block.style;\n  return node;\n}\n\n\/** Insert a block without checks. The UI and the bridge go through `applyOp`, which checks. *\/\nexport function addBlock(state: EditorState, block: NewBlock, at: Placement = {}): EditorState {\n  const node = makeNode(state, block, at);\n  return { ...state, tree: { nodes: { ...state.tree.nodes, [node.id]: node } } };\n}\n\n\/** A new block of a host kind, with its defaults. *\/\nexport function hostBlock(kind: BlockKind): NewBlock {\n  return { type: hostType(kind.kind), props: structuredClone(kind.defaults) as Record<string, unknown> };\n}\n\n\/** Append every `required: \"once\"` kind the state lacks. Returns the labels added. *\/\nexport function ensureRequired(state: EditorState, kinds: readonly BlockKind[] | undefined): { state: EditorState; added: string[] } {\n  const added: string[] = [];\n  let s = state;\n  for (const kind of kinds ?? []) {\n    if (kind.required !== \"once\") continue;\n    const present = Object.values(s.tree.nodes).some((n) => n.type === hostType(kind.kind));\n    if (!present) {\n      s = addBlock(s, hostBlock(kind));\n      added.push(kind.label);\n    }\n  }\n  return { state: s, added };\n}\n\n\/** An empty template holding `blocks`, then every required-once kind. *\/\nexport function createState(blocks: NewBlock[] = [], kinds?: readonly BlockKind[]): EditorState {\n  let s = emptyState();\n  for (const b of blocks) s = addBlock(s, b);\n  return ensureRequired(s, kinds).state;\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/model.ts"},{"path":"components\/fancy\/template-builder\/RichTextField.tsx","content":"import { useEffect, useRef, useState } from \"react\";\nimport { Button, Command, Editor, useEditor } from \"@particle-academy\/react-fancy\";\nimport type { FieldOption } from \".\/context\";\n\nexport interface FieldPickerProps {\n  options: FieldOption[];\n  onPick(option: FieldOption): void;\n  \/** Extra chips that are not fields, such as page numbers in a band. *\/\n  extra?: FieldOption[];\n  label?: string;\n  disabled?: boolean;\n}\n\n\/**\n * \"Insert field\": a react-fancy Command palette over the host's field list.\n * Only offered tokens can be picked, so nobody types braces.\n *\/\nexport function FieldPicker({ options, onPick, extra = [], label = \"Insert field\", disabled }: FieldPickerProps) {\n  const [open, setOpen] = useState(false);\n  const all = [...options, ...extra];\n  const groups = [...new Set(all.map((o) => o.group))];\n  return (\n    <>\n      <Button\n        type=\"button\"\n        size=\"xs\"\n        variant=\"ghost\"\n        icon=\"braces\"\n        disabled={disabled || all.length === 0}\n        data-ftb-field-picker=\"\"\n        onClick={() => setOpen(true)}\n      >\n        {label}\n      <\/Button>\n      <Command open={open} onClose={() => setOpen(false)}>\n        <Command.Input placeholder=\"Search fields\" \/>\n        <Command.List>\n          <Command.Empty>No field matches.<\/Command.Empty>\n          {groups.map((g) => (\n            <Command.Group key={g} heading={g}>\n              {all\n                .filter((o) => o.group === g)\n                .map((o) => (\n                  <Command.Item\n                    key={o.token}\n                    value={`${o.label} ${o.token}`}\n                    onSelect={() => {\n                      setOpen(false);\n                      onPick(o);\n                    }}\n                  >\n                    <span data-ftb-field={o.token}>{o.label}<\/span>\n                  <\/Command.Item>\n                ))}\n            <\/Command.Group>\n          ))}\n        <\/Command.List>\n      <\/Command>\n    <\/>\n  );\n}\n\nfunction InsertField({ options, extra, disabled }: { options: FieldOption[]; extra?: FieldOption[]; disabled?: boolean }) {\n  const editor = useEditor();\n  return (\n    <FieldPicker\n      options={options}\n      extra={extra}\n      disabled={disabled}\n      onPick={(o) => editor.insertToken({ id: o.token, label: o.label })}\n    \/>\n  );\n}\n\nconst FORMAT_ACTIONS = [\n  { label: \"Bold\", command: \"bold\", icon: \"B\" },\n  { label: \"Italic\", command: \"italic\", icon: \"I\" },\n  { label: \"Underline\", command: \"underline\", icon: \"U\" },\n];\nconst LIST_ACTIONS = [\n  { label: \"Bulleted list\", command: \"insertUnorderedList\", icon: \"\u2022\" },\n  { label: \"Numbered list\", command: \"insertOrderedList\", icon: \"1.\" },\n];\n\nfunction Toolbar({ lists, options, extra, disabled }: { lists: boolean; options: FieldOption[]; extra?: FieldOption[]; disabled?: boolean }) {\n  const editor = useEditor();\n  const actions = lists ? [...FORMAT_ACTIONS, ...LIST_ACTIONS] : FORMAT_ACTIONS;\n  return (\n    <Editor.Toolbar>\n      {actions.map((a) => (\n        <Button\n          key={a.command}\n          type=\"button\"\n          size=\"xs\"\n          variant=\"ghost\"\n          aria-label={a.label}\n          title={a.label}\n          data-ftb-format={a.command}\n          disabled={disabled}\n          onClick={() => editor.exec(a.command)}\n        >\n          {a.icon}\n        <\/Button>\n      ))}\n      <Editor.Toolbar.Separator \/>\n      <InsertField options={options} extra={extra} disabled={disabled} \/>\n    <\/Editor.Toolbar>\n  );\n}\n\nexport interface RichTextFieldProps {\n  \/** HTML the model produced (from `parasToHtml` \/ `runsToHtml`). *\/\n  html: string;\n  \/** Called with the Editor's HTML on every change. *\/\n  onHtmlChange(html: string): void;\n  \/** Normalises HTML to the model and back, so an echo is recognised as one. *\/\n  canonical(html: string): string;\n  options: FieldOption[];\n  extra?: FieldOption[];\n  lists?: boolean;\n  placeholder?: string;\n  disabled?: boolean;\n  \/** A stable handle for this field. *\/\n  handle: string;\n  maxHeight?: number;\n}\n\n\/**\n * The react-fancy Editor over model runs. Holds the Editor's own HTML locally\n * and re-seeds only when the model changed from OUTSIDE (an agent's edit, a\n * different block), so typing never fights the caret.\n *\/\nexport function RichTextField({ html, onHtmlChange, canonical, options, extra, lists = false, placeholder, disabled, handle, maxHeight = 220 }: RichTextFieldProps) {\n  const [local, setLocal] = useState(html);\n  const lastSent = useRef<string | null>(null);\n  useEffect(() => {\n    if (lastSent.current !== null && canonical(lastSent.current) === canonical(html)) return;\n    setLocal(html);\n    lastSent.current = null;\n  }, [html, canonical]);\n  return (\n    <div data-ftb-rich={handle}>\n      <Editor\n        value={local}\n        outputFormat=\"html\"\n        valueFormat=\"html\"\n        placeholder={placeholder}\n        mode={disabled ? \"view\" : \"edit\"}\n        onChange={(next) => {\n          setLocal(next);\n          lastSent.current = next;\n          onHtmlChange(next);\n        }}\n      >\n        <Toolbar lists={lists} options={options} extra={extra} disabled={disabled} \/>\n        <Editor.Content maxHeight={maxHeight} \/>\n      <\/Editor>\n    <\/div>\n  );\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/RichTextField.tsx"},{"path":"components\/fancy\/template-builder\/runs-html.ts","content":"\/**\n * Rich runs <-> the react-fancy Editor's HTML. The Editor edits HTML; the model\n * holds last-word runs (plan section 5.1), so this is the only place that\n * parses markup, and it parses only what it wrote: paragraphs, lists, bold,\n * italic, underline and field chips. Anything else is reduced to its text.\n *\/\nimport { editorTokenHtml } from \"@particle-academy\/react-fancy\";\nimport type { BandPart, RichRun, TextPara } from \".\/core\/types\";\n\nconst TOKEN_ATTR = \"data-react-fancy-editor-token\";\n\/** Page-number chips in a band carry these ids; they are not fields. *\/\nexport const PAGE_TOKEN = \"$page\";\nexport const PAGES_TOKEN = \"$pages\";\n\nfunction esc(s: string): string {\n  return s.replace(\/&\/g, \"&amp;\").replace(\/<\/g, \"&lt;\").replace(\/>\/g, \"&gt;\");\n}\n\nexport type LabelOf = (token: string) => string;\n\nexport function runsToHtml(runs: RichRun[], labelOf: LabelOf): string {\n  return runs\n    .map((r) => {\n      let inner = r.field !== undefined ? editorTokenHtml({ id: r.field, label: labelOf(r.field) }) : esc(r.text ?? \"\").replace(\/\\n\/g, \"<br>\");\n      if (r.underline) inner = `<u>${inner}<\/u>`;\n      if (r.italic) inner = `<em>${inner}<\/em>`;\n      if (r.bold) inner = `<strong>${inner}<\/strong>`;\n      return inner;\n    })\n    .join(\"\");\n}\n\nexport function parasToHtml(paras: TextPara[], labelOf: LabelOf): string {\n  return paras\n    .map((p) => {\n      if (p.type === \"list\") {\n        const tag = p.ordered ? \"ol\" : \"ul\";\n        return `<${tag}>${p.items.map((it) => `<li>${runsToHtml(it, labelOf)}<\/li>`).join(\"\")}<\/${tag}>`;\n      }\n      return `<p>${runsToHtml(p.runs, labelOf)}<\/p>`;\n    })\n    .join(\"\");\n}\n\ninterface Marks {\n  bold?: boolean;\n  italic?: boolean;\n  underline?: boolean;\n}\n\nfunction sameMarks(a: RichRun, b: Marks): boolean {\n  return !!a.bold === !!b.bold && !!a.italic === !!b.italic && !!a.underline === !!b.underline;\n}\n\nfunction pushText(out: RichRun[], text: string, marks: Marks): void {\n  if (text === \"\") return;\n  const last = out[out.length - 1];\n  if (last && last.text !== undefined && sameMarks(last, marks)) {\n    last.text += text;\n    return;\n  }\n  const run: RichRun = { text };\n  if (marks.bold) run.bold = true;\n  if (marks.italic) run.italic = true;\n  if (marks.underline) run.underline = true;\n  out.push(run);\n}\n\nfunction inline(node: Node, marks: Marks, out: RichRun[]): void {\n  if (node.nodeType === 3) {\n    pushText(out, (node.textContent ?? \"\").replace(\/\u00a0\/g, \" \"), marks);\n    return;\n  }\n  if (node.nodeType !== 1) return;\n  const el = node as Element;\n  if (el.hasAttribute(TOKEN_ATTR)) {\n    const run: RichRun = { field: el.getAttribute(TOKEN_ATTR) ?? \"\" };\n    if (marks.bold) run.bold = true;\n    if (marks.italic) run.italic = true;\n    if (marks.underline) run.underline = true;\n    out.push(run);\n    return;\n  }\n  const tag = el.tagName.toLowerCase();\n  if (tag === \"br\") {\n    pushText(out, \"\\n\", marks);\n    return;\n  }\n  const next: Marks = { ...marks };\n  if (tag === \"strong\" || tag === \"b\") next.bold = true;\n  if (tag === \"em\" || tag === \"i\") next.italic = true;\n  if (tag === \"u\") next.underline = true;\n  el.childNodes.forEach((c) => inline(c, next, out));\n}\n\n\/**\n * Drop the line breaks at a block's edges: contentEditable keeps a lone `<br>`\n * as the placeholder of an empty line, before or after what a person typed,\n * and it is not a break they meant. Breaks between content are kept.\n *\/\nfunction trimTrailingBreak(runs: RichRun[]): RichRun[] {\n  const last = runs[runs.length - 1];\n  if (last?.text !== undefined && last.text.endsWith(\"\\n\")) {\n    last.text = last.text.slice(0, -1);\n    if (last.text === \"\") runs.pop();\n  }\n  const first = runs[0];\n  if (first?.text !== undefined && first.text.startsWith(\"\\n\")) {\n    first.text = first.text.slice(1);\n    if (first.text === \"\") runs.shift();\n  }\n  return runs;\n}\n\nfunction parse(html: string): HTMLElement {\n  const box = document.createElement(\"div\");\n  \/\/ Parsed into an inert template first, so nothing in it runs or loads.\n  const tpl = document.createElement(\"template\");\n  tpl.innerHTML = html;\n  box.appendChild(tpl.content.cloneNode(true));\n  return box;\n}\n\n\/** The Editor's HTML back to paragraphs and lists. *\/\nexport function htmlToParas(html: string): TextPara[] {\n  const root = parse(html);\n  const paras: TextPara[] = [];\n  let loose: RichRun[] = [];\n  const flush = () => {\n    if (loose.length) paras.push({ type: \"paragraph\", runs: trimTrailingBreak(loose) });\n    loose = [];\n  };\n  root.childNodes.forEach((n) => {\n    if (n.nodeType === 1) {\n      const tag = (n as Element).tagName.toLowerCase();\n      if (tag === \"ul\" || tag === \"ol\") {\n        flush();\n        const items: RichRun[][] = [];\n        (n as Element).querySelectorAll(\":scope > li\").forEach((li) => {\n          const runs: RichRun[] = [];\n          li.childNodes.forEach((c) => inline(c, {}, runs));\n          items.push(trimTrailingBreak(runs));\n        });\n        const para: TextPara = { type: \"list\", items };\n        if (tag === \"ol\") para.ordered = true;\n        paras.push(para);\n        return;\n      }\n      if (\/^(p|div|h[1-6]|blockquote|pre)$\/.test(tag)) {\n        flush();\n        const runs: RichRun[] = [];\n        n.childNodes.forEach((c) => inline(c, {}, runs));\n        paras.push({ type: \"paragraph\", runs: trimTrailingBreak(runs) });\n        return;\n      }\n    }\n    inline(n, {}, loose);\n  });\n  flush();\n  return paras;\n}\n\n\/** One line of runs (a heading, a table cell): every paragraph joined by a line break. *\/\nexport function htmlToRuns(html: string): RichRun[] {\n  const out: RichRun[] = [];\n  \/\/ An empty paragraph (a cleared line) contributes nothing to one line of runs.\n  htmlToParas(html)\n    .map((p) => (p.type === \"list\" ? p.items.flat() : p.runs))\n    .filter((runs) => runs.length > 0)\n    .forEach((runs, i) => {\n    if (i > 0) pushText(out, \"\\n\", {});\n    for (const r of runs) {\n      if (r.field !== undefined) out.push({ ...r });\n      else pushText(out, r.text ?? \"\", r);\n    }\n    });\n  return out;\n}\n\n\/** A band slot to Editor HTML: page-number parts become chips too. *\/\nexport function bandToHtml(parts: BandPart[] | undefined, labelOf: LabelOf, pageLabels: { page: string; pages: string }): string {\n  if (!parts) return \"\";\n  return parts\n    .map((p) => {\n      if (\"field\" in p) return editorTokenHtml({ id: p.field, label: labelOf(p.field) });\n      if (\"page\" in p) {\n        return editorTokenHtml(p.page === \"pages\" ? { id: PAGES_TOKEN, label: pageLabels.pages } : { id: PAGE_TOKEN, label: pageLabels.page });\n      }\n      return esc(p.text);\n    })\n    .join(\"\");\n}\n\nexport function htmlToBand(html: string): BandPart[] | undefined {\n  const parts: BandPart[] = [];\n  for (const r of htmlToRuns(html)) {\n    if (r.field === PAGE_TOKEN) parts.push({ page: \"page\" });\n    else if (r.field === PAGES_TOKEN) parts.push({ page: \"pages\" });\n    else if (r.field !== undefined) parts.push({ field: r.field });\n    else if (r.text) parts.push({ text: r.text.replace(\/\\n\/g, \" \") });\n  }\n  return parts.length ? parts : undefined;\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/runs-html.ts"},{"path":"components\/fancy\/template-builder\/core\/safe.ts","content":"\/**\n * Guards against prototype pollution. Field tokens, list tokens, sample paths,\n * style and page patches (an agent's JSON, through the bridge) and an imported\n * document's keys are all consumer-reachable, so a key never reaches an\n * assignment as `__proto__`, `constructor` or `prototype` unchecked.\n *\/\n\nconst FORBIDDEN = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n\/** fancy-template's `name` grammar (SPEC section 5). *\/\nconst NAME = \/^[A-Za-z_][A-Za-z0-9_]*$\/;\n\nexport function isForbiddenKey(key: string): boolean {\n  return FORBIDDEN.has(key);\n}\n\n\/**\n * A dotted field path every segment of which is a fancy-template name and none a\n * prototype key. Anything else is refused as a field, a list or a sample path.\n *\/\nexport function isSafePath(path: string): boolean {\n  if (typeof path !== \"string\" || path === \"\") return false;\n  return path.split(\".\").every((seg) => NAME.test(seg) && !FORBIDDEN.has(seg));\n}\n\n\/**\n * Set an own, enumerable data property, whatever the key. For copying keys that\n * are DATA (an imported document's), where a forbidden name must survive as a\n * plain property rather than be dropped or become a prototype.\n *\/\nexport function setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n  Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/safe.ts"},{"path":"components\/fancy\/template-builder\/core\/schema.ts","content":"\/**\n * A small JSON Schema validator for host block-kind props: the subset a\n * settings panel needs (type, properties, required, additionalProperties: false,\n * items, enum, const, numeric and length bounds, pattern). Written here rather\n * than taking a validator dependency; an unsupported keyword is ignored, which\n * fails open, so a kind's `render` must still be defensive.\n *\/\nimport type { Json, JsonSchema } from \".\/types\";\n\nfunction typeOf(v: unknown): string {\n  if (v === null) return \"null\";\n  if (Array.isArray(v)) return \"array\";\n  if (typeof v === \"number\") return Number.isInteger(v) ? \"integer\" : \"number\";\n  return typeof v;\n}\n\nfunction matchesType(v: unknown, t: string): boolean {\n  const actual = typeOf(v);\n  if (t === \"number\") return actual === \"number\" || actual === \"integer\";\n  return actual === t;\n}\n\n\/** Every error as `\"<path>: <reason>\"`; empty when valid. *\/\nexport function validateSchema(value: unknown, schema: JsonSchema, path = \"\"): string[] {\n  const errors: string[] = [];\n  const at = path === \"\" ? \"(root)\" : path;\n  const s = schema as Record<string, unknown>;\n\n  if (s.type !== undefined) {\n    const types = Array.isArray(s.type) ? (s.type as string[]) : [s.type as string];\n    if (!types.some((t) => matchesType(value, t))) {\n      return [`${at}: expected ${types.join(\" or \")}`];\n    }\n  }\n  if (Array.isArray(s.enum) && !(s.enum as Json[]).some((e) => JSON.stringify(e) === JSON.stringify(value))) {\n    errors.push(`${at}: not one of the allowed values`);\n  }\n  if (s.const !== undefined && JSON.stringify(s.const) !== JSON.stringify(value)) {\n    errors.push(`${at}: must be ${JSON.stringify(s.const)}`);\n  }\n  if (typeof value === \"number\") {\n    if (typeof s.minimum === \"number\" && value < s.minimum) errors.push(`${at}: below ${s.minimum}`);\n    if (typeof s.maximum === \"number\" && value > s.maximum) errors.push(`${at}: above ${s.maximum}`);\n  }\n  if (typeof value === \"string\") {\n    const len = [...value].length;\n    if (typeof s.minLength === \"number\" && len < s.minLength) errors.push(`${at}: shorter than ${s.minLength}`);\n    if (typeof s.maxLength === \"number\" && len > s.maxLength) errors.push(`${at}: longer than ${s.maxLength}`);\n    if (typeof s.pattern === \"string\" && !new RegExp(s.pattern, \"u\").test(value)) errors.push(`${at}: does not match the pattern`);\n  }\n  if (Array.isArray(value)) {\n    if (typeof s.minItems === \"number\" && value.length < s.minItems) errors.push(`${at}: fewer than ${s.minItems} items`);\n    if (typeof s.maxItems === \"number\" && value.length > s.maxItems) errors.push(`${at}: more than ${s.maxItems} items`);\n    if (s.items && typeof s.items === \"object\") {\n      value.forEach((item, i) => errors.push(...validateSchema(item, s.items as JsonSchema, `${path}\/${i}`)));\n    }\n  }\n  if (typeOf(value) === \"object\") {\n    const obj = value as Record<string, unknown>;\n    const props = (s.properties ?? {}) as Record<string, JsonSchema>;\n    for (const key of (s.required as string[] | undefined) ?? []) {\n      if (!Object.hasOwn(obj, key)) errors.push(`${path}\/${key}: required`);\n    }\n    for (const [key, v] of Object.entries(obj)) {\n      if (Object.hasOwn(props, key)) errors.push(...validateSchema(v, props[key]!, `${path}\/${key}`));\n      else if (s.additionalProperties === false) errors.push(`${path}\/${key}: not allowed`);\n    }\n  }\n  return errors;\n}\n","type":"registry:ui","target":"components\/fancy\/template-builder\/core\/schema.ts"}]}