@mainsoft/agent-cms 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +359 -2
- package/TODO.md +178 -0
- package/UPGRADE-0.6.md +236 -0
- package/dist/agent.cjs +250 -0
- package/dist/agent.d.cts +88 -0
- package/dist/agent.d.ts +88 -0
- package/dist/agent.js +24 -0
- package/dist/ai.cjs +555 -0
- package/dist/ai.d.cts +48 -0
- package/dist/ai.d.ts +48 -0
- package/dist/ai.js +73 -0
- package/dist/bin.js +1556 -0
- package/dist/chunk-2NTK7H4W.js +10 -0
- package/dist/chunk-52NUUZC7.js +1446 -0
- package/dist/chunk-6K5ZTGHQ.js +30 -0
- package/dist/chunk-AKN7SUXU.js +281 -0
- package/dist/chunk-CRDW6Q72.js +188 -0
- package/dist/chunk-DD56PTZ4.js +78 -0
- package/dist/chunk-DOADAH4L.js +52 -0
- package/dist/chunk-EXV6JNLY.js +251 -0
- package/dist/chunk-IGL2V6US.js +324 -0
- package/dist/chunk-IW3D4I7Q.js +317 -0
- package/dist/chunk-OQ55GEF3.js +6 -0
- package/dist/chunk-QC2M4NZY.js +158 -0
- package/dist/chunk-QQV6VLYJ.js +204 -0
- package/dist/chunk-T66ZKBHF.js +25 -0
- package/dist/chunk-VICZ76TR.js +118 -0
- package/dist/chunk-Y63XQS2J.js +6 -0
- package/dist/cli.cjs +1596 -0
- package/dist/cli.d.cts +89 -0
- package/dist/cli.d.ts +89 -0
- package/dist/cli.js +534 -0
- package/dist/client.cjs +185 -0
- package/dist/client.d.cts +228 -0
- package/dist/client.d.ts +228 -0
- package/dist/client.js +13 -0
- package/dist/cms-BPp01z-8.d.ts +411 -0
- package/dist/cms-D6D89-qZ.d.cts +411 -0
- package/dist/config.cjs +61 -0
- package/dist/config.d.cts +36 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.js +11 -0
- package/dist/diff.cjs +316 -0
- package/dist/diff.d.cts +122 -0
- package/dist/diff.d.ts +122 -0
- package/dist/diff.js +29 -0
- package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
- package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
- package/dist/errors.cjs +193 -0
- package/dist/errors.d.cts +109 -0
- package/dist/errors.d.ts +109 -0
- package/dist/errors.js +16 -0
- package/dist/frontmatter.cjs +103 -0
- package/dist/frontmatter.d.cts +32 -0
- package/dist/frontmatter.d.ts +32 -0
- package/dist/frontmatter.js +9 -0
- package/dist/http.cjs +1105 -0
- package/dist/http.d.cts +75 -0
- package/dist/http.d.ts +75 -0
- package/dist/http.js +321 -0
- package/dist/index.cjs +3066 -0
- package/dist/index.d.cts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +263 -0
- package/dist/markdown.cjs +220 -0
- package/dist/markdown.d.cts +88 -0
- package/dist/markdown.d.ts +88 -0
- package/dist/markdown.js +23 -0
- package/dist/mcp.cjs +652 -0
- package/dist/mcp.d.cts +43 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +26 -0
- package/dist/messages/en.cjs +76 -0
- package/dist/messages/en.d.cts +7 -0
- package/dist/messages/en.d.ts +7 -0
- package/dist/messages/en.js +7 -0
- package/dist/messages/ko.cjs +76 -0
- package/dist/messages/ko.d.cts +7 -0
- package/dist/messages/ko.d.ts +7 -0
- package/dist/messages/ko.js +53 -0
- package/dist/registry/cms-audit.json +25 -0
- package/dist/registry/cms-command.json +23 -0
- package/dist/registry/cms-doc-editor.json +36 -0
- package/dist/registry/cms-doc-list.json +29 -0
- package/dist/registry/cms-empty.json +22 -0
- package/dist/registry/cms-keys.json +29 -0
- package/dist/registry/cms-lib.json +33 -0
- package/dist/registry/cms-merge.json +26 -0
- package/dist/registry/cms-shell.json +22 -0
- package/dist/registry/cms-versions.json +26 -0
- package/dist/registry/registry.json +255 -0
- package/dist/repo-BWI2Pkrv.d.ts +162 -0
- package/dist/repo-CeDxUxO6.d.cts +162 -0
- package/dist/tables.cjs +356 -0
- package/dist/tables.d.cts +3515 -0
- package/dist/tables.d.ts +3515 -0
- package/dist/tables.js +35 -0
- package/dist/tools.cjs +420 -0
- package/dist/tools.d.cts +27 -0
- package/dist/tools.d.ts +27 -0
- package/dist/tools.js +18 -0
- package/dist/types.cjs +226 -0
- package/dist/types.d.cts +286 -0
- package/dist/types.d.ts +286 -0
- package/dist/types.js +28 -0
- package/package.json +277 -4
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "cms-doc-editor",
|
|
4
|
+
"type": "registry:component",
|
|
5
|
+
"title": "Document editor",
|
|
6
|
+
"description": "Info form generated from the collection schema, markdown with live preview, autosave and restore, problems on the fields, agent change review (accept, revert), save, publish, preview links.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"@mainsoft/agent-cms",
|
|
9
|
+
"lucide-react"
|
|
10
|
+
],
|
|
11
|
+
"registryDependencies": [
|
|
12
|
+
"button",
|
|
13
|
+
"checkbox",
|
|
14
|
+
"dialog",
|
|
15
|
+
"dropdown-menu",
|
|
16
|
+
"input",
|
|
17
|
+
"label",
|
|
18
|
+
"select",
|
|
19
|
+
"tabs",
|
|
20
|
+
"textarea",
|
|
21
|
+
"cms-lib",
|
|
22
|
+
"cms-merge"
|
|
23
|
+
],
|
|
24
|
+
"files": [
|
|
25
|
+
{
|
|
26
|
+
"path": "registry/cms/cms-doc-editor.tsx",
|
|
27
|
+
"type": "registry:component",
|
|
28
|
+
"content": "// agent-cms registry: cms-doc-editor (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish, preview links, and a merge screen when\n// someone saved first.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, Link as LinkIcon, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema } from \"@mainsoft/agent-cms/client\";\nimport { splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.get(collection, slug, { draft: true }), client.changes(collection, slug).catch(() => [] as AgentChange[])]).then(\n ([d, ch]) => {\n if (!live) return;\n applyDoc(d);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean) => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n setStatus({ text: publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n onCreated?.(collection, d.slug);\n return;\n }\n if (!doc) return;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n } finally {\n setBusy(false);\n }\n };\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={st.state} />\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n\n const saveButtons = (cls?: string) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish ? (\n <Button type=\"button\" className={cls} disabled={busy || (!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish)} onClick={() => void save(true)}>\n {t(\"publish\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n {blocks}\n <Textarea\n id={bodyId}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"min-h-[360px] flex-1 resize-none rounded-none border-0 font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n />\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog =\n previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n {publicUrl || previewAllowed ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\")}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"path": "registry/cms/cms-field-form.tsx",
|
|
32
|
+
"type": "registry:component",
|
|
33
|
+
"content": "// agent-cms registry: cms-doc-editor (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The document info form: title, slug, summary, category, keywords and the\n// collection's own fields, generated from `_schema` (JSON Schema plus the\n// `admin` hints: label, help, widget). Problems from `diagnose()` land on the\n// field they belong to (aria-invalid + aria-describedby).\n\"use client\";\n\nimport * as React from \"react\";\nimport { Lock, X } from \"lucide-react\";\nimport type { CollectionSchema } from \"@mainsoft/agent-cms/client\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport type { DocContent } from \"./use-cms\";\nimport { useCms } from \"./use-cms\";\n\nexport type Widget = \"text\" | \"textarea\" | \"number\" | \"switch\" | \"select\" | \"multiselect\" | \"date\" | \"tags\" | \"json\";\n\ntype JsonSchema = {\n type?: string | string[];\n enum?: unknown[];\n items?: JsonSchema;\n anyOf?: JsonSchema[];\n format?: string;\n description?: string;\n maxLength?: number;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n};\n\nexport interface FieldSpec {\n key: string;\n label: string;\n help?: string;\n widget: Widget;\n required: boolean;\n options?: string[];\n integer?: boolean;\n}\n\n/** Drop `null` from `anyOf: [X, null]` (nullable fields). */\nfunction unwrap(s: JsonSchema): JsonSchema {\n if (s.anyOf) {\n const rest = s.anyOf.filter((x) => x.type !== \"null\");\n if (rest.length === 1) return { ...unwrap(rest[0]), description: s.description ?? rest[0].description };\n }\n return s;\n}\n\n/** Which widget fits a JSON Schema property (an `admin.widget` hint wins). */\nexport function widgetFor(schema: JsonSchema, hint?: string): Widget {\n if (hint) return hint as Widget;\n const s = unwrap(schema);\n const type = Array.isArray(s.type) ? s.type.find((x) => x !== \"null\") : s.type;\n if (s.enum && s.enum.every((x) => typeof x === \"string\")) return \"select\";\n if (type === \"string\") return s.format === \"date\" || s.format === \"date-time\" ? \"date\" : (s.maxLength ?? 0) > 200 ? \"textarea\" : \"text\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"switch\";\n if (type === \"array\") {\n const it = s.items ? unwrap(s.items) : {};\n if (it.enum && it.enum.every((x) => typeof x === \"string\")) return \"multiselect\";\n if (it.type === \"string\") return \"tags\";\n }\n return \"json\";\n}\n\n/** The custom fields of a collection, in schema order. */\nexport function fieldSpecs(schema: CollectionSchema): FieldSpec[] {\n const root = (schema.fields ?? {}) as JsonSchema;\n const props = root.properties ?? {};\n const req = new Set(root.required ?? []);\n return Object.entries(props).map(([key, raw]) => {\n const s = unwrap(raw);\n const hint = schema.admin?.[key];\n const widget = widgetFor(raw, hint?.widget);\n const options = (widget === \"select\" ? s.enum : widget === \"multiselect\" ? (s.items ? unwrap(s.items).enum : undefined) : undefined) as string[] | undefined;\n return { key, label: hint?.label ?? key, help: hint?.help ?? s.description, widget, required: req.has(key), options, integer: s.type === \"integer\" };\n });\n}\n\n// ── problems per field ───────────────────────────────────────────────────────\n\nexport interface FieldProblem {\n path: string;\n message: string;\n severity: \"error\" | \"warning\";\n}\n\n/** `fields.tags.0` → `fields.tags`; `title` → `title`. */\nexport function problemKey(path: string): string {\n const p = path.split(\".\");\n return p[0] === \"fields\" && p[1] ? `fields.${p[1]}` : p[0];\n}\n\n// ── small inputs ─────────────────────────────────────────────────────────────\n\ninterface Described {\n id: string;\n help?: string;\n errors?: FieldProblem[];\n}\n\nfunction describedBy({ id, help, errors }: Described): string | undefined {\n const ids = [help ? `${id}-help` : null, errors?.length ? `${id}-err` : null].filter(Boolean);\n return ids.length ? ids.join(\" \") : undefined;\n}\n\nfunction FieldShell({ id, label, help, errors, required, children, className, asGroup }: Described & { label: React.ReactNode; required?: boolean; children: React.ReactNode; className?: string; asGroup?: boolean }) {\n const { t } = useCms();\n const hasError = errors?.some((e) => e.severity === \"error\");\n const msgs = (\n <>\n {help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {help}\n </p>\n ) : null}\n {errors?.length ? (\n <p id={`${id}-err`} className={cn(\"text-xs\", hasError ? \"text-destructive\" : \"text-amber-700\")}>\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </>\n );\n const req = required ? (\n <span className=\"ml-0.5 text-destructive\" aria-hidden title={t(\"required\")}>\n *\n </span>\n ) : null;\n if (asGroup)\n return (\n <fieldset className={cn(\"flex min-w-0 flex-col gap-1.5\", className)} aria-describedby={describedBy({ id, help, errors })}>\n <legend className=\"mb-1.5 text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </legend>\n {children}\n {msgs}\n </fieldset>\n );\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-1.5\", className)}>\n <Label htmlFor={id} className=\"text-xs font-medium text-muted-foreground\">\n {label}\n {req}\n </Label>\n {children}\n {msgs}\n </div>\n );\n}\n\n/** Chips with an input: Enter or comma adds, the x removes. */\nexport function TagsInput({ id, value, onChange, invalid, describedBy: by, required }: { id: string; value: string[]; onChange: (v: string[]) => void; invalid?: boolean; describedBy?: string; required?: boolean }) {\n const { t } = useCms();\n const [text, setText] = React.useState(\"\");\n const add = () => {\n const parts = text\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((s) => !value.includes(s));\n if (parts.length) onChange([...value, ...parts]);\n setText(\"\");\n };\n return (\n <div className={cn(\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 focus-within:ring-1 focus-within:ring-ring\", invalid && \"border-destructive\")}>\n {value.map((tag) => (\n <span key={tag} className=\"inline-flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-xs\">\n {tag}\n <button type=\"button\" className=\"rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\" aria-label={t(\"tag_remove\", { tag })} onClick={() => onChange(value.filter((x) => x !== tag))}>\n <X aria-hidden className=\"h-3 w-3\" />\n </button>\n </span>\n ))}\n <input\n id={id}\n value={text}\n placeholder={value.length ? \"\" : t(\"tags_add\")}\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n aria-required={required || undefined}\n className=\"min-w-[6rem] flex-1 bg-transparent py-0.5 text-sm outline-none placeholder:text-muted-foreground\"\n onChange={(e) => setText(e.target.value)}\n onBlur={add}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \",\") {\n e.preventDefault();\n add();\n } else if (e.key === \"Backspace\" && !text && value.length) onChange(value.slice(0, -1));\n }}\n />\n </div>\n );\n}\n\nfunction JsonInput({ id, value, onChange, invalid, describedBy: by, onLocalError }: { id: string; value: unknown; onChange: (v: unknown) => void; invalid?: boolean; describedBy?: string; onLocalError: (msg: string | null) => void }) {\n const { t } = useCms();\n const [text, setText] = React.useState(() => (value === undefined ? \"\" : JSON.stringify(value, null, 2)));\n const last = React.useRef(value);\n React.useEffect(() => {\n if (JSON.stringify(last.current) !== JSON.stringify(value)) {\n setText(value === undefined ? \"\" : JSON.stringify(value, null, 2));\n last.current = value;\n }\n }, [value]);\n return (\n <Textarea\n id={id}\n value={text}\n rows={4}\n spellCheck={false}\n className=\"font-mono text-xs\"\n aria-invalid={invalid || undefined}\n aria-describedby={by}\n onChange={(e) => {\n const v = e.target.value;\n setText(v);\n if (!v.trim()) {\n last.current = undefined;\n onLocalError(null);\n onChange(undefined);\n return;\n }\n try {\n const parsed = JSON.parse(v);\n last.current = parsed;\n onLocalError(null);\n onChange(parsed);\n } catch {\n onLocalError(t(\"json_invalid\"));\n }\n }}\n />\n );\n}\n\n// ── one custom field ─────────────────────────────────────────────────────────\n\nexport function FieldInput({ spec, idPrefix, value, onChange, problems }: { spec: FieldSpec; idPrefix: string; value: unknown; onChange: (v: unknown) => void; problems?: FieldProblem[] }) {\n const { t } = useCms();\n const id = `${idPrefix}-f-${spec.key}`;\n const [localError, setLocalError] = React.useState<string | null>(null);\n const errors = [...(problems ?? []), ...(localError ? [{ path: spec.key, message: localError, severity: \"error\" as const }] : [])];\n const invalid = errors.some((e) => e.severity === \"error\");\n const by = describedBy({ id, help: spec.help, errors });\n const common = { id, \"aria-invalid\": invalid || undefined, \"aria-describedby\": by, \"aria-required\": spec.required || undefined } as const;\n const shell = (children: React.ReactNode, o: { asGroup?: boolean; className?: string } = {}) => (\n <FieldShell id={id} label={spec.label} help={spec.help} errors={errors} required={spec.required} asGroup={o.asGroup} className={o.className}>\n {children}\n </FieldShell>\n );\n\n switch (spec.widget) {\n case \"textarea\":\n return shell(<Textarea {...common} rows={3} value={typeof value === \"string\" ? value : \"\"} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />, { className: \"md:col-span-2\" });\n case \"number\":\n return shell(\n <Input\n {...common}\n type=\"number\"\n inputMode={spec.integer ? \"numeric\" : \"decimal\"}\n step={spec.integer ? 1 : \"any\"}\n value={typeof value === \"number\" ? String(value) : \"\"}\n onChange={(e) => onChange(e.target.value === \"\" ? undefined : Number(e.target.value))}\n />\n );\n case \"switch\":\n return (\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <div className=\"flex items-center gap-2 pt-5\">\n <Checkbox {...common} checked={value === true} onCheckedChange={(v) => onChange(v === true)} />\n <Label htmlFor={id} className=\"text-sm font-normal\">\n {spec.label}\n </Label>\n </div>\n {spec.help ? (\n <p id={`${id}-help`} className=\"text-xs text-muted-foreground\">\n {spec.help}\n </p>\n ) : null}\n {errors.length ? (\n <p id={`${id}-err`} className=\"text-xs text-destructive\">\n {errors.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </div>\n );\n case \"select\":\n return shell(\n <Select value={typeof value === \"string\" ? value : \"\"} onValueChange={(v: string | null) => onChange(!v || v === \"__none\" ? undefined : v)}>\n <SelectTrigger {...common} className=\"h-9\">\n <SelectValue>{typeof value === \"string\" && value ? value : <span className=\"text-muted-foreground\">{t(\"pick_one\")}</span>}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n {!spec.required ? <SelectItem value=\"__none\">{t(\"none\")}</SelectItem> : null}\n {(spec.options ?? []).map((o) => (\n <SelectItem key={o} value={o}>\n {o}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n );\n case \"multiselect\": {\n const arr = Array.isArray(value) ? (value as string[]) : [];\n return shell(\n <div className=\"flex flex-wrap gap-x-4 gap-y-2\" role=\"group\">\n {(spec.options ?? []).map((o) => {\n const oid = `${id}-${o}`;\n return (\n <div key={o} className=\"flex items-center gap-1.5\">\n <Checkbox\n id={oid}\n aria-invalid={invalid || undefined}\n checked={arr.includes(o)}\n onCheckedChange={(v) => {\n const next = v === true ? [...arr, o] : arr.filter((x) => x !== o);\n onChange(next.length ? next : undefined);\n }}\n />\n <Label htmlFor={oid} className=\"text-sm font-normal\">\n {o}\n </Label>\n </div>\n );\n })}\n </div>,\n { asGroup: true }\n );\n }\n case \"date\":\n return shell(<Input {...common} type=\"date\" value={typeof value === \"string\" ? value.slice(0, 10) : \"\"} onChange={(e) => onChange(e.target.value || undefined)} />);\n case \"tags\":\n return shell(<TagsInput id={id} required={spec.required} invalid={invalid} describedBy={by} value={Array.isArray(value) ? (value as string[]) : []} onChange={(v) => onChange(v.length ? v : undefined)} />);\n case \"json\":\n return shell(<JsonInput id={id} value={value} invalid={invalid} describedBy={by} onChange={onChange} onLocalError={setLocalError} />, { className: \"md:col-span-2\" });\n default:\n return shell(<Input {...common} value={typeof value === \"string\" ? value : value === undefined || value === null ? \"\" : String(value)} onChange={(e) => onChange(e.target.value === \"\" ? undefined : e.target.value)} />);\n }\n}\n\n// ── the whole form ───────────────────────────────────────────────────────────\n\nexport interface CmsFieldFormProps {\n schema: CollectionSchema;\n value: DocContent;\n onChange: (next: DocContent) => void;\n /** Problems from diagnose(), keyed by `problemKey(path)`. */\n problems?: Record<string, FieldProblem[]>;\n /** The slug cannot change once published. */\n slugLocked?: boolean;\n /** Text before the slug (e.g. \"/guide/\"). */\n slugPrefix?: string;\n idPrefix?: string;\n className?: string;\n}\n\nexport function CmsFieldForm({ schema, value, onChange, problems = {}, slugLocked, slugPrefix, idPrefix = \"cms\", className }: CmsFieldFormProps) {\n const { t } = useCms();\n const specs = React.useMemo(() => fieldSpecs(schema), [schema]);\n const set = <K extends keyof DocContent>(k: K, v: DocContent[K]) => onChange({ ...value, [k]: v });\n const setField = (k: string, v: unknown) => {\n const fields = { ...value.fields };\n if (v === undefined) delete fields[k];\n else fields[k] = v;\n onChange({ ...value, fields });\n };\n\n const text = (key: \"title\" | \"slug\" | \"summary\", label: string, o: { mono?: boolean; disabled?: boolean; help?: string; wide?: boolean } = {}) => {\n const id = `${idPrefix}-${key}`;\n const errors = problems[key];\n const invalid = errors?.some((e) => e.severity === \"error\");\n const help = o.help;\n return (\n <FieldShell id={id} label={label} errors={errors} help={help} required={key !== \"summary\"} className={o.wide ? \"md:col-span-2\" : undefined}>\n <div className=\"relative flex items-center gap-1\">\n {key === \"slug\" && slugPrefix ? <span className=\"shrink-0 font-mono text-sm text-muted-foreground\">{slugPrefix}</span> : null}\n <Input\n id={id}\n value={value[key]}\n disabled={o.disabled}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy({ id, help, errors })}\n aria-required={key !== \"summary\" || undefined}\n className={cn(\"h-9\", o.mono && \"font-mono\", o.disabled && \"pr-8\")}\n onChange={(e) => set(key, e.target.value)}\n />\n {o.disabled ? <Lock aria-hidden className=\"absolute right-3 h-3.5 w-3.5 text-muted-foreground\" /> : null}\n </div>\n </FieldShell>\n );\n };\n\n const catId = `${idPrefix}-category`;\n const kwId = `${idPrefix}-keywords`;\n const catErr = problems.category;\n const kwErr = problems.keywords;\n\n return (\n <div className={cn(\"grid grid-cols-1 gap-x-3 gap-y-3 md:grid-cols-2 xl:grid-cols-3\", className)}>\n {text(\"title\", t(\"field_title\"))}\n {text(\"slug\", t(\"field_slug\"), { mono: true, disabled: slugLocked, help: slugLocked ? t(\"field_slug_locked\") : undefined })}\n {schema.categories?.length ? (\n <FieldShell id={catId} label={t(\"field_category\")} errors={catErr}>\n <Select value={value.category ?? \"__none\"} onValueChange={(v: string | null) => set(\"category\", !v || v === \"__none\" ? null : v)}>\n <SelectTrigger id={catId} className=\"h-9\" aria-invalid={catErr?.some((e) => e.severity === \"error\") || undefined} aria-describedby={describedBy({ id: catId, errors: catErr })}>\n <SelectValue>{value.category ?? t(\"no_category\")}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__none\">{t(\"no_category\")}</SelectItem>\n {schema.categories.map((c) => (\n <SelectItem key={c} value={c}>\n {c}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </FieldShell>\n ) : null}\n {text(\"summary\", t(\"field_summary\"), { wide: true })}\n {specs.map((s) => (\n <FieldInput key={s.key} spec={s} idPrefix={idPrefix} value={value.fields[s.key]} onChange={(v) => setField(s.key, v)} problems={problems[`fields.${s.key}`]} />\n ))}\n <FieldShell id={kwId} label={t(\"field_keywords\")} errors={kwErr}>\n <TagsInput id={kwId} value={value.keywords} onChange={(v) => set(\"keywords\", v)} invalid={kwErr?.some((e) => e.severity === \"error\")} describedBy={describedBy({ id: kwId, errors: kwErr })} />\n </FieldShell>\n </div>\n );\n}\n"
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
|
@@ -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
|
+
}
|