@mainsoft/agent-cms 0.7.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +291 -32
  3. package/TODO.md +72 -26
  4. package/UPGRADE-0.10.md +36 -0
  5. package/UPGRADE-0.8.md +117 -0
  6. package/dist/agent.cjs +39 -17
  7. package/dist/agent.d.cts +2 -2
  8. package/dist/agent.d.ts +2 -2
  9. package/dist/agent.js +9 -7
  10. package/dist/bin.js +4528 -355
  11. package/dist/{chunk-OQ55GEF3.js → chunk-3OPKTBEI.js} +1 -1
  12. package/dist/chunk-6PB4ZCHH.js +328 -0
  13. package/dist/chunk-7SCYDG2G.js +2943 -0
  14. package/dist/chunk-7WJIIJCI.js +544 -0
  15. package/dist/chunk-7Y6TU2UA.js +150 -0
  16. package/dist/{chunk-EXV6JNLY.js → chunk-AKCXMT3X.js} +15 -22
  17. package/dist/{chunk-QC2M4NZY.js → chunk-BFVBHIHV.js} +72 -1
  18. package/dist/chunk-DSJETZT4.js +493 -0
  19. package/dist/{chunk-IW3D4I7Q.js → chunk-IU2SMWAM.js} +246 -4
  20. package/dist/{chunk-VICZ76TR.js → chunk-KAO3Z3CF.js} +43 -2
  21. package/dist/{chunk-CRDW6Q72.js → chunk-MA6VKJ3F.js} +87 -25
  22. package/dist/{chunk-6K5ZTGHQ.js → chunk-PEQY4N73.js} +16 -0
  23. package/dist/{chunk-DOADAH4L.js → chunk-PGV2QPIL.js} +40 -0
  24. package/dist/{chunk-Y63XQS2J.js → chunk-TOZQYJFG.js} +1 -1
  25. package/dist/cli.cjs +4528 -355
  26. package/dist/cli.d.cts +19 -3
  27. package/dist/cli.d.ts +19 -3
  28. package/dist/cli.js +206 -16
  29. package/dist/client.cjs +72 -1
  30. package/dist/client.d.cts +308 -6
  31. package/dist/client.d.ts +308 -6
  32. package/dist/client.js +1 -1
  33. package/dist/cms-C_vkAxYV.d.cts +1537 -0
  34. package/dist/cms-pqJyowu1.d.ts +1537 -0
  35. package/dist/config.d.cts +7 -1
  36. package/dist/config.d.ts +7 -1
  37. package/dist/drizzle-repo-CviH3EX7.d.cts +146 -0
  38. package/dist/drizzle-repo-DWLD0rWe.d.ts +146 -0
  39. package/dist/errors.cjs +82 -1
  40. package/dist/errors.d.cts +43 -3
  41. package/dist/errors.d.ts +43 -3
  42. package/dist/errors.js +2 -2
  43. package/dist/frontmatter.d.cts +5 -4
  44. package/dist/frontmatter.d.ts +5 -4
  45. package/dist/http.cjs +640 -94
  46. package/dist/http.d.cts +51 -2
  47. package/dist/http.d.ts +51 -2
  48. package/dist/http.js +203 -13
  49. package/dist/index.cjs +3759 -575
  50. package/dist/index.d.cts +8 -8
  51. package/dist/index.d.ts +8 -8
  52. package/dist/index.js +226 -30
  53. package/dist/markdown.cjs +89 -25
  54. package/dist/markdown.d.cts +57 -3
  55. package/dist/markdown.d.ts +57 -3
  56. package/dist/markdown.js +5 -1
  57. package/dist/mcp.cjs +314 -37
  58. package/dist/mcp.d.cts +3 -2
  59. package/dist/mcp.d.ts +3 -2
  60. package/dist/mcp.js +12 -9
  61. package/dist/messages/en.cjs +40 -0
  62. package/dist/messages/en.js +1 -1
  63. package/dist/messages/ko.cjs +40 -0
  64. package/dist/messages/ko.js +40 -0
  65. package/dist/registry/cms-audit.json +1 -1
  66. package/dist/registry/cms-doc-editor.json +15 -4
  67. package/dist/registry/cms-doc-list.json +2 -1
  68. package/dist/registry/cms-files.json +29 -0
  69. package/dist/registry/cms-lib.json +3 -3
  70. package/dist/registry/cms-media-picker.json +29 -0
  71. package/dist/registry/cms-media.json +28 -0
  72. package/dist/registry/cms-preview-comments.json +24 -0
  73. package/dist/registry/cms-releases.json +28 -0
  74. package/dist/registry/cms-shell.json +2 -2
  75. package/dist/registry/cms-trash.json +24 -0
  76. package/dist/registry/cms-versions.json +2 -1
  77. package/dist/registry/registry.json +163 -3
  78. package/dist/storage-s3.cjs +168 -0
  79. package/dist/storage-s3.d.cts +53 -0
  80. package/dist/storage-s3.d.ts +53 -0
  81. package/dist/storage-s3.js +143 -0
  82. package/dist/storage.cjs +373 -0
  83. package/dist/storage.d.cts +183 -0
  84. package/dist/storage.d.ts +183 -0
  85. package/dist/storage.js +49 -0
  86. package/dist/tables.cjs +251 -3
  87. package/dist/tables.d.cts +4965 -681
  88. package/dist/tables.d.ts +4965 -681
  89. package/dist/tables.js +14 -2
  90. package/dist/tools.cjs +331 -20
  91. package/dist/tools.d.cts +54 -7
  92. package/dist/tools.d.ts +54 -7
  93. package/dist/tools.js +16 -7
  94. package/dist/types.cjs +99 -1
  95. package/dist/types.d.cts +205 -5
  96. package/dist/types.d.ts +205 -5
  97. package/dist/types.js +5 -3
  98. package/package.json +32 -22
  99. package/dist/ai.cjs +0 -555
  100. package/dist/ai.d.cts +0 -48
  101. package/dist/ai.d.ts +0 -48
  102. package/dist/ai.js +0 -73
  103. package/dist/chunk-52NUUZC7.js +0 -1446
  104. package/dist/chunk-IGL2V6US.js +0 -324
  105. package/dist/chunk-QQV6VLYJ.js +0 -204
  106. package/dist/cms-BPp01z-8.d.ts +0 -411
  107. package/dist/cms-D6D89-qZ.d.cts +0 -411
  108. package/dist/drizzle-repo-B1rt7r4j.d.ts +0 -90
  109. package/dist/drizzle-repo-Cn-kL2FK.d.cts +0 -90
  110. package/dist/repo-BWI2Pkrv.d.ts +0 -162
  111. package/dist/repo-CeDxUxO6.d.cts +0 -162
@@ -3,7 +3,7 @@
3
3
  "name": "cms-doc-editor",
4
4
  "type": "registry:component",
5
5
  "title": "Document editor",
6
- "description": "Info form generated from the collection schema, markdown with live preview, autosave and restore, problems on the fields, agent change review (accept, revert), save, publish, preview links.",
6
+ "description": "Info form generated from the collection schema, markdown with live preview, autosave and restore, problems on the fields, agent change review (accept, revert), save, publish, preview links. Image and file fields and \"Insert media\" open the media picker when the app has a media library.",
7
7
  "dependencies": [
8
8
  "@mainsoft/agent-cms",
9
9
  "lucide-react"
@@ -19,18 +19,29 @@
19
19
  "tabs",
20
20
  "textarea",
21
21
  "cms-lib",
22
- "cms-merge"
22
+ "cms-merge",
23
+ "cms-media-picker"
23
24
  ],
24
25
  "files": [
25
26
  {
26
27
  "path": "registry/cms/cms-doc-editor.tsx",
27
28
  "type": "registry:component",
28
- "content": "// agent-cms registry: cms-doc-editor (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish, preview links, and a merge screen when\n// someone saved first.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, Link as LinkIcon, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema } from \"@mainsoft/agent-cms/client\";\nimport { splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.get(collection, slug, { draft: true }), client.changes(collection, slug).catch(() => [] as AgentChange[])]).then(\n ([d, ch]) => {\n if (!live) return;\n applyDoc(d);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean) => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n setStatus({ text: publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n onCreated?.(collection, d.slug);\n return;\n }\n if (!doc) return;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n } finally {\n setBusy(false);\n }\n };\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={st.state} />\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n\n const saveButtons = (cls?: string) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish ? (\n <Button type=\"button\" className={cls} disabled={busy || (!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish)} onClick={() => void save(true)}>\n {t(\"publish\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n {blocks}\n <Textarea\n id={bodyId}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"min-h-[360px] flex-1 resize-none rounded-none border-0 font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n />\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog =\n previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n {publicUrl || previewAllowed ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\")}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
29
+ "content": "// agent-cms registry: cms-doc-editor (0.10.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish (now or at a set time), review requests,\n// comments, who else has it open, preview links, and a merge screen when\n// someone saved first and the two edits overlap.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, ImagePlus, Layers, Link as LinkIcon, MessageSquare, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema, type CommentThread, type DocRelease } from \"@mainsoft/agent-cms/client\";\nimport { mergeDocs, resolveDocMerge, splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState, type Presence } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { AddToReleaseDialog, BodyBackdrop, CommentsPanel, offsetOf, placeOf, PublishButton, ReviewStrip, ScheduleStrip, type BodyCursor } from \"./cms-flow\";\nimport { assetMarkdown, CmsMediaPicker } from \"./cms-media-picker\";\nimport { pasteAsMarkdown } from \"./cms-paste\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, People, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, formatZoned as formatZonedTime, personColor, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n /** Open a release (the \"in the release ...\" strip). */\n onOpenRelease?: (id: string) => void;\n /** How often this screen says \"I am here\" and looks for other people's saves, in ms. Default 15000 (3000 while someone else is here); 0 turns it off. */\n presenceMs?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, onOpenRelease, presenceMs = 15000, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const bodyRef = React.useRef<HTMLTextAreaElement>(null);\n /** Where the cursor last was in the body (null: the person never put it there). */\n const caretRef = React.useRef<[number, number] | null>(null);\n const [picking, setPicking] = React.useState(false);\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n const [release, setRelease] = React.useState<DocRelease | null>(null);\n const [threads, setThreads] = React.useState<CommentThread[]>([]);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n const [releaseOpen, setReleaseOpen] = React.useState(false);\n const [others, setOthers] = React.useState<Presence[]>([]);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n const loadComments = React.useCallback(\n async (s: string) => {\n try {\n setThreads(await client.comments(collection, s));\n } catch {\n /* readers do not see comments */\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.getWithRelease(collection, slug), client.changes(collection, slug).catch(() => [] as AgentChange[]), client.comments(collection, slug).catch(() => [] as CommentThread[])]).then(\n ([r, ch, cm]) => {\n if (!live) return;\n const d = r.doc;\n applyDoc(d);\n setRelease(r.release ?? null);\n setThreads(cm);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean): Promise<CmsDoc | null> => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n setStatus({ text: publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n onCreated?.(collection, d.slug);\n return d;\n }\n if (!doc) return null;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n return d;\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return null;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return null;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n return null;\n } finally {\n setBusy(false);\n }\n };\n\n // ── schedule and review ──\n /** The saved document these actions apply to: unsaved edits are saved first. */\n const savedDoc = async (): Promise<CmsDoc> => {\n const d = dirty ? await save(false) : doc;\n if (!d) throw new Error(\"not saved\");\n return d;\n };\n const flow = async (fn: (d: CmsDoc) => Promise<CmsDoc>, done: (d: CmsDoc) => string, rethrow = false) => {\n setBusy(true);\n setStatus(null);\n try {\n const d = await fn(await savedDoc());\n applyDoc(d);\n setStatus({ text: done(d), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e)) setStatus({ text: errorMessage(e, t), tone: \"error\" });\n if (rethrow) throw e;\n } finally {\n setBusy(false);\n }\n };\n const zone = me?.timeZone;\n const scheduleAt = (when: { publishAt: string | null; unpublishAt: string | null }) =>\n flow(\n (d) => client.schedule(collection, d.slug, { ...when, expectedVersion: d.version }),\n (d) => (d.schedule?.publishAt ? t(\"sched_done\", { version: d.schedule.version, time: formatZonedTime(d.schedule.publishAt, locale, zone) }) : t(\"sched_go\")),\n true\n );\n const unschedule = () => flow((d) => client.unschedule(collection, d.slug), () => t(\"sched_cleared\"), true);\n const requestReview = () => flow((d) => client.requestReview(collection, d.slug), () => t(\"review_requested_done\"));\n const approve = () => flow((d) => client.approveReview(collection, d.slug, { publish: true }), (d) => t(\"published_v\", { version: d.publishedVersion ?? d.version }));\n const reject = (note: string) => flow((d) => client.rejectReview(collection, d.slug, note || null), () => t(\"review_rejected_done\"), true);\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── who else is here, and their saves ──\n const live = React.useRef({ content, saved, baseVersion, dirty, others: 0 });\n live.current = { content, saved, baseVersion, dirty, others: others.length };\n const slugNow = doc?.slug;\n React.useEffect(() => {\n if (!slugNow || !presenceMs || mode.kind !== \"edit\") return;\n let stop = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const point = (at: number) => {\n const before = live.current.content.body.slice(0, at).split(\"\\n\");\n return { line: before.length, ch: before[before.length - 1].length };\n };\n /** Someone else saved: take it when nothing is unsaved here, merge when the two edits do not overlap. */\n const catchUp = async () => {\n const latest = await client.get(collection, slugNow, { draft: true });\n const now = live.current;\n if (stop || latest.version <= now.baseVersion) return;\n const who = latest.updatedByAgent ?? latest.updatedBy ?? \"\";\n if (!now.dirty) {\n applyDoc(latest);\n void loadChanges(slugNow);\n setStatus({ text: t(\"other_saved\", { who, version: latest.version }), tone: \"muted\" });\n return;\n }\n const m = mergeDocs(now.saved, now.content, contentOf(latest));\n if (m.body.conflicts.length || m.fieldConflicts.length) return; // saving opens the merge screen\n autosave.cancel();\n const merged = contentOf(resolveDocMerge(m, {}));\n // Keep the cursor where it was: text that arrived above it pushes it down.\n const el = bodyRef.current;\n const sel = caretRef.current;\n let same = 0;\n while (same < merged.body.length && merged.body[same] === now.content.body[same]) same++;\n const shift = (at: number) => (at <= same ? at : Math.max(same, at + merged.body.length - now.content.body.length));\n setDoc(latest);\n setSaved(contentOf(latest));\n setBaseVersion(latest.version);\n setContentRaw(merged);\n if (el && sel && document.activeElement === el)\n requestAnimationFrame(() => {\n el.setSelectionRange(shift(sel[0]), shift(sel[1]));\n caretRef.current = [shift(sel[0]), shift(sel[1])];\n });\n setStatus({ text: t(\"other_merged\", { who, version: latest.version }), tone: \"muted\" });\n };\n const beat = async () => {\n try {\n if (document.visibilityState !== \"hidden\") {\n const sel = caretRef.current;\n const r = await client.presence(collection, slugNow, { cursor: sel ? point(sel[1]) : null, selection: sel && sel[0] !== sel[1] ? point(sel[0]) : null });\n if (stop) return;\n setOthers(r.others);\n if (r.version > live.current.baseVersion) await catchUp();\n }\n } catch {\n /* a reader, or offline: nobody is shown */\n }\n if (!stop) timer = setTimeout(() => void beat(), live.current.others ? Math.min(presenceMs, 3000) : presenceMs);\n };\n void beat();\n return () => {\n stop = true;\n if (timer) clearTimeout(timer);\n setOthers([]);\n void client.leave(collection, slugNow).catch(() => undefined);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, collection, slugNow, presenceMs, mode.kind]);\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={doc?.review ? (doc.review.state === \"requested\" ? \"review\" : \"changes\") : st.state} />\n {doc?.schedule?.publishAt ? <StateBadge state=\"scheduled\" /> : null}\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n const mustReview = !!schema.needsReview;\n const openThreads = threads.filter((x) => !x.resolvedAt);\n /** Answering a request is for people who may publish, and never for the one who asked when everyone needs a review. */\n const mayAnswer = canPublish && me?.actor.kind === \"user\" && !(schema.review?.everyone === \"required\" && doc?.review?.byKind === \"user\" && !doc.review.byAgent && doc.review.byId === me.actor.id);\n const quiet = (p: Promise<unknown>) => void p.catch(() => undefined);\n\n const saveButtons = (cls?: string, up?: boolean) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish && !mustReview ? (\n <PublishButton\n className={cls}\n up={up}\n busy={busy}\n disabled={!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish}\n canSchedule={!!doc}\n schedule={doc?.schedule ?? null}\n onPublish={() => void save(true)}\n onSchedule={scheduleAt}\n onUnschedule={unschedule}\n />\n ) : doc && doc.review?.state !== \"requested\" ? (\n <Button type=\"button\" className={cls} disabled={busy} title={mustReview ? t(\"review_needed\") : undefined} onClick={() => void requestReview()}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const strips = doc ? (\n <>\n <ReviewStrip doc={doc} canAnswer={!!mayAnswer} canWrite={canWrite} busy={busy} onApprove={() => void approve()} onReject={reject} onRequest={() => void requestReview()} />\n <ScheduleStrip\n doc={doc}\n canPublish={canPublish}\n busy={busy}\n onAgain={() => doc.schedule && quiet(scheduleAt({ publishAt: doc.schedule.publishAt, unpublishAt: doc.schedule.unpublishAt }))}\n onUnschedule={() => quiet(unschedule())}\n />\n {release ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\">\n <Layers aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"release_in\", { name: release.name })}</span>\n {release.publishAt ? <span className=\"text-xs tabular-nums text-muted-foreground\">{formatZonedTime(release.publishAt, locale, zone)}</span> : null}\n <span className=\"flex-1\" />\n {onOpenRelease ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => onOpenRelease(release.id)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null;\n\n /** Select a part of the body and bring it into view (a comment was pressed). */\n const showInBody = (start: number, end: number) => {\n setMobileTab(\"edit\");\n requestAnimationFrame(() => {\n const el = bodyRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(start, end);\n caretRef.current = [start, end];\n const line = content.body.slice(0, start).split(\"\\n\").length - 1;\n el.scrollTop = Math.max(0, line * (parseFloat(getComputedStyle(el).lineHeight) || 24) - el.clientHeight / 3);\n });\n };\n const comments = (onClose?: () => void) =>\n doc ? (\n <CommentsPanel collection={collection} slug={doc.slug} body={content.body} canWrite={canWrite} threads={threads} onChanged={() => void loadComments(doc.slug)} getSelection={() => (caretRef.current && bodyRef.current ? [bodyRef.current.selectionStart, bodyRef.current.selectionEnd] : caretRef.current)} onGo={showInBody} onClose={onClose} />\n ) : null;\n // Drawn behind the text: what open comments are attached to, and where the others are.\n const marks = [\n ...openThreads.map((th) => placeOf(content.body, th)).filter((x): x is NonNullable<typeof x> => !!x && x.end > x.start),\n ...others\n .filter((o) => o.cursor && o.selection)\n .map((o) => {\n const a = offsetOf(content.body, o.cursor!.line, o.cursor!.ch);\n const b = offsetOf(content.body, o.selection!.line, o.selection!.ch);\n return { start: Math.min(a, b), end: Math.max(a, b), tone: \"select\" as const };\n }),\n ];\n const cursors: BodyCursor[] = others\n .filter((o) => o.cursor)\n .map((o) => ({ id: o.actorId, at: offsetOf(content.body, o.cursor!.line, o.cursor!.ch), label: o.agent ?? o.label, color: personColor(o.actorId, o.kind !== \"user\" || !!o.agent) }));\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n /** Put a file at the cursor: media on a line of its own, other files as a link. */\n const insertAsset = (a: Parameters<typeof assetMarkdown>[0]) => {\n const el = bodyRef.current;\n const [at, end] = caretRef.current ?? [content.body.length, content.body.length];\n const before = content.body.slice(0, at);\n const after = content.body.slice(end);\n const md = assetMarkdown(a);\n const block = md.startsWith(\"!\");\n const lead = !block || !before || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const tail = !block || after.startsWith(\"\\n\\n\") ? \"\" : after.startsWith(\"\\n\") || !after ? \"\\n\" : \"\\n\\n\";\n setContent({ ...content, body: `${before}${lead}${md}${tail}${after}` });\n const caret = before.length + lead.length + (block ? 2 : md.length);\n requestAnimationFrame(() => {\n el?.focus();\n // An image without alt text: leave the cursor between the brackets.\n el?.setSelectionRange(block && !a.alt ? caret : before.length + lead.length + md.length, block && !a.alt ? caret : before.length + lead.length + md.length);\n });\n };\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n {me?.media && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\" onClick={() => setPicking(true)}>\n <ImagePlus aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_insert_button\")}\n </Button>\n ) : null}\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n <CmsMediaPicker open={picking} onOpenChange={setPicking} onPick={insertAsset} />\n {blocks}\n <div className=\"relative flex min-h-[360px] flex-1 flex-col\">\n {marks.length || cursors.length ? <BodyBackdrop box={bodyRef} text={content.body} marks={marks} cursors={cursors} /> : null}\n <Textarea\n ref={bodyRef}\n id={bodyId}\n onSelect={(e) => (caretRef.current = [e.currentTarget.selectionStart, e.currentTarget.selectionEnd])}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"relative min-h-[360px] flex-1 resize-none rounded-none border-0 bg-transparent font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0 dark:bg-transparent\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n onPaste={(e) => {\n if (!canWrite) return;\n const r = pasteAsMarkdown({ html: e.clipboardData.getData(\"text/html\"), plain: e.clipboardData.getData(\"text/plain\") });\n if (!r) return; // nothing to tidy: the browser pastes as usual\n e.preventDefault();\n const el = e.currentTarget;\n const [a, b] = [el.selectionStart, el.selectionEnd];\n // insertText keeps the browser's undo history; where it is missing, set the text directly.\n if (!(typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, r.text))) {\n setContent({ ...content, body: content.body.slice(0, a) + r.text + content.body.slice(b) });\n requestAnimationFrame(() => el.setSelectionRange(a + r.text.length, a + r.text.length));\n }\n if (r.dropped) setStatus({ text: t(\"paste_dropped\"), tone: \"muted\" });\n }}\n />\n </div>\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog = (\n <>\n {previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null}\n {doc ? (\n <AddToReleaseDialog\n open={releaseOpen}\n onOpenChange={setReleaseOpen}\n collection={collection}\n slug={doc.slug}\n published={published}\n onAdded={(r) => {\n setRelease({ id: r.id, name: r.name, state: \"open\", publishAt: null });\n setStatus({ text: t(\"release_added\", { name: r.name }), tone: \"ok\" });\n }}\n />\n ) : null}\n </>\n );\n const canRelease = !!doc && canWrite && !release;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n <People people={others} max={2} />\n {publicUrl || previewAllowed || canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n {canRelease ? <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n {strips}\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n {doc && canWrite ? (\n <TabsTrigger value=\"comments\" className=\"h-6 text-xs\">\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </TabsTrigger>\n ) : null}\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n <TabsContent value=\"comments\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {comments()}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 z-10 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\", true)}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n <People people={others} className=\"mr-1\" />\n {doc && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" aria-pressed={commentsOpen} onClick={() => setCommentsOpen((v) => !v)}>\n <MessageSquare aria-hidden className=\"h-4 w-4\" />\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </Button>\n ) : null}\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {strips}\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n {commentsOpen ? comments(() => setCommentsOpen(false)) : null}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [comments, setComments] = React.useState(false);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl, { comments }).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, comments, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm\">\n <input type=\"checkbox\" className=\"h-4 w-4 accent-primary\" checked={comments} onChange={(e) => setComments(e.target.checked)} />\n {t(\"pl_comments\")}\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
29
30
  },
30
31
  {
31
32
  "path": "registry/cms/cms-field-form.tsx",
32
33
  "type": "registry:component",
33
- "content": "// agent-cms registry: cms-doc-editor (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The document info form: title, slug, summary, category, keywords and the\n// collection's own fields, generated from `_schema` (JSON Schema plus the\n// `admin` hints: label, help, widget). Problems from `diagnose()` land on the\n// field they belong to (aria-invalid + aria-describedby).\n\"use client\";\n\nimport * as React from \"react\";\nimport { Lock, X } from \"lucide-react\";\nimport type { CollectionSchema } from \"@mainsoft/agent-cms/client\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport type { DocContent } from \"./use-cms\";\nimport { useCms } from \"./use-cms\";\n\nexport type Widget = \"text\" | \"textarea\" | \"number\" | \"switch\" | \"select\" | \"multiselect\" | \"date\" | \"tags\" | \"json\";\n\ntype JsonSchema = {\n type?: string | string[];\n enum?: unknown[];\n items?: JsonSchema;\n anyOf?: JsonSchema[];\n format?: string;\n description?: string;\n maxLength?: number;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n};\n\nexport interface FieldSpec {\n key: string;\n label: string;\n help?: string;\n widget: Widget;\n required: boolean;\n options?: string[];\n integer?: boolean;\n}\n\n/** Drop `null` from `anyOf: [X, null]` (nullable fields). */\nfunction unwrap(s: JsonSchema): JsonSchema {\n if (s.anyOf) {\n const rest = s.anyOf.filter((x) => x.type !== \"null\");\n if (rest.length === 1) return { ...unwrap(rest[0]), description: s.description ?? rest[0].description };\n }\n return s;\n}\n\n/** Which widget fits a JSON Schema property (an `admin.widget` hint wins). */\nexport function widgetFor(schema: JsonSchema, hint?: string): Widget {\n if (hint) return hint as Widget;\n const s = unwrap(schema);\n const type = Array.isArray(s.type) ? s.type.find((x) => x !== \"null\") : s.type;\n if (s.enum && s.enum.every((x) => typeof x === \"string\")) return \"select\";\n if (type === \"string\") return s.format === \"date\" || s.format === \"date-time\" ? \"date\" : (s.maxLength ?? 0) > 200 ? \"textarea\" : \"text\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"switch\";\n if (type === \"array\") {\n const it = s.items ? unwrap(s.items) : {};\n if (it.enum && it.enum.every((x) => typeof x === \"string\")) return \"multiselect\";\n if (it.type === \"string\") return \"tags\";\n }\n return \"json\";\n}\n\n/** The custom fields of a collection, in schema order. */\nexport function fieldSpecs(schema: CollectionSchema): FieldSpec[] {\n const root = (schema.fields ?? {}) as JsonSchema;\n const props = root.properties ?? {};\n const req = new Set(root.required ?? []);\n return Object.entries(props).map(([key, raw]) => {\n const s = unwrap(raw);\n const hint = schema.admin?.[key];\n const widget = widgetFor(raw, hint?.widget);\n const options = (widget === \"select\" ? s.enum : widget === \"multiselect\" ? (s.items ? unwrap(s.items).enum : undefined) : undefined) as string[] | undefined;\n return { key, label: hint?.label ?? key, help: hint?.help ?? s.description, widget, required: req.has(key), options, integer: s.type === \"integer\" };\n });\n}\n\n// ── problems per field ───────────────────────────────────────────────────────\n\nexport interface FieldProblem {\n path: string;\n message: string;\n severity: \"error\" | \"warning\";\n}\n\n/** `fields.tags.0` → `fields.tags`; `title` → `title`. */\nexport function problemKey(path: string): string {\n const p = path.split(\".\");\n return p[0] === \"fields\" && p[1] ? `fields.${p[1]}` : p[0];\n}\n\n// ── small inputs ─────────────────────────────────────────────────────────────\n\ninterface Described {\n id: string;\n help?: string;\n errors?: FieldProblem[];\n}\n\nfunction describedBy({ id, help, errors }: Described): string | undefined {\n const ids = [help ? `${id}-help` : null, errors?.length ? `${id}-err` : null].filter(Boolean);\n return ids.length ? ids.join(\" \") : undefined;\n}\n\nfunction FieldShell({ id, label, help, errors, required, children, className, asGroup }: Described & { label: React.ReactNode; required?: boolean; children: React.ReactNode; className?: string; asGroup?: boolean }) {\n const { t } = useCms();\n const hasError = errors?.some((e) => e.severity === \"error\");\n const msgs = (\n <>\n {help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {help}\n </p>\n ) : null}\n {errors?.length ? (\n <p id={`${id}-err`} className={cn(\"text-xs\", hasError ? \"text-destructive\" : \"text-amber-700\")}>\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </>\n );\n const req = required ? (\n <span className=\"ml-0.5 text-destructive\" aria-hidden title={t(\"required\")}>\n *\n </span>\n ) : null;\n if (asGroup)\n return (\n <fieldset className={cn(\"flex min-w-0 flex-col gap-1.5\", className)} aria-describedby={describedBy({ id, help, errors })}>\n <legend className=\"mb-1.5 text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </legend>\n {children}\n {msgs}\n </fieldset>\n );\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-1.5\", className)}>\n <Label htmlFor={id} className=\"text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </Label>\n {children}\n {msgs}\n </div>\n );\n}\n\n/** Chips with an input: Enter or comma adds, the x removes. */\nexport function TagsInput({ id, value, onChange, invalid, describedBy: by, required }: { id: string; value: string[]; onChange: (v: string[]) => void; invalid?: boolean; describedBy?: string; required?: boolean }) {\n const { t } = useCms();\n const [text, setText] = React.useState(\"\");\n const add = () => {\n const parts = text\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((s) => !value.includes(s));\n if (parts.length) onChange([...value, ...parts]);\n setText(\"\");\n };\n return (\n <div className={cn(\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 focus-within:ring-1 focus-within:ring-ring\", invalid && \"border-destructive\")}>\n {value.map((tag) => (\n <span key={tag} className=\"inline-flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-xs\">\n {tag}\n <button type=\"button\" className=\"rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\" aria-label={t(\"tag_remove\", { tag })} onClick={() => onChange(value.filter((x) => x !== tag))}>\n <X aria-hidden className=\"h-3 w-3\" />\n </button>\n </span>\n ))}\n <input\n id={id}\n value={text}\n placeholder={value.length ? \"\" : t(\"tags_add\")}\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n aria-required={required || undefined}\n className=\"min-w-[6rem] flex-1 bg-transparent py-0.5 text-sm outline-none placeholder:text-muted-foreground\"\n onChange={(e) => setText(e.target.value)}\n onBlur={add}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \",\") {\n e.preventDefault();\n add();\n } else if (e.key === \"Backspace\" && !text && value.length) onChange(value.slice(0, -1));\n }}\n />\n </div>\n );\n}\n\nfunction JsonInput({ id, value, onChange, invalid, describedBy: by, onLocalError }: { id: string; value: unknown; onChange: (v: unknown) => void; invalid?: boolean; describedBy?: string; onLocalError: (msg: string | null) => void }) {\n const { t } = useCms();\n const [text, setText] = React.useState(() => (value === undefined ? \"\" : JSON.stringify(value, null, 2)));\n const last = React.useRef(value);\n React.useEffect(() => {\n if (JSON.stringify(last.current) !== JSON.stringify(value)) {\n setText(value === undefined ? \"\" : JSON.stringify(value, null, 2));\n last.current = value;\n }\n }, [value]);\n return (\n <Textarea\n id={id}\n value={text}\n rows={4}\n spellCheck={false}\n className=\"font-mono text-xs\"\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n onChange={(e) => {\n const v = e.target.value;\n setText(v);\n if (!v.trim()) {\n last.current = undefined;\n onLocalError(null);\n onChange(undefined);\n return;\n }\n try {\n const parsed = JSON.parse(v);\n last.current = parsed;\n onLocalError(null);\n onChange(parsed);\n } catch {\n onLocalError(t(\"json_invalid\"));\n }\n }}\n />\n );\n}\n\n// ── one custom field ─────────────────────────────────────────────────────────\n\nexport function FieldInput({ spec, idPrefix, value, onChange, problems }: { spec: FieldSpec; idPrefix: string; value: unknown; onChange: (v: unknown) => void; problems?: FieldProblem[] }) {\n const { t } = useCms();\n const id = `${idPrefix}-f-${spec.key}`;\n const [localError, setLocalError] = React.useState<string | null>(null);\n const errors = [...(problems ?? []), ...(localError ? [{ path: spec.key, message: localError, severity: \"error\" as const }] : [])];\n const invalid = errors.some((e) => e.severity === \"error\");\n const by = describedBy({ id, help: spec.help, errors });\n const common = { id, \"aria-invalid\": invalid || undefined, \"aria-describedby\": by, \"aria-required\": spec.required || undefined } as const;\n const shell = (children: React.ReactNode, o: { asGroup?: boolean; className?: string } = {}) => (\n <FieldShell id={id} label={spec.label} help={spec.help} errors={errors} required={spec.required} asGroup={o.asGroup} className={o.className}>\n {children}\n </FieldShell>\n );\n\n switch (spec.widget) {\n case \"textarea\":\n return shell(<Textarea {...common} rows={3} value={typeof value === \"string\" ? value : \"\"} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />, { className: \"md:col-span-2\" });\n case \"number\":\n return shell(\n <Input\n {...common}\n type=\"number\"\n inputMode={spec.integer ? \"numeric\" : \"decimal\"}\n step={spec.integer ? 1 : \"any\"}\n value={typeof value === \"number\" ? String(value) : \"\"}\n onChange={(e) => onChange(e.target.value === \"\" ? undefined : Number(e.target.value))}\n />\n );\n case \"switch\":\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <div className=\"flex items-center gap-2 pt-5\">\n <Checkbox {...common} checked={value === true} onCheckedChange={(v) => onChange(v === true)} />\n <Label htmlFor={id} className=\"text-sm font-normal\">\n {spec.label}\n </Label>\n </div>\n {spec.help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {spec.help}\n </p>\n ) : null}\n {errors.length ? (\n <p id={`${id}-err`} className=\"text-xs text-destructive\">\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </div>\n );\n case \"select\":\n return shell(\n <Select value={typeof value === \"string\" ? value : \"\"} onValueChange={(v: string | null) => onChange(!v || v === \"__none\" ? undefined : v)}>\n <SelectTrigger {...common} className=\"h-9\">\n <SelectValue>{typeof value === \"string\" && value ? value : <span className=\"text-muted-foreground\">{t(\"pick_one\")}</span>}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n {!spec.required ? <SelectItem value=\"__none\">{t(\"none\")}</SelectItem> : null}\n {(spec.options ?? []).map((o) => (\n <SelectItem key={o} value={o}>\n {o}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n );\n case \"multiselect\": {\n const arr = Array.isArray(value) ? (value as string[]) : [];\n return shell(\n <div className=\"flex flex-wrap gap-x-4 gap-y-2\" role=\"group\">\n {(spec.options ?? []).map((o) => {\n const oid = `${id}-${o}`;\n return (\n <div key={o} className=\"flex items-center gap-1.5\">\n <Checkbox\n id={oid}\n aria-invalid={invalid || undefined}\n checked={arr.includes(o)}\n onCheckedChange={(v) => {\n const next = v === true ? [...arr, o] : arr.filter((x) => x !== o);\n onChange(next.length ? next : undefined);\n }}\n />\n <Label htmlFor={oid} className=\"text-sm font-normal\">\n {o}\n </Label>\n </div>\n );\n })}\n </div>,\n { asGroup: true }\n );\n }\n case \"date\":\n return shell(<Input {...common} type=\"date\" value={typeof value === \"string\" ? value.slice(0, 10) : \"\"} onChange={(e) => onChange(e.target.value || undefined)} />);\n case \"tags\":\n return shell(<TagsInput id={id} required={spec.required} invalid={invalid} describedBy={by} value={Array.isArray(value) ? (value as string[]) : []} onChange={(v) => onChange(v.length ? v : undefined)} />);\n case \"json\":\n return shell(<JsonInput id={id} value={value} invalid={invalid} describedBy={by} onChange={onChange} onLocalError={setLocalError} />, { className: \"md:col-span-2\" });\n default:\n return shell(<Input {...common} value={typeof value === \"string\" ? value : value === undefined || value === null ? \"\" : String(value)} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />);\n }\n}\n\n// ── the whole form ───────────────────────────────────────────────────────────\n\nexport interface CmsFieldFormProps {\n schema: CollectionSchema;\n value: DocContent;\n onChange: (next: DocContent) => void;\n /** Problems from diagnose(), keyed by `problemKey(path)`. */\n problems?: Record<string, FieldProblem[]>;\n /** The slug cannot change once published. */\n slugLocked?: boolean;\n /** Text before the slug (e.g. \"/guide/\"). */\n slugPrefix?: string;\n idPrefix?: string;\n className?: string;\n}\n\nexport function CmsFieldForm({ schema, value, onChange, problems = {}, slugLocked, slugPrefix, idPrefix = \"cms\", className }: CmsFieldFormProps) {\n const { t } = useCms();\n const specs = React.useMemo(() => fieldSpecs(schema), [schema]);\n const set = <K extends keyof DocContent>(k: K, v: DocContent[K]) => onChange({ ...value, [k]: v });\n const setField = (k: string, v: unknown) => {\n const fields = { ...value.fields };\n if (v === undefined) delete fields[k];\n else fields[k] = v;\n onChange({ ...value, fields });\n };\n\n const text = (key: \"title\" | \"slug\" | \"summary\", label: string, o: { mono?: boolean; disabled?: boolean; help?: string; wide?: boolean } = {}) => {\n const id = `${idPrefix}-${key}`;\n const errors = problems[key];\n const invalid = errors?.some((e) => e.severity === \"error\");\n const help = o.help;\n return (\n <FieldShell id={id} label={label} errors={errors} help={help} required={key !== \"summary\"} className={o.wide ? \"md:col-span-2\" : undefined}>\n <div className=\"relative flex items-center gap-1\">\n {key === \"slug\" && slugPrefix ? <span className=\"shrink-0 font-mono text-sm text-muted-foreground\">{slugPrefix}</span> : null}\n <Input\n id={id}\n value={value[key]}\n disabled={o.disabled}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy({ id, help, errors })}\n aria-required={key !== \"summary\" || undefined}\n className={cn(\"h-9\", o.mono && \"font-mono\", o.disabled && \"pr-8\")}\n onChange={(e) => set(key, e.target.value)}\n />\n {o.disabled ? <Lock aria-hidden className=\"absolute right-3 h-3.5 w-3.5 text-muted-foreground\" /> : null}\n </div>\n </FieldShell>\n );\n };\n\n const catId = `${idPrefix}-category`;\n const kwId = `${idPrefix}-keywords`;\n const catErr = problems.category;\n const kwErr = problems.keywords;\n\n return (\n <div className={cn(\"grid grid-cols-1 gap-x-3 gap-y-3 md:grid-cols-2 xl:grid-cols-3\", className)}>\n {text(\"title\", t(\"field_title\"))}\n {text(\"slug\", t(\"field_slug\"), { mono: true, disabled: slugLocked, help: slugLocked ? t(\"field_slug_locked\") : undefined })}\n {schema.categories?.length ? (\n <FieldShell id={catId} label={t(\"field_category\")} errors={catErr}>\n <Select value={value.category ?? \"__none\"} onValueChange={(v: string | null) => set(\"category\", !v || v === \"__none\" ? null : v)}>\n <SelectTrigger id={catId} className=\"h-9\" aria-invalid={catErr?.some((e) => e.severity === \"error\") || undefined} aria-describedby={describedBy({ id: catId, errors: catErr })}>\n <SelectValue>{value.category ?? t(\"no_category\")}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__none\">{t(\"no_category\")}</SelectItem>\n {schema.categories.map((c) => (\n <SelectItem key={c} value={c}>\n {c}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </FieldShell>\n ) : null}\n {text(\"summary\", t(\"field_summary\"), { wide: true })}\n {specs.map((s) => (\n <FieldInput key={s.key} spec={s} idPrefix={idPrefix} value={value.fields[s.key]} onChange={(v) => setField(s.key, v)} problems={problems[`fields.${s.key}`]} />\n ))}\n <FieldShell id={kwId} label={t(\"field_keywords\")} errors={kwErr}>\n <TagsInput id={kwId} value={value.keywords} onChange={(v) => set(\"keywords\", v)} invalid={kwErr?.some((e) => e.severity === \"error\")} describedBy={describedBy({ id: kwId, errors: kwErr })} />\n </FieldShell>\n </div>\n );\n}\n"
34
+ "content": "// agent-cms registry: cms-doc-editor (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The document info form: title, slug, summary, category, keywords and the\n// collection's own fields, generated from `_schema` (JSON Schema plus the\n// `admin` hints: label, help, widget). Problems from `diagnose()` land on the\n// field they belong to (aria-invalid + aria-describedby).\n\"use client\";\n\nimport * as React from \"react\";\nimport { Lock, X } from \"lucide-react\";\nimport type { CollectionSchema } from \"@mainsoft/agent-cms/client\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\nimport { AssetThumb, assetMeta, CmsMediaPicker } from \"./cms-media-picker\";\nimport type { DocContent } from \"./use-cms\";\nimport { useAsset, useCms } from \"./use-cms\";\n\nexport type Widget = \"text\" | \"textarea\" | \"number\" | \"switch\" | \"select\" | \"multiselect\" | \"date\" | \"tags\" | \"json\" | \"image\" | \"file\";\n\ntype JsonSchema = {\n type?: string | string[];\n enum?: unknown[];\n items?: JsonSchema;\n anyOf?: JsonSchema[];\n format?: string;\n description?: string;\n maxLength?: number;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n};\n\nexport interface FieldSpec {\n key: string;\n label: string;\n help?: string;\n widget: Widget;\n required: boolean;\n options?: string[];\n integer?: boolean;\n /** For `image` and `file`: the collection the field belongs to and the field's own upload rules. */\n collection?: string;\n accept?: string[];\n store?: string;\n}\n\n/** Drop `null` from `anyOf: [X, null]` (nullable fields). */\nfunction unwrap(s: JsonSchema): JsonSchema {\n if (s.anyOf) {\n const rest = s.anyOf.filter((x) => x.type !== \"null\");\n if (rest.length === 1) return { ...unwrap(rest[0]), description: s.description ?? rest[0].description };\n }\n return s;\n}\n\n/** Which widget fits a JSON Schema property (an `admin.widget` hint wins). */\nexport function widgetFor(schema: JsonSchema, hint?: string): Widget {\n if (hint) return hint as Widget;\n const s = unwrap(schema);\n const type = Array.isArray(s.type) ? s.type.find((x) => x !== \"null\") : s.type;\n if (s.enum && s.enum.every((x) => typeof x === \"string\")) return \"select\";\n if (type === \"string\") return s.format === \"date\" || s.format === \"date-time\" ? \"date\" : (s.maxLength ?? 0) > 200 ? \"textarea\" : \"text\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"switch\";\n if (type === \"array\") {\n const it = s.items ? unwrap(s.items) : {};\n if (it.enum && it.enum.every((x) => typeof x === \"string\")) return \"multiselect\";\n if (it.type === \"string\") return \"tags\";\n }\n return \"json\";\n}\n\n/** The custom fields of a collection, in schema order. */\nexport function fieldSpecs(schema: CollectionSchema): FieldSpec[] {\n const root = (schema.fields ?? {}) as JsonSchema;\n const props = root.properties ?? {};\n const req = new Set(root.required ?? []);\n return Object.entries(props).map(([key, raw]) => {\n const s = unwrap(raw);\n const hint = schema.admin?.[key];\n const widget = widgetFor(raw, hint?.widget);\n const options = (widget === \"select\" ? s.enum : widget === \"multiselect\" ? (s.items ? unwrap(s.items).enum : undefined) : undefined) as string[] | undefined;\n return { key, label: hint?.label ?? key, help: hint?.help ?? s.description, widget, required: req.has(key), options, integer: s.type === \"integer\", collection: schema.slug, accept: hint?.accept ?? (widget === \"image\" ? [\"image/*\"] : undefined), store: hint?.store };\n });\n}\n\n// ── problems per field ───────────────────────────────────────────────────────\n\nexport interface FieldProblem {\n path: string;\n message: string;\n severity: \"error\" | \"warning\";\n}\n\n/** `fields.tags.0` → `fields.tags`; `title` → `title`. */\nexport function problemKey(path: string): string {\n const p = path.split(\".\");\n return p[0] === \"fields\" && p[1] ? `fields.${p[1]}` : p[0];\n}\n\n// ── small inputs ─────────────────────────────────────────────────────────────\n\ninterface Described {\n id: string;\n help?: string;\n errors?: FieldProblem[];\n}\n\nfunction describedBy({ id, help, errors }: Described): string | undefined {\n const ids = [help ? `${id}-help` : null, errors?.length ? `${id}-err` : null].filter(Boolean);\n return ids.length ? ids.join(\" \") : undefined;\n}\n\nfunction FieldShell({ id, label, help, errors, required, children, className, asGroup }: Described & { label: React.ReactNode; required?: boolean; children: React.ReactNode; className?: string; asGroup?: boolean }) {\n const { t } = useCms();\n const hasError = errors?.some((e) => e.severity === \"error\");\n const msgs = (\n <>\n {help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {help}\n </p>\n ) : null}\n {errors?.length ? (\n <p id={`${id}-err`} className={cn(\"text-xs\", hasError ? \"text-destructive\" : \"text-amber-700\")}>\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </>\n );\n const req = required ? (\n <span className=\"ml-0.5 text-destructive\" aria-hidden title={t(\"required\")}>\n *\n </span>\n ) : null;\n if (asGroup)\n return (\n <fieldset className={cn(\"flex min-w-0 flex-col gap-1.5\", className)} aria-describedby={describedBy({ id, help, errors })}>\n <legend className=\"mb-1.5 text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </legend>\n {children}\n {msgs}\n </fieldset>\n );\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-1.5\", className)}>\n <Label htmlFor={id} className=\"text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </Label>\n {children}\n {msgs}\n </div>\n );\n}\n\n/** Chips with an input: Enter or comma adds, the x removes. */\nexport function TagsInput({ id, value, onChange, invalid, describedBy: by, required }: { id: string; value: string[]; onChange: (v: string[]) => void; invalid?: boolean; describedBy?: string; required?: boolean }) {\n const { t } = useCms();\n const [text, setText] = React.useState(\"\");\n const add = () => {\n const parts = text\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((s) => !value.includes(s));\n if (parts.length) onChange([...value, ...parts]);\n setText(\"\");\n };\n return (\n <div className={cn(\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 focus-within:ring-1 focus-within:ring-ring\", invalid && \"border-destructive\")}>\n {value.map((tag) => (\n <span key={tag} className=\"inline-flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-xs\">\n {tag}\n <button type=\"button\" className=\"rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\" aria-label={t(\"tag_remove\", { tag })} onClick={() => onChange(value.filter((x) => x !== tag))}>\n <X aria-hidden className=\"h-3 w-3\" />\n </button>\n </span>\n ))}\n <input\n id={id}\n value={text}\n placeholder={value.length ? \"\" : t(\"tags_add\")}\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n aria-required={required || undefined}\n className=\"min-w-[6rem] flex-1 bg-transparent py-0.5 text-sm outline-none placeholder:text-muted-foreground\"\n onChange={(e) => setText(e.target.value)}\n onBlur={add}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \",\") {\n e.preventDefault();\n add();\n } else if (e.key === \"Backspace\" && !text && value.length) onChange(value.slice(0, -1));\n }}\n />\n </div>\n );\n}\n\nfunction JsonInput({ id, value, onChange, invalid, describedBy: by, onLocalError }: { id: string; value: unknown; onChange: (v: unknown) => void; invalid?: boolean; describedBy?: string; onLocalError: (msg: string | null) => void }) {\n const { t } = useCms();\n const [text, setText] = React.useState(() => (value === undefined ? \"\" : JSON.stringify(value, null, 2)));\n const last = React.useRef(value);\n React.useEffect(() => {\n if (JSON.stringify(last.current) !== JSON.stringify(value)) {\n setText(value === undefined ? \"\" : JSON.stringify(value, null, 2));\n last.current = value;\n }\n }, [value]);\n return (\n <Textarea\n id={id}\n value={text}\n rows={4}\n spellCheck={false}\n className=\"font-mono text-xs\"\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n onChange={(e) => {\n const v = e.target.value;\n setText(v);\n if (!v.trim()) {\n last.current = undefined;\n onLocalError(null);\n onChange(undefined);\n return;\n }\n try {\n const parsed = JSON.parse(v);\n last.current = parsed;\n onLocalError(null);\n onChange(parsed);\n } catch {\n onLocalError(t(\"json_invalid\"));\n }\n }}\n />\n );\n}\n\n// ── one custom field ─────────────────────────────────────────────────────────\n\nexport function FieldInput({ spec, idPrefix, value, onChange, problems }: { spec: FieldSpec; idPrefix: string; value: unknown; onChange: (v: unknown) => void; problems?: FieldProblem[] }) {\n const { t } = useCms();\n const id = `${idPrefix}-f-${spec.key}`;\n const [localError, setLocalError] = React.useState<string | null>(null);\n const errors = [...(problems ?? []), ...(localError ? [{ path: spec.key, message: localError, severity: \"error\" as const }] : [])];\n const invalid = errors.some((e) => e.severity === \"error\");\n const by = describedBy({ id, help: spec.help, errors });\n const common = { id, \"aria-invalid\": invalid || undefined, \"aria-describedby\": by, \"aria-required\": spec.required || undefined } as const;\n const shell = (children: React.ReactNode, o: { asGroup?: boolean; className?: string } = {}) => (\n <FieldShell id={id} label={spec.label} help={spec.help} errors={errors} required={spec.required} asGroup={o.asGroup} className={o.className}>\n {children}\n </FieldShell>\n );\n\n switch (spec.widget) {\n case \"textarea\":\n return shell(<Textarea {...common} rows={3} value={typeof value === \"string\" ? value : \"\"} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />, { className: \"md:col-span-2\" });\n case \"number\":\n return shell(\n <Input\n {...common}\n type=\"number\"\n inputMode={spec.integer ? \"numeric\" : \"decimal\"}\n step={spec.integer ? 1 : \"any\"}\n value={typeof value === \"number\" ? String(value) : \"\"}\n onChange={(e) => onChange(e.target.value === \"\" ? undefined : Number(e.target.value))}\n />\n );\n case \"switch\":\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <div className=\"flex items-center gap-2 pt-5\">\n <Checkbox {...common} checked={value === true} onCheckedChange={(v) => onChange(v === true)} />\n <Label htmlFor={id} className=\"text-sm font-normal\">\n {spec.label}\n </Label>\n </div>\n {spec.help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {spec.help}\n </p>\n ) : null}\n {errors.length ? (\n <p id={`${id}-err`} className=\"text-xs text-destructive\">\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </div>\n );\n case \"select\":\n return shell(\n <Select value={typeof value === \"string\" ? value : \"\"} onValueChange={(v: string | null) => onChange(!v || v === \"__none\" ? undefined : v)}>\n <SelectTrigger {...common} className=\"h-9\">\n <SelectValue>{typeof value === \"string\" && value ? value : <span className=\"text-muted-foreground\">{t(\"pick_one\")}</span>}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n {!spec.required ? <SelectItem value=\"__none\">{t(\"none\")}</SelectItem> : null}\n {(spec.options ?? []).map((o) => (\n <SelectItem key={o} value={o}>\n {o}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n );\n case \"multiselect\": {\n const arr = Array.isArray(value) ? (value as string[]) : [];\n return shell(\n <div className=\"flex flex-wrap gap-x-4 gap-y-2\" role=\"group\">\n {(spec.options ?? []).map((o) => {\n const oid = `${id}-${o}`;\n return (\n <div key={o} className=\"flex items-center gap-1.5\">\n <Checkbox\n id={oid}\n aria-invalid={invalid || undefined}\n checked={arr.includes(o)}\n onCheckedChange={(v) => {\n const next = v === true ? [...arr, o] : arr.filter((x) => x !== o);\n onChange(next.length ? next : undefined);\n }}\n />\n <Label htmlFor={oid} className=\"text-sm font-normal\">\n {o}\n </Label>\n </div>\n );\n })}\n </div>,\n { asGroup: true }\n );\n }\n case \"image\":\n case \"file\":\n return shell(<AssetField spec={spec} id={id} value={typeof value === \"string\" ? value : null} onChange={onChange} invalid={invalid} describedBy={by} />, { className: \"md:col-span-2\", asGroup: true });\n case \"date\":\n return shell(<Input {...common} type=\"date\" value={typeof value === \"string\" ? value.slice(0, 10) : \"\"} onChange={(e) => onChange(e.target.value || undefined)} />);\n case \"tags\":\n return shell(<TagsInput id={id} required={spec.required} invalid={invalid} describedBy={by} value={Array.isArray(value) ? (value as string[]) : []} onChange={(v) => onChange(v.length ? v : undefined)} />);\n case \"json\":\n return shell(<JsonInput id={id} value={value} invalid={invalid} describedBy={by} onChange={onChange} onLocalError={setLocalError} />, { className: \"md:col-span-2\" });\n default:\n return shell(<Input {...common} value={typeof value === \"string\" ? value : value === undefined || value === null ? \"\" : String(value)} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />);\n }\n}\n\n/** A file from the media library: its small picture and name, or a button that opens the picker. */\nfunction AssetField({ spec, id, value, onChange, invalid, describedBy: by }: { spec: FieldSpec; id: string; value: string | null; onChange: (v: unknown) => void; invalid?: boolean; describedBy?: string }) {\n const { t, me } = useCms();\n const asset = useAsset(value);\n const [open, setOpen] = React.useState(false);\n if (!me?.media) return <Input id={id} value={value ?? \"\"} aria-invalid={invalid || undefined} aria-describedby={by} onChange={(e) => onChange(e.target.value || undefined)} />;\n return (\n <div className={cn(\"flex min-h-[60px] items-center gap-3 rounded-md border border-input p-2\", invalid && \"border-destructive\")} aria-describedby={by}>\n {value ? (\n <>\n {asset ? <AssetThumb asset={asset} className=\"aspect-[4/3] w-16 shrink-0\" /> : <span className=\"aspect-[4/3] w-16 shrink-0 rounded-md border bg-muted\" />}\n <div className=\"min-w-0 flex-1\">\n <div className=\"truncate text-sm font-medium\">{asset?.name ?? value}</div>\n {asset ? <div className=\"truncate text-xs tabular-nums text-muted-foreground\">{assetMeta(asset)}</div> : null}\n </div>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" id={id} onClick={() => setOpen(true)}>\n {t(\"media_replace\")}\n </Button>\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={() => onChange(undefined)}>\n {t(\"media_remove\")}\n </Button>\n </>\n ) : (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" id={id} onClick={() => setOpen(true)}>\n {t(\"media_choose\")}\n </Button>\n )}\n <CmsMediaPicker open={open} onOpenChange={setOpen} onPick={(a) => onChange(a.id)} kinds={spec.widget === \"image\" ? [\"image\"] : undefined} accept={spec.accept} store={spec.store} field={spec.collection ? { collection: spec.collection, path: spec.key } : undefined} />\n </div>\n );\n}\n\n// ── the whole form ───────────────────────────────────────────────────────────\n\nexport interface CmsFieldFormProps {\n schema: CollectionSchema;\n value: DocContent;\n onChange: (next: DocContent) => void;\n /** Problems from diagnose(), keyed by `problemKey(path)`. */\n problems?: Record<string, FieldProblem[]>;\n /** The slug cannot change once published. */\n slugLocked?: boolean;\n /** Text before the slug (e.g. \"/guide/\"). */\n slugPrefix?: string;\n idPrefix?: string;\n className?: string;\n}\n\nexport function CmsFieldForm({ schema, value, onChange, problems = {}, slugLocked, slugPrefix, idPrefix = \"cms\", className }: CmsFieldFormProps) {\n const { t } = useCms();\n const specs = React.useMemo(() => fieldSpecs(schema), [schema]);\n const set = <K extends keyof DocContent>(k: K, v: DocContent[K]) => onChange({ ...value, [k]: v });\n const setField = (k: string, v: unknown) => {\n const fields = { ...value.fields };\n if (v === undefined) delete fields[k];\n else fields[k] = v;\n onChange({ ...value, fields });\n };\n\n const text = (key: \"title\" | \"slug\" | \"summary\", label: string, o: { mono?: boolean; disabled?: boolean; help?: string; wide?: boolean } = {}) => {\n const id = `${idPrefix}-${key}`;\n const errors = problems[key];\n const invalid = errors?.some((e) => e.severity === \"error\");\n const help = o.help;\n return (\n <FieldShell id={id} label={label} errors={errors} help={help} required={key !== \"summary\"} className={o.wide ? \"md:col-span-2\" : undefined}>\n <div className=\"relative flex items-center gap-1\">\n {key === \"slug\" && slugPrefix ? <span className=\"shrink-0 font-mono text-sm text-muted-foreground\">{slugPrefix}</span> : null}\n <Input\n id={id}\n value={value[key]}\n disabled={o.disabled}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy({ id, help, errors })}\n aria-required={key !== \"summary\" || undefined}\n className={cn(\"h-9\", o.mono && \"font-mono\", o.disabled && \"pr-8\")}\n onChange={(e) => set(key, e.target.value)}\n />\n {o.disabled ? <Lock aria-hidden className=\"absolute right-3 h-3.5 w-3.5 text-muted-foreground\" /> : null}\n </div>\n </FieldShell>\n );\n };\n\n const catId = `${idPrefix}-category`;\n const kwId = `${idPrefix}-keywords`;\n const catErr = problems.category;\n const kwErr = problems.keywords;\n\n return (\n <div className={cn(\"grid grid-cols-1 gap-x-3 gap-y-3 md:grid-cols-2 xl:grid-cols-3\", className)}>\n {text(\"title\", t(\"field_title\"))}\n {text(\"slug\", t(\"field_slug\"), { mono: true, disabled: slugLocked, help: slugLocked ? t(\"field_slug_locked\") : undefined })}\n {schema.categories?.length ? (\n <FieldShell id={catId} label={t(\"field_category\")} errors={catErr}>\n <Select value={value.category ?? \"__none\"} onValueChange={(v: string | null) => set(\"category\", !v || v === \"__none\" ? null : v)}>\n <SelectTrigger id={catId} className=\"h-9\" aria-invalid={catErr?.some((e) => e.severity === \"error\") || undefined} aria-describedby={describedBy({ id: catId, errors: catErr })}>\n <SelectValue>{value.category ?? t(\"no_category\")}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__none\">{t(\"no_category\")}</SelectItem>\n {schema.categories.map((c) => (\n <SelectItem key={c} value={c}>\n {c}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </FieldShell>\n ) : null}\n {text(\"summary\", t(\"field_summary\"), { wide: true })}\n {specs.map((s) => (\n <FieldInput key={s.key} spec={s} idPrefix={idPrefix} value={value.fields[s.key]} onChange={(v) => setField(s.key, v)} problems={problems[`fields.${s.key}`]} />\n ))}\n <FieldShell id={kwId} label={t(\"field_keywords\")} errors={kwErr}>\n <TagsInput id={kwId} value={value.keywords} onChange={(v) => set(\"keywords\", v)} invalid={kwErr?.some((e) => e.severity === \"error\")} describedBy={describedBy({ id: kwId, errors: kwErr })} />\n </FieldShell>\n </div>\n );\n}\n"
35
+ },
36
+ {
37
+ "path": "registry/cms/cms-flow.tsx",
38
+ "type": "registry:component",
39
+ "content": "// agent-cms registry: cms-doc-editor (0.10.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The pieces of the publishing flow the editor shows: the publish button\n// with its schedule panel, the schedule and review strips, the comments\n// panel, and the \"add to a release\" dialog.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, CalendarClock, Check, ChevronDown, MessageSquare, RotateCcw, Undo2, X } from \"lucide-react\";\nimport type { CommentThread } from \"@mainsoft/agent-cms/client\";\nimport { splitSections } from \"@mainsoft/agent-cms/markdown\";\nimport type { CmsComment, CmsDoc, CmsRelease } from \"@mainsoft/agent-cms/types\";\nimport { Button } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { Segmented, StatusText } from \"./cms-parts\";\nimport { formatZoned, personColor, relativeTime, useCms, zonedParts, zonedToIso } from \"./use-cms\";\n\nexport const FLOW_SELECT = \"h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring\";\nconst FIELD = \"h-9 rounded-md border border-input bg-background px-2.5 text-sm tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring\";\n\n// ── where things are in a body ───────────────────────────────────────────────\n\nexport interface Place {\n start: number;\n end: number;\n kind: \"quote\" | \"section\" | \"doc\";\n}\n\n/** Every `#` / `##` heading of `body` with its anchor (the same anchors `splitSections` gives) and where its line starts. */\nexport function sectionStarts(body: string): { anchor: string; start: number; end: number }[] {\n const out: { anchor: string; start: number; end: number }[] = [];\n let at = 0;\n let fence = false;\n for (const line of body.split(\"\\n\")) {\n if (/^```/.test(line)) fence = !fence;\n else if (!fence && /^#{1,2}\\s+\\S/.test(line)) {\n const secs = splitSections(body.slice(0, at + line.length));\n out.push({ anchor: secs[secs.length - 1]?.anchor ?? \"\", start: at, end: at + line.length });\n }\n at += line.length + 1;\n }\n return out;\n}\n\n/** The anchor of the section the character at `offset` is in (\"\" before the first heading). */\nexport function sectionAt(body: string, offset: number): string {\n let anchor = \"\";\n for (const s of sectionStarts(body)) if (s.start <= offset) anchor = s.anchor;\n return anchor;\n}\n\n/** Where a comment sits in `body` now: on its quoted text, else on its section's heading, else nowhere (null). */\nexport function placeOf(body: string, c: Pick<CmsComment, \"anchor\" | \"quote\">): Place | null {\n if (c.quote) {\n const i = body.indexOf(c.quote);\n if (i >= 0) return { start: i, end: i + c.quote.length, kind: \"quote\" };\n }\n if (!c.anchor) return c.quote ? null : { start: 0, end: 0, kind: \"doc\" };\n const s = sectionStarts(body).find((x) => x.anchor === c.anchor);\n return s ? { start: s.start, end: s.end, kind: \"section\" } : null;\n}\n\n// ── marks behind the body ────────────────────────────────────────────────────\n\nexport interface BodyCursor {\n id: string;\n /** Character offset in the body. */\n at: number;\n label: string;\n color: string;\n}\n\n/** The character offset of a 1-based line and a column in `body` (clamped to what exists). */\nexport function offsetOf(body: string, line: number, ch: number): number {\n let at = 0;\n for (let i = 1; i < line; i++) {\n const n = body.indexOf(\"\\n\", at);\n if (n < 0) return body.length;\n at = n + 1;\n }\n const end = body.indexOf(\"\\n\", at);\n return Math.min(at + Math.max(0, ch), end < 0 ? body.length : end);\n}\n\n/**\n * Sits behind the body's text box and draws what a text box cannot: the\n * places comments are attached to, and where other people's cursors are.\n * It copies the box's font and padding and follows its scrolling, so its\n * (invisible) text lines up with the real text.\n */\nexport function BodyBackdrop({ box, text, marks, cursors }: { box: React.RefObject<HTMLTextAreaElement | null>; text: string; marks: { start: number; end: number; tone?: \"select\" }[]; cursors: BodyCursor[] }) {\n const ref = React.useRef<HTMLDivElement>(null);\n // An effect, not a layout effect: the text box is a later sibling, and its ref is not set yet when layout effects of this one run.\n React.useEffect(() => {\n const el = box.current;\n const back = ref.current;\n if (!el || !back) return;\n const fit = () => {\n const cs = getComputedStyle(el);\n const bar = el.offsetWidth - el.clientWidth;\n Object.assign(back.style, { font: cs.font, letterSpacing: cs.letterSpacing, lineHeight: cs.lineHeight, paddingTop: cs.paddingTop, paddingBottom: cs.paddingBottom, paddingLeft: cs.paddingLeft, paddingRight: `${(parseFloat(cs.paddingRight) || 0) + Math.max(0, bar)}px`, tabSize: cs.tabSize });\n back.scrollTop = el.scrollTop;\n };\n fit();\n const follow = () => (back.scrollTop = el.scrollTop);\n el.addEventListener(\"scroll\", follow);\n const ro = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(fit);\n ro?.observe(el);\n return () => {\n el.removeEventListener(\"scroll\", follow);\n ro?.disconnect();\n };\n }, [box, text]);\n\n // Cut the text at every mark edge and cursor, in order.\n const cuts = new Set<number>([0, text.length]);\n for (const m of marks) (cuts.add(Math.min(m.start, text.length)), cuts.add(Math.min(m.end, text.length)));\n for (const c of cursors) cuts.add(Math.min(c.at, text.length));\n const points = [...cuts].sort((a, b) => a - b);\n const out: React.ReactNode[] = [];\n points.forEach((from, i) => {\n for (const c of cursors.filter((x) => Math.min(x.at, text.length) === from))\n out.push(\n <span key={`c${c.id}`} data-cms-cursor={c.label} className=\"relative -mr-0.5 inline-block h-[1.15em] w-0.5 align-text-bottom\" style={{ background: c.color }}>\n <span className=\"absolute -top-3.5 left-0 whitespace-nowrap rounded-[3px] rounded-bl-none px-1 font-sans text-[10px] font-semibold leading-[15px] text-white\" style={{ background: c.color }}>\n {c.label}\n </span>\n </span>\n );\n const to = points[i + 1];\n if (to === undefined) return;\n const piece = text.slice(from, to);\n const over = marks.filter((m) => m.start <= from && m.end >= to && m.end > m.start);\n out.push(\n over.length ? (\n <mark key={from} className={cn(\"rounded-sm text-transparent\", over.some((m) => !m.tone) ? \"bg-amber-200/70\" : \"bg-neutral-500/20\")}>\n {piece}\n </mark>\n ) : (\n piece\n )\n );\n });\n return (\n <div ref={ref} aria-hidden data-cms-backdrop=\"\" className=\"pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words text-transparent\">\n {out}\n {\"\\n\"}\n </div>\n );\n}\n\n// ── publish button with the schedule panel ───────────────────────────────────\n\nexport interface PublishButtonProps {\n disabled?: boolean;\n busy?: boolean;\n /** False for a document that was never saved: there is no version to schedule yet. */\n canSchedule: boolean;\n schedule: CmsDoc[\"schedule\"];\n /** Open the panel upwards (a bar at the bottom of the screen). */\n up?: boolean;\n className?: string;\n onPublish: () => void;\n onSchedule: (when: { publishAt: string | null; unpublishAt: string | null }) => Promise<void>;\n onUnschedule: () => Promise<void>;\n}\n\n/** \"Publish\", and beside it the choice between now and a set time. Times are entered on the CMS's clock. */\nexport function PublishButton({ disabled, busy, canSchedule, schedule, up, className, onPublish, onSchedule, onUnschedule }: PublishButtonProps) {\n const { t, me } = useCms();\n const zone = me?.timeZone ?? \"UTC\";\n const [open, setOpen] = React.useState(false);\n const [mode, setMode] = React.useState<\"now\" | \"later\">(\"later\");\n const [pub, setPub] = React.useState({ date: \"\", time: \"\" });\n const [down, setDown] = React.useState({ date: \"\", time: \"\" });\n const [error, setError] = React.useState<string | null>(null);\n const [working, setWorking] = React.useState(false);\n const wrap = React.useRef<HTMLDivElement>(null);\n const toggle = React.useRef<HTMLButtonElement>(null);\n const id = React.useId();\n\n const show = () => {\n // Tomorrow at nine, unless something is already set.\n const tomorrow = zonedParts(new Date(Date.now() + 86_400_000).toISOString(), zone).date;\n setPub(schedule?.publishAt ? zonedParts(schedule.publishAt, zone) : schedule ? { date: \"\", time: \"\" } : { date: tomorrow, time: \"09:00\" });\n setDown(schedule?.unpublishAt ? zonedParts(schedule.unpublishAt, zone) : { date: \"\", time: \"\" });\n setMode(\"later\");\n setError(null);\n setOpen(true);\n };\n const close = (focus = true) => {\n setOpen(false);\n if (focus) toggle.current?.focus();\n };\n\n React.useEffect(() => {\n if (!open) return;\n const away = (e: PointerEvent) => {\n if (wrap.current && !wrap.current.contains(e.target as Node)) close(false);\n };\n document.addEventListener(\"pointerdown\", away);\n return () => document.removeEventListener(\"pointerdown\", away);\n }, [open]);\n\n const submit = async () => {\n if (mode === \"now\") {\n close();\n return onPublish();\n }\n const publishAt = pub.date ? zonedToIso(pub.date, pub.time || \"09:00\", zone) : null;\n const unpublishAt = down.date ? zonedToIso(down.date, down.time || \"09:00\", zone) : null;\n const now = Date.now();\n if ((publishAt && Date.parse(publishAt) <= now) || (unpublishAt && Date.parse(unpublishAt) <= now)) return setError(t(\"sched_past\"));\n if (publishAt && unpublishAt && Date.parse(unpublishAt) <= Date.parse(publishAt)) return setError(t(\"sched_order\"));\n setWorking(true);\n setError(null);\n try {\n await onSchedule({ publishAt, unpublishAt });\n close();\n } catch (e) {\n setError(errorMessage(e, t));\n } finally {\n setWorking(false);\n }\n };\n\n const when = (label: string, v: { date: string; time: string }, set: (x: { date: string; time: string }) => void, withZone: boolean) => (\n <fieldset className=\"grid gap-1.5\">\n <legend className=\"mb-1.5 flex w-full items-center text-xs font-medium\">\n <span className=\"flex-1\">{label}</span>\n {withZone ? <span className=\"font-normal text-muted-foreground\">{zone}</span> : null}\n </legend>\n <div className=\"flex gap-2\">\n <input type=\"date\" aria-label={`${label}: ${t(\"sched_date\")}`} className={cn(FIELD, \"min-w-0 flex-1\")} value={v.date} onChange={(e) => set({ ...v, date: e.target.value })} />\n <input type=\"time\" aria-label={`${label}: ${t(\"sched_time\")}`} className={cn(FIELD, \"w-[112px]\")} value={v.time} onChange={(e) => set({ ...v, time: e.target.value })} />\n </div>\n </fieldset>\n );\n\n return (\n <div ref={wrap} className={cn(\"relative inline-flex\", className)}>\n <Button type=\"button\" className=\"flex-1 rounded-r-none\" disabled={disabled || busy} onClick={onPublish}>\n {t(\"publish\")}\n </Button>\n <Button\n ref={toggle}\n type=\"button\"\n className=\"rounded-l-none border-l border-primary-foreground/25 px-2\"\n aria-label={t(\"publish_options\")}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n disabled={busy || !canSchedule}\n onClick={() => (open ? close() : show())}\n >\n <ChevronDown aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n {open ? (\n <div\n role=\"dialog\"\n aria-label={t(\"publish_later\")}\n className={cn(\"absolute right-0 z-50 flex w-80 max-w-[calc(100vw-1rem)] flex-col gap-3 rounded-lg border bg-background p-3.5 text-sm shadow-lg\", up ? \"bottom-full mb-1.5\" : \"top-full mt-1.5\")}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.stopPropagation();\n close();\n }\n }}\n >\n <div role=\"radiogroup\" aria-label={t(\"publish_options\")} className=\"grid gap-2.5\">\n {([\"now\", \"later\"] as const).map((m) => (\n <label key={m} className=\"flex cursor-pointer items-center gap-2\">\n <input type=\"radio\" name={`${id}-mode`} className=\"h-4 w-4 accent-primary\" checked={mode === m} disabled={m === \"now\" && !!disabled} onChange={() => setMode(m)} autoFocus={m === \"later\"} />\n {t(m === \"now\" ? \"publish_now\" : \"publish_later\")}\n </label>\n ))}\n </div>\n {mode === \"later\" ? (\n <>\n {when(t(\"sched_publish_at\"), pub, setPub, true)}\n {when(t(\"sched_unpublish_at\"), down, setDown, false)}\n </>\n ) : null}\n {error ? <StatusText tone=\"error\" className=\"text-xs\">{error}</StatusText> : null}\n <div className=\"flex items-center justify-end gap-2\">\n {schedule ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"mr-auto h-8 px-2 text-destructive hover:text-destructive\"\n disabled={working}\n onClick={() => {\n setWorking(true);\n onUnschedule().then(\n () => (setWorking(false), close()),\n (e) => (setWorking(false), setError(errorMessage(e, t)))\n );\n }}\n >\n {t(\"sched_cancel\")}\n </Button>\n ) : null}\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-8\" onClick={() => close()}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-8\" disabled={working || (mode === \"later\" && !pub.date && !down.date)} onClick={() => void submit()}>\n {mode === \"now\" ? t(\"publish\") : t(\"sched_go\")}\n </Button>\n </div>\n </div>\n ) : null}\n </div>\n );\n}\n\n// ── strips under the header ──────────────────────────────────────────────────\n\nconst STRIP = \"flex flex-wrap items-center gap-x-2.5 gap-y-1.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\";\n\n/** What is scheduled, and a warning when the document changed after that. */\nexport function ScheduleStrip({ doc, canPublish, busy, onAgain, onUnschedule }: { doc: CmsDoc; canPublish: boolean; busy?: boolean; onAgain: () => void; onUnschedule: () => void }) {\n const { t, locale, me } = useCms();\n const s = doc.schedule;\n if (!s) return null;\n const zone = me?.timeZone;\n const stale = !!s.publishAt && s.version !== doc.version;\n return (\n <div role=\"status\" className={STRIP}>\n <CalendarClock aria-hidden className=\"h-4 w-4 shrink-0\" />\n {s.publishAt ? <span>{t(\"sched_banner\", { version: s.version, time: formatZoned(s.publishAt, locale, zone) })}</span> : null}\n {s.unpublishAt ? <span>{t(\"sched_banner_down\", { time: formatZoned(s.unpublishAt, locale, zone) })}</span> : null}\n <span className=\"text-xs text-muted-foreground\">{s.byAgent ?? s.by}</span>\n {stale ? <span className=\"font-medium text-amber-700\">{t(\"sched_stale\")}</span> : null}\n <span className=\"flex-1\" />\n {canPublish ? (\n <>\n {stale ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={onAgain}>\n {t(\"sched_again\")}\n </Button>\n ) : null}\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" disabled={busy} onClick={onUnschedule}>\n {t(\"sched_cancel\")}\n </Button>\n </>\n ) : null}\n </div>\n );\n}\n\n/** \"docs-bot asked for a review of v2\", with the answer buttons for people who may publish. */\nexport function ReviewStrip({ doc, canAnswer, canWrite, busy, onApprove, onReject, onRequest }: { doc: CmsDoc; canAnswer: boolean; canWrite: boolean; busy?: boolean; onApprove: () => void; onReject: (note: string) => Promise<void>; onRequest: () => void }) {\n const { t, locale } = useCms();\n const [rejecting, setRejecting] = React.useState(false);\n const [note, setNote] = React.useState(\"\");\n const [error, setError] = React.useState<string | null>(null);\n const [working, setWorking] = React.useState(false);\n const r = doc.review;\n if (!r) return null;\n const asked = r.state === \"requested\";\n const bot = r.byKind !== \"user\" || !!r.byAgent;\n return (\n <div role=\"status\" className={STRIP}>\n {!asked ? <Undo2 aria-hidden className=\"h-4 w-4 shrink-0\" /> : bot ? <Bot aria-hidden className=\"h-4 w-4 shrink-0\" /> : null}\n <span>{asked ? t(\"review_requested_by\", { who: r.byAgent ?? r.by ?? \"\", version: r.version }) : t(\"review_changes_by\", { who: r.answeredBy ?? \"\", version: r.version })}</span>\n <span className=\"text-xs text-muted-foreground\">{relativeTime(asked ? r.at : (r.answeredAt ?? r.at), t, locale)}</span>\n {r.note ? <span className=\"min-w-0 basis-full text-[13px] text-muted-foreground md:basis-auto md:truncate\">{r.note}</span> : null}\n <span className=\"flex-1\" />\n {asked && canAnswer ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={() => (setNote(\"\"), setError(null), setRejecting(true))}>\n {t(\"review_reject\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-7\" disabled={busy} onClick={onApprove}>\n {t(\"review_approve_publish\")}\n </Button>\n </>\n ) : null}\n {!asked && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={onRequest}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n <Dialog open={rejecting} onOpenChange={setRejecting}>\n <DialogContent className=\"max-w-[460px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n setWorking(true);\n onReject(note.trim()).then(\n () => (setWorking(false), setRejecting(false)),\n (err) => (setWorking(false), setError(errorMessage(err, t)))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"review_reject\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"review_requested_by\", { who: r.byAgent ?? r.by ?? \"\", version: r.version })}</DialogDescription>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-review-note\">{t(\"review_note\")}</Label>\n <Textarea id=\"cms-review-note\" autoFocus rows={4} maxLength={2000} value={note} onChange={(e) => setNote(e.target.value)} />\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setRejecting(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={working}>\n {t(\"review_reject\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n </div>\n );\n}\n\n// ── comments ─────────────────────────────────────────────────────────────────\n\nfunction Author({ c }: { c: CmsComment }) {\n const { t, locale } = useCms();\n const bot = c.authorKind === \"key\" || c.authorKind === \"system\" || !!c.authorAgent;\n const name = c.authorAgent ?? c.authorLabel ?? \"\";\n return (\n <>\n <span aria-hidden style={{ background: personColor(c.authorId ?? name, bot) }} className=\"grid h-6 w-6 shrink-0 place-items-center rounded-full text-[11px] font-semibold text-white\">\n {bot ? <Bot className=\"h-3 w-3\" /> : (name || \"?\").trim().charAt(0).toUpperCase()}\n </span>\n <span className=\"truncate font-medium\">{name}</span>\n {c.authorKind === \"guest\" ? <span className=\"shrink-0 rounded border px-1 text-[11px] text-muted-foreground\">{t(\"comment_guest\")}</span> : null}\n <span className=\"shrink-0 text-xs text-muted-foreground\">{relativeTime(c.createdAt, t, locale)}</span>\n </>\n );\n}\n\nexport interface CommentsPanelProps {\n collection: string;\n slug: string;\n /** The body as it is in the editor now (comments follow the text as it is typed). */\n body: string;\n canWrite: boolean;\n threads: CommentThread[];\n onChanged: () => void;\n /** The selection in the body, to hang a new comment on. */\n getSelection?: () => [number, number] | null;\n /** Show this part of the body (a comment's quote or heading was pressed). */\n onGo?: (start: number, end: number) => void;\n onClose?: () => void;\n className?: string;\n}\n\n/** Comments on sections and quoted text, with one level of replies. */\nexport function CommentsPanel({ collection, slug, body, canWrite, threads, onChanged, getSelection, onGo, onClose, className }: CommentsPanelProps) {\n const { client, t } = useCms();\n const [tab, setTab] = React.useState<\"open\" | \"resolved\">(\"open\");\n const [text, setText] = React.useState(\"\");\n const [replies, setReplies] = React.useState<Record<string, string>>({});\n const [error, setError] = React.useState<string | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [target, setTarget] = React.useState<{ kind: Place[\"kind\"]; quote: string; anchor: string }>({ kind: \"doc\", quote: \"\", anchor: \"\" });\n\n const act = async (fn: () => Promise<unknown>) => {\n setBusy(true);\n setError(null);\n try {\n await fn();\n onChanged();\n } catch (e) {\n setError(errorMessage(e, t));\n } finally {\n setBusy(false);\n }\n };\n /** Read where the cursor is when the person starts writing: the selection, else the section, else the whole document. */\n const aim = () => {\n const sel = getSelection?.() ?? null;\n if (!sel) return setTarget({ kind: \"doc\", quote: \"\", anchor: \"\" });\n const anchor = sectionAt(body, sel[0]);\n const quote = body.slice(sel[0], sel[1]).trim();\n setTarget(quote && !quote.includes(\"\\n\") && quote.length <= 300 ? { kind: \"quote\", quote, anchor } : { kind: anchor ? \"section\" : \"doc\", quote: \"\", anchor });\n };\n\n const open = threads.filter((x) => !x.resolvedAt);\n const done = threads.filter((x) => x.resolvedAt);\n const placed = (tab === \"open\" ? open : done).map((th) => ({ th, at: placeOf(body, th) }));\n const here = placed.filter((x) => x.at).sort((a, b) => a.at!.start - b.at!.start);\n const lost = placed.filter((x) => !x.at);\n\n const thread = ({ th, at }: { th: CommentThread; at: Place | null }) => (\n <li key={th.id} className=\"flex flex-col gap-2 border-b p-3 text-[13.5px]\">\n <div className=\"flex items-center gap-1.5\">\n <Author c={th} />\n <span className=\"flex-1\" />\n {canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-6 gap-1 px-1.5 text-xs\" disabled={busy} onClick={() => void act(() => client.resolveComment(collection, slug, th.id, !th.resolvedAt))}>\n {th.resolvedAt ? <RotateCcw aria-hidden className=\"h-3.5 w-3.5\" /> : <Check aria-hidden className=\"h-3.5 w-3.5\" />}\n {t(th.resolvedAt ? \"comment_reopen\" : \"comment_resolve\")}\n </Button>\n ) : null}\n </div>\n {th.quote || (at && at.kind === \"section\") ? (\n <button\n type=\"button\"\n disabled={!at || !onGo}\n onClick={() => at && onGo?.(at.start, at.end)}\n className=\"truncate border-l-2 pl-2 text-left font-mono text-[12.5px] text-muted-foreground outline-none enabled:hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {at?.kind === \"section\" || !th.quote ? body.slice(at!.start, at!.end) : th.quote}\n </button>\n ) : null}\n <p className=\"whitespace-pre-wrap break-words\">{th.body}</p>\n {th.replies.length ? (\n <ul className=\"ml-3.5 flex flex-col gap-2 border-l pl-3\">\n {th.replies.map((r) => (\n <li key={r.id} className=\"flex flex-col gap-1\">\n <div className=\"flex items-center gap-1.5\">\n <Author c={r} />\n </div>\n <p className=\"whitespace-pre-wrap break-words\">{r.body}</p>\n </li>\n ))}\n </ul>\n ) : null}\n {canWrite && !th.resolvedAt ? (\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const b = (replies[th.id] ?? \"\").trim();\n if (b) void act(() => client.addComment(collection, slug, { body: b, threadId: th.id }).then(() => setReplies((r) => ({ ...r, [th.id]: \"\" }))));\n }}\n >\n <Input aria-label={`${t(\"comment_reply\")}: ${th.authorAgent ?? th.authorLabel ?? \"\"}`} placeholder={t(\"comment_reply\")} className=\"h-8 text-[13px]\" maxLength={4000} value={replies[th.id] ?? \"\"} onChange={(e) => setReplies((r) => ({ ...r, [th.id]: e.target.value }))} />\n </form>\n ) : null}\n </li>\n );\n\n return (\n <aside aria-label={t(\"comments\")} className={cn(\"flex min-h-0 w-full shrink-0 flex-col md:w-80 md:border-l\", className)}>\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <MessageSquare aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"comments\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"comments_filter\")}\n value={tab}\n onChange={setTab}\n options={[\n { value: \"open\", label: t(\"comments_open\", { n: open.length }) },\n { value: \"resolved\", label: t(\"comments_resolved\", { n: done.length }) },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n {onClose ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-6 w-6\" aria-label={t(\"close\")} onClick={onClose}>\n <X aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n ) : null}\n </div>\n {canWrite && tab === \"open\" ? (\n <form\n className=\"flex flex-col gap-2 border-b p-3\"\n onSubmit={(e) => {\n e.preventDefault();\n const b = text.trim();\n if (b) void act(() => client.addComment(collection, slug, { body: b, anchor: target.anchor, quote: target.quote }).then(() => setText(\"\")));\n }}\n >\n <Textarea aria-label={t(\"comment_write\")} placeholder={t(\"comment_write\")} rows={2} maxLength={4000} className=\"min-h-[60px] resize-none text-[13px]\" value={text} onFocus={aim} onChange={(e) => setText(e.target.value)} />\n <div className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">\n {t(target.kind === \"quote\" ? \"comment_on_selection\" : target.kind === \"section\" ? \"comment_on_section\" : \"comment_on_doc\")}\n {target.quote ? <span className=\"font-mono\">: {target.quote}</span> : null}\n </span>\n <Button type=\"submit\" size=\"sm\" className=\"h-7\" disabled={busy || !text.trim()}>\n {t(\"comment_add\")}\n </Button>\n </div>\n </form>\n ) : null}\n {error ? <StatusText tone=\"error\" className=\"px-3 py-2 text-xs\">{error}</StatusText> : null}\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {!placed.length ? <p className=\"px-3 py-8 text-center text-[13px] text-muted-foreground\">{t(\"comment_empty\")}</p> : null}\n <ul>{here.map(thread)}</ul>\n {lost.length ? (\n <>\n <h3 className=\"border-b bg-muted/40 px-3 py-1.5 text-xs font-medium text-muted-foreground\">{t(\"comment_lost\")}</h3>\n <ul>{lost.map(thread)}</ul>\n </>\n ) : null}\n </div>\n </aside>\n );\n}\n\n// ── releases ─────────────────────────────────────────────────────────────────\n\n/** Put this document in an open release (or a new one), to publish or to unpublish with the rest of it. */\nexport function AddToReleaseDialog({ open, onOpenChange, collection, slug, published, onAdded }: { open: boolean; onOpenChange: (o: boolean) => void; collection: string; slug: string; published: boolean; onAdded: (r: { id: string; name: string }) => void }) {\n const { client, t } = useCms();\n const [list, setList] = React.useState<CmsRelease[] | null>(null);\n const [id, setId] = React.useState(\"\");\n const [name, setName] = React.useState(\"\");\n const [action, setAction] = React.useState<\"publish\" | \"unpublish\">(\"publish\");\n const [error, setError] = React.useState<string | null>(null);\n const [busy, setBusy] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setError(null);\n setName(\"\");\n setAction(\"publish\");\n client.releases().then(\n (all) => {\n if (!live) return;\n const openOnes = all.filter((r) => r.state !== \"published\");\n setList(openOnes);\n setId(openOnes[0]?.id ?? \"\");\n },\n (e) => live && setError(errorMessage(e, t))\n );\n return () => {\n live = false;\n };\n }, [open, client, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[420px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n (async () => {\n const target = id ? (list ?? []).find((r) => r.id === id)! : await client.createRelease(name.trim());\n await client.addToRelease(target.id, [{ collection, slug, action }]);\n return target;\n })().then(\n (r) => (setBusy(false), onAdded({ id: r.id, name: r.name }), onOpenChange(false)),\n (err) => (setBusy(false), setError(errorMessage(err, t)))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"release_add_to\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"nav_releases\")}</DialogDescription>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-rel-pick\">{t(\"nav_releases\")}</Label>\n <select id=\"cms-rel-pick\" className={FLOW_SELECT} value={id} onChange={(e) => setId(e.target.value)}>\n {(list ?? []).map((r) => (\n <option key={r.id} value={r.id}>\n {r.name}\n </option>\n ))}\n <option value=\"\">{t(\"release_new\")}</option>\n </select>\n </div>\n {!id ? (\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-rel-name\">{t(\"name\")}</Label>\n <Input id=\"cms-rel-name\" autoFocus maxLength={120} value={name} onChange={(e) => setName(e.target.value)} />\n </div>\n ) : null}\n {published ? (\n <div className=\"grid gap-1.5\">\n <span id=\"cms-rel-action\" className=\"text-sm font-medium\">\n {t(\"release_action\")}\n </span>\n <Segmented\n labelledBy=\"cms-rel-action\"\n value={action}\n onChange={setAction}\n options={[\n { value: \"publish\", label: t(\"publish\") },\n { value: \"unpublish\", label: t(\"release_unpublish\") },\n ]}\n />\n </div>\n ) : null}\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !list || (!id && !name.trim())}>\n {t(\"release_add_to\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n"
40
+ },
41
+ {
42
+ "path": "registry/cms/cms-paste.ts",
43
+ "type": "registry:lib",
44
+ "content": "// agent-cms registry: cms-doc-editor (0.10.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// What a paste becomes in the body: text copied from a web page or a\n// document program arrives as HTML and is rewritten as the markdown the CMS\n// renders (headings, lists, bold, links, tables, code). Things markdown has\n// no place for (colours, font sizes) are left out, and the caller is told.\n\n/** Remove invisible characters, straighten curly quotes, and use plain line breaks and spaces. */\nexport function cleanText(s: string): string {\n return s\n .replace(/\\r\\n?/g, \"\\n\")\n .replace(/[\\u200B-\\u200D\\u2060\\uFEFF\\u00AD]/g, \"\")\n .replace(/\\u00A0/g, \" \")\n .replace(/[\\u2018\\u2019\\u201A\\u2032]/g, \"'\")\n .replace(/[\\u201C\\u201D\\u201E\\u2033]/g, '\"');\n}\n\n/** True when the HTML says something markdown can keep. Editors that copy coloured `<div>`s and `<span>`s (code editors) are pasted as their plain text instead. */\nexport function hasStructure(html: string): boolean {\n return /<(h[1-6]|p|ul|ol|table|strong|b|em|i|a|pre|blockquote|img)\\b/i.test(html);\n}\n\nconst BLOCKS = new Set([\"P\", \"DIV\", \"SECTION\", \"ARTICLE\", \"HEADER\", \"FOOTER\", \"MAIN\", \"FIGURE\", \"FIGCAPTION\", \"H1\", \"H2\", \"H3\", \"H4\", \"H5\", \"H6\", \"UL\", \"OL\", \"LI\", \"TABLE\", \"BLOCKQUOTE\", \"PRE\", \"HR\"]);\nconst SKIP = new Set([\"SCRIPT\", \"STYLE\", \"META\", \"LINK\", \"HEAD\", \"TITLE\", \"NOSCRIPT\", \"TEMPLATE\", \"SVG\", \"BUTTON\", \"INPUT\", \"SELECT\", \"TEXTAREA\", \"IFRAME\"]);\nconst LOST = new Set([\"FONT\", \"U\", \"MARK\", \"SUB\", \"SUP\", \"SMALL\", \"BIG\"]);\n\n/**\n * HTML from the clipboard as markdown. `dropped` is true when something was\n * left out that the person could see in what they copied (a colour, a font\n * size, underline).\n */\nexport function htmlToMarkdown(html: string): { markdown: string; dropped: boolean } {\n const doc = new DOMParser().parseFromString(html, \"text/html\");\n let dropped = false;\n\n const wrap = (mark: string, s: string) => {\n // Markers go inside the spaces: \"** bold**\" is not bold.\n const m = /^(\\s*)([\\s\\S]*?)(\\s*)$/.exec(s)!;\n return m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : s;\n };\n\n const inline = (node: Node): string => {\n if (node.nodeType === 3) return (node.textContent ?? \"\").replace(/\\s+/g, \" \");\n if (node.nodeType !== 1) return \"\";\n const el = node as HTMLElement;\n const tag = el.tagName;\n if (SKIP.has(tag)) return \"\";\n if (tag === \"BR\") return \"\\n\";\n if (LOST.has(tag)) dropped = true;\n const style = el.getAttribute(\"style\") ?? \"\";\n if (/(^|;)\\s*(color|background(-color)?|font-size|text-decoration)\\s*:/i.test(style) && !/color\\s*:\\s*(#000|#000000|rgb\\(0,\\s*0,\\s*0\\)|black|inherit)/i.test(style)) dropped = true;\n if (tag === \"IMG\") {\n const src = el.getAttribute(\"src\") ?? \"\";\n return /^https:\\/\\//i.test(src) ? `![${(el.getAttribute(\"alt\") ?? \"\").replace(/[\\[\\]]/g, \"\")}](${src})` : \"\";\n }\n if (tag === \"CODE\") return el.textContent ? `\\`${el.textContent}\\`` : \"\";\n const inner = Array.from(el.childNodes).map(inline).join(\"\");\n if (tag === \"A\") {\n const href = el.getAttribute(\"href\") ?? \"\";\n return /^(https?:|mailto:|\\/)/i.test(href) && inner.trim() ? `[${inner.trim()}](${href})` : inner;\n }\n // Google Docs wraps everything in <b style=\"font-weight:normal\">; Word and Docs mark bold with spans.\n const weight = /font-weight\\s*:\\s*(\\w+)/i.exec(style)?.[1]?.toLowerCase();\n const bold = weight ? weight === \"bold\" || Number(weight) >= 600 : tag === \"B\" || tag === \"STRONG\";\n const italic = /font-style\\s*:\\s*italic/i.test(style) || tag === \"I\" || tag === \"EM\";\n let out = inner;\n if (italic) out = wrap(\"*\", out);\n if (bold) out = wrap(\"**\", out);\n return out;\n };\n\n /** A node's children as paragraphs: runs of inline nodes are joined, block children are rendered on their own. */\n const blocks = (parent: Node, depth: number): string[] => {\n const out: string[] = [];\n let run = \"\";\n const flush = () => {\n const s = run\n .split(\"\\n\")\n .map((l) => l.trim())\n .join(\"\\n\")\n .trim();\n if (s) out.push(s);\n run = \"\";\n };\n for (const child of Array.from(parent.childNodes)) {\n const el = child.nodeType === 1 ? (child as HTMLElement) : null;\n // An inline wrapper around paragraphs (Google Docs puts everything in one <b>) is only a container.\n if (el && !BLOCKS.has(el.tagName) && !SKIP.has(el.tagName) && el.querySelector(\"p,div,h1,h2,h3,h4,h5,h6,ul,ol,table,blockquote,pre\")) {\n flush();\n out.push(...blocks(el, depth));\n continue;\n }\n if (!el || !BLOCKS.has(el.tagName)) {\n run += inline(child);\n continue;\n }\n flush();\n out.push(...block(el, depth));\n }\n flush();\n return out;\n };\n\n const list = (el: HTMLElement, depth: number): string => {\n const ordered = el.tagName === \"OL\";\n let n = Number(el.getAttribute(\"start\")) || 1;\n const lines: string[] = [];\n for (const li of Array.from(el.children)) {\n if (li.tagName !== \"LI\") continue;\n const parts = blocks(li, depth + 1);\n const mark = ordered ? `${n++}. ` : \"- \";\n const pad = \" \".repeat(mark.length);\n const text = parts.join(\"\\n\").split(\"\\n\");\n lines.push(`${mark}${text[0] ?? \"\"}`, ...text.slice(1).map((l) => `${pad}${l}`));\n }\n return lines.join(\"\\n\");\n };\n\n const table = (el: HTMLElement): string => {\n const rows = Array.from(el.querySelectorAll(\"tr\")).map((tr) => Array.from(tr.children).map((c) => inline(c).replace(/\\s*\\n\\s*/g, \" \").replace(/\\|/g, \"\\\\|\").trim()));\n const width = Math.max(0, ...rows.map((r) => r.length));\n if (!width) return \"\";\n const line = (cells: string[]) => `| ${Array.from({ length: width }, (_, i) => cells[i] ?? \"\").join(\" | \")} |`;\n return [line(rows[0]), line(Array.from({ length: width }, () => \"---\")), ...rows.slice(1).map(line)].join(\"\\n\");\n };\n\n const block = (el: HTMLElement, depth: number): string[] => {\n const tag = el.tagName;\n const h = /^H([1-6])$/.exec(tag);\n if (h) {\n const text = inline(el).replace(/\\*\\*/g, \"\").replace(/\\s+/g, \" \").trim();\n return text ? [`${\"#\".repeat(Number(h[1]))} ${text}`] : [];\n }\n if (tag === \"UL\" || tag === \"OL\") return [list(el, depth)].filter(Boolean);\n if (tag === \"TABLE\") return [table(el)].filter(Boolean);\n if (tag === \"HR\") return [\"---\"];\n if (tag === \"PRE\") {\n const lang = /language-([\\w-]+)/.exec(el.querySelector(\"code\")?.className ?? \"\")?.[1] ?? \"\";\n return [`\\`\\`\\`${lang}\\n${(el.textContent ?? \"\").replace(/\\n$/, \"\")}\\n\\`\\`\\``];\n }\n if (tag === \"BLOCKQUOTE\")\n return [\n blocks(el, depth)\n .join(\"\\n\\n\")\n .split(\"\\n\")\n .map((l) => (l ? `> ${l}` : \">\"))\n .join(\"\\n\"),\n ].filter((s) => s.trim() !== \"\");\n return blocks(el, depth);\n };\n\n const markdown = cleanText(blocks(doc.body, 0).join(\"\\n\\n\"))\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n return { markdown, dropped };\n}\n\n/** What to put in the body for a paste, or null to let the browser paste as it would. */\nexport function pasteAsMarkdown(data: { html: string; plain: string }): { text: string; dropped: boolean } | null {\n if (data.html && hasStructure(data.html)) {\n const r = htmlToMarkdown(data.html);\n if (r.markdown) return { text: r.markdown, dropped: r.dropped };\n }\n const text = cleanText(data.plain);\n return text === data.plain ? null : { text, dropped: false };\n}\n"
34
45
  }
35
46
  ]
36
47
  }