@mainsoft/agent-cms 0.0.0-stage → 0.6.1

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 (108) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +21 -0
  3. package/README.md +347 -2
  4. package/TODO.md +178 -0
  5. package/UPGRADE-0.6.md +236 -0
  6. package/dist/agent.cjs +250 -0
  7. package/dist/agent.d.cts +88 -0
  8. package/dist/agent.d.ts +88 -0
  9. package/dist/agent.js +24 -0
  10. package/dist/ai.cjs +555 -0
  11. package/dist/ai.d.cts +48 -0
  12. package/dist/ai.d.ts +48 -0
  13. package/dist/ai.js +73 -0
  14. package/dist/bin.js +1556 -0
  15. package/dist/chunk-2NTK7H4W.js +10 -0
  16. package/dist/chunk-52NUUZC7.js +1446 -0
  17. package/dist/chunk-6K5ZTGHQ.js +30 -0
  18. package/dist/chunk-AKN7SUXU.js +281 -0
  19. package/dist/chunk-BTO42652.js +249 -0
  20. package/dist/chunk-CRDW6Q72.js +188 -0
  21. package/dist/chunk-DD56PTZ4.js +78 -0
  22. package/dist/chunk-DOADAH4L.js +52 -0
  23. package/dist/chunk-IGL2V6US.js +324 -0
  24. package/dist/chunk-IW3D4I7Q.js +317 -0
  25. package/dist/chunk-OQ55GEF3.js +6 -0
  26. package/dist/chunk-QC2M4NZY.js +158 -0
  27. package/dist/chunk-QIUXAUQ6.js +6 -0
  28. package/dist/chunk-QQV6VLYJ.js +204 -0
  29. package/dist/chunk-T66ZKBHF.js +25 -0
  30. package/dist/chunk-VICZ76TR.js +118 -0
  31. package/dist/cli.cjs +1596 -0
  32. package/dist/cli.d.cts +89 -0
  33. package/dist/cli.d.ts +89 -0
  34. package/dist/cli.js +534 -0
  35. package/dist/client.cjs +185 -0
  36. package/dist/client.d.cts +228 -0
  37. package/dist/client.d.ts +228 -0
  38. package/dist/client.js +13 -0
  39. package/dist/cms-BPp01z-8.d.ts +411 -0
  40. package/dist/cms-D6D89-qZ.d.cts +411 -0
  41. package/dist/config.cjs +61 -0
  42. package/dist/config.d.cts +36 -0
  43. package/dist/config.d.ts +36 -0
  44. package/dist/config.js +11 -0
  45. package/dist/diff.cjs +316 -0
  46. package/dist/diff.d.cts +122 -0
  47. package/dist/diff.d.ts +122 -0
  48. package/dist/diff.js +29 -0
  49. package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
  50. package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
  51. package/dist/errors.cjs +193 -0
  52. package/dist/errors.d.cts +109 -0
  53. package/dist/errors.d.ts +109 -0
  54. package/dist/errors.js +16 -0
  55. package/dist/frontmatter.cjs +103 -0
  56. package/dist/frontmatter.d.cts +32 -0
  57. package/dist/frontmatter.d.ts +32 -0
  58. package/dist/frontmatter.js +9 -0
  59. package/dist/http.cjs +1104 -0
  60. package/dist/http.d.cts +67 -0
  61. package/dist/http.d.ts +67 -0
  62. package/dist/http.js +321 -0
  63. package/dist/index.cjs +3066 -0
  64. package/dist/index.d.cts +19 -0
  65. package/dist/index.d.ts +19 -0
  66. package/dist/index.js +263 -0
  67. package/dist/markdown.cjs +220 -0
  68. package/dist/markdown.d.cts +88 -0
  69. package/dist/markdown.d.ts +88 -0
  70. package/dist/markdown.js +23 -0
  71. package/dist/mcp.cjs +649 -0
  72. package/dist/mcp.d.cts +33 -0
  73. package/dist/mcp.d.ts +33 -0
  74. package/dist/mcp.js +24 -0
  75. package/dist/messages/en.cjs +76 -0
  76. package/dist/messages/en.d.cts +7 -0
  77. package/dist/messages/en.d.ts +7 -0
  78. package/dist/messages/en.js +7 -0
  79. package/dist/messages/ko.cjs +76 -0
  80. package/dist/messages/ko.d.cts +7 -0
  81. package/dist/messages/ko.d.ts +7 -0
  82. package/dist/messages/ko.js +53 -0
  83. package/dist/registry/cms-audit.json +25 -0
  84. package/dist/registry/cms-command.json +23 -0
  85. package/dist/registry/cms-doc-editor.json +36 -0
  86. package/dist/registry/cms-doc-list.json +29 -0
  87. package/dist/registry/cms-empty.json +22 -0
  88. package/dist/registry/cms-keys.json +29 -0
  89. package/dist/registry/cms-lib.json +33 -0
  90. package/dist/registry/cms-merge.json +26 -0
  91. package/dist/registry/cms-shell.json +22 -0
  92. package/dist/registry/cms-versions.json +26 -0
  93. package/dist/registry/registry.json +255 -0
  94. package/dist/repo-BWI2Pkrv.d.ts +162 -0
  95. package/dist/repo-CeDxUxO6.d.cts +162 -0
  96. package/dist/tables.cjs +356 -0
  97. package/dist/tables.d.cts +3515 -0
  98. package/dist/tables.d.ts +3515 -0
  99. package/dist/tables.js +35 -0
  100. package/dist/tools.cjs +420 -0
  101. package/dist/tools.d.cts +27 -0
  102. package/dist/tools.d.ts +27 -0
  103. package/dist/tools.js +18 -0
  104. package/dist/types.cjs +226 -0
  105. package/dist/types.d.cts +286 -0
  106. package/dist/types.d.ts +286 -0
  107. package/dist/types.js +28 -0
  108. package/package.json +277 -4
@@ -0,0 +1,29 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-doc-list",
4
+ "type": "registry:component",
5
+ "title": "Document list",
6
+ "description": "State tabs with counts, category and author filters, search, 7-day views, selection with bulk publish, unpublish, hide, unhide and delete. Cards with long-press selection on phones.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "button",
13
+ "checkbox",
14
+ "dialog",
15
+ "dropdown-menu",
16
+ "input",
17
+ "select",
18
+ "table",
19
+ "cms-lib",
20
+ "cms-empty"
21
+ ],
22
+ "files": [
23
+ {
24
+ "path": "registry/cms/cms-doc-list.tsx",
25
+ "type": "registry:component",
26
+ "content": "// agent-cms registry: cms-doc-list (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Documents of one collection: state tabs with counts, category and author\n// filters, search, 7-day views, selection with bulk actions (confirm, then a\n// result per document). A table on desktop, cards on phones (press and hold\n// a card to start selecting).\n\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronRight, CircleAlert, CircleCheck, EyeOff, Eye, MoreHorizontal, Plus, Search, Trash2, Undo2, Upload, X, type LucideIcon } from \"lucide-react\";\nimport type { RestClient } from \"@mainsoft/agent-cms/client\";\nimport type { DocSummary } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Input } from \"@/components/ui/input\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\nimport type { MessageKey } from \"./cms-messages\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsEmpty } from \"./cms-empty\";\nimport { ConfirmDialog, ModifiedMark, PageHeader, Segmented, StateBadge, StatusText, Who } from \"./cms-parts\";\nimport { relativeTime, useAsync, useCms, useDebounced, useIsMobile } from \"./use-cms\";\n\ntype BulkAction = Parameters<RestClient[\"bulk\"]>[1];\ntype BulkResult = Awaited<ReturnType<RestClient[\"bulk\"]>>[number];\ntype Tab = \"all\" | \"draft\" | \"published\" | \"modified\" | \"archived\";\n\nconst ACTIONS: { action: BulkAction; Icon: LucideIcon }[] = [\n { action: \"publish\", Icon: Upload },\n { action: \"unpublish\", Icon: Undo2 },\n { action: \"archive\", Icon: EyeOff },\n { action: \"unarchive\", Icon: Eye },\n { action: \"delete\", Icon: Trash2 },\n];\n\nexport interface CmsDocListProps {\n collection: string;\n /** Open a document (row click, result dialog \"Open\"). */\n onOpenDocument?: (collection: string, slug: string) => void;\n /** Make titles real links (middle-click, open in new tab). */\n hrefFor?: (collection: string, slug: string) => string;\n /** \"New document\"; hidden when missing. */\n onNewDocument?: (collection: string) => void;\n /** Passed to the empty state's \"Create an API key\". */\n keysHref?: string;\n /** Page size for \"Load more\". Default 50. */\n pageSize?: number;\n className?: string;\n}\n\nexport function CmsDocList({ collection, onOpenDocument, hrefFor, onNewDocument, keysHref, pageSize = 50, className }: CmsDocListProps) {\n const { client, t, locale } = useCms();\n const mobile = useIsMobile();\n const schema = useAsync(() => client.schema(collection), [client, collection]);\n const counts = useAsync(() => client.counts(collection), [client, collection]);\n\n const [tab, setTab] = React.useState<Tab>(\"all\");\n const [category, setCategory] = React.useState<string>(\"__all\");\n const [by, setBy] = React.useState<\"__all\" | \"user\" | \"key\" | \"system\">(\"__all\");\n const [qInput, setQInput] = React.useState(\"\");\n const [q, setQ] = React.useState(\"\");\n const setQLater = useDebounced((v: string) => setQ(v), 250);\n const [searchOpen, setSearchOpen] = React.useState(false);\n\n const [docs, setDocs] = React.useState<DocSummary[]>([]);\n const [total, setTotal] = React.useState(0);\n const [cursor, setCursor] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(true);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [reloadTick, setReloadTick] = React.useState(0);\n\n const [selected, setSelected] = React.useState<Set<string>>(new Set());\n const [selectMode, setSelectMode] = React.useState(false);\n const [confirm, setConfirm] = React.useState<{ action: BulkAction; slugs: string[] } | null>(null);\n const [running, setRunning] = React.useState(false);\n const [runError, setRunError] = React.useState<string | null>(null);\n const [results, setResults] = React.useState<{ action: BulkAction; results: BulkResult[]; titles: Record<string, string> } | null>(null);\n\n const query = React.useMemo(\n () => ({\n state: tab === \"all\" ? undefined : tab,\n q: q || undefined,\n category: category === \"__all\" ? undefined : category,\n by: by === \"__all\" ? undefined : by,\n hits: true,\n limit: pageSize,\n }),\n [tab, q, category, by, pageSize]\n );\n\n React.useEffect(() => {\n let live = true;\n setLoading(true);\n client.list(collection, query).then(\n (r) => {\n if (!live) return;\n setDocs(r.docs);\n setTotal(r.total);\n setCursor(r.nextCursor);\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, query, reloadTick]);\n\n // A new filter clears the selection.\n React.useEffect(() => setSelected(new Set()), [collection, query]);\n\n const loadMore = async () => {\n if (!cursor) return;\n setLoading(true);\n try {\n const r = await client.list(collection, { ...query, cursor });\n setDocs((d) => [...d, ...r.docs]);\n setCursor(r.nextCursor);\n setTotal(r.total);\n } catch (e) {\n setLoadError(e);\n } finally {\n setLoading(false);\n }\n };\n\n const toggle = (slug: string, on?: boolean) =>\n setSelected((s) => {\n const n = new Set(s);\n if (on ?? !n.has(slug)) n.add(slug);\n else n.delete(slug);\n return n;\n });\n const allSelected = docs.length > 0 && docs.every((d) => selected.has(d.slug));\n const someSelected = docs.some((d) => selected.has(d.slug));\n const selectAll = (on: boolean) => setSelected(on ? new Set(docs.map((d) => d.slug)) : new Set());\n const clearSelection = () => {\n setSelected(new Set());\n setSelectMode(false);\n };\n\n const open = (slug: string) => onOpenDocument?.(collection, slug);\n\n const run = async () => {\n if (!confirm) return;\n setRunning(true);\n setRunError(null);\n const bySlug = new Map(docs.map((d) => [d.slug, d]));\n try {\n const res = await client.bulk(\n collection,\n confirm.action,\n confirm.slugs.map((slug) => ({ slug, expectedVersion: bySlug.get(slug)?.version }))\n );\n setResults({ action: confirm.action, results: res, titles: Object.fromEntries(confirm.slugs.map((s) => [s, bySlug.get(s)?.title ?? s])) });\n setConfirm(null);\n clearSelection();\n setReloadTick((n) => n + 1);\n counts.reload();\n } catch (e) {\n setRunError(errorMessage(e, t));\n } finally {\n setRunning(false);\n }\n };\n\n const c = counts.data;\n const sch = schema.data;\n const canWrite = sch?.canWrite ?? false;\n const canPublish = sch?.canPublish ?? false;\n const filtered = tab !== \"all\" || !!q || category !== \"__all\" || by !== \"__all\";\n const isEmpty = !loading && !loadError && c?.all === 0 && !filtered;\n\n const actionAllowed = (a: BulkAction) => (a === \"publish\" || a === \"unpublish\" || a === \"delete\" ? canPublish : canWrite);\n\n const tabs: { value: Tab; key: MessageKey; n: number | undefined }[] = [\n { value: \"all\", key: \"tab_all\", n: c?.all },\n { value: \"draft\", key: \"tab_draft\", n: c?.draft },\n { value: \"published\", key: \"tab_published\", n: c?.published },\n { value: \"modified\", key: \"tab_modified\", n: c?.modified },\n { value: \"archived\", key: \"tab_archived\", n: c?.archived },\n ];\n const tabControl = (\n <Segmented\n label={t(\"state_filter\")}\n value={tab}\n onChange={setTab}\n options={tabs.map((x) => ({ value: x.value, label: t(x.key, { n: x.n ?? \"\" }).trim() }))}\n className={mobile ? \"flex-nowrap overflow-x-auto\" : undefined}\n />\n );\n\n const categories = sch?.categories ?? [];\n const filters = (\n <>\n {categories.length ? (\n <Select value={category} onValueChange={(v: string | null) => setCategory(v ?? \"__all\")}>\n <SelectTrigger className=\"h-8 w-auto gap-1.5 text-[13px]\" aria-label={t(\"filter_category_label\")}>\n <SelectValue>{t(\"filter_category\", { value: category === \"__all\" ? t(\"all\") : category })}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__all\">{t(\"all\")}</SelectItem>\n {categories.map((x) => (\n <SelectItem key={x} value={x}>\n {x}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : null}\n <Select value={by} onValueChange={(v: string | null) => setBy((v ?? \"__all\") as typeof by)}>\n <SelectTrigger className=\"h-8 w-auto gap-1.5 text-[13px]\" aria-label={t(\"filter_author_label\")}>\n <SelectValue>{t(\"filter_author\", { value: by === \"__all\" ? t(\"all\") : t(by === \"user\" ? \"author_user\" : by === \"key\" ? \"author_key\" : \"author_system\") })}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__all\">{t(\"all\")}</SelectItem>\n <SelectItem value=\"user\">{t(\"author_user\")}</SelectItem>\n <SelectItem value=\"key\">{t(\"author_key\")}</SelectItem>\n <SelectItem value=\"system\">{t(\"author_system\")}</SelectItem>\n </SelectContent>\n </Select>\n </>\n );\n\n const searchBox = (\n <div className={cn(\"relative\", mobile ? \"w-full\" : \"w-60\")}>\n <label htmlFor={`cms-list-q-${collection}`} className=\"sr-only\">\n {t(\"list_search_label\")}\n </label>\n <Search aria-hidden className=\"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground\" />\n <Input\n id={`cms-list-q-${collection}`}\n type=\"search\"\n value={qInput}\n placeholder={t(\"list_search\")}\n className=\"h-8 pl-8 text-[13px]\"\n onChange={(e) => {\n setQInput(e.target.value);\n setQLater(e.target.value.trim());\n }}\n />\n </div>\n );\n\n const bulkButtons = (size: \"sm\" | \"default\") =>\n ACTIONS.filter((a) => actionAllowed(a.action)).map(({ action, Icon }) => (\n <Button\n key={action}\n type=\"button\"\n variant=\"outline\"\n size={size === \"sm\" ? \"sm\" : \"default\"}\n className={cn(\"gap-1.5\", size === \"sm\" ? \"h-7 px-2.5 text-[13px]\" : \"h-9 flex-1 px-2 text-xs\", action === \"delete\" && \"text-destructive hover:text-destructive\")}\n onClick={() => setConfirm({ action, slugs: [...selected] })}\n >\n <Icon aria-hidden className=\"h-3.5 w-3.5\" />\n {t(`action_${action}` as MessageKey)}\n </Button>\n ));\n\n const titleLink = (d: DocSummary, className?: string) =>\n hrefFor ? (\n <a\n href={hrefFor(collection, d.slug)}\n className={cn(\"font-medium hover:underline\", className)}\n onClick={(e) => {\n if (onOpenDocument && !e.metaKey && !e.ctrlKey && !e.shiftKey && e.button === 0) {\n e.preventDefault();\n open(d.slug);\n }\n }}\n >\n {d.title || d.slug}\n </a>\n ) : (\n <button type=\"button\" className={cn(\"text-left font-medium hover:underline\", className)} onClick={() => open(d.slug)}>\n {d.title || d.slug}\n </button>\n );\n\n const stateCell = (d: DocSummary) => (\n <div className=\"flex flex-col items-start gap-0.5\">\n <StateBadge state={d.state} />\n {d.modifiedSincePublish ? <ModifiedMark /> : null}\n </div>\n );\n\n const rowMenu = (d: DocSummary) => (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-7 w-7\" })} aria-label={t(\"row_actions\", { title: d.title || d.slug })}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => open(d.slug)}>{t(\"open\")}</DropdownMenuItem>\n <DropdownMenuSeparator />\n {ACTIONS.filter((a) => actionAllowed(a.action)).map(({ action }) => (\n <DropdownMenuItem key={action} className={action === \"delete\" ? \"text-destructive\" : undefined} onClick={() => setConfirm({ action, slugs: [d.slug] })}>\n {t(`action_${action}` as MessageKey)}\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n );\n\n // ── mobile: long press to select ──\n const press = React.useRef<{ timer: ReturnType<typeof setTimeout> | null; fired: boolean }>({ timer: null, fired: false });\n const startPress = (slug: string) => {\n press.current.fired = false;\n if (press.current.timer) clearTimeout(press.current.timer);\n press.current.timer = setTimeout(() => {\n press.current.fired = true;\n setSelectMode(true);\n toggle(slug, true);\n }, 500);\n };\n const endPress = () => {\n if (press.current.timer) clearTimeout(press.current.timer);\n press.current.timer = null;\n };\n\n const header = mobile && selectMode ? (\n <PageHeader\n back={\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"exit_selection\")} onClick={clearSelection}>\n <X aria-hidden className=\"h-4 w-4\" />\n </Button>\n }\n title={t(\"selected_n\", { n: selected.size })}\n >\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={() => selectAll(!allSelected)}>\n {allSelected ? t(\"clear_selection\") : t(\"select_all\")}\n </Button>\n </PageHeader>\n ) : (\n <PageHeader title={sch?.label ?? collection}>\n {mobile ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"search\")} aria-expanded={searchOpen} onClick={() => setSearchOpen((v) => !v)}>\n <Search aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n {onNewDocument && canWrite ? (\n <Button type=\"button\" size={mobile ? \"sm\" : \"default\"} className=\"gap-1.5\" onClick={() => onNewDocument(collection)}>\n <Plus aria-hidden className=\"h-4 w-4\" />\n {t(\"new_document\")}\n </Button>\n ) : null}\n </PageHeader>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n {header}\n {isEmpty ? (\n <CmsEmpty collection={collection} onNewDocument={onNewDocument} keysHref={keysHref} />\n ) : mobile ? (\n <>\n {!selectMode ? (\n <div className=\"flex flex-col gap-2 border-b px-4 py-2.5\">\n {searchOpen ? searchBox : null}\n {tabControl}\n </div>\n ) : null}\n <ul className=\"flex-1\" aria-label={sch?.label ?? collection}>\n {docs.map((d) => {\n const on = selected.has(d.slug);\n return (\n <li key={d.slug} className={cn(\"border-b\", on && \"bg-muted/60\")}>\n <button\n type=\"button\"\n aria-pressed={selectMode ? on : undefined}\n className=\"flex w-full select-none items-start gap-3 px-4 py-3 text-left outline-none focus-visible:bg-muted\"\n onPointerDown={() => startPress(d.slug)}\n onPointerUp={endPress}\n onPointerLeave={endPress}\n onPointerCancel={endPress}\n onContextMenu={(e) => {\n e.preventDefault();\n endPress();\n if (!press.current.fired) {\n setSelectMode(true);\n toggle(d.slug, true);\n }\n press.current.fired = true;\n }}\n onClick={() => {\n if (press.current.fired) {\n press.current.fired = false;\n return;\n }\n if (selectMode) toggle(d.slug);\n else open(d.slug);\n }}\n >\n {selectMode ? (\n <span aria-hidden className={cn(\"mt-0.5 grid h-4 w-4 shrink-0 place-items-center rounded-sm border border-primary\", on && \"bg-primary text-primary-foreground\")}>\n {on ? <CircleCheck className=\"h-3 w-3\" /> : null}\n </span>\n ) : null}\n <span className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <span className=\"flex items-center gap-2\">\n <span className=\"flex-1 truncate font-medium\">{d.title || d.slug}</span>\n {!selectMode ? <ChevronRight aria-hidden className=\"h-4 w-4 text-muted-foreground\" /> : null}\n </span>\n <span className=\"flex flex-wrap items-center gap-1.5\">\n <StateBadge state={d.state} />\n {d.modifiedSincePublish ? <ModifiedMark /> : d.category ? <span className=\"text-xs text-muted-foreground\">{d.category}</span> : null}\n </span>\n {!selectMode ? (\n <span className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n <Who kind={d.updatedByKind} label={`${d.updatedBy ?? \"\"}, ${relativeTime(d.updatedAt, t, locale)}`} />\n </span>\n ) : null}\n </span>\n </button>\n </li>\n );\n })}\n </ul>\n {selectMode ? (\n <div role=\"toolbar\" aria-label={t(\"bulk_bar\")} className=\"sticky bottom-0 flex gap-1.5 border-t bg-background p-2\">\n {selected.size ? bulkButtons(\"default\") : <span className=\"p-2 text-sm text-muted-foreground\">{t(\"long_press_hint\")}</span>}\n </div>\n ) : null}\n </>\n ) : (\n <div className=\"flex-1 px-6 py-4\">\n <div className=\"mb-3 flex flex-wrap items-center gap-2\">\n {searchBox}\n {tabControl}\n {filters}\n </div>\n {selected.size ? (\n <div role=\"toolbar\" aria-label={t(\"bulk_bar\")} className=\"mb-2.5 flex flex-wrap items-center gap-1.5 rounded-lg border bg-muted/40 py-1.5 pl-3 pr-2\">\n <span className=\"mr-1 text-[13px] font-medium\">{t(\"selected_n\", { n: selected.size })}</span>\n {bulkButtons(\"sm\")}\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7 text-[13px]\" onClick={clearSelection}>\n {t(\"clear_selection\")}\n </Button>\n </div>\n ) : null}\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead className=\"w-8\">\n <Checkbox\n aria-label={t(\"select_all\")}\n checked={allSelected}\n aria-checked={allSelected ? true : someSelected ? \"mixed\" : false}\n onCheckedChange={(v) => selectAll(v === true)}\n disabled={!docs.length}\n />\n </TableHead>\n <TableHead className=\"w-[38%]\">{t(\"col_title\")}</TableHead>\n <TableHead>{t(\"col_category\")}</TableHead>\n <TableHead>{t(\"col_state\")}</TableHead>\n <TableHead>{t(\"col_updated\")}</TableHead>\n <TableHead className=\"text-right\">{t(\"col_views\")}</TableHead>\n <TableHead className=\"w-10\">\n <span className=\"sr-only\">{t(\"col_actions\")}</span>\n </TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {docs.map((d) => {\n const on = selected.has(d.slug);\n return (\n <TableRow key={d.slug} data-state={on ? \"selected\" : undefined}>\n <TableCell>\n <Checkbox aria-label={t(\"select_row\", { title: d.title || d.slug })} checked={on} onCheckedChange={(v) => toggle(d.slug, v === true)} />\n </TableCell>\n <TableCell>\n {titleLink(d)}\n <div className=\"font-mono text-xs text-muted-foreground\">{d.slug}</div>\n </TableCell>\n <TableCell className=\"text-[13.5px]\">{d.category ?? \"\"}</TableCell>\n <TableCell>{stateCell(d)}</TableCell>\n <TableCell className=\"text-[13.5px]\">\n <Who kind={d.updatedByKind} label={d.updatedBy} />\n <div className=\"text-xs text-muted-foreground\">{relativeTime(d.updatedAt, t, locale)}</div>\n </TableCell>\n <TableCell className={cn(\"text-right tabular-nums\", !d.hits7d && \"text-muted-foreground\")}>{d.hits7d ?? 0}</TableCell>\n <TableCell>{rowMenu(d)}</TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n </div>\n )}\n {!isEmpty ? (\n <div className={cn(\"flex items-center justify-between gap-2 py-3 text-xs text-muted-foreground\", mobile ? \"px-4\" : \"px-6\")}>\n <StatusText className=\"text-xs\" tone={loadError ? \"error\" : \"muted\"}>\n {loadError ? errorMessage(loadError, t) : loading ? t(\"loading\") : docs.length === 0 ? t(\"no_results\") : t(\"shown_of\", { shown: docs.length, total })}\n </StatusText>\n {cursor ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={loading} onClick={() => void loadMore()}>\n {t(\"load_more\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n\n <ConfirmDialog\n open={!!confirm}\n onOpenChange={(o) => {\n if (!o) {\n setConfirm(null);\n setRunError(null);\n }\n }}\n title={confirm ? t(`confirm_${confirm.action}` as MessageKey, { n: confirm.slugs.length }) : \"\"}\n description={confirm?.action === \"delete\" ? t(\"confirm_delete_note\") : undefined}\n confirmLabel={confirm ? t(`action_${confirm.action}` as MessageKey) : \"\"}\n destructive={confirm?.action === \"delete\"}\n busy={running}\n error={runError}\n onConfirm={run}\n >\n {confirm ? (\n <ul className=\"overflow-hidden rounded-md border\">\n {confirm.slugs.map((s) => {\n const d = docs.find((x) => x.slug === s);\n return (\n <li key={s} className=\"flex items-center gap-2 border-b px-3 py-2 last:border-b-0\">\n <span className=\"flex-1 truncate text-sm font-medium\">{d?.title || s}</span>\n {d ? <span className=\"text-xs text-muted-foreground\">v{d.version}</span> : null}\n </li>\n );\n })}\n </ul>\n ) : null}\n </ConfirmDialog>\n\n <Dialog open={!!results} onOpenChange={(o) => !o && setResults(null)}>\n <DialogContent className=\"max-w-[500px]\">\n {results ? <BulkResults {...results} onOpen={(slug) => (setResults(null), open(slug))} canOpen={!!onOpenDocument} onClose={() => setResults(null)} /> : null}\n </DialogContent>\n </Dialog>\n </div>\n );\n}\n\nfunction BulkResults({ action, results, titles, onOpen, canOpen, onClose }: { action: BulkAction; results: BulkResult[]; titles: Record<string, string>; onOpen: (slug: string) => void; canOpen: boolean; onClose: () => void }) {\n const { t } = useCms();\n const ok = results.filter((r) => r.ok).length;\n const failed = results.length - ok;\n const done = t(`done_${action}` as MessageKey);\n return (\n <>\n <DialogHeader>\n <DialogTitle>{failed ? t(\"result_title\", { ok, failed, action: done }) : t(\"result_all_ok\", { n: ok, action: done })}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"bulk_bar\")}</DialogDescription>\n </DialogHeader>\n <ul className=\"overflow-hidden rounded-md border\">\n {results.map((r) => (\n <li key={r.slug} className=\"flex flex-col gap-0.5 border-b px-3 py-2 last:border-b-0\">\n <div className=\"flex items-center gap-2\">\n {r.ok ? <CircleCheck aria-hidden className=\"h-4 w-4 text-green-600\" /> : <CircleAlert aria-hidden className=\"h-4 w-4 text-destructive\" />}\n <span className=\"flex-1 truncate text-sm font-medium\">{titles[r.slug] ?? r.slug}</span>\n {r.ok ? (\n <span className=\"text-xs text-muted-foreground\">{done}</span>\n ) : canOpen && action !== \"delete\" ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7\" onClick={() => onOpen(r.slug)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n {!r.ok && r.error ? <p className=\"pl-6 text-xs text-red-900\">{r.error.message}</p> : null}\n </li>\n ))}\n </ul>\n <DialogFooter>\n <Button type=\"button\" onClick={onClose}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </>\n );\n}\n"
27
+ }
28
+ ]
29
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-empty",
4
+ "type": "registry:component",
5
+ "title": "Empty collection",
6
+ "description": "New document, and how to write with an agent instead (CLI one-liner, MCP URL, API key link).",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "button",
13
+ "cms-lib"
14
+ ],
15
+ "files": [
16
+ {
17
+ "path": "registry/cms/cms-empty.tsx",
18
+ "type": "registry:component",
19
+ "content": "// agent-cms registry: cms-empty (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// What an empty collection shows: \"New document\" and how to write with an\n// agent instead (the CLI one-liner, the MCP URL, a link to make an API key).\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, FileText, KeyRound, Plus } from \"lucide-react\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\nimport { CodeBox } from \"./cms-parts\";\nimport { cmsUrl, useCms } from \"./use-cms\";\n\nexport interface CmsEmptyProps {\n collection: string;\n /** Called by \"New document\"; hidden when missing or when you cannot write. */\n onNewDocument?: (collection: string) => void;\n /** Where \"Create an API key\" goes (admins only). */\n keysHref?: string;\n /** Or a callback for it. */\n onCreateKey?: () => void;\n /** Override the icon on top. */\n icon?: React.ReactNode;\n className?: string;\n}\n\nexport function CmsEmpty({ collection, onNewDocument, keysHref, onCreateKey, icon, className }: CmsEmptyProps) {\n const { t, me, appUrl, baseUrl } = useCms();\n const col = me?.collections.find((c) => c.slug === collection);\n const canWrite = col ? col.canWrite : true;\n const mcp = `${cmsUrl(appUrl, baseUrl)}/mcp`;\n const cli = `npx agent-cms put ${collection} ./post.md`;\n return (\n <div className={cn(\"grid flex-1 place-items-center px-4 py-10\", className)}>\n <div className=\"flex w-full max-w-[560px] flex-col items-center gap-2.5 text-center\">\n <div aria-hidden className=\"grid h-11 w-11 place-items-center rounded-xl bg-muted\">\n {icon ?? <FileText className=\"h-5 w-5\" />}\n </div>\n <h2 className=\"font-semibold\">{t(\"empty_title\")}</h2>\n {onNewDocument && canWrite ? (\n <Button type=\"button\" onClick={() => onNewDocument(collection)} className=\"gap-1.5\">\n <Plus aria-hidden className=\"h-4 w-4\" />\n {t(\"new_document\")}\n </Button>\n ) : null}\n <section aria-labelledby=\"cms-empty-agent\" className=\"mt-4 w-full rounded-lg border p-3.5 text-left\">\n <h3 id=\"cms-empty-agent\" className=\"mb-2.5 flex items-center gap-2 font-semibold\">\n <Bot aria-hidden className=\"h-4 w-4\" />\n {t(\"agent_guide\")}\n </h3>\n <div className=\"flex flex-col gap-2.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">CLI</span>\n <CodeBox value={cli} label=\"CLI\" />\n </div>\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">MCP</span>\n <CodeBox value={mcp} label=\"MCP\" />\n </div>\n </div>\n {me?.isAdmin && (keysHref || onCreateKey) ? (\n <div className=\"mt-3\">\n {keysHref ? (\n <a href={keysHref} className={buttonVariants({ variant: \"outline\", size: \"sm\", className: \"gap-1.5\" })}>\n <KeyRound aria-hidden className=\"h-4 w-4\" />\n {t(\"create_api_key\")}\n </a>\n ) : (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"gap-1.5\" onClick={onCreateKey}>\n <KeyRound aria-hidden className=\"h-4 w-4\" />\n {t(\"create_api_key\")}\n </Button>\n )}\n </div>\n ) : null}\n </section>\n </div>\n </div>\n );\n}\n"
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-keys",
4
+ "type": "registry:component",
5
+ "title": "API keys",
6
+ "description": "Keys with scopes, collections, last use and expiry; revoke; create with the secret shown once and MCP and CLI setup to copy.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "checkbox",
15
+ "dialog",
16
+ "input",
17
+ "label",
18
+ "table",
19
+ "tabs",
20
+ "cms-lib"
21
+ ],
22
+ "files": [
23
+ {
24
+ "path": "registry/cms/cms-keys.tsx",
25
+ "type": "registry:component",
26
+ "content": "// agent-cms registry: cms-keys (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// API keys for agents and scripts: list (scopes, collections, last used,\n// expiry), revoke, and create. A new key's secret is shown once, with the\n// MCP config and the CLI .env lines to copy.\n\"use client\";\n\nimport * as React from \"react\";\nimport { CircleCheck, Plus } from \"lucide-react\";\nimport type { CmsKey, KeyScope } from \"@mainsoft/agent-cms/types\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CodeBox, ConfirmDialog, PageHeader, Segmented, StatusText } from \"./cms-parts\";\nimport { cmsUrl, formatDate, relativeTime, useAsync, useCms, useIsMobile } from \"./use-cms\";\n\nconst SCOPES: KeyScope[] = [\"read\", \"write\", \"publish\", \"admin\"];\ntype Expiry = \"none\" | \"30\" | \"90\" | \"365\" | \"custom\";\n\nexport interface CmsKeysProps {\n /** Name of the MCP server in the copied config. Default \"agent-cms\". */\n mcpServerName?: string;\n className?: string;\n}\n\nexport function CmsKeys({ mcpServerName = \"agent-cms\", className }: CmsKeysProps) {\n const { client, t, locale, me } = useCms();\n const mobile = useIsMobile();\n const keys = useAsync(() => client.keys(), [client]);\n const [creating, setCreating] = React.useState(false);\n const [created, setCreated] = React.useState<{ key: CmsKey; secret: string } | null>(null);\n const [revoking, setRevoking] = React.useState<CmsKey | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n\n const colLabel = (slug: string) => me?.collections.find((c) => c.slug === slug)?.label ?? slug;\n const now = Date.now();\n\n const revoke = async () => {\n if (!revoking) return;\n setBusy(true);\n setError(null);\n try {\n await client.revokeKey(revoking.id);\n setRevoking(null);\n keys.reload();\n } catch (e) {\n setError(errorMessage(e, t));\n } finally {\n setBusy(false);\n }\n };\n\n const list = keys.data ?? [];\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={t(\"keys_title\")}>\n <Button type=\"button\" className=\"gap-1.5\" size={mobile ? \"sm\" : \"default\"} onClick={() => setCreating(true)}>\n <Plus aria-hidden className=\"h-4 w-4\" />\n {t(\"new_key\")}\n </Button>\n </PageHeader>\n <div className=\"flex-1 overflow-x-auto px-4 py-4 md:px-6\">\n <StatusText tone={keys.error ? \"error\" : \"muted\"} className=\"mb-2 text-xs\">\n {keys.error ? errorMessage(keys.error, t) : keys.loading && !keys.data ? t(\"loading\") : keys.data && !list.length ? t(\"no_keys\") : \"\"}\n </StatusText>\n {list.length ? (\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"key_name\")}</TableHead>\n <TableHead>{t(\"key_key\")}</TableHead>\n <TableHead>{t(\"key_scopes\")}</TableHead>\n <TableHead>{t(\"key_collections\")}</TableHead>\n <TableHead>{t(\"key_last_used\")}</TableHead>\n <TableHead>{t(\"key_expires\")}</TableHead>\n <TableHead>\n <span className=\"sr-only\">{t(\"col_actions\")}</span>\n </TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {list.map((k) => {\n const expired = !!k.expiresAt && Date.parse(k.expiresAt) <= now;\n const dead = expired || !!k.revokedAt;\n return (\n <TableRow key={k.id} className={cn(dead && \"text-muted-foreground\")}>\n <TableCell className={cn(!dead && \"font-medium\")}>{k.name}</TableCell>\n <TableCell className=\"font-mono text-xs\">{k.prefix}</TableCell>\n <TableCell>\n <span className=\"flex flex-wrap gap-1\">\n {k.scopes.map((s) => (\n <Badge key={s} variant=\"outline\" className=\"rounded-full px-2 py-0 text-[11.5px] font-medium\">\n {s}\n </Badge>\n ))}\n </span>\n </TableCell>\n <TableCell className=\"text-[13.5px]\">{k.collections?.length ? k.collections.map(colLabel).join(\", \") : t(\"key_all_collections\")}</TableCell>\n <TableCell className=\"text-xs\">{k.lastUsedAt ? relativeTime(k.lastUsedAt, t, locale) : t(\"key_none\")}</TableCell>\n <TableCell className=\"text-xs\">\n {expired ? (\n <Badge variant=\"outline\" className=\"rounded-full border-red-200 bg-red-50 px-2 py-0 text-[11.5px] text-red-700\">\n {t(\"key_expired\")}\n </Badge>\n ) : k.expiresAt ? (\n formatDate(k.expiresAt, locale, true)\n ) : (\n <span className=\"text-muted-foreground\">{t(\"key_never\")}</span>\n )}\n </TableCell>\n <TableCell className=\"text-right\">\n {k.revokedAt ? (\n <Badge variant=\"outline\" className=\"rounded-full border-red-200 bg-red-50 px-2 py-0 text-[11.5px] text-red-700\">\n {t(\"key_revoked\")}\n </Badge>\n ) : (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7 text-destructive hover:text-destructive\" aria-label={`${t(\"revoke\")}: ${k.name}`} onClick={() => setRevoking(k)}>\n {t(\"revoke\")}\n </Button>\n )}\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n ) : null}\n </div>\n\n <NewKeyDialog\n open={creating}\n onOpenChange={setCreating}\n onCreated={(r) => {\n setCreating(false);\n setCreated(r);\n keys.reload();\n }}\n />\n\n <Dialog open={!!created} onOpenChange={(o) => !o && setCreated(null)}>\n <DialogContent className=\"max-w-[540px]\">{created ? <KeyCreated name={created.key.name} secret={created.secret} mcpServerName={mcpServerName} onClose={() => setCreated(null)} /> : null}</DialogContent>\n </Dialog>\n\n <ConfirmDialog\n open={!!revoking}\n onOpenChange={(o) => {\n if (!o) {\n setRevoking(null);\n setError(null);\n }\n }}\n title={t(\"revoke_confirm\", { name: revoking?.name ?? \"\" })}\n description={t(\"revoke_note\")}\n confirmLabel={t(\"revoke\")}\n destructive\n busy={busy}\n error={error}\n onConfirm={revoke}\n />\n </div>\n );\n}\n\nfunction NewKeyDialog({ open, onOpenChange, onCreated }: { open: boolean; onOpenChange: (o: boolean) => void; onCreated: (r: { key: CmsKey; secret: string }) => void }) {\n const { client, t, me } = useCms();\n const [name, setName] = React.useState(\"\");\n const [scopes, setScopes] = React.useState<KeyScope[]>([\"read\", \"write\"]);\n const [cols, setCols] = React.useState<string[]>([]);\n const [expiry, setExpiry] = React.useState<Expiry>(\"none\");\n const [date, setDate] = React.useState(\"\");\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n\n React.useEffect(() => {\n if (open) {\n setName(\"\");\n setScopes([\"read\", \"write\"]);\n setCols([]);\n setExpiry(\"none\");\n setDate(\"\");\n setError(null);\n }\n }, [open]);\n\n const expiresAt = (): string | null => {\n if (expiry === \"none\") return null;\n if (expiry === \"custom\") return date ? new Date(`${date}T23:59:59`).toISOString() : null;\n return new Date(Date.now() + Number(expiry) * 86_400_000).toISOString();\n };\n\n const submit = async (e: React.FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n try {\n const r = await client.createKey({ name: name.trim(), scopes, collections: cols.length ? cols : null, expiresAt: expiresAt() });\n onCreated(r);\n } catch (err) {\n setError(errorMessage(err, t));\n } finally {\n setBusy(false);\n }\n };\n\n const toggle = <T,>(list: T[], v: T, on: boolean) => (on ? [...list.filter((x) => x !== v), v] : list.filter((x) => x !== v));\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[480px]\">\n <form onSubmit={submit} className=\"flex flex-col gap-4\">\n <DialogHeader>\n <DialogTitle>{t(\"new_key\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"scope_help\")}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-1.5\">\n <Label htmlFor=\"cms-key-name\" className=\"text-xs text-muted-foreground\">\n {t(\"key_name\")}\n </Label>\n <Input id=\"cms-key-name\" value={name} required maxLength={60} autoComplete=\"off\" onChange={(e) => setName(e.target.value)} />\n </div>\n <fieldset className=\"flex flex-col gap-1.5\" aria-describedby=\"cms-key-scopes-help\">\n <legend className=\"mb-1.5 text-xs font-medium text-muted-foreground\">{t(\"key_scopes\")}</legend>\n <div className=\"flex flex-wrap gap-x-4 gap-y-2\">\n {SCOPES.map((s) => (\n <div key={s} className=\"flex items-center gap-1.5\">\n <Checkbox id={`cms-key-scope-${s}`} checked={scopes.includes(s)} onCheckedChange={(v) => setScopes((x) => toggle(x, s, v === true))} />\n <Label htmlFor={`cms-key-scope-${s}`} className=\"font-normal\">\n {s}\n </Label>\n </div>\n ))}\n </div>\n <p id=\"cms-key-scopes-help\" className=\"text-xs text-muted-foreground\">\n {t(\"scope_help\")}\n </p>\n </fieldset>\n <fieldset className=\"flex flex-col gap-1.5\" aria-describedby=\"cms-key-cols-help\">\n <legend className=\"mb-1.5 text-xs font-medium text-muted-foreground\">{t(\"key_collections\")}</legend>\n <div className=\"flex flex-wrap gap-x-4 gap-y-2\">\n {(me?.collections ?? []).map((c) => (\n <div key={c.slug} className=\"flex items-center gap-1.5\">\n <Checkbox id={`cms-key-col-${c.slug}`} checked={cols.includes(c.slug)} onCheckedChange={(v) => setCols((x) => toggle(x, c.slug, v === true))} />\n <Label htmlFor={`cms-key-col-${c.slug}`} className=\"font-normal\">\n {c.label}\n </Label>\n </div>\n ))}\n </div>\n <p id=\"cms-key-cols-help\" className=\"text-xs text-muted-foreground\">\n {t(\"collections_help\")}\n </p>\n </fieldset>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-key-expiry\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"key_expires\")}\n </span>\n <Segmented\n labelledBy=\"cms-key-expiry\"\n value={expiry}\n onChange={setExpiry}\n options={[\n { value: \"none\", label: t(\"expiry_none\") },\n { value: \"30\", label: t(\"expiry_30\") },\n { value: \"90\", label: t(\"expiry_90\") },\n { value: \"365\", label: t(\"expiry_365\") },\n { value: \"custom\", label: t(\"expiry_custom\") },\n ]}\n />\n {expiry === \"custom\" ? (\n <div className=\"mt-1 flex flex-col gap-1.5\">\n <Label htmlFor=\"cms-key-date\" className=\"text-xs text-muted-foreground\">\n {t(\"expiry_date\")}\n </Label>\n <Input id=\"cms-key-date\" type=\"date\" required value={date} min={new Date(Date.now() + 86_400_000).toISOString().slice(0, 10)} onChange={(e) => setDate(e.target.value)} />\n </div>\n ) : null}\n </div>\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 || !name.trim() || !scopes.length}>\n {t(\"create\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\n/** The one time a secret is visible: the key and how to plug it into an agent. */\nexport function KeyCreated({ name, secret, mcpServerName = \"agent-cms\", onClose }: { name: string; secret: string; mcpServerName?: string; onClose: () => void }) {\n const { t, appUrl, baseUrl } = useCms();\n const url = cmsUrl(appUrl, baseUrl);\n const mcp = JSON.stringify({ mcpServers: { [mcpServerName]: { type: \"http\", url: `${url}/mcp`, headers: { Authorization: `Bearer ${secret}` } } } }, null, 2);\n const env = `AGENT_CMS_URL=${url}\\nAGENT_CMS_KEY=${secret}`;\n return (\n <>\n <DialogHeader>\n <DialogTitle className=\"flex items-center gap-2\">\n <CircleCheck aria-hidden className=\"h-5 w-5 text-green-600\" />\n {name}\n </DialogTitle>\n <DialogDescription>{t(\"key_once\")}</DialogDescription>\n </DialogHeader>\n <CodeBox value={secret} label={t(\"key_secret\")} />\n <Tabs defaultValue=\"cli\" className=\"mt-1\">\n <TabsList aria-label={t(\"key_connect\")}>\n <TabsTrigger value=\"mcp\">MCP</TabsTrigger>\n <TabsTrigger value=\"cli\">CLI (.env)</TabsTrigger>\n </TabsList>\n <TabsContent value=\"mcp\">\n <CodeBox value={mcp} label=\"MCP\" multiline />\n </TabsContent>\n <TabsContent value=\"cli\" className=\"flex flex-col gap-2\">\n <CodeBox value={env} label=\".env\" multiline />\n <CodeBox value=\"npx agent-cms collections\" label=\"CLI\" />\n </TabsContent>\n </Tabs>\n <DialogFooter>\n <Button type=\"button\" onClick={onClose}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </>\n );\n}\n"
27
+ }
28
+ ]
29
+ }
@@ -0,0 +1,33 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-lib",
4
+ "type": "registry:lib",
5
+ "title": "agent-cms client and helpers",
6
+ "description": "CmsProvider and useCms (REST client, UI strings in English and Korean), small hooks, shared parts (state badge, copy box, confirm dialog, page header, markdown preview).",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "dialog"
15
+ ],
16
+ "files": [
17
+ {
18
+ "path": "registry/cms/use-cms.ts",
19
+ "type": "registry:lib",
20
+ "content": "// agent-cms registry: cms-lib (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The one place the admin screens get their REST client, strings and a few\n// small hooks from. Wrap the admin pages once:\n//\n// <CmsProvider baseUrl=\"/api/cms\" messages={ko}>{children}</CmsProvider>\n\"use client\";\n\nimport * as React from \"react\";\nimport { createRestClient, type Me, type RestClient } from \"@mainsoft/agent-cms/client\";\nimport type { DocLike } from \"@mainsoft/agent-cms/diff\";\nimport { createT, en, type CmsMessages, type T } from \"./cms-messages\";\n\n/** What create / update / autosave take. */\nexport type DocInputWire = Parameters<RestClient[\"update\"]>[2];\n\nexport interface CmsProviderProps {\n /** Where the CMS route is mounted. Default \"/api/cms\". */\n baseUrl?: string;\n /** UI strings (any subset); e.g. `ko` from ./cms-messages. Default English. */\n messages?: Partial<CmsMessages>;\n /** The app's public origin, for the MCP URL shown to agents. Default: the page's origin. */\n appUrl?: string;\n /** Custom fetch (tests, server-side rendering). */\n fetch?: typeof fetch;\n children?: React.ReactNode;\n}\n\nexport interface CmsContextValue {\n client: RestClient;\n t: T;\n locale: string;\n baseUrl: string;\n appUrl: string;\n /** `GET /_me` (null while loading). */\n me: Me | null;\n meError: unknown;\n reloadMe: () => void;\n}\n\nconst CmsContext = React.createContext<CmsContextValue | null>(null);\n\nexport function CmsProvider({ baseUrl = \"/api/cms\", messages, appUrl, fetch: f, children }: CmsProviderProps) {\n const client = React.useMemo(() => createRestClient({ url: baseUrl, fetch: f }), [baseUrl, f]);\n const t = React.useMemo(() => createT(messages), [messages]);\n const locale = messages?._locale ?? en._locale;\n const [me, setMe] = React.useState<Me | null>(null);\n const [meError, setMeError] = React.useState<unknown>(null);\n const [tick, setTick] = React.useState(0);\n React.useEffect(() => {\n let live = true;\n client.me().then(\n (m) => live && (setMe(m), setMeError(null)),\n (e) => live && setMeError(e)\n );\n return () => {\n live = false;\n };\n }, [client, tick]);\n const origin = appUrl ?? (typeof window !== \"undefined\" ? window.location.origin : \"\");\n const value = React.useMemo<CmsContextValue>(\n () => ({ client, t, locale, baseUrl, appUrl: origin.replace(/\\/+$/, \"\"), me, meError, reloadMe: () => setTick((n) => n + 1) }),\n [client, t, locale, baseUrl, origin, me, meError]\n );\n return React.createElement(CmsContext.Provider, { value }, children);\n}\n\nexport function useCms(): CmsContextValue {\n const v = React.useContext(CmsContext);\n if (!v) throw new Error(\"agent-cms: wrap the admin screens in <CmsProvider>.\");\n return v;\n}\n\n/** Full URL of the CMS endpoint (e.g. https://app.example.com/api/cms). */\nexport function cmsUrl(appUrl: string, baseUrl: string): string {\n return /^https?:\\/\\//.test(baseUrl) ? baseUrl.replace(/\\/+$/, \"\") : `${appUrl}${baseUrl.startsWith(\"/\") ? \"\" : \"/\"}${baseUrl.replace(/\\/+$/, \"\")}`;\n}\n\n// ── data hooks ────────────────────────────────────────────────────────────────\n\nexport interface AsyncState<T> {\n data: T | undefined;\n error: unknown;\n loading: boolean;\n reload: () => void;\n setData: React.Dispatch<React.SetStateAction<T | undefined>>;\n}\n\n/** Run `fn` when `deps` change; `reload()` runs it again. Stale results are dropped. */\nexport function useAsync<T>(fn: () => Promise<T>, deps: React.DependencyList): AsyncState<T> {\n const [data, setData] = React.useState<T | undefined>(undefined);\n const [error, setError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(true);\n const [tick, setTick] = React.useState(0);\n const fnRef = React.useRef(fn);\n fnRef.current = fn;\n React.useEffect(() => {\n let live = true;\n setLoading(true);\n fnRef.current().then(\n (d) => {\n if (!live) return;\n setData(d);\n setError(null);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, tick]);\n const reload = React.useCallback(() => setTick((n) => n + 1), []);\n return { data, error, loading, reload, setData };\n}\n\n/** `window.matchMedia` as state (false where it does not exist). */\nexport function useMediaQuery(query: string): boolean {\n // Start false on the server and on the first client render (same HTML for\n // hydration), then follow the real value.\n const [match, setMatch] = React.useState(false);\n React.useEffect(() => {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n const mq = window.matchMedia(query);\n const on = () => setMatch(mq.matches);\n on();\n mq.addEventListener?.(\"change\", on);\n return () => mq.removeEventListener?.(\"change\", on);\n }, [query]);\n return match;\n}\n\n/** Narrower than 768px: sidebar in a sheet, cards instead of tables, tabs in the editor. */\nexport function useIsMobile(): boolean {\n return useMediaQuery(\"(max-width: 767px)\");\n}\n\n/** State remembered in localStorage (JSON). */\nexport function useLocalStorage<T>(key: string, initial: T): [T, (v: T) => void] {\n const [value, setValue] = React.useState<T>(initial);\n // Read after mount so server and first client render agree (hydration).\n React.useEffect(() => {\n try {\n const raw = window.localStorage.getItem(key);\n if (raw !== null) setValue(JSON.parse(raw) as T);\n } catch {\n /* private mode or bad JSON */\n }\n }, [key]);\n const set = React.useCallback(\n (v: T) => {\n setValue(v);\n try {\n window.localStorage.setItem(key, JSON.stringify(v));\n } catch {\n /* private mode */\n }\n },\n [key]\n );\n return [value, set];\n}\n\n/** Call `fn` once `delay` ms after the last call. */\nexport function useDebounced<A extends unknown[]>(fn: (...a: A) => void, delay: number) {\n const fnRef = React.useRef(fn);\n fnRef.current = fn;\n const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n React.useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);\n return React.useMemo(() => {\n const run = (...a: A) => {\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => {\n timer.current = null;\n fnRef.current(...a);\n }, delay);\n };\n run.cancel = () => {\n if (timer.current) clearTimeout(timer.current);\n timer.current = null;\n };\n return run;\n }, [delay]);\n}\n\n// ── shell navigation (the mobile menu button inside each screen's header) ────\n\nexport const ShellNavContext = React.createContext<{ openNav: () => void } | null>(null);\nexport const useShellNav = () => React.useContext(ShellNavContext);\n\n// ── formatting ────────────────────────────────────────────────────────────────\n\n/** \"8 min ago\", \"2 h ago\", \"yesterday\", else a short date. */\nexport function relativeTime(iso: string | null | undefined, t: T, locale: string, now: Date = new Date()): string {\n if (!iso) return \"\";\n const d = new Date(iso);\n const ms = now.getTime() - d.getTime();\n if (ms < 60_000) return t(\"just_now\");\n if (ms < 3_600_000) return t(\"minutes_ago\", { n: Math.floor(ms / 60_000) });\n const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();\n if (d.getTime() >= startOfToday) return t(\"hours_ago\", { n: Math.floor(ms / 3_600_000) });\n if (d.getTime() >= startOfToday - 86_400_000) return t(\"yesterday\");\n return formatDate(iso, locale, d.getFullYear() !== now.getFullYear());\n}\n\nexport function formatDate(iso: string, locale: string, withYear = false): string {\n return new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\", ...(withYear ? { year: \"numeric\" } : {}) }).format(new Date(iso));\n}\n\nexport function formatDateTime(iso: string, locale: string): string {\n return new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\", hour: \"2-digit\", minute: \"2-digit\", hour12: false }).format(new Date(iso));\n}\n\nexport function formatTime(iso: string, locale: string): string {\n return new Intl.DateTimeFormat(locale, { hour: \"numeric\", minute: \"2-digit\" }).format(new Date(iso));\n}\n\n/** \"Nov 20, 1:46 AM\": the moment a link or key stops working. */\nexport function formatUntil(iso: string, locale: string): string {\n return new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\", hour: \"numeric\", minute: \"2-digit\" }).format(new Date(iso));\n}\n\n// ── documents ─────────────────────────────────────────────────────────────────\n\nexport type DocContent = DocLike;\n\nexport function contentOf(d: DocLike): DocContent {\n return { slug: d.slug, title: d.title, summary: d.summary, body: d.body, category: d.category, keywords: [...(d.keywords ?? [])], fields: structuredClone(d.fields ?? {}) };\n}\n\n/**\n * The REST body for saving `next` over a document whose fields were `prev`.\n * `fields` is a JSON Merge Patch on update, so keys that went away are sent\n * as null.\n */\nexport function toInput(next: DocContent, prevFields?: Record<string, unknown>): DocInputWire {\n const fields: Record<string, unknown> = { ...next.fields };\n for (const k of Object.keys(prevFields ?? {})) if (!(k in fields) || fields[k] === undefined) fields[k] = null;\n return { slug: next.slug, title: next.title, summary: next.summary, body: next.body, category: next.category, keywords: next.keywords, fields };\n}\n\nexport const sameContent = (a: DocContent, b: DocContent) => JSON.stringify(contentOf(a)) === JSON.stringify(contentOf(b));\n"
21
+ },
22
+ {
23
+ "path": "registry/cms/cms-messages.ts",
24
+ "type": "registry:lib",
25
+ "content": "// agent-cms registry: cms-lib (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// UI strings for the admin screens. `en` is the default; pass `ko` (or your\n// own catalog, any subset of keys) to <CmsProvider messages={...}>.\n// Placeholders look like {name}. Server errors arrive already translated by\n// the CMS (`createCms({ messages })`), see `errorMessage`.\n\nimport { isCmsRemoteError } from \"@mainsoft/agent-cms/client\";\n\nexport const en = {\n _locale: \"en\",\n\n // common\n loading: \"Loading…\",\n cancel: \"Cancel\",\n close: \"Close\",\n copy: \"Copy\",\n copied: \"Copied\",\n open: \"Open\",\n save: \"Save\",\n publish: \"Publish\",\n retry: \"Try again\",\n load_more: \"Load more\",\n error_generic: \"Something went wrong. Try again.\",\n none: \"None\",\n all: \"All\",\n required: \"Required\",\n just_now: \"just now\",\n minutes_ago: \"{n} min ago\",\n hours_ago: \"{n} h ago\",\n yesterday: \"yesterday\",\n menu: \"Menu\",\n back: \"Back\",\n\n // states\n state_draft: \"Draft\",\n state_published: \"Published\",\n state_archived: \"Hidden\",\n state_modified: \"Modified since publish\",\n draft_version: \"Draft v{version}\",\n\n // shell\n shell_title: \"Admin\",\n nav_collections: \"Collections\",\n nav_ops: \"Operations\",\n nav_keys: \"API keys\",\n nav_audit: \"Audit log\",\n search: \"Search\",\n nav_label: \"Admin navigation\",\n\n // list\n new_document: \"New document\",\n list_search: \"Find by title or slug\",\n list_search_label: \"Search documents\",\n tab_all: \"All {n}\",\n tab_draft: \"Draft {n}\",\n tab_published: \"Published {n}\",\n tab_modified: \"Modified since publish {n}\",\n tab_archived: \"Hidden {n}\",\n state_filter: \"State\",\n filter_category: \"Category: {value}\",\n filter_category_label: \"Category\",\n filter_author: \"Author: {value}\",\n filter_author_label: \"Author\",\n author_user: \"People\",\n author_key: \"Agents\",\n author_system: \"System\",\n col_title: \"Title\",\n col_category: \"Category\",\n col_state: \"State\",\n col_updated: \"Last edited\",\n col_views: \"Views (7 days)\",\n col_actions: \"Actions\",\n select_all: \"Select all\",\n select_row: \"Select {title}\",\n selected_n: \"{n} selected\",\n clear_selection: \"Clear selection\",\n bulk_bar: \"Bulk actions\",\n action_publish: \"Publish\",\n action_unpublish: \"Unpublish\",\n action_archive: \"Hide\",\n action_unarchive: \"Unhide\",\n action_delete: \"Delete\",\n confirm_publish: \"Publish {n} documents?\",\n confirm_unpublish: \"Unpublish {n} documents?\",\n confirm_archive: \"Hide {n} documents?\",\n confirm_unarchive: \"Unhide {n} documents?\",\n confirm_delete: \"Delete {n} documents?\",\n confirm_delete_note: \"Deleted documents and their versions cannot be brought back.\",\n done_publish: \"Published\",\n done_unpublish: \"Unpublished\",\n done_archive: \"Hidden\",\n done_unarchive: \"Unhidden\",\n done_delete: \"Deleted\",\n result_title: \"{action} {ok}, {failed} failed\",\n result_all_ok: \"{action} {n} documents\",\n shown_of: \"{shown} of {total}\",\n no_results: \"No documents match.\",\n row_actions: \"Actions for {title}\",\n selection_mode: \"Selection mode\",\n exit_selection: \"Leave selection mode\",\n long_press_hint: \"Press and hold a document to select it\",\n\n // empty\n empty_title: \"No documents yet\",\n agent_guide: \"Write with an agent\",\n create_api_key: \"Create an API key\",\n\n // editor\n doc_info: \"Document info\",\n doc_info_summary: \"Title, slug, category, summary, {n} fields\",\n field_title: \"Title\",\n field_slug: \"Slug\",\n field_slug_locked: \"The slug of a published document cannot change.\",\n field_summary: \"Summary\",\n field_category: \"Category\",\n field_keywords: \"Search keywords\",\n field_body: \"Markdown\",\n tags_add: \"Type and press Enter\",\n tag_remove: \"Remove {tag}\",\n json_invalid: \"Not valid JSON\",\n no_category: \"No category\",\n pick_one: \"Choose…\",\n chars: \"{n} chars\",\n preview: \"Preview\",\n edit: \"Edit\",\n preview_width: \"Preview width\",\n width_full: \"Full\",\n public_page: \"Public page\",\n preview_link: \"Preview link\",\n versions: \"Version history\",\n more: \"More\",\n problems_none: \"No problems\",\n problems_n: \"{n} problems\",\n problems_list: \"Problems\",\n autosaved_at: \"Autosaved {time}\",\n autosaving: \"Saving draft…\",\n unsaved: \"Unsaved changes\",\n autosave_failed: \"Autosave failed\",\n saved: \"Saved v{version}\",\n published_v: \"Published v{version}\",\n restore_title: \"Unsaved edits from {time} ({who})\",\n restore: \"Restore\",\n discard: \"Discard\",\n agent_banner: \"{who} changed {n} places in v{version} (reviewed {done}/{total})\",\n agent_banner_many: \"Agents changed {n} places (reviewed {done}/{total})\",\n accept: \"Accept\",\n accept_all: \"Accept all\",\n revert: \"Revert\",\n accepted_by: \"{who}, accepted\",\n reverted_by: \"{who}, reverted (saved with your next save)\",\n agent_changes: \"Agent changes\",\n change_at_line: \"line {n}\",\n new_doc_title: \"New document\",\n\n // preview link\n pl_version: \"Version\",\n pl_current: \"v{version} (current draft)\",\n pl_expiry: \"Expires in\",\n pl_link: \"Link\",\n pl_until: \"Valid until {time}\",\n ttl_1h: \"1 hour\",\n ttl_24h: \"24 hours\",\n ttl_7d: \"7 days\",\n pl_making: \"Making a link…\",\n\n // merge\n merge: \"Merge\",\n merge_save: \"Save merged\",\n merge_banner: \"{who} saved v{version} first. Your edits are still here.\",\n merge_counts: \"Merged automatically {auto}, to choose {conflicts}\",\n merge_choose: \"To choose {i}/{n}\",\n merge_base: \"Original (v{version})\",\n merge_theirs: \"Theirs ({who}, v{version})\",\n merge_mine: \"Mine\",\n merge_both: \"Both\",\n merge_auto: \"Merged automatically\",\n merge_whose: \"Whose edit\",\n merge_content: \"Content\",\n merge_from_both: \"Both (same edit)\",\n merge_location: \"{heading}, line {line}\",\n merge_line: \"line {line}\",\n merge_pick_all: \"Choose an option for every conflict first.\",\n merge_again: \"{who} saved again (v{version}). Merge once more.\",\n merge_no_current: \"Someone else saved this document and you cannot read their copy. Reload the page.\",\n merge_field_empty: \"(empty)\",\n\n // versions\n versions_back: \"Back to editing\",\n versions_list: \"Versions\",\n compare_from: \"Compare from\",\n compare_to: \"Compare to\",\n version_published_tag: \"v{version} (published)\",\n view_mode: \"Diff view\",\n side_by_side: \"Side by side\",\n unified: \"Unified\",\n restore_version: \"Restore v{version}\",\n restore_confirm: \"Restore v{version}?\",\n restore_confirm_note: \"This saves a new version with the content of v{version}. Nothing is lost.\",\n publish_version: \"Publish v{version}\",\n restored: \"Restored as v{version}\",\n restored_from: \"Restored v{version}\",\n field: \"Field\",\n no_diff: \"These versions are the same.\",\n kind_agent: \"Agent\",\n kind_user: \"Person\",\n changed_fields: \"Changed: {fields}\",\n\n // keys\n keys_title: \"API keys\",\n new_key: \"New key\",\n key_name: \"Name\",\n key_key: \"Key\",\n key_scopes: \"Scopes\",\n key_collections: \"Collections\",\n key_last_used: \"Last used\",\n key_expires: \"Expires\",\n key_never: \"Never\",\n key_none: \"None\",\n key_all_collections: \"All\",\n key_expired: \"Expired\",\n key_revoked: \"Revoked\",\n revoke: \"Revoke\",\n revoke_confirm: \"Revoke {name}?\",\n revoke_note: \"Agents and scripts using this key stop working right away.\",\n create: \"Create\",\n expiry_none: \"None\",\n expiry_30: \"30 days\",\n expiry_90: \"90 days\",\n expiry_365: \"1 year\",\n expiry_custom: \"Pick a date\",\n expiry_date: \"Expiry date\",\n key_once: \"This key is shown only now, once.\",\n key_secret: \"Key\",\n key_connect: \"How to connect\",\n scope_help: \"read: read drafts, write: edit, publish: publish and delete, admin: keys and audit log\",\n collections_help: \"Leave all unchecked for every collection.\",\n no_keys: \"No keys yet.\",\n\n // audit\n audit_title: \"Audit log\",\n audit_action: \"Action: {value}\",\n audit_action_label: \"Action\",\n audit_actor: \"Who: {value}\",\n audit_actor_label: \"Who\",\n audit_outcome: \"Result: {value}\",\n audit_outcome_label: \"Result\",\n audit_time: \"Time\",\n audit_who: \"Who\",\n audit_what: \"Action\",\n audit_target: \"Target\",\n audit_result: \"Result\",\n audit_via: \"Via\",\n audit_empty: \"Nothing logged yet.\",\n outcome_ok: \"OK\",\n outcome_denied: \"Denied\",\n outcome_failed: \"Failed\",\n via_rest: \"REST\",\n via_mcp: \"MCP\",\n via_ai: \"AI SDK\",\n via_cli: \"CLI\",\n via_app: \"Admin\",\n actor_user: \"People\",\n actor_key: \"Keys\",\n actor_system: \"System\",\n actor_anonymous: \"Unknown\",\n unknown_key: \"Unknown key\",\n \"audit.key.create\": \"Create key\",\n \"audit.key.revoke\": \"Revoke key\",\n \"audit.doc.publish\": \"Publish\",\n \"audit.doc.unpublish\": \"Unpublish\",\n \"audit.doc.archive\": \"Hide\",\n \"audit.doc.unarchive\": \"Unhide\",\n \"audit.doc.delete\": \"Delete\",\n \"audit.doc.restore\": \"Restore\",\n \"audit.preview.create\": \"Preview link\",\n \"audit.access.denied\": \"Access\",\n \"audit.auth.failed\": \"Sign-in\",\n\n // command\n cmd_placeholder: \"Search documents and actions\",\n cmd_title: \"Quick open\",\n cmd_docs: \"Documents\",\n cmd_actions: \"Actions\",\n cmd_new_in: \"New document in {collection}\",\n cmd_publish: \"Publish {title}\",\n cmd_versions: \"Version history of {title}\",\n cmd_empty: \"Nothing found.\",\n cmd_move: \"Move\",\n cmd_open: \"Open\",\n} as const;\n\nexport type MessageKey = keyof typeof en;\nexport type CmsMessages = Record<MessageKey, string>;\n\nexport const ko: CmsMessages = {\n _locale: \"ko\",\n\n loading: \"불러오는 중…\",\n cancel: \"취소\",\n close: \"닫기\",\n copy: \"복사\",\n copied: \"복사했어요\",\n open: \"열기\",\n save: \"저장\",\n publish: \"게시\",\n retry: \"다시 시도\",\n load_more: \"더 보기\",\n error_generic: \"문제가 생겼어요. 다시 시도해 주세요.\",\n none: \"없음\",\n all: \"전체\",\n required: \"필수\",\n just_now: \"방금\",\n minutes_ago: \"{n}분 전\",\n hours_ago: \"{n}시간 전\",\n yesterday: \"어제\",\n menu: \"메뉴\",\n back: \"뒤로\",\n\n state_draft: \"초안\",\n state_published: \"게시됨\",\n state_archived: \"숨김\",\n state_modified: \"게시 후 수정됨\",\n draft_version: \"초안 v{version}\",\n\n shell_title: \"관리\",\n nav_collections: \"컬렉션\",\n nav_ops: \"운영\",\n nav_keys: \"API 키\",\n nav_audit: \"감사 로그\",\n search: \"검색\",\n nav_label: \"관리 메뉴\",\n\n new_document: \"새 문서\",\n list_search: \"제목, 주소로 찾기\",\n list_search_label: \"문서 찾기\",\n tab_all: \"전체 {n}\",\n tab_draft: \"초안 {n}\",\n tab_published: \"게시됨 {n}\",\n tab_modified: \"게시 후 수정됨 {n}\",\n tab_archived: \"숨김 {n}\",\n state_filter: \"상태\",\n filter_category: \"분류: {value}\",\n filter_category_label: \"분류\",\n filter_author: \"작성자: {value}\",\n filter_author_label: \"작성자\",\n author_user: \"사람\",\n author_key: \"에이전트\",\n author_system: \"시스템\",\n col_title: \"제목\",\n col_category: \"분류\",\n col_state: \"상태\",\n col_updated: \"마지막 수정\",\n col_views: \"7일 조회\",\n col_actions: \"동작\",\n select_all: \"모두 선택\",\n select_row: \"{title} 선택\",\n selected_n: \"{n}개 선택됨\",\n clear_selection: \"선택 해제\",\n bulk_bar: \"일괄 작업\",\n action_publish: \"게시\",\n action_unpublish: \"게시 취소\",\n action_archive: \"숨김\",\n action_unarchive: \"숨김 해제\",\n action_delete: \"삭제\",\n confirm_publish: \"문서 {n}개를 게시할까요?\",\n confirm_unpublish: \"문서 {n}개의 게시를 취소할까요?\",\n confirm_archive: \"문서 {n}개를 숨길까요?\",\n confirm_unarchive: \"문서 {n}개의 숨김을 해제할까요?\",\n confirm_delete: \"문서 {n}개를 삭제할까요?\",\n confirm_delete_note: \"삭제한 문서와 버전은 되살릴 수 없어요.\",\n done_publish: \"게시함\",\n done_unpublish: \"게시 취소함\",\n done_archive: \"숨김\",\n done_unarchive: \"숨김 해제함\",\n done_delete: \"삭제함\",\n result_title: \"{ok}개 {action}, {failed}개 실패\",\n result_all_ok: \"{n}개 {action}\",\n shown_of: \"{total}개 중 {shown}개\",\n no_results: \"맞는 문서가 없어요.\",\n row_actions: \"{title} 동작\",\n selection_mode: \"선택 모드\",\n exit_selection: \"선택 모드 끝내기\",\n long_press_hint: \"문서를 길게 누르면 선택할 수 있어요\",\n\n empty_title: \"아직 문서가 없어요\",\n agent_guide: \"에이전트로 쓰기\",\n create_api_key: \"API 키 만들기\",\n\n doc_info: \"문서 정보\",\n doc_info_summary: \"제목, 주소, 분류, 요약, 필드 {n}개\",\n field_title: \"제목\",\n field_slug: \"주소\",\n field_slug_locked: \"게시한 문서의 주소는 바꿀 수 없어요.\",\n field_summary: \"요약\",\n field_category: \"분류\",\n field_keywords: \"검색어\",\n field_body: \"마크다운\",\n tags_add: \"입력하고 Enter\",\n tag_remove: \"{tag} 빼기\",\n json_invalid: \"JSON 형식이 아니에요\",\n no_category: \"분류 없음\",\n pick_one: \"고르세요\",\n chars: \"{n}자\",\n preview: \"미리보기\",\n edit: \"편집\",\n preview_width: \"미리보기 폭\",\n width_full: \"전체\",\n public_page: \"공개 화면\",\n preview_link: \"미리보기 링크\",\n versions: \"버전 기록\",\n more: \"더 보기\",\n problems_none: \"문제 없음\",\n problems_n: \"문제 {n}개\",\n problems_list: \"문제 목록\",\n autosaved_at: \"자동 저장됨 {time}\",\n autosaving: \"자동 저장 중…\",\n unsaved: \"저장하지 않은 수정\",\n autosave_failed: \"자동 저장 실패\",\n saved: \"v{version} 저장함\",\n published_v: \"v{version} 게시함\",\n restore_title: \"{time}에 저장하지 않은 수정이 있어요 ({who})\",\n restore: \"복구\",\n discard: \"버리기\",\n agent_banner: \"{who}가 v{version}에서 {n}곳을 바꿨어요 (검토 {done}/{total})\",\n agent_banner_many: \"에이전트가 {n}곳을 바꿨어요 (검토 {done}/{total})\",\n accept: \"수락\",\n accept_all: \"모두 수락\",\n revert: \"되돌리기\",\n accepted_by: \"{who}, 수락함\",\n reverted_by: \"{who}, 되돌림 (다음 저장 때 반영)\",\n agent_changes: \"에이전트 변경\",\n change_at_line: \"{n}줄\",\n new_doc_title: \"새 문서\",\n\n pl_version: \"버전\",\n pl_current: \"v{version} (지금 초안)\",\n pl_expiry: \"만료\",\n pl_link: \"링크\",\n pl_until: \"{time}까지\",\n ttl_1h: \"1시간\",\n ttl_24h: \"24시간\",\n ttl_7d: \"7일\",\n pl_making: \"링크 만드는 중…\",\n\n merge: \"합치기\",\n merge_save: \"합쳐서 저장\",\n merge_banner: \"{who}가 먼저 v{version}를 저장했어요. 내 수정은 그대로 있어요.\",\n merge_counts: \"자동으로 합친 곳 {auto}, 고를 곳 {conflicts}\",\n merge_choose: \"고를 곳 {i}/{n}\",\n merge_base: \"원래 (v{version})\",\n merge_theirs: \"상대 것 ({who}, v{version})\",\n merge_mine: \"내 것\",\n merge_both: \"둘 다\",\n merge_auto: \"자동으로 합친 곳\",\n merge_whose: \"누구 수정\",\n merge_content: \"내용\",\n merge_from_both: \"둘 다 (같은 수정)\",\n merge_location: \"{heading}, {line}줄\",\n merge_line: \"{line}줄\",\n merge_pick_all: \"고를 곳마다 하나씩 먼저 골라 주세요.\",\n merge_again: \"{who}가 또 저장했어요 (v{version}). 한 번 더 합쳐 주세요.\",\n merge_no_current: \"다른 곳에서 저장했는데 그 내용을 읽을 권한이 없어요. 페이지를 다시 불러와 주세요.\",\n merge_field_empty: \"(비어 있음)\",\n\n versions_back: \"편집으로\",\n versions_list: \"버전 목록\",\n compare_from: \"비교 기준\",\n compare_to: \"비교 대상\",\n version_published_tag: \"v{version} (게시됨)\",\n view_mode: \"보기 방식\",\n side_by_side: \"나란히\",\n unified: \"한 줄\",\n restore_version: \"v{version}로 되돌리기\",\n restore_confirm: \"v{version}로 되돌릴까요?\",\n restore_confirm_note: \"v{version}의 내용으로 새 버전을 저장해요. 지금 내용도 버전 기록에 남아요.\",\n publish_version: \"v{version} 게시\",\n restored: \"v{version}로 저장함\",\n restored_from: \"v{version}로 되돌림\",\n field: \"필드\",\n no_diff: \"두 버전이 같아요.\",\n kind_agent: \"에이전트\",\n kind_user: \"사람\",\n changed_fields: \"바뀐 곳: {fields}\",\n\n keys_title: \"API 키\",\n new_key: \"새 키\",\n key_name: \"이름\",\n key_key: \"키\",\n key_scopes: \"권한\",\n key_collections: \"컬렉션\",\n key_last_used: \"마지막 사용\",\n key_expires: \"만료\",\n key_never: \"없음\",\n key_none: \"없음\",\n key_all_collections: \"전체\",\n key_expired: \"만료됨\",\n key_revoked: \"폐기됨\",\n revoke: \"폐기\",\n revoke_confirm: \"{name} 키를 폐기할까요?\",\n revoke_note: \"이 키를 쓰는 에이전트와 스크립트가 바로 멈춰요.\",\n create: \"만들기\",\n expiry_none: \"없음\",\n expiry_30: \"30일\",\n expiry_90: \"90일\",\n expiry_365: \"1년\",\n expiry_custom: \"날짜 지정\",\n expiry_date: \"만료일\",\n key_once: \"이 키는 지금 한 번만 보여요.\",\n key_secret: \"키 값\",\n key_connect: \"연결 방법\",\n scope_help: \"read: 초안 읽기, write: 수정, publish: 게시와 삭제, admin: 키와 감사 로그\",\n collections_help: \"모두 비워 두면 전체 컬렉션이에요.\",\n no_keys: \"아직 키가 없어요.\",\n\n audit_title: \"감사 로그\",\n audit_action: \"동작: {value}\",\n audit_action_label: \"동작\",\n audit_actor: \"누가: {value}\",\n audit_actor_label: \"누가\",\n audit_outcome: \"결과: {value}\",\n audit_outcome_label: \"결과\",\n audit_time: \"시각\",\n audit_who: \"누가\",\n audit_what: \"동작\",\n audit_target: \"대상\",\n audit_result: \"결과\",\n audit_via: \"경로\",\n audit_empty: \"아직 기록이 없어요.\",\n outcome_ok: \"성공\",\n outcome_denied: \"거부\",\n outcome_failed: \"실패\",\n via_rest: \"REST\",\n via_mcp: \"MCP\",\n via_ai: \"AI SDK\",\n via_cli: \"CLI\",\n via_app: \"어드민\",\n actor_user: \"사람\",\n actor_key: \"키\",\n actor_system: \"시스템\",\n actor_anonymous: \"알 수 없음\",\n unknown_key: \"알 수 없는 키\",\n \"audit.key.create\": \"키 만들기\",\n \"audit.key.revoke\": \"키 폐기\",\n \"audit.doc.publish\": \"게시\",\n \"audit.doc.unpublish\": \"게시 취소\",\n \"audit.doc.archive\": \"숨김\",\n \"audit.doc.unarchive\": \"숨김 해제\",\n \"audit.doc.delete\": \"삭제\",\n \"audit.doc.restore\": \"되돌리기\",\n \"audit.preview.create\": \"미리보기 링크\",\n \"audit.access.denied\": \"권한\",\n \"audit.auth.failed\": \"인증\",\n\n cmd_placeholder: \"문서와 동작 찾기\",\n cmd_title: \"빠른 열기\",\n cmd_docs: \"문서\",\n cmd_actions: \"동작\",\n cmd_new_in: \"{collection}에 새 문서\",\n cmd_publish: \"{title} 게시\",\n cmd_versions: \"{title} 버전 기록\",\n cmd_empty: \"찾은 게 없어요.\",\n cmd_move: \"이동\",\n cmd_open: \"열기\",\n};\n\nexport type MessageParams = Record<string, string | number | null | undefined>;\n\n/** Fill `{name}` placeholders. Unknown placeholders stay as they are. */\nexport function format(template: string, params: MessageParams = {}): string {\n return template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (params[k] === undefined || params[k] === null ? m : String(params[k])));\n}\n\n/** A translator over a catalog (missing keys fall back to English). */\nexport function createT(messages: Partial<CmsMessages> = {}) {\n const all: CmsMessages = { ...en, ...messages };\n return (key: MessageKey, params?: MessageParams) => format(all[key] ?? key, params);\n}\n\nexport type T = ReturnType<typeof createT>;\n\n/**\n * What to show for a failed call: the server's message (already in the CMS's\n * language) for a CmsRemoteError, else a generic line.\n */\nexport function errorMessage(e: unknown, t: T): string {\n if (isCmsRemoteError(e)) return e.code === \"network\" || e.code === \"http\" ? t(\"error_generic\") : e.message;\n return t(\"error_generic\");\n}\n"
26
+ },
27
+ {
28
+ "path": "registry/cms/cms-parts.tsx",
29
+ "type": "registry:lib",
30
+ "content": "// agent-cms registry: cms-lib (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Small pieces the admin screens share: state badges, avatars, copy\n// buttons, the confirm dialog, the page header and the markdown preview.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, Copy, Lightbulb, Link as LinkIcon, Menu, Pencil, TriangleAlert, Info } from \"lucide-react\";\nimport { parseMarkdown, type Block, type Inline } from \"@mainsoft/agent-cms/markdown\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { cn } from \"@/lib/utils\";\nimport { useCms, useShellNav } from \"./use-cms\";\n\n// ── state ────────────────────────────────────────────────────────────────────\n\nconst DOT: Record<string, string> = { published: \"bg-green-600\", draft: \"bg-amber-500\", archived: \"bg-neutral-400\" };\n\nexport function StateBadge({ state, label, className }: { state: \"draft\" | \"published\" | \"archived\"; label?: string; className?: string }) {\n const { t } = useCms();\n return (\n <Badge variant=\"outline\" className={cn(\"gap-1.5 whitespace-nowrap rounded-full px-2 py-0 text-[11.5px] font-medium\", className)}>\n <span aria-hidden className={cn(\"h-1.5 w-1.5 rounded-full\", DOT[state])} />\n {label ?? t(state === \"draft\" ? \"state_draft\" : state === \"published\" ? \"state_published\" : \"state_archived\")}\n </Badge>\n );\n}\n\nexport function ModifiedMark({ className }: { className?: string }) {\n const { t } = useCms();\n return (\n <span className={cn(\"inline-flex items-center gap-1 whitespace-nowrap text-[11.5px] font-medium text-amber-700\", className)}>\n <Pencil aria-hidden className=\"h-3 w-3\" />\n {t(\"state_modified\")}\n </span>\n );\n}\n\n// ── people ───────────────────────────────────────────────────────────────────\n\nexport function Avatar({ kind, label, className }: { kind: string | null | undefined; label: string | null | undefined; className?: string }) {\n const bot = kind === \"key\" || kind === \"system\";\n return (\n <span aria-hidden className={cn(\"inline-grid h-5 w-5 shrink-0 place-items-center rounded-full text-[10px] font-semibold\", bot ? \"bg-blue-100 text-blue-700\" : \"bg-muted text-foreground\", className)}>\n {bot ? <Bot className=\"h-3 w-3\" /> : (label ?? \"?\").trim().charAt(0).toUpperCase() || \"?\"}\n </span>\n );\n}\n\nexport function Who({ kind, label, className }: { kind: string | null | undefined; label: string | null | undefined; className?: string }) {\n return (\n <span className={cn(\"inline-flex items-center gap-1.5\", className)}>\n <Avatar kind={kind} label={label} />\n <span>{label}</span>\n </span>\n );\n}\n\n// ── copy ─────────────────────────────────────────────────────────────────────\n\nexport async function copyText(text: string): Promise<boolean> {\n try {\n if (typeof navigator !== \"undefined\" && navigator.clipboard) {\n await navigator.clipboard.writeText(text);\n return true;\n }\n } catch {\n /* fall through */\n }\n return false;\n}\n\n/** A copy button; `label` names what is copied for screen readers. */\nexport function CopyButton({ value, label, className }: { value: string; label?: string; className?: string }) {\n const { t } = useCms();\n const [done, setDone] = React.useState(false);\n React.useEffect(() => {\n if (!done) return;\n const id = setTimeout(() => setDone(false), 1500);\n return () => clearTimeout(id);\n }, [done]);\n return (\n <>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className={cn(\"h-7 shrink-0 gap-1 px-2 font-sans text-xs\", className)}\n aria-label={label ? `${t(\"copy\")}: ${label}` : undefined}\n onClick={async () => setDone(await copyText(value))}\n >\n {done ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Copy aria-hidden className=\"h-3.5 w-3.5\" />}\n {done ? t(\"copied\") : t(\"copy\")}\n </Button>\n <span role=\"status\" className=\"sr-only\">\n {done ? t(\"copied\") : \"\"}\n </span>\n </>\n );\n}\n\n/** Monospace value with a copy button (key secrets, URLs, commands). */\nexport function CodeBox({ value, label, className, multiline }: { value: string; label?: string; className?: string; multiline?: boolean }) {\n return (\n <div className={cn(\"flex items-start gap-2 rounded-md border bg-muted/50 px-3 py-2\", className)}>\n <code className={cn(\"min-w-0 flex-1 font-mono text-xs leading-5\", multiline ? \"whitespace-pre-wrap break-all\" : \"truncate\")}>\n {value}\n </code>\n <CopyButton value={value} label={label} />\n </div>\n );\n}\n\n// ── segmented choice ─────────────────────────────────────────────────────────\n\nexport interface SegmentedProps<V extends string> {\n value: V;\n onChange: (v: V) => void;\n options: { value: V; label: React.ReactNode; disabled?: boolean }[];\n /** Accessible name (or use `labelledBy`). */\n label?: string;\n labelledBy?: string;\n className?: string;\n itemClassName?: string;\n}\n\n/**\n * One-of-many buttons (tabs that filter, ttl, view mode): a radio group of\n * plain buttons, so it works with either shadcn base (Radix or Base UI).\n * Arrow keys move and select; only the selected button is in the tab order.\n */\nexport function Segmented<V extends string>({ value, onChange, options, label, labelledBy, className, itemClassName }: SegmentedProps<V>) {\n const refs = React.useRef<(HTMLButtonElement | null)[]>([]);\n const enabled = options.map((o, i) => (o.disabled ? -1 : i)).filter((i) => i >= 0);\n const current = options.findIndex((o) => o.value === value);\n const focusable = current >= 0 && !options[current]?.disabled ? current : enabled[0];\n const onKeyDown = (e: React.KeyboardEvent, i: number) => {\n const step = e.key === \"ArrowRight\" || e.key === \"ArrowDown\" ? 1 : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? -1 : 0;\n const edge = e.key === \"Home\" ? enabled[0] : e.key === \"End\" ? enabled[enabled.length - 1] : undefined;\n if (!step && edge === undefined) return;\n e.preventDefault();\n const pos = enabled.indexOf(i);\n const next = edge ?? enabled[(pos + step + enabled.length) % enabled.length];\n if (next === undefined) return;\n refs.current[next]?.focus();\n onChange(options[next]!.value);\n };\n return (\n <div\n role=\"radiogroup\"\n aria-label={labelledBy ? undefined : label}\n aria-labelledby={labelledBy}\n className={cn(\"inline-flex w-fit flex-wrap justify-start gap-0.5 rounded-md bg-muted p-0.5\", className)}\n >\n {options.map((o, i) => {\n const on = o.value === value;\n return (\n <button\n key={o.value}\n ref={(el) => {\n refs.current[i] = el;\n }}\n type=\"button\"\n role=\"radio\"\n aria-checked={on}\n data-state={on ? \"on\" : \"off\"}\n disabled={o.disabled}\n tabIndex={i === focusable ? 0 : -1}\n onClick={() => onChange(o.value)}\n onKeyDown={(e) => onKeyDown(e, i)}\n className={cn(\n \"inline-flex h-7 items-center justify-center whitespace-nowrap rounded-sm px-2.5 text-[13px] font-normal text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-background data-[state=on]:font-medium data-[state=on]:text-foreground data-[state=on]:shadow-sm\",\n itemClassName\n )}\n >\n {o.label}\n </button>\n );\n })}\n </div>\n );\n}\n\n// ── status and errors ────────────────────────────────────────────────────────\n\n/** A live region for status lines (saved, failed, counts). */\nexport function StatusText({ children, className, tone }: { children?: React.ReactNode; className?: string; tone?: \"muted\" | \"error\" | \"ok\" }) {\n return (\n <div role=\"status\" className={cn(\"text-sm\", tone === \"error\" ? \"text-destructive\" : tone === \"ok\" ? \"text-green-700\" : \"text-muted-foreground\", className)}>\n {children}\n </div>\n );\n}\n\n// ── confirm ──────────────────────────────────────────────────────────────────\n\nexport interface ConfirmDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: React.ReactNode;\n description?: React.ReactNode;\n children?: React.ReactNode;\n confirmLabel: React.ReactNode;\n destructive?: boolean;\n busy?: boolean;\n onConfirm: () => void | Promise<void>;\n error?: React.ReactNode;\n}\n\nexport function ConfirmDialog({ open, onOpenChange, title, description, children, confirmLabel, destructive, busy, onConfirm, error }: ConfirmDialogProps) {\n const { t } = useCms();\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[460px]\">\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n {description ? <DialogDescription>{description}</DialogDescription> : null}\n </DialogHeader>\n {children}\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=\"button\" variant={destructive ? \"destructive\" : \"default\"} disabled={busy} onClick={() => void onConfirm()}>\n {confirmLabel}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\n// ── page header ──────────────────────────────────────────────────────────────\n\n/** The bar on top of each screen. On phones it shows the menu button of <CmsShell>. */\nexport function PageHeader({ title, crumbs, children, after, className, back }: { title: React.ReactNode; crumbs?: React.ReactNode[]; children?: React.ReactNode; after?: React.ReactNode; className?: string; back?: React.ReactNode }) {\n const nav = useShellNav();\n const { t } = useCms();\n return (\n <header className={cn(\"flex min-h-14 flex-wrap items-center gap-2.5 border-b px-4 py-2.5 md:px-6\", className)}>\n {back ??\n (nav ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8 md:hidden\" aria-label={t(\"menu\")} onClick={nav.openNav}>\n <Menu aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null)}\n {crumbs?.length ? (\n <nav aria-label=\"Breadcrumb\" className=\"hidden items-center gap-1 text-sm text-muted-foreground md:flex\">\n {crumbs.map((c, i) => (\n <span key={i} className=\"inline-flex items-center gap-1\">\n {c}\n <span aria-hidden>/</span>\n </span>\n ))}\n </nav>\n ) : null}\n <h1 className=\"min-w-0 truncate text-base font-semibold md:text-lg\">{title}</h1>\n {after}\n <span className=\"flex-1\" />\n <div className=\"flex flex-wrap items-center gap-1.5\">{children}</div>\n </header>\n );\n}\n\n// ── markdown preview ─────────────────────────────────────────────────────────\n\nfunction Inlines({ items }: { items: Inline[] }) {\n return (\n <>\n {items.map((i, n) => {\n if (i.t === \"strong\") return <strong key={n}>{i.v}</strong>;\n if (i.t === \"code\") return <code key={n} className=\"rounded bg-muted px-1 py-0.5 font-mono text-[0.9em]\">{i.v}</code>;\n if (i.t === \"link\")\n return (\n <a key={n} href={i.href} className=\"underline underline-offset-2\" target=\"_blank\" rel=\"noreferrer\">\n {i.v}\n </a>\n );\n if (i.t === \"applink\") return <AppLinkChip key={n} label={i.v} linkKey={i.key} />;\n return <React.Fragment key={n}>{i.v}</React.Fragment>;\n })}\n </>\n );\n}\n\nfunction AppLinkChip({ label, linkKey }: { label: string; linkKey: string }) {\n return (\n <span title={linkKey} className=\"mx-0.5 inline-flex items-center gap-1 rounded-md border bg-muted/60 px-1.5 py-px text-[0.92em] font-medium\">\n <LinkIcon aria-hidden className=\"h-3 w-3\" />\n {label}\n </span>\n );\n}\n\nconst CALLOUT_ICON = { note: Info, tip: Lightbulb, warning: TriangleAlert } as const;\n\nfunction Blocks({ blocks }: { blocks: Block[] }) {\n return (\n <>\n {blocks.map((b, n) => {\n switch (b.t) {\n case \"heading\":\n return b.level === 2 ? (\n <h2 key={n} id={b.id} className=\"mb-2 mt-6 text-lg font-semibold\">\n <Inlines items={b.inline} />\n </h2>\n ) : (\n <h3 key={n} id={b.id} className=\"mb-1.5 mt-4 font-semibold\">\n <Inlines items={b.inline} />\n </h3>\n );\n case \"p\":\n return (\n <p key={n} className=\"my-2 leading-7\">\n <Inlines items={b.inline} />\n </p>\n );\n case \"list\": {\n const L = b.ordered ? \"ol\" : \"ul\";\n return (\n <L key={n} className={cn(\"my-2 space-y-1 pl-6 leading-7\", b.ordered ? \"list-decimal\" : \"list-disc\")}>\n {b.items.map((it, k) => (\n <li key={k}>\n <Inlines items={it} />\n </li>\n ))}\n </L>\n );\n }\n case \"quote\": {\n if (b.callout) {\n const Icon = CALLOUT_ICON[b.callout];\n return (\n <div key={n} className={cn(\"my-3 flex gap-2 rounded-md border px-3 py-2.5 text-sm\", b.callout === \"warning\" ? \"border-amber-200 bg-amber-50\" : \"border-blue-200 bg-blue-50\")}>\n <Icon aria-hidden className=\"mt-1 h-4 w-4 shrink-0\" />\n <div className=\"min-w-0 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0\">\n <Blocks blocks={b.blocks} />\n </div>\n </div>\n );\n }\n return (\n <blockquote key={n} className=\"my-3 border-l-2 pl-3 text-muted-foreground\">\n <Blocks blocks={b.blocks} />\n </blockquote>\n );\n }\n case \"code\":\n return (\n <pre key={n} className=\"my-3 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs\">\n <code>{b.v}</code>\n </pre>\n );\n case \"hr\":\n return <hr key={n} className=\"my-5\" />;\n case \"links\":\n return (\n <div key={n} className=\"my-3 flex flex-wrap gap-2\">\n {b.items.map((l, k) => (\n <AppLinkChip key={k} label={l.v} linkKey={l.key} />\n ))}\n </div>\n );\n default:\n return null;\n }\n })}\n </>\n );\n}\n\n/** Draws a document the way `./markdown` parses it. Swap in your own public components here. */\nexport function MarkdownPreview({ title, summary, body, className }: { title?: string; summary?: string; body: string; className?: string }) {\n const blocks = React.useMemo(() => parseMarkdown(body), [body]);\n return (\n <article className={cn(\"text-[15px]\", className)}>\n {title ? <h1 className=\"mb-1 text-2xl font-bold\">{title}</h1> : null}\n {summary ? <p className=\"mb-4 mt-0 text-muted-foreground\">{summary}</p> : null}\n <Blocks blocks={blocks} />\n </article>\n );\n}\n"
31
+ }
32
+ ]
33
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-merge",
4
+ "type": "registry:component",
5
+ "title": "Merge after a conflict",
6
+ "description": "Three-way merge when someone saved first: what merged automatically, and theirs, mine or both for each conflict.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "label",
15
+ "radio-group",
16
+ "table",
17
+ "cms-lib"
18
+ ],
19
+ "files": [
20
+ {
21
+ "path": "registry/cms/cms-merge.tsx",
22
+ "type": "registry:component",
23
+ "content": "// agent-cms registry: cms-merge (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Someone saved first. Shows what merged by itself and, for each place both\n// sides changed, lets you pick theirs, mine or both (body) / theirs or mine\n// (other fields). \"Save merged\" saves on top of their version; if they saved\n// yet again, the merge starts over with the newest copy.\n\"use client\";\n\nimport * as React from \"react\";\nimport { GitMerge } from \"lucide-react\";\nimport type { CmsDoc } from \"@mainsoft/agent-cms/types\";\nimport { diffWords, mergeDocs, resolveDocMerge, type DocLike, type MergeChoice } from \"@mainsoft/agent-cms/diff\";\nimport { isCmsRemoteError } from \"@mainsoft/agent-cms/client\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/ui/radio-group\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage, type MessageKey } from \"./cms-messages\";\nimport { Avatar, PageHeader, StatusText, Who } from \"./cms-parts\";\nimport { contentOf, toInput, useCms } from \"./use-cms\";\n\nexport interface CmsMergeProps {\n collection: string;\n slug: string;\n /** The version both edits started from (`version(c, s, baseVersion).snapshot`). */\n base: DocLike;\n baseVersion: number;\n /** The editor's content. */\n mine: DocLike;\n /** The copy someone else saved (`CmsRemoteError.current` of the 409). */\n theirs: CmsDoc;\n /** Saved: the new document. */\n onSaved: (doc: CmsDoc) => void;\n /** Back to the editor without saving. */\n onCancel: () => void;\n /** Breadcrumb before the title (e.g. the collection and document). */\n crumbs?: React.ReactNode[];\n className?: string;\n}\n\nconst FIELD_LABEL: Record<string, MessageKey> = { title: \"field_title\", slug: \"field_slug\", summary: \"field_summary\", category: \"field_category\", keywords: \"field_keywords\", body: \"field_body\" };\n\nconst show = (v: unknown, empty: string): string => (v === undefined || v === null || v === \"\" ? empty : Array.isArray(v) ? v.join(\", \") : typeof v === \"object\" ? JSON.stringify(v) : String(v));\n\n/** Where a conflict sits: the nearest heading above and the line in the merged text. */\nfunction locate(chunks: ReturnType<typeof mergeDocs>[\"body\"][\"chunks\"], id: number): { heading: string | null; line: number } {\n let line = 1;\n let heading: string | null = null;\n for (const c of chunks) {\n if (c.t === \"conflict\" && c.id === id) return { heading, line };\n const lines = c.t === \"ok\" ? c.lines : c.theirs;\n for (const l of lines) if (/^#{1,6}\\s/.test(l)) heading = l;\n line += lines.length;\n }\n return { heading, line };\n}\n\nexport function CmsMerge({ collection, slug, base: base0, baseVersion: baseVersion0, mine: mine0, theirs: theirs0, onSaved, onCancel, crumbs, className }: CmsMergeProps) {\n const { client, t } = useCms();\n const [round, setRound] = React.useState({ base: contentOf(base0), baseVersion: baseVersion0, mine: contentOf(mine0), theirs: theirs0, again: false });\n const m = React.useMemo(() => mergeDocs(round.base, round.mine, contentOf(round.theirs)), [round]);\n const [body, setBody] = React.useState<Record<number, MergeChoice>>({});\n const [fields, setFields] = React.useState<Record<string, \"mine\" | \"theirs\">>({});\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n\n const total = m.body.conflicts.length + m.fieldConflicts.length;\n const chosen = m.body.conflicts.filter((c) => body[c.id]).length + m.fieldConflicts.filter((f) => fields[f.path]).length;\n const theirsWho = round.theirs.updatedBy ?? \"\";\n const theirsKind = round.theirs.updatedByKind;\n\n const auto = React.useMemo(() => {\n const rows: { where: string; from: \"mine\" | \"theirs\" | \"both\"; content: React.ReactNode }[] = [];\n for (const a of m.autoMerged) {\n if (a.path === \"body\") continue;\n const label = FIELD_LABEL[a.path] ? t(FIELD_LABEL[a.path]) : a.path.replace(/^fields\\./, \"\");\n const get = (d: DocLike) => (a.path.startsWith(\"fields.\") ? a.path.slice(7).split(\".\").reduce<unknown>((o, k) => (o && typeof o === \"object\" ? (o as Record<string, unknown>)[k] : undefined), d.fields) : (d as unknown as Record<string, unknown>)[a.path]);\n const before = show(get(round.base), \"\");\n const after = show(get(m.merged), t(\"merge_field_empty\"));\n rows.push({ where: label, from: a.from, content: <WordIns a={before} b={after} /> });\n }\n let line = 1;\n let heading: string | null = null;\n for (const c of m.body.chunks) {\n const lines = c.t === \"ok\" ? c.lines : c.theirs;\n if (c.t === \"ok\" && c.from !== \"base\") {\n rows.push({\n where: heading ? t(\"merge_location\", { heading, line }) : t(\"merge_line\", { line }),\n from: c.from,\n content: <span className=\"whitespace-pre-wrap\">{c.lines.join(\"\\n\")}</span>,\n });\n }\n for (const l of lines) if (/^#{1,6}\\s/.test(l)) heading = l;\n line += lines.length;\n }\n return rows;\n }, [m, round.base, t]);\n\n const save = async () => {\n if (chosen < total) {\n setError(t(\"merge_pick_all\"));\n return;\n }\n setBusy(true);\n setError(null);\n const merged = resolveDocMerge(m, { body, fields });\n try {\n const doc = await client.update(collection, slug, toInput(merged, round.theirs.fields), { expectedVersion: round.theirs.version });\n onSaved(doc);\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && e.current) {\n // They saved again: merge what we resolved against the newest copy.\n setRound({ base: contentOf(round.theirs), baseVersion: round.theirs.version, mine: merged, theirs: e.current as CmsDoc, again: true });\n setBody({});\n setFields({});\n } else setError(errorMessage(e, t));\n } finally {\n setBusy(false);\n }\n };\n\n let index = 0;\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={t(\"merge\")} crumbs={crumbs}>\n <Button type=\"button\" variant=\"ghost\" onClick={onCancel}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"button\" onClick={() => void save()} disabled={busy}>\n {t(\"merge_save\")}\n </Button>\n </PageHeader>\n <div className=\"flex max-w-4xl flex-col gap-3.5 px-4 py-4 md:px-6\">\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.5 text-sm text-amber-950\">\n <GitMerge aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{round.again ? t(\"merge_again\", { who: theirsWho, version: round.theirs.version }) : t(\"merge_banner\", { who: theirsWho, version: round.theirs.version })}</span>\n <span className=\"flex-1\" />\n <span className=\"text-xs\">{t(\"merge_counts\", { auto: auto.length, conflicts: total })}</span>\n </div>\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n\n {m.body.conflicts.map((c) => {\n index++;\n const loc = locate(m.body.chunks, c.id);\n const name = `cms-merge-body-${c.id}`;\n const titleId = `${name}-title`;\n return (\n <section key={`b${c.id}`} aria-labelledby={titleId} className=\"rounded-lg border p-3.5\">\n <div className=\"mb-2 flex flex-wrap items-center gap-2\">\n <Badge id={titleId} variant=\"outline\" className=\"border-red-200 bg-red-50 text-red-700\">\n {t(\"merge_choose\", { i: index, n: total })}\n </Badge>\n <span className=\"font-mono text-xs text-muted-foreground\">{loc.heading ? t(\"merge_location\", { heading: loc.heading, line: loc.line }) : t(\"merge_line\", { line: loc.line })}</span>\n </div>\n <div className=\"mb-1 text-xs text-muted-foreground\">{t(\"merge_base\", { version: round.baseVersion })}</div>\n <pre className=\"mb-3 whitespace-pre-wrap rounded-md bg-muted/50 px-2.5 py-1.5 font-mono text-xs text-muted-foreground\">{c.base.join(\"\\n\") || t(\"merge_field_empty\")}</pre>\n <RadioGroup aria-labelledby={titleId} value={body[c.id] ?? \"\"} onValueChange={(v) => setBody((b) => ({ ...b, [c.id]: v as MergeChoice }))} className=\"grid gap-2 md:grid-cols-3\">\n {(\n [\n { v: \"theirs\", head: <><Avatar kind={theirsKind} label={theirsWho} />{t(\"merge_theirs\", { who: theirsWho, version: round.theirs.version })}</>, lines: c.theirs },\n { v: \"mine\", head: <>{t(\"merge_mine\")}</>, lines: c.mine },\n { v: \"both\", head: <>{t(\"merge_both\")}</>, lines: [...c.theirs, ...c.mine] },\n ] as const\n ).map((o) => (\n <Option key={o.v} id={`${name}-${o.v}`} value={o.v} selected={body[c.id] === o.v} head={o.head}>\n {o.lines.join(\"\\n\") || t(\"merge_field_empty\")}\n </Option>\n ))}\n </RadioGroup>\n </section>\n );\n })}\n\n {m.fieldConflicts.map((f) => {\n index++;\n const name = `cms-merge-f-${f.path.replace(/[^a-z0-9_-]/gi, \"-\")}`;\n const titleId = `${name}-title`;\n const label = FIELD_LABEL[f.path] ? t(FIELD_LABEL[f.path]) : f.path.replace(/^fields\\./, \"\");\n return (\n <section key={f.path} aria-labelledby={titleId} className=\"rounded-lg border p-3.5\">\n <div className=\"mb-2 flex flex-wrap items-center gap-2\">\n <Badge variant=\"outline\" className=\"border-red-200 bg-red-50 text-red-700\">\n {t(\"merge_choose\", { i: index, n: total })}\n </Badge>\n <span id={titleId} className=\"text-sm font-medium\">\n {label}\n </span>\n </div>\n <div className=\"mb-1 text-xs text-muted-foreground\">{t(\"merge_base\", { version: round.baseVersion })}</div>\n <div className=\"mb-3 rounded-md bg-muted/50 px-2.5 py-1.5 text-xs text-muted-foreground\">{show(f.base, t(\"merge_field_empty\"))}</div>\n <RadioGroup aria-labelledby={titleId} value={fields[f.path] ?? \"\"} onValueChange={(v) => setFields((x) => ({ ...x, [f.path]: v as \"mine\" | \"theirs\" }))} className=\"grid gap-2 md:grid-cols-2\">\n <Option id={`${name}-theirs`} value=\"theirs\" selected={fields[f.path] === \"theirs\"} head={<><Avatar kind={theirsKind} label={theirsWho} />{t(\"merge_theirs\", { who: theirsWho, version: round.theirs.version })}</>}>\n {show(f.theirs, t(\"merge_field_empty\"))}\n </Option>\n <Option id={`${name}-mine`} value=\"mine\" selected={fields[f.path] === \"mine\"} head={<>{t(\"merge_mine\")}</>}>\n {show(f.mine, t(\"merge_field_empty\"))}\n </Option>\n </RadioGroup>\n </section>\n );\n })}\n\n {auto.length ? (\n <section aria-label={t(\"merge_auto\")} className=\"rounded-lg border\">\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"merge_auto\")}</TableHead>\n <TableHead>{t(\"merge_whose\")}</TableHead>\n <TableHead>{t(\"merge_content\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {auto.map((r, i) => (\n <TableRow key={i}>\n <TableCell className=\"whitespace-nowrap align-top text-xs\">{r.where}</TableCell>\n <TableCell className=\"whitespace-nowrap align-top text-sm\">\n {r.from === \"theirs\" ? <Who kind={theirsKind} label={theirsWho} /> : r.from === \"mine\" ? t(\"merge_mine\") : t(\"merge_from_both\")}\n </TableCell>\n <TableCell className=\"align-top text-sm\">{r.content}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </section>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction Option({ id, value, selected, head, children }: { id: string; value: string; selected: boolean; head: React.ReactNode; children: React.ReactNode }) {\n return (\n <div className={cn(\"flex flex-col gap-1.5 rounded-md border p-2.5\", selected && \"border-foreground ring-1 ring-foreground\")}>\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id={id} value={value} />\n <Label htmlFor={id} className=\"flex items-center gap-1.5 text-sm font-medium\">\n {head}\n </Label>\n </div>\n <pre className=\"whitespace-pre-wrap font-mono text-xs\">{children}</pre>\n </div>\n );\n}\n\nfunction WordIns({ a, b }: { a: string; b: string }) {\n return (\n <>\n {diffWords(a, b).map((p, i) =>\n p.t === \"del\" ? null : p.t === \"ins\" ? (\n <ins key={i} className=\"bg-green-200 no-underline\">\n {p.v}\n </ins>\n ) : (\n <React.Fragment key={i}>{p.v}</React.Fragment>\n )\n )}\n </>\n );\n}\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-shell",
4
+ "type": "registry:component",
5
+ "title": "Admin layout",
6
+ "description": "Sidebar with collections, API keys and audit log, plus extraNav for your app's own screens. A sheet menu under 768px.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "sheet",
13
+ "cms-lib"
14
+ ],
15
+ "files": [
16
+ {
17
+ "path": "registry/cms/cms-shell.tsx",
18
+ "type": "registry:component",
19
+ "content": "// agent-cms registry: cms-shell (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The admin layout: a sidebar with the collections you may read, the\n// operations screens (API keys, audit log, admins only) and `extraNav`, the\n// place for your app's own screens. Under 768px the sidebar opens in a sheet.\n\"use client\";\n\nimport * as React from \"react\";\nimport { BookOpen, KeyRound, ScrollText, Search, FileText } from \"lucide-react\";\nimport { Sheet, SheetContent, SheetDescription, SheetTitle } from \"@/components/ui/sheet\";\nimport { cn } from \"@/lib/utils\";\nimport { ShellNavContext, useCms } from \"./use-cms\";\n\nexport interface CmsNavItem {\n label: string;\n href: string;\n badge?: React.ReactNode;\n icon?: React.ReactNode;\n}\n\nexport interface CmsNavGroup {\n label: string;\n items: CmsNavItem[];\n}\n\nexport interface CmsLinkProps {\n href: string;\n className?: string;\n children: React.ReactNode;\n \"aria-current\"?: \"page\" | undefined;\n onClick?: () => void;\n}\n\nexport type CmsShellTarget = { kind: \"collection\"; slug: string } | { kind: \"keys\" } | { kind: \"audit\" };\n\nexport interface CmsShellProps {\n children?: React.ReactNode;\n /** Brand text on top of the sidebar. Default \"Admin\". */\n title?: React.ReactNode;\n /** Brand mark (logo) before the title. */\n logo?: React.ReactNode;\n /** The collection shown now (highlighted). */\n activeCollection?: string;\n /** The current path; highlights the ops or `extraNav` link with this href. */\n activeHref?: string;\n /** Where the admin pages live, for the default links. Default \"/admin\". */\n basePath?: string;\n /** Override the link of a sidebar entry. Default `${basePath}/<collection>`, `${basePath}/keys`, `${basePath}/audit`. */\n hrefFor?: (target: CmsShellTarget) => string;\n /** Your app's own screens, shown under the operations section. */\n extraNav?: CmsNavGroup[];\n /** Show the search button (pair it with <CmsCommand>). */\n onSearch?: () => void;\n /** Render links with your router, e.g. `LinkComponent={Link}` from next/link. Default `<a>`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n LinkComponent?: React.ComponentType<CmsLinkProps> | React.ComponentType<any>;\n /** Full control over links (wins over LinkComponent). */\n renderLink?: (props: CmsLinkProps) => React.ReactNode;\n /** Item counts beside collections; default: the \"all\" count from `counts()` for collections you can edit. */\n counts?: Record<string, number>;\n className?: string;\n}\n\nexport function CmsShell({ children, title, logo, activeCollection, activeHref, basePath = \"/admin\", hrefFor, extraNav, onSearch, LinkComponent, renderLink, counts, className }: CmsShellProps) {\n const { t, me, client } = useCms();\n const [open, setOpen] = React.useState(false);\n const [loaded, setLoaded] = React.useState<Record<string, number>>({});\n\n React.useEffect(() => {\n if (counts || !me) return;\n let live = true;\n void Promise.all(\n me.collections\n .filter((c) => c.canWrite)\n .map((c) =>\n client.counts(c.slug).then(\n (n) => [c.slug, n.all] as const,\n () => null\n )\n )\n ).then((rows) => {\n if (live) setLoaded(Object.fromEntries(rows.filter((r): r is readonly [string, number] => !!r)));\n });\n return () => {\n live = false;\n };\n }, [client, me, counts]);\n const shown = counts ?? loaded;\n\n const href = (target: CmsShellTarget) =>\n hrefFor?.(target) ?? (target.kind === \"collection\" ? `${basePath}/${encodeURIComponent(target.slug)}` : `${basePath}/${target.kind}`);\n\n const link = (p: CmsLinkProps) => {\n if (renderLink) return renderLink(p);\n const L = LinkComponent;\n if (L) return <L {...p} />;\n return (\n <a href={p.href} className={p.className} aria-current={p[\"aria-current\"]} onClick={p.onClick}>\n {p.children}\n </a>\n );\n };\n\n const navClass = (active: boolean) =>\n cn(\n \"flex h-8 items-center gap-2 rounded-md px-2 text-sm text-foreground/80 outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n active && \"bg-accent font-medium text-accent-foreground\"\n );\n\n const close = () => setOpen(false);\n\n const nav = (\n <nav aria-label={t(\"nav_label\")} className=\"flex flex-col gap-0.5 text-sm\">\n {onSearch ? (\n <button\n type=\"button\"\n onClick={() => {\n close();\n onSearch();\n }}\n className=\"mb-3 flex h-8 items-center gap-2 rounded-md border bg-background px-2 text-sm text-muted-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <Search aria-hidden className=\"h-4 w-4\" />\n <span className=\"flex-1 text-left\">{t(\"search\")}</span>\n <kbd className=\"rounded border border-b-2 px-1 font-mono text-[11px]\">⌘K</kbd>\n </button>\n ) : null}\n <h2 className=\"px-2 pb-1 pt-2 text-xs font-medium text-muted-foreground\">{t(\"nav_collections\")}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {(me?.collections ?? []).map((c) => {\n const active = c.slug === activeCollection;\n return (\n <li key={c.slug}>\n {link({\n href: href({ kind: \"collection\", slug: c.slug }),\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n <BookOpen aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span className=\"flex-1 truncate\">{c.label}</span>\n {shown[c.slug] !== undefined ? <span className=\"text-xs tabular-nums text-muted-foreground\">{shown[c.slug]}</span> : null}\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n {me?.isAdmin ? (\n <>\n <h2 className=\"px-2 pb-1 pt-4 text-xs font-medium text-muted-foreground\">{t(\"nav_ops\")}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {(\n [\n { kind: \"keys\", label: t(\"nav_keys\"), Icon: KeyRound },\n { kind: \"audit\", label: t(\"nav_audit\"), Icon: ScrollText },\n ] as const\n ).map(({ kind, label, Icon }) => {\n const h = href({ kind });\n const active = activeHref === h;\n return (\n <li key={kind}>\n {link({\n href: h,\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n <Icon aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span className=\"flex-1 truncate\">{label}</span>\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n </>\n ) : null}\n {(extraNav ?? []).map((g, gi) => (\n <div key={gi} data-cms-extra-nav=\"\">\n <h2 className=\"px-2 pb-1 pt-4 text-xs font-medium text-muted-foreground\">{g.label}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {g.items.map((it) => {\n const active = activeHref === it.href;\n return (\n <li key={it.href}>\n {link({\n href: it.href,\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n {it.icon ?? <FileText aria-hidden className=\"h-4 w-4 shrink-0\" />}\n <span className=\"flex-1 truncate\">{it.label}</span>\n {it.badge !== undefined && it.badge !== null ? <span className=\"text-xs tabular-nums text-muted-foreground\">{it.badge}</span> : null}\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n </div>\n ))}\n </nav>\n );\n\n const brand = (\n <div className=\"mb-4 flex items-center gap-2 px-2 font-semibold\">\n {logo}\n <span className=\"truncate\">{title ?? t(\"shell_title\")}</span>\n </div>\n );\n\n const navCtx = React.useMemo(() => ({ openNav: () => setOpen(true) }), []);\n\n return (\n <ShellNavContext.Provider value={navCtx}>\n <div className={cn(\"flex min-h-screen bg-background text-foreground\", className)}>\n <aside className=\"sticky top-0 hidden h-screen w-60 shrink-0 overflow-y-auto border-r bg-muted/30 p-3 md:block\">\n {brand}\n {nav}\n </aside>\n <Sheet open={open} onOpenChange={setOpen}>\n <SheetContent side=\"left\" className=\"w-72 overflow-y-auto p-3\">\n <SheetTitle className=\"sr-only\">{t(\"menu\")}</SheetTitle>\n <SheetDescription className=\"sr-only\">{t(\"nav_label\")}</SheetDescription>\n {brand}\n {nav}\n </SheetContent>\n </Sheet>\n <main className=\"flex min-w-0 flex-1 flex-col\">{children}</main>\n </div>\n </ShellNavContext.Provider>\n );\n}\n"
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-versions",
4
+ "type": "registry:component",
5
+ "title": "Version history",
6
+ "description": "Versions with author, note and changed fields; compare any two side by side or unified with word highlights; restore or publish a version.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "dialog",
15
+ "label",
16
+ "select",
17
+ "cms-lib"
18
+ ],
19
+ "files": [
20
+ {
21
+ "path": "registry/cms/cms-versions.tsx",
22
+ "type": "registry:component",
23
+ "content": "// agent-cms registry: cms-versions (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Version history of one document: who saved what (agent or person, note,\n// published marker, changed fields), a compare of any two versions (side by\n// side or unified, word-level highlight), restore and publish a version.\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowLeft, ArrowRight, ChevronLeft, RotateCcw } from \"lucide-react\";\nimport { diffWords, type Hunk, type HunkLine } from \"@mainsoft/agent-cms/diff\";\nimport type { CmsDoc, VersionSummary } from \"@mainsoft/agent-cms/types\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage, type MessageKey } from \"./cms-messages\";\nimport { ConfirmDialog, PageHeader, Segmented, StateBadge, StatusText, Who } from \"./cms-parts\";\nimport { relativeTime, useAsync, useCms, useIsMobile, useLocalStorage } from \"./use-cms\";\n\ntype DocDiff = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"diff\"]>>;\n\nexport interface CmsVersionsProps {\n collection: string;\n slug: string;\n /** \"Back to editing\". */\n onBack?: () => void;\n /** After a restore or publish. */\n onChanged?: (doc: CmsDoc) => void;\n className?: string;\n}\n\nconst FIELD_LABEL: Record<string, MessageKey> = { title: \"field_title\", slug: \"field_slug\", summary: \"field_summary\", category: \"field_category\", keywords: \"field_keywords\", body: \"field_body\" };\nconst show = (v: unknown): string => (v === undefined || v === null ? \"\" : Array.isArray(v) ? v.join(\", \") : typeof v === \"object\" ? JSON.stringify(v) : String(v));\n\n/** Pair the removed and added lines of a hunk row by row (for side by side and word highlight). */\ntype Row = { t: \"ctx\"; a: HunkLine; b: HunkLine } | { t: \"chg\"; a: HunkLine | null; b: HunkLine | null };\nfunction rowsOf(h: Hunk): Row[] {\n const out: Row[] = [];\n let dels: HunkLine[] = [];\n let adds: HunkLine[] = [];\n const flush = () => {\n for (let i = 0; i < Math.max(dels.length, adds.length); i++) out.push({ t: \"chg\", a: dels[i] ?? null, b: adds[i] ?? null });\n dels = [];\n adds = [];\n };\n for (const l of h.lines) {\n if (l.t === \"-\") dels.push(l);\n else if (l.t === \"+\") adds.push(l);\n else {\n flush();\n out.push({ t: \"ctx\", a: l, b: l });\n }\n }\n flush();\n return out;\n}\n\nfunction Words({ a, b, side }: { a: string; b: string; side: \"a\" | \"b\" }) {\n return (\n <>\n {diffWords(a, b).map((p, i) =>\n p.t === \"eq\" ? (\n <React.Fragment key={i}>{p.v}</React.Fragment>\n ) : p.t === \"del\" && side === \"a\" ? (\n <del key={i} className=\"bg-red-200 no-underline\">\n {p.v}\n </del>\n ) : p.t === \"ins\" && side === \"b\" ? (\n <ins key={i} className=\"bg-green-200 no-underline\">\n {p.v}\n </ins>\n ) : null\n )}\n </>\n );\n}\n\nfunction headingBefore(body: string | undefined, line: number): string | null {\n if (!body) return null;\n const lines = body.split(\"\\n\").slice(0, Math.max(0, line - 1));\n for (let i = lines.length - 1; i >= 0; i--) if (/^#{1,6}\\s/.test(lines[i])) return lines[i];\n return null;\n}\n\nexport function CmsVersions({ collection, slug, onBack, onChanged, className }: CmsVersionsProps) {\n const { client, t, locale } = useCms();\n const mobile = useIsMobile();\n const schema = useAsync(() => client.schema(collection), [client, collection]);\n const list = useAsync(() => client.versions(collection, slug), [client, collection, slug]);\n const versions = list.data ?? [];\n const latest = versions[0]?.version ?? 0;\n const publishedV = versions.find((v) => v.published)?.version ?? null;\n\n const [to, setTo] = React.useState<number | null>(null);\n const [from, setFrom] = React.useState<number | null>(null);\n const [savedView, setView] = useLocalStorage<\"split\" | \"unified\">(\"agent-cms:diff-view\", \"split\");\n const view = mobile ? \"unified\" : savedView;\n const [confirm, setConfirm] = React.useState<\"restore\" | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [status, setStatus] = React.useState<{ text: string; tone: \"ok\" | \"error\" } | null>(null);\n\n // Default: latest against the published version (or the one before).\n React.useEffect(() => {\n if (!versions.length || to !== null) return;\n const b = versions[0].version;\n const a = publishedV !== null && publishedV !== b ? publishedV : (versions[1]?.version ?? b);\n setTo(b);\n setFrom(a);\n }, [versions, to, publishedV]);\n\n const diff = useAsync<{ d: DocDiff; body?: string } | null>(\n async () => {\n if (from === null || to === null) return null;\n const [d, v] = await Promise.all([client.diff(collection, slug, from, to), client.version(collection, slug, to).catch(() => null)]);\n return { d, body: v?.snapshot.body };\n },\n [client, collection, slug, from, to]\n );\n\n const pick = (v: VersionSummary) => {\n setTo(v.version);\n const idx = versions.findIndex((x) => x.version === v.version);\n const prev = versions[idx + 1]?.version;\n setFrom(publishedV !== null && publishedV < v.version ? publishedV : (prev ?? v.version));\n };\n\n const run = async (what: \"restore\" | \"publish\") => {\n if (from === null || to === null) return;\n setBusy(true);\n setStatus(null);\n try {\n const d = what === \"restore\" ? await client.restore(collection, slug, from, { expectedVersion: latest }) : await client.publish(collection, slug, { version: to, expectedVersion: latest });\n setStatus({ text: what === \"restore\" ? t(\"restored\", { version: d.version }) : t(\"published_v\", { version: to }), tone: \"ok\" });\n setConfirm(null);\n setTo(null);\n list.reload();\n onChanged?.(d);\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n } finally {\n setBusy(false);\n }\n };\n\n const canWrite = schema.data?.canWrite ?? false;\n const canPublish = schema.data?.canPublish ?? false;\n const label = (n: number) => (n === publishedV ? t(\"version_published_tag\", { version: n }) : `v${n}`);\n const toInfo = versions.find((v) => v.version === to);\n\n const picker = (id: string, text: string, value: number | null, set: (n: number) => void) => (\n <div className={cn(\"flex flex-col gap-1\", mobile && \"flex-1\")}>\n <Label htmlFor={id} className=\"sr-only\">\n {text}\n </Label>\n <Select value={value === null ? undefined : String(value)} onValueChange={(v: string | null) => v && set(Number(v))}>\n <SelectTrigger id={id} className={cn(\"h-8 text-[13px]\", mobile ? \"w-full\" : \"w-40\")}>\n <SelectValue>{value === null ? null : label(value)}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n {versions.map((v) => (\n <SelectItem key={v.version} value={String(v.version)}>\n {label(v.version)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n\n const compare = (\n <div className=\"flex flex-wrap items-center gap-2\" role=\"group\" aria-label={`${t(\"compare_from\")}, ${t(\"compare_to\")}`}>\n {picker(\"cms-v-from\", t(\"compare_from\"), from, setFrom)}\n <ArrowRight aria-hidden className=\"h-4 w-4 text-muted-foreground\" />\n {picker(\"cms-v-to\", t(\"compare_to\"), to, setTo)}\n {!mobile ? (\n <Segmented\n label={t(\"view_mode\")}\n value={savedView}\n onChange={setView}\n options={[\n { value: \"split\", label: t(\"side_by_side\") },\n { value: \"unified\", label: t(\"unified\") },\n ]}\n />\n ) : null}\n </div>\n );\n\n const actions = (cls?: string) =>\n from !== null && to !== null ? (\n <>\n {canWrite && from !== latest ? (\n <Button type=\"button\" variant=\"outline\" className={cn(\"gap-1.5\", cls)} disabled={busy} onClick={() => setConfirm(\"restore\")}>\n <RotateCcw aria-hidden className=\"h-4 w-4\" />\n {t(\"restore_version\", { version: from })}\n </Button>\n ) : null}\n {canPublish && to !== publishedV ? (\n <Button type=\"button\" className={cls} disabled={busy} onClick={() => void run(\"publish\")}>\n {t(\"publish_version\", { version: to })}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const d = diff.data?.d;\n const body = diff.data?.body;\n\n const fieldTable = d && d.fields.length ? (\n <div className=\"overflow-hidden rounded-lg border\">\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th className=\"px-3 py-2 font-medium\">{t(\"field\")}</th>\n {!mobile ? <th className=\"px-3 py-2 font-medium\">{label(d.a)}</th> : null}\n <th className=\"px-3 py-2 font-medium\">{mobile ? `${label(d.a)} → v${d.b}` : `v${d.b}`}</th>\n </tr>\n </thead>\n <tbody>\n {d.fields.map((f) => {\n const name = FIELD_LABEL[f.path] ? t(FIELD_LABEL[f.path]) : f.path.replace(/^fields\\./, \"\");\n const a = show(f.from);\n const b = show(f.to);\n return (\n <tr key={f.path} className=\"border-b last:border-b-0 align-top\">\n <td className=\"px-3 py-2 text-xs\">{name}</td>\n {!mobile ? (\n <td className=\"px-3 py-2 font-mono text-xs\">\n <Words a={a} b={b} side=\"a\" />\n </td>\n ) : null}\n <td className=\"px-3 py-2 font-mono text-xs\">\n <Words a={a} b={b} side=\"b\" />\n </td>\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n ) : null;\n\n const hunkHead = (h: Hunk) => {\n const head = headingBefore(body, h.bStart + 1);\n return `@@ ${head ?? `-${h.aStart},${h.aLines} +${h.bStart},${h.bLines}`}`;\n };\n\n const lineCls = (k: \"del\" | \"add\" | \"ctx\" | \"pad\") => cn(\"flex min-w-0 gap-2 px-2 font-mono text-xs leading-6\", k === \"del\" && \"bg-red-50\", k === \"add\" && \"bg-green-50\", k === \"pad\" && \"bg-muted/40\");\n const num = (n?: number) => (\n <i aria-hidden className=\"w-8 shrink-0 select-none text-right not-italic text-muted-foreground\">\n {n ?? \"\"}\n </i>\n );\n\n const split = d ? (\n <div className=\"overflow-hidden rounded-lg border\">\n <div className=\"grid grid-cols-2 border-b text-xs font-medium text-muted-foreground\">\n <span className=\"px-3 py-1.5\">{label(d.a)}</span>\n <span className=\"border-l px-3 py-1.5\">v{d.b}</span>\n </div>\n {d.hunks.map((h, hi) => (\n <div key={hi}>\n <div className=\"border-y bg-muted/40 px-3 py-1 font-mono text-xs text-muted-foreground first:border-t-0\">{hunkHead(h)}</div>\n <div className=\"grid grid-cols-2\">\n {rowsOf(h).map((r, i) => (\n <React.Fragment key={i}>\n <div className={lineCls(r.t === \"ctx\" ? \"ctx\" : r.a ? \"del\" : \"pad\")}>\n {num(r.a?.a)}\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {r.t === \"chg\" && r.a ? <span className=\"sr-only\">- </span> : null}\n {r.a ? r.t === \"chg\" && r.b ? <Words a={r.a.v} b={r.b.v} side=\"a\" /> : r.a.v : \"\"}\n </span>\n </div>\n <div className={cn(lineCls(r.t === \"ctx\" ? \"ctx\" : r.b ? \"add\" : \"pad\"), \"border-l\")}>\n {num(r.b?.b)}\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {r.t === \"chg\" && r.b ? <span className=\"sr-only\">+ </span> : null}\n {r.b ? r.t === \"chg\" && r.a ? <Words a={r.a.v} b={r.b.v} side=\"b\" /> : r.b.v : \"\"}\n </span>\n </div>\n </React.Fragment>\n ))}\n </div>\n </div>\n ))}\n </div>\n ) : null;\n\n const unified = d ? (\n <div className={cn(\"overflow-hidden\", mobile ? \"border-t\" : \"rounded-lg border\")}>\n {d.hunks.map((h, hi) => {\n const rows = rowsOf(h);\n const pairs = new Map<HunkLine, string>();\n for (const r of rows) if (r.t === \"chg\" && r.a && r.b) (pairs.set(r.a, r.b.v), pairs.set(r.b, r.a.v));\n return (\n <div key={hi}>\n <div className=\"border-b bg-muted/40 px-3 py-1 font-mono text-xs text-muted-foreground\">{hunkHead(h)}</div>\n {h.lines.map((l, i) => {\n const other = pairs.get(l);\n return (\n <div key={i} className={lineCls(l.t === \"-\" ? \"del\" : l.t === \"+\" ? \"add\" : \"ctx\")}>\n <span aria-hidden className=\"w-3 shrink-0 select-none text-muted-foreground\">\n {l.t === \"-\" ? \"−\" : l.t === \"+\" ? \"+\" : \" \"}\n </span>\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {l.t !== \" \" ? <span className=\"sr-only\">{l.t} </span> : null}\n {other !== undefined ? l.t === \"-\" ? <Words a={l.v} b={other} side=\"a\" /> : <Words a={other} b={l.v} side=\"b\" /> : l.v}\n </span>\n </div>\n );\n })}\n </div>\n );\n })}\n </div>\n ) : null;\n\n const diffArea = (\n <div className=\"flex min-w-0 flex-1 flex-col gap-3\">\n {diff.error ? <StatusText tone=\"error\">{errorMessage(diff.error, t)}</StatusText> : null}\n {d && !d.fields.length && !d.hunks.length ? <p className=\"text-sm text-muted-foreground\">{t(\"no_diff\")}</p> : null}\n {fieldTable}\n {d && d.hunks.length ? (view === \"unified\" ? unified : split) : null}\n </div>\n );\n\n const confirmDialog = (\n <ConfirmDialog\n open={confirm === \"restore\"}\n onOpenChange={(o) => !o && setConfirm(null)}\n title={t(\"restore_confirm\", { version: from ?? 0 })}\n description={t(\"restore_confirm_note\", { version: from ?? 0 })}\n confirmLabel={t(\"restore_version\", { version: from ?? 0 })}\n busy={busy}\n onConfirm={() => run(\"restore\")}\n />\n );\n\n const statusLine = (\n <StatusText tone={status?.tone === \"error\" ? \"error\" : \"ok\"} className=\"text-xs\">\n {status?.text ?? (list.loading && !versions.length ? t(\"loading\") : \"\")}\n </StatusText>\n );\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={t(\"versions\")}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"versions_back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n />\n <div className=\"border-b px-4 py-2.5\">{compare}</div>\n <div className=\"flex-1\">\n {toInfo ? (\n <div className=\"flex flex-col gap-0.5 px-4 py-2.5 text-xs\">\n <div className=\"flex items-center gap-2\">\n <Who kind={toInfo.authorKind} label={toInfo.authorLabel} className=\"font-medium\" />\n <span className=\"text-muted-foreground\">{relativeTime(toInfo.createdAt, t, locale)}</span>\n </div>\n {toInfo.note ? <div className=\"text-muted-foreground\">{toInfo.note}</div> : null}\n </div>\n ) : null}\n <div className=\"px-4 pb-2\">{statusLine}</div>\n {diffArea}\n </div>\n <div className=\"sticky bottom-0 flex gap-2 border-t bg-background p-2\">{actions(\"flex-1\")}</div>\n {confirmDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={t(\"versions\")} crumbs={[schema.data?.label ?? collection, slug]}>\n {onBack ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={onBack}>\n <ArrowLeft aria-hidden className=\"h-4 w-4\" />\n {t(\"versions_back\")}\n </Button>\n ) : null}\n </PageHeader>\n <div className=\"flex min-h-0 flex-1\">\n <nav aria-label={t(\"versions_list\")} className=\"w-64 shrink-0 overflow-y-auto border-r\">\n <ul>\n {versions.map((v) => {\n const on = v.version === to;\n const cmp = v.version === from && !on;\n return (\n <li key={v.version}>\n <button\n type=\"button\"\n aria-current={on ? \"true\" : undefined}\n onClick={() => pick(v)}\n className={cn(\"flex w-full flex-col gap-1 border-b px-3.5 py-2.5 text-left outline-none hover:bg-muted/50 focus-visible:bg-muted\", on && \"bg-muted\", cmp && \"bg-muted/40\")}\n >\n <span className=\"flex w-full items-center gap-2 text-sm\">\n <b>v{v.version}</b>\n {v.published ? <StateBadge state=\"published\" /> : null}\n <span className=\"flex-1\" />\n <span className=\"text-xs text-muted-foreground\">{relativeTime(v.createdAt, t, locale)}</span>\n </span>\n <span className=\"flex items-center gap-1.5 text-xs\">\n <Who kind={v.authorKind} label={v.authorLabel} />\n <Badge variant=\"outline\" className={cn(\"h-4 rounded-full px-1.5 text-[10.5px] font-normal\", v.authorKind !== \"user\" && \"border-blue-200 bg-blue-50 text-blue-700\")}>\n {v.authorKind === \"user\" ? t(\"kind_user\") : t(\"kind_agent\")}\n </Badge>\n </span>\n {v.note ? <span className=\"text-xs text-muted-foreground\">{v.note}</span> : null}\n {v.changed?.fields.length ? (\n <span className=\"text-[11px] text-muted-foreground\">\n {t(\"changed_fields\", { fields: v.changed.fields.map((f) => (FIELD_LABEL[f] ? t(FIELD_LABEL[f]) : f.replace(/^fields\\./, \"\"))).join(\", \") })}\n </span>\n ) : null}\n </button>\n </li>\n );\n })}\n </ul>\n </nav>\n <div className=\"flex min-w-0 flex-1 flex-col gap-3 overflow-y-auto px-6 py-4\">\n <div className=\"flex flex-wrap items-center gap-2\">\n {compare}\n <span className=\"flex-1\" />\n {actions()}\n </div>\n {statusLine}\n {diffArea}\n </div>\n </div>\n {confirmDialog}\n </div>\n );\n}\n"
24
+ }
25
+ ]
26
+ }