@mainsoft/agent-cms 0.10.2 → 0.11.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 +16 -0
- package/README.md +91 -2
- package/TODO.md +6 -6
- package/UPGRADE-0.11.md +43 -0
- package/dist/agent.d.cts +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +7 -7
- package/dist/bin.js +236 -23
- package/dist/{chunk-IU2SMWAM.js → chunk-42PW3HQ3.js} +15 -1
- package/dist/{chunk-6PB4ZCHH.js → chunk-CIMW73L3.js} +58 -1
- package/dist/{chunk-7Y6TU2UA.js → chunk-HY4ED7LT.js} +2 -2
- package/dist/{chunk-DSJETZT4.js → chunk-I3DF6DMI.js} +15 -10
- package/dist/{chunk-KAO3Z3CF.js → chunk-I5UHTAAW.js} +3 -1
- package/dist/{chunk-7SCYDG2G.js → chunk-J25IKU7C.js} +164 -28
- package/dist/{chunk-BFVBHIHV.js → chunk-J5DW3RFQ.js} +4 -1
- package/dist/{chunk-7WJIIJCI.js → chunk-LELPCGDX.js} +8 -5
- package/dist/{chunk-5ODZ2ZJF.js → chunk-NO6S7KOL.js} +1 -1
- package/dist/{chunk-5FMVVBDR.js → chunk-OLHLSSTD.js} +3 -3
- package/dist/{chunk-3OPKTBEI.js → chunk-SV3ZA6XP.js} +1 -1
- package/dist/{chunk-PEQY4N73.js → chunk-TKKTEGHL.js} +1 -0
- package/dist/{chunk-PGV2QPIL.js → chunk-WWG7XDIZ.js} +2 -0
- package/dist/cli.cjs +236 -23
- package/dist/cli.d.cts +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +18 -16
- package/dist/client.cjs +4 -1
- package/dist/client.d.cts +14 -2
- package/dist/client.d.ts +14 -2
- package/dist/client.js +1 -1
- package/dist/{cms-pqJyowu1.d.ts → cms-A9tmLmTP.d.ts} +100 -5
- package/dist/{cms-C_vkAxYV.d.cts → cms-CaB81PPX.d.cts} +100 -5
- package/dist/config.d.cts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/{drizzle-repo-DWLD0rWe.d.ts → drizzle-repo-BXV-hFkE.d.ts} +1 -1
- package/dist/{drizzle-repo-CviH3EX7.d.cts → drizzle-repo-CblPVYnK.d.cts} +1 -1
- package/dist/errors.cjs +4 -0
- package/dist/errors.d.cts +3 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.js +2 -2
- package/dist/frontmatter.d.cts +1 -1
- package/dist/frontmatter.d.ts +1 -1
- package/dist/http.cjs +17 -7
- package/dist/http.d.cts +2 -2
- package/dist/http.d.ts +2 -2
- package/dist/http.js +16 -15
- package/dist/image-sharp.cjs +104 -0
- package/dist/image-sharp.d.cts +47 -0
- package/dist/image-sharp.d.ts +47 -0
- package/dist/image-sharp.js +70 -0
- package/dist/index.cjs +244 -27
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +21 -21
- package/dist/mcp.cjs +9 -4
- package/dist/mcp.d.cts +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +11 -11
- package/dist/messages/en.cjs +2 -0
- package/dist/messages/en.js +1 -1
- package/dist/messages/ko.cjs +2 -0
- package/dist/messages/ko.js +2 -0
- package/dist/registry/cms-doc-editor.json +6 -1
- package/dist/registry/cms-lib.json +2 -2
- package/dist/registry/cms-media-picker.json +2 -2
- package/dist/registry/cms-media.json +1 -1
- package/dist/registry/registry.json +4 -0
- package/dist/storage-vercel-blob.cjs +199 -0
- package/dist/storage-vercel-blob.d.cts +98 -0
- package/dist/storage-vercel-blob.d.ts +98 -0
- package/dist/storage-vercel-blob.js +165 -0
- package/dist/storage.cjs +63 -3
- package/dist/storage.d.cts +27 -2
- package/dist/storage.d.ts +27 -2
- package/dist/storage.js +9 -3
- package/dist/tables.cjs +15 -1
- package/dist/tables.d.cts +160 -7
- package/dist/tables.d.ts +160 -7
- package/dist/tables.js +2 -2
- package/dist/tools.cjs +8 -3
- package/dist/tools.d.cts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +9 -9
- package/dist/types.cjs +5 -0
- package/dist/types.d.cts +6 -1
- package/dist/types.d.ts +6 -1
- package/dist/types.js +3 -3
- package/package.json +36 -2
package/dist/mcp.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { C as CmsLike } from './cms-
|
|
3
|
+
import { C as CmsLike } from './cms-CaB81PPX.cjs';
|
|
4
4
|
import { Actor } from './types.cjs';
|
|
5
5
|
import './storage.cjs';
|
|
6
6
|
import './markdown.cjs';
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { C as CmsLike } from './cms-
|
|
3
|
+
import { C as CmsLike } from './cms-A9tmLmTP.js';
|
|
4
4
|
import { Actor } from './types.js';
|
|
5
5
|
import './storage.js';
|
|
6
6
|
import './markdown.js';
|
package/dist/mcp.js
CHANGED
|
@@ -5,19 +5,19 @@ import {
|
|
|
5
5
|
createMcpServer,
|
|
6
6
|
handleMcp,
|
|
7
7
|
toJsonSchema
|
|
8
|
-
} from "./chunk-
|
|
9
|
-
import "./chunk-
|
|
10
|
-
import "./chunk-
|
|
11
|
-
import "./chunk-
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-7SCYDG2G.js";
|
|
8
|
+
} from "./chunk-OLHLSSTD.js";
|
|
9
|
+
import "./chunk-NO6S7KOL.js";
|
|
10
|
+
import "./chunk-I3DF6DMI.js";
|
|
11
|
+
import "./chunk-HY4ED7LT.js";
|
|
12
|
+
import "./chunk-J25IKU7C.js";
|
|
14
13
|
import "./chunk-MA6VKJ3F.js";
|
|
15
|
-
import "./chunk-
|
|
16
|
-
import "./chunk-
|
|
14
|
+
import "./chunk-TKKTEGHL.js";
|
|
15
|
+
import "./chunk-I5UHTAAW.js";
|
|
16
|
+
import "./chunk-WWG7XDIZ.js";
|
|
17
|
+
import "./chunk-SV3ZA6XP.js";
|
|
17
18
|
import "./chunk-AKN7SUXU.js";
|
|
18
|
-
import "./chunk-
|
|
19
|
-
import "./chunk-
|
|
20
|
-
import "./chunk-6PB4ZCHH.js";
|
|
19
|
+
import "./chunk-J5DW3RFQ.js";
|
|
20
|
+
import "./chunk-CIMW73L3.js";
|
|
21
21
|
import "./chunk-2NTK7H4W.js";
|
|
22
22
|
export {
|
|
23
23
|
ANONYMOUS_READ_TOOLS,
|
package/dist/messages/en.cjs
CHANGED
|
@@ -79,6 +79,8 @@ var en = {
|
|
|
79
79
|
import_blocked: "That address cannot be fetched",
|
|
80
80
|
import_failed: "Could not fetch the file ({reason})",
|
|
81
81
|
asset_rejected: "This file did not pass the check",
|
|
82
|
+
asset_replace_type: "A file can only be replaced by one of the same type ({mime})",
|
|
83
|
+
unknown_image_size: "There is no image size named \u201C{size}\u201D",
|
|
82
84
|
asset_missing: "The file {id} does not exist",
|
|
83
85
|
asset_wrong_kind: "The file {id} is not a kind this field takes",
|
|
84
86
|
asset_alt_missing: "The image on line {line} has no alt text",
|
package/dist/messages/en.js
CHANGED
package/dist/messages/ko.cjs
CHANGED
|
@@ -79,6 +79,8 @@ var ko = {
|
|
|
79
79
|
import_blocked: "\uAC00\uC838\uC62C \uC218 \uC5C6\uB294 \uC8FC\uC18C\uC608\uC694",
|
|
80
80
|
import_failed: "\uD30C\uC77C\uC744 \uAC00\uC838\uC624\uC9C0 \uBABB\uD588\uC5B4\uC694({reason})",
|
|
81
81
|
asset_rejected: "\uAC80\uC0AC\uB97C \uD1B5\uACFC\uD558\uC9C0 \uBABB\uD55C \uD30C\uC77C\uC774\uC5D0\uC694",
|
|
82
|
+
asset_replace_type: "\uAC19\uC740 \uD615\uC2DD({mime})\uC758 \uD30C\uC77C\uB85C\uB9CC \uBC14\uAFC0 \uC218 \uC788\uC5B4\uC694",
|
|
83
|
+
unknown_image_size: "\u201C{size}\u201D\uB77C\uB294 \uC774\uBBF8\uC9C0 \uD06C\uAE30\uB294 \uC5C6\uC5B4\uC694",
|
|
82
84
|
asset_missing: "\uC5C6\uB294 \uD30C\uC77C\uC774\uC5D0\uC694: {id}",
|
|
83
85
|
asset_wrong_kind: "\uC774 \uD544\uB4DC\uC5D0 \uB123\uC744 \uC218 \uC5C6\uB294 \uC885\uB958\uC758 \uD30C\uC77C\uC774\uC5D0\uC694: {id}",
|
|
84
86
|
asset_alt_missing: "{line}\uBC88\uC9F8 \uC904\uC758 \uC774\uBBF8\uC9C0\uC5D0 \uB300\uCCB4 \uD14D\uC2A4\uD2B8\uAC00 \uC5C6\uC5B4\uC694",
|
package/dist/messages/ko.js
CHANGED
|
@@ -57,6 +57,8 @@ var ko = {
|
|
|
57
57
|
import_blocked: "\uAC00\uC838\uC62C \uC218 \uC5C6\uB294 \uC8FC\uC18C\uC608\uC694",
|
|
58
58
|
import_failed: "\uD30C\uC77C\uC744 \uAC00\uC838\uC624\uC9C0 \uBABB\uD588\uC5B4\uC694({reason})",
|
|
59
59
|
asset_rejected: "\uAC80\uC0AC\uB97C \uD1B5\uACFC\uD558\uC9C0 \uBABB\uD55C \uD30C\uC77C\uC774\uC5D0\uC694",
|
|
60
|
+
asset_replace_type: "\uAC19\uC740 \uD615\uC2DD({mime})\uC758 \uD30C\uC77C\uB85C\uB9CC \uBC14\uAFC0 \uC218 \uC788\uC5B4\uC694",
|
|
61
|
+
unknown_image_size: "\u201C{size}\u201D\uB77C\uB294 \uC774\uBBF8\uC9C0 \uD06C\uAE30\uB294 \uC5C6\uC5B4\uC694",
|
|
60
62
|
asset_missing: "\uC5C6\uB294 \uD30C\uC77C\uC774\uC5D0\uC694: {id}",
|
|
61
63
|
asset_wrong_kind: "\uC774 \uD544\uB4DC\uC5D0 \uB123\uC744 \uC218 \uC5C6\uB294 \uC885\uB958\uC758 \uD30C\uC77C\uC774\uC5D0\uC694: {id}",
|
|
62
64
|
asset_alt_missing: "{line}\uBC88\uC9F8 \uC904\uC758 \uC774\uBBF8\uC9C0\uC5D0 \uB300\uCCB4 \uD14D\uC2A4\uD2B8\uAC00 \uC5C6\uC5B4\uC694",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
{
|
|
27
27
|
"path": "registry/cms/cms-doc-editor.tsx",
|
|
28
28
|
"type": "registry:component",
|
|
29
|
-
"content": "// agent-cms registry: cms-doc-editor (0.10.1). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish (now or at a set time), review requests,\n// comments, who else has it open, preview links, and a merge screen when\n// someone saved first and the two edits overlap.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, ImagePlus, Layers, Link as LinkIcon, MessageSquare, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema, type CommentThread, type DocRelease } from \"@mainsoft/agent-cms/client\";\nimport { mergeDocs, resolveDocMerge, splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState, type Presence } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { AddToReleaseDialog, BodyBackdrop, CommentsPanel, offsetOf, placeOf, PublishButton, ReviewStrip, ScheduleStrip, type BodyCursor } from \"./cms-flow\";\nimport { assetMarkdown, CmsMediaPicker } from \"./cms-media-picker\";\nimport { pasteAsMarkdown } from \"./cms-paste\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, People, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, formatZoned as formatZonedTime, personColor, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n /** Open a release (the \"in the release ...\" strip). */\n onOpenRelease?: (id: string) => void;\n /** How often this screen says \"I am here\" and looks for other people's saves, in ms. Default 15000 (3000 while someone else is here); 0 turns it off. */\n presenceMs?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\n/**\n * \"Saved v1\" for a new document has to outlive the editor that made it: most apps\n * answer `onCreated` by moving to the document's own address, which mounts a new\n * editor. The line waits in sessionStorage for that editor, for a few seconds.\n */\nconst KEPT_STATUS_MS = 15000;\nconst keptStatusKey = (collection: string, slug: string) => `agent-cms:saved:${collection}/${slug}`;\n\nfunction keepStatus(collection: string, slug: string, text: string) {\n try {\n window.sessionStorage.setItem(keptStatusKey(collection, slug), JSON.stringify({ text, at: Date.now() }));\n } catch {\n /* no storage: the line is simply not carried over */\n }\n}\n\nfunction takeStatus(collection: string, slug: string): string | null {\n try {\n const key = keptStatusKey(collection, slug);\n const raw = window.sessionStorage.getItem(key);\n if (!raw) return null;\n window.sessionStorage.removeItem(key);\n const v = JSON.parse(raw) as { text?: unknown; at?: unknown };\n return typeof v.text === \"string\" && typeof v.at === \"number\" && Date.now() - v.at < KEPT_STATUS_MS ? v.text : null;\n } catch {\n return null;\n }\n}\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, onOpenRelease, presenceMs = 15000, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const bodyRef = React.useRef<HTMLTextAreaElement>(null);\n /** Where the cursor last was in the body (null: the person never put it there). */\n const caretRef = React.useRef<[number, number] | null>(null);\n const [picking, setPicking] = React.useState(false);\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n const [release, setRelease] = React.useState<DocRelease | null>(null);\n const [threads, setThreads] = React.useState<CommentThread[]>([]);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n const [releaseOpen, setReleaseOpen] = React.useState(false);\n const [others, setOthers] = React.useState<Presence[]>([]);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n const loadComments = React.useCallback(\n async (s: string) => {\n try {\n setThreads(await client.comments(collection, s));\n } catch {\n /* readers do not see comments */\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.getWithRelease(collection, slug), client.changes(collection, slug).catch(() => [] as AgentChange[]), client.comments(collection, slug).catch(() => [] as CommentThread[])]).then(\n ([r, ch, cm]) => {\n if (!live) return;\n const d = r.doc;\n applyDoc(d);\n setRelease(r.release ?? null);\n setThreads(cm);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n const kept = takeStatus(collection, slug);\n if (kept) setStatus({ text: kept, tone: \"ok\" });\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean): Promise<CmsDoc | null> => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n const text = publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version });\n setStatus({ text, tone: \"ok\" });\n onSaved?.(d);\n if (onCreated) keepStatus(collection, d.slug, text);\n onCreated?.(collection, d.slug);\n return d;\n }\n if (!doc) return null;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n return d;\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return null;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return null;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n return null;\n } finally {\n setBusy(false);\n }\n };\n\n // ── schedule and review ──\n /** The saved document these actions apply to: unsaved edits are saved first. */\n const savedDoc = async (): Promise<CmsDoc> => {\n const d = dirty ? await save(false) : doc;\n if (!d) throw new Error(\"not saved\");\n return d;\n };\n const flow = async (fn: (d: CmsDoc) => Promise<CmsDoc>, done: (d: CmsDoc) => string, rethrow = false) => {\n setBusy(true);\n setStatus(null);\n try {\n const d = await fn(await savedDoc());\n applyDoc(d);\n setStatus({ text: done(d), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e)) setStatus({ text: errorMessage(e, t), tone: \"error\" });\n if (rethrow) throw e;\n } finally {\n setBusy(false);\n }\n };\n const zone = me?.timeZone;\n const scheduleAt = (when: { publishAt: string | null; unpublishAt: string | null }) =>\n flow(\n (d) => client.schedule(collection, d.slug, { ...when, expectedVersion: d.version }),\n (d) => (d.schedule?.publishAt ? t(\"sched_done\", { version: d.schedule.version, time: formatZonedTime(d.schedule.publishAt, locale, zone) }) : t(\"sched_go\")),\n true\n );\n const unschedule = () => flow((d) => client.unschedule(collection, d.slug), () => t(\"sched_cleared\"), true);\n const requestReview = () => flow((d) => client.requestReview(collection, d.slug), () => t(\"review_requested_done\"));\n const approve = () => flow((d) => client.approveReview(collection, d.slug, { publish: true }), (d) => t(\"published_v\", { version: d.publishedVersion ?? d.version }));\n const reject = (note: string) => flow((d) => client.rejectReview(collection, d.slug, note || null), () => t(\"review_rejected_done\"), true);\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── who else is here, and their saves ──\n const live = React.useRef({ content, saved, baseVersion, dirty, others: 0 });\n live.current = { content, saved, baseVersion, dirty, others: others.length };\n const slugNow = doc?.slug;\n React.useEffect(() => {\n if (!slugNow || !presenceMs || mode.kind !== \"edit\") return;\n let stop = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const point = (at: number) => {\n const before = live.current.content.body.slice(0, at).split(\"\\n\");\n return { line: before.length, ch: before[before.length - 1].length };\n };\n /** Someone else saved: take it when nothing is unsaved here, merge when the two edits do not overlap. */\n const catchUp = async () => {\n const latest = await client.get(collection, slugNow, { draft: true });\n const now = live.current;\n if (stop || latest.version <= now.baseVersion) return;\n const who = latest.updatedByAgent ?? latest.updatedBy ?? \"\";\n if (!now.dirty) {\n applyDoc(latest);\n void loadChanges(slugNow);\n setStatus({ text: t(\"other_saved\", { who, version: latest.version }), tone: \"muted\" });\n return;\n }\n const m = mergeDocs(now.saved, now.content, contentOf(latest));\n if (m.body.conflicts.length || m.fieldConflicts.length) return; // saving opens the merge screen\n autosave.cancel();\n const merged = contentOf(resolveDocMerge(m, {}));\n // Keep the cursor where it was: text that arrived above it pushes it down.\n const el = bodyRef.current;\n const sel = caretRef.current;\n let same = 0;\n while (same < merged.body.length && merged.body[same] === now.content.body[same]) same++;\n const shift = (at: number) => (at <= same ? at : Math.max(same, at + merged.body.length - now.content.body.length));\n setDoc(latest);\n setSaved(contentOf(latest));\n setBaseVersion(latest.version);\n setContentRaw(merged);\n if (el && sel && document.activeElement === el)\n requestAnimationFrame(() => {\n el.setSelectionRange(shift(sel[0]), shift(sel[1]));\n caretRef.current = [shift(sel[0]), shift(sel[1])];\n });\n setStatus({ text: t(\"other_merged\", { who, version: latest.version }), tone: \"muted\" });\n };\n const beat = async () => {\n try {\n if (document.visibilityState !== \"hidden\") {\n const sel = caretRef.current;\n const r = await client.presence(collection, slugNow, { cursor: sel ? point(sel[1]) : null, selection: sel && sel[0] !== sel[1] ? point(sel[0]) : null });\n if (stop) return;\n setOthers(r.others);\n if (r.version > live.current.baseVersion) await catchUp();\n }\n } catch {\n /* a reader, or offline: nobody is shown */\n }\n if (!stop) timer = setTimeout(() => void beat(), live.current.others ? Math.min(presenceMs, 3000) : presenceMs);\n };\n void beat();\n return () => {\n stop = true;\n if (timer) clearTimeout(timer);\n setOthers([]);\n void client.leave(collection, slugNow).catch(() => undefined);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, collection, slugNow, presenceMs, mode.kind]);\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={doc?.review ? (doc.review.state === \"requested\" ? \"review\" : \"changes\") : st.state} />\n {doc?.schedule?.publishAt ? <StateBadge state=\"scheduled\" /> : null}\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n const mustReview = !!schema.needsReview;\n const openThreads = threads.filter((x) => !x.resolvedAt);\n /** Answering a request is for people who may publish, and never for the one who asked when everyone needs a review. */\n const mayAnswer = canPublish && me?.actor.kind === \"user\" && !(schema.review?.everyone === \"required\" && doc?.review?.byKind === \"user\" && !doc.review.byAgent && doc.review.byId === me.actor.id);\n const quiet = (p: Promise<unknown>) => void p.catch(() => undefined);\n\n const saveButtons = (cls?: string, up?: boolean) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish && !mustReview ? (\n <PublishButton\n className={cls}\n up={up}\n busy={busy}\n disabled={!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish}\n canSchedule={!!doc}\n schedule={doc?.schedule ?? null}\n onPublish={() => void save(true)}\n onSchedule={scheduleAt}\n onUnschedule={unschedule}\n />\n ) : doc && doc.review?.state !== \"requested\" ? (\n <Button type=\"button\" className={cls} disabled={busy} title={mustReview ? t(\"review_needed\") : undefined} onClick={() => void requestReview()}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const strips = doc ? (\n <>\n <ReviewStrip doc={doc} canAnswer={!!mayAnswer} canWrite={canWrite} busy={busy} onApprove={() => void approve()} onReject={reject} onRequest={() => void requestReview()} />\n <ScheduleStrip\n doc={doc}\n canPublish={canPublish}\n busy={busy}\n onAgain={() => doc.schedule && quiet(scheduleAt({ publishAt: doc.schedule.publishAt, unpublishAt: doc.schedule.unpublishAt }))}\n onUnschedule={() => quiet(unschedule())}\n />\n {release ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\">\n <Layers aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"release_in\", { name: release.name })}</span>\n {release.publishAt ? <span className=\"text-xs tabular-nums text-muted-foreground\">{formatZonedTime(release.publishAt, locale, zone)}</span> : null}\n <span className=\"flex-1\" />\n {onOpenRelease ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => onOpenRelease(release.id)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null;\n\n /** Select a part of the body and bring it into view (a comment was pressed). */\n const showInBody = (start: number, end: number) => {\n setMobileTab(\"edit\");\n requestAnimationFrame(() => {\n const el = bodyRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(start, end);\n caretRef.current = [start, end];\n const line = content.body.slice(0, start).split(\"\\n\").length - 1;\n el.scrollTop = Math.max(0, line * (parseFloat(getComputedStyle(el).lineHeight) || 24) - el.clientHeight / 3);\n });\n };\n const comments = (onClose?: () => void) =>\n doc ? (\n <CommentsPanel collection={collection} slug={doc.slug} body={content.body} canWrite={canWrite} threads={threads} onChanged={() => void loadComments(doc.slug)} getSelection={() => (caretRef.current && bodyRef.current ? [bodyRef.current.selectionStart, bodyRef.current.selectionEnd] : caretRef.current)} onGo={showInBody} onClose={onClose} />\n ) : null;\n // Drawn behind the text: what open comments are attached to, and where the others are.\n const marks = [\n ...openThreads.map((th) => placeOf(content.body, th)).filter((x): x is NonNullable<typeof x> => !!x && x.end > x.start),\n ...others\n .filter((o) => o.cursor && o.selection)\n .map((o) => {\n const a = offsetOf(content.body, o.cursor!.line, o.cursor!.ch);\n const b = offsetOf(content.body, o.selection!.line, o.selection!.ch);\n return { start: Math.min(a, b), end: Math.max(a, b), tone: \"select\" as const };\n }),\n ];\n const cursors: BodyCursor[] = others\n .filter((o) => o.cursor)\n .map((o) => ({ id: o.actorId, at: offsetOf(content.body, o.cursor!.line, o.cursor!.ch), label: o.agent ?? o.label, color: personColor(o.actorId, o.kind !== \"user\" || !!o.agent) }));\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n /** Put a file at the cursor: media on a line of its own, other files as a link. */\n const insertAsset = (a: Parameters<typeof assetMarkdown>[0]) => {\n const el = bodyRef.current;\n const [at, end] = caretRef.current ?? [content.body.length, content.body.length];\n const before = content.body.slice(0, at);\n const after = content.body.slice(end);\n const md = assetMarkdown(a);\n const block = md.startsWith(\"!\");\n const lead = !block || !before || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const tail = !block || after.startsWith(\"\\n\\n\") ? \"\" : after.startsWith(\"\\n\") || !after ? \"\\n\" : \"\\n\\n\";\n setContent({ ...content, body: `${before}${lead}${md}${tail}${after}` });\n const caret = before.length + lead.length + (block ? 2 : md.length);\n requestAnimationFrame(() => {\n el?.focus();\n // An image without alt text: leave the cursor between the brackets.\n el?.setSelectionRange(block && !a.alt ? caret : before.length + lead.length + md.length, block && !a.alt ? caret : before.length + lead.length + md.length);\n });\n };\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n {me?.media && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\" onClick={() => setPicking(true)}>\n <ImagePlus aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_insert_button\")}\n </Button>\n ) : null}\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n <CmsMediaPicker open={picking} onOpenChange={setPicking} onPick={insertAsset} />\n {blocks}\n <div className=\"relative flex min-h-[360px] flex-1 flex-col\">\n {marks.length || cursors.length ? <BodyBackdrop box={bodyRef} text={content.body} marks={marks} cursors={cursors} /> : null}\n <Textarea\n ref={bodyRef}\n id={bodyId}\n onSelect={(e) => (caretRef.current = [e.currentTarget.selectionStart, e.currentTarget.selectionEnd])}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"relative min-h-[360px] flex-1 resize-none rounded-none border-0 bg-transparent font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0 dark:bg-transparent\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n onPaste={(e) => {\n if (!canWrite) return;\n const r = pasteAsMarkdown({ html: e.clipboardData.getData(\"text/html\"), plain: e.clipboardData.getData(\"text/plain\") });\n if (!r) return; // nothing to tidy: the browser pastes as usual\n e.preventDefault();\n const el = e.currentTarget;\n const [a, b] = [el.selectionStart, el.selectionEnd];\n // insertText keeps the browser's undo history; where it is missing, set the text directly.\n if (!(typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, r.text))) {\n setContent({ ...content, body: content.body.slice(0, a) + r.text + content.body.slice(b) });\n requestAnimationFrame(() => el.setSelectionRange(a + r.text.length, a + r.text.length));\n }\n if (r.dropped) setStatus({ text: t(\"paste_dropped\"), tone: \"muted\" });\n }}\n />\n </div>\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog = (\n <>\n {previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null}\n {doc ? (\n <AddToReleaseDialog\n open={releaseOpen}\n onOpenChange={setReleaseOpen}\n collection={collection}\n slug={doc.slug}\n published={published}\n onAdded={(r) => {\n setRelease({ id: r.id, name: r.name, state: \"open\", publishAt: null });\n setStatus({ text: t(\"release_added\", { name: r.name }), tone: \"ok\" });\n }}\n />\n ) : null}\n </>\n );\n const canRelease = !!doc && canWrite && !release;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n <People people={others} max={2} />\n {publicUrl || previewAllowed || canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n {canRelease ? <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n {strips}\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n {doc && canWrite ? (\n <TabsTrigger value=\"comments\" className=\"h-6 text-xs\">\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </TabsTrigger>\n ) : null}\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n <TabsContent value=\"comments\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {comments()}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 z-10 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\", true)}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n <People people={others} className=\"mr-1\" />\n {doc && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" aria-pressed={commentsOpen} onClick={() => setCommentsOpen((v) => !v)}>\n <MessageSquare aria-hidden className=\"h-4 w-4\" />\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </Button>\n ) : null}\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {strips}\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n {commentsOpen ? comments(() => setCommentsOpen(false)) : null}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [comments, setComments] = React.useState(false);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl, { comments }).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, comments, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm\">\n <input type=\"checkbox\" className=\"h-4 w-4 accent-primary\" checked={comments} onChange={(e) => setComments(e.target.checked)} />\n {t(\"pl_comments\")}\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
|
|
29
|
+
"content": "// agent-cms registry: cms-doc-editor (0.11.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 that follows the text (and finds its lines when clicked),\n// the order of the sections, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish (now or at a set time), review requests,\n// comments, who else has it open, preview links, and a merge screen when\n// someone saved first and the two edits overlap.\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowUpDown, Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, ImagePlus, Layers, Link as LinkIcon, MessageSquare, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema, type CommentThread, type DocRelease } from \"@mainsoft/agent-cms/client\";\nimport { mergeDocs, resolveDocMerge, splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState, type Presence } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { AddToReleaseDialog, BodyBackdrop, CommentsPanel, offsetOf, placeOf, PublishButton, ReviewStrip, ScheduleStrip, type BodyCursor } from \"./cms-flow\";\nimport { assetMarkdown, CmsMediaPicker } from \"./cms-media-picker\";\nimport { SectionsOrder, bodySections, lineAt, usePreviewSync } from \"./cms-body-tools\";\nimport { pasteAsMarkdown } from \"./cms-paste\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, People, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, formatZoned as formatZonedTime, personColor, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n /** Open a release (the \"in the release ...\" strip). */\n onOpenRelease?: (id: string) => void;\n /** How often this screen says \"I am here\" and looks for other people's saves, in ms. Default 15000 (3000 while someone else is here); 0 turns it off. */\n presenceMs?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\n/**\n * \"Saved v1\" for a new document has to outlive the editor that made it: most apps\n * answer `onCreated` by moving to the document's own address, which mounts a new\n * editor. The line waits in sessionStorage for that editor, for a few seconds.\n */\nconst KEPT_STATUS_MS = 15000;\nconst keptStatusKey = (collection: string, slug: string) => `agent-cms:saved:${collection}/${slug}`;\n\nfunction keepStatus(collection: string, slug: string, text: string) {\n try {\n window.sessionStorage.setItem(keptStatusKey(collection, slug), JSON.stringify({ text, at: Date.now() }));\n } catch {\n /* no storage: the line is simply not carried over */\n }\n}\n\nfunction takeStatus(collection: string, slug: string): string | null {\n try {\n const key = keptStatusKey(collection, slug);\n const raw = window.sessionStorage.getItem(key);\n if (!raw) return null;\n window.sessionStorage.removeItem(key);\n const v = JSON.parse(raw) as { text?: unknown; at?: unknown };\n return typeof v.text === \"string\" && typeof v.at === \"number\" && Date.now() - v.at < KEPT_STATUS_MS ? v.text : null;\n } catch {\n return null;\n }\n}\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, onOpenRelease, presenceMs = 15000, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const bodyRef = React.useRef<HTMLTextAreaElement>(null);\n /** Where the cursor last was in the body (null: the person never put it there). */\n const caretRef = React.useRef<[number, number] | null>(null);\n const [picking, setPicking] = React.useState(false);\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n const [release, setRelease] = React.useState<DocRelease | null>(null);\n const [threads, setThreads] = React.useState<CommentThread[]>([]);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n const [releaseOpen, setReleaseOpen] = React.useState(false);\n const [others, setOthers] = React.useState<Presence[]>([]);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n const loadComments = React.useCallback(\n async (s: string) => {\n try {\n setThreads(await client.comments(collection, s));\n } catch {\n /* readers do not see comments */\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.getWithRelease(collection, slug), client.changes(collection, slug).catch(() => [] as AgentChange[]), client.comments(collection, slug).catch(() => [] as CommentThread[])]).then(\n ([r, ch, cm]) => {\n if (!live) return;\n const d = r.doc;\n applyDoc(d);\n setRelease(r.release ?? null);\n setThreads(cm);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n const kept = takeStatus(collection, slug);\n if (kept) setStatus({ text: kept, tone: \"ok\" });\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean): Promise<CmsDoc | null> => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n const text = publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version });\n setStatus({ text, tone: \"ok\" });\n onSaved?.(d);\n if (onCreated) keepStatus(collection, d.slug, text);\n onCreated?.(collection, d.slug);\n return d;\n }\n if (!doc) return null;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n return d;\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return null;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return null;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n return null;\n } finally {\n setBusy(false);\n }\n };\n\n // ── schedule and review ──\n /** The saved document these actions apply to: unsaved edits are saved first. */\n const savedDoc = async (): Promise<CmsDoc> => {\n const d = dirty ? await save(false) : doc;\n if (!d) throw new Error(\"not saved\");\n return d;\n };\n const flow = async (fn: (d: CmsDoc) => Promise<CmsDoc>, done: (d: CmsDoc) => string, rethrow = false) => {\n setBusy(true);\n setStatus(null);\n try {\n const d = await fn(await savedDoc());\n applyDoc(d);\n setStatus({ text: done(d), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e)) setStatus({ text: errorMessage(e, t), tone: \"error\" });\n if (rethrow) throw e;\n } finally {\n setBusy(false);\n }\n };\n const zone = me?.timeZone;\n const scheduleAt = (when: { publishAt: string | null; unpublishAt: string | null }) =>\n flow(\n (d) => client.schedule(collection, d.slug, { ...when, expectedVersion: d.version }),\n (d) => (d.schedule?.publishAt ? t(\"sched_done\", { version: d.schedule.version, time: formatZonedTime(d.schedule.publishAt, locale, zone) }) : t(\"sched_go\")),\n true\n );\n const unschedule = () => flow((d) => client.unschedule(collection, d.slug), () => t(\"sched_cleared\"), true);\n const requestReview = () => flow((d) => client.requestReview(collection, d.slug), () => t(\"review_requested_done\"));\n const approve = () => flow((d) => client.approveReview(collection, d.slug, { publish: true }), (d) => t(\"published_v\", { version: d.publishedVersion ?? d.version }));\n const reject = (note: string) => flow((d) => client.rejectReview(collection, d.slug, note || null), () => t(\"review_rejected_done\"), true);\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── who else is here, and their saves ──\n const live = React.useRef({ content, saved, baseVersion, dirty, others: 0 });\n live.current = { content, saved, baseVersion, dirty, others: others.length };\n const slugNow = doc?.slug;\n React.useEffect(() => {\n if (!slugNow || !presenceMs || mode.kind !== \"edit\") return;\n let stop = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const point = (at: number) => {\n const before = live.current.content.body.slice(0, at).split(\"\\n\");\n return { line: before.length, ch: before[before.length - 1].length };\n };\n /** Someone else saved: take it when nothing is unsaved here, merge when the two edits do not overlap. */\n const catchUp = async () => {\n const latest = await client.get(collection, slugNow, { draft: true });\n const now = live.current;\n if (stop || latest.version <= now.baseVersion) return;\n const who = latest.updatedByAgent ?? latest.updatedBy ?? \"\";\n if (!now.dirty) {\n applyDoc(latest);\n void loadChanges(slugNow);\n setStatus({ text: t(\"other_saved\", { who, version: latest.version }), tone: \"muted\" });\n return;\n }\n const m = mergeDocs(now.saved, now.content, contentOf(latest));\n if (m.body.conflicts.length || m.fieldConflicts.length) return; // saving opens the merge screen\n autosave.cancel();\n const merged = contentOf(resolveDocMerge(m, {}));\n // Keep the cursor where it was: text that arrived above it pushes it down.\n const el = bodyRef.current;\n const sel = caretRef.current;\n let same = 0;\n while (same < merged.body.length && merged.body[same] === now.content.body[same]) same++;\n const shift = (at: number) => (at <= same ? at : Math.max(same, at + merged.body.length - now.content.body.length));\n setDoc(latest);\n setSaved(contentOf(latest));\n setBaseVersion(latest.version);\n setContentRaw(merged);\n if (el && sel && document.activeElement === el)\n requestAnimationFrame(() => {\n el.setSelectionRange(shift(sel[0]), shift(sel[1]));\n caretRef.current = [shift(sel[0]), shift(sel[1])];\n });\n setStatus({ text: t(\"other_merged\", { who, version: latest.version }), tone: \"muted\" });\n };\n const beat = async () => {\n try {\n if (document.visibilityState !== \"hidden\") {\n const sel = caretRef.current;\n const r = await client.presence(collection, slugNow, { cursor: sel ? point(sel[1]) : null, selection: sel && sel[0] !== sel[1] ? point(sel[0]) : null });\n if (stop) return;\n setOthers(r.others);\n if (r.version > live.current.baseVersion) await catchUp();\n }\n } catch {\n /* a reader, or offline: nobody is shown */\n }\n if (!stop) timer = setTimeout(() => void beat(), live.current.others ? Math.min(presenceMs, 3000) : presenceMs);\n };\n void beat();\n return () => {\n stop = true;\n if (timer) clearTimeout(timer);\n setOthers([]);\n void client.leave(collection, slugNow).catch(() => undefined);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, collection, slugNow, presenceMs, mode.kind]);\n\n // ── render ──\n // The body beside its preview: scrolling together, a click in the preview finds the lines, and the section cards.\n const previewRef = React.useRef<HTMLDivElement>(null);\n const [outline, setOutline] = React.useState(false);\n const wide = !mobile && !loading && !!schema && !loadError && mode.kind !== \"merge\";\n const sync = usePreviewSync(bodyRef, previewRef, content.body, wide, width);\n // Wide screens: the row with the text and the preview is as tall as the window minus the header and the\n // status line, which both stay in place. The info form scrolls away above it once you work in the body.\n const rootRef = React.useRef<HTMLDivElement>(null);\n const headRef = React.useRef<HTMLDivElement>(null);\n const rowRef = React.useRef<HTMLDivElement>(null);\n const footRef = React.useRef<HTMLDivElement>(null);\n const [rowHeight, setRowHeight] = React.useState<number | null>(null);\n React.useEffect(() => {\n const [root, head, foot] = [rootRef.current, headRef.current, footRef.current];\n if (!wide || !root || !head || !foot) return;\n const fit = () => setRowHeight(Math.max(360, root.clientHeight - head.offsetHeight - foot.offsetHeight));\n fit();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(fit);\n for (const el of [root, head, foot]) ro.observe(el);\n return () => ro.disconnect();\n }, [wide]);\n /** Scrolling or typing in the body: give it the whole window (the form is one scroll up). */\n const showBody = React.useCallback(() => {\n const [root, head, row] = [rootRef.current, headRef.current, rowRef.current];\n if (!root || !head || !row) return;\n const top = row.offsetTop - head.offsetHeight;\n if (root.scrollTop >= top - 1) return;\n if (typeof root.scrollTo === \"function\") root.scrollTo({ top, behavior: \"smooth\" });\n else root.scrollTop = top;\n }, []);\n const sectionCount = React.useMemo(() => bodySections(content.body).length, [content.body]);\n const pendingPick = React.useRef<[number, number] | null>(null);\n const pickLines = (line: number, endLine: number) => {\n setOutline(false);\n if (mobile && mobileTab !== \"edit\") {\n // The text box is on the other tab: go there first.\n pendingPick.current = [line, endLine];\n setMobileTab(\"edit\");\n } else requestAnimationFrame(() => sync.select(line, endLine));\n };\n React.useEffect(() => {\n const p = pendingPick.current;\n if (!p || mobileTab !== \"edit\") return;\n pendingPick.current = null;\n const id = requestAnimationFrame(() => sync.select(p[0], p[1]));\n return () => cancelAnimationFrame(id);\n }, [mobileTab, sync]);\n\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={doc?.review ? (doc.review.state === \"requested\" ? \"review\" : \"changes\") : st.state} />\n {doc?.schedule?.publishAt ? <StateBadge state=\"scheduled\" /> : null}\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n const mustReview = !!schema.needsReview;\n const openThreads = threads.filter((x) => !x.resolvedAt);\n /** Answering a request is for people who may publish, and never for the one who asked when everyone needs a review. */\n const mayAnswer = canPublish && me?.actor.kind === \"user\" && !(schema.review?.everyone === \"required\" && doc?.review?.byKind === \"user\" && !doc.review.byAgent && doc.review.byId === me.actor.id);\n const quiet = (p: Promise<unknown>) => void p.catch(() => undefined);\n\n const saveButtons = (cls?: string, up?: boolean) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish && !mustReview ? (\n <PublishButton\n className={cls}\n up={up}\n busy={busy}\n disabled={!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish}\n canSchedule={!!doc}\n schedule={doc?.schedule ?? null}\n onPublish={() => void save(true)}\n onSchedule={scheduleAt}\n onUnschedule={unschedule}\n />\n ) : doc && doc.review?.state !== \"requested\" ? (\n <Button type=\"button\" className={cls} disabled={busy} title={mustReview ? t(\"review_needed\") : undefined} onClick={() => void requestReview()}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const strips = doc ? (\n <>\n <ReviewStrip doc={doc} canAnswer={!!mayAnswer} canWrite={canWrite} busy={busy} onApprove={() => void approve()} onReject={reject} onRequest={() => void requestReview()} />\n <ScheduleStrip\n doc={doc}\n canPublish={canPublish}\n busy={busy}\n onAgain={() => doc.schedule && quiet(scheduleAt({ publishAt: doc.schedule.publishAt, unpublishAt: doc.schedule.unpublishAt }))}\n onUnschedule={() => quiet(unschedule())}\n />\n {release ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\">\n <Layers aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"release_in\", { name: release.name })}</span>\n {release.publishAt ? <span className=\"text-xs tabular-nums text-muted-foreground\">{formatZonedTime(release.publishAt, locale, zone)}</span> : null}\n <span className=\"flex-1\" />\n {onOpenRelease ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => onOpenRelease(release.id)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null;\n\n /** Select a part of the body and bring it into view (a comment was pressed). */\n const showInBody = (start: number, end: number) => {\n setMobileTab(\"edit\");\n requestAnimationFrame(() => {\n const el = bodyRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(start, end);\n caretRef.current = [start, end];\n const line = content.body.slice(0, start).split(\"\\n\").length - 1;\n el.scrollTop = Math.max(0, line * (parseFloat(getComputedStyle(el).lineHeight) || 24) - el.clientHeight / 3);\n });\n };\n const comments = (onClose?: () => void) =>\n doc ? (\n <CommentsPanel collection={collection} slug={doc.slug} body={content.body} canWrite={canWrite} threads={threads} onChanged={() => void loadComments(doc.slug)} getSelection={() => (caretRef.current && bodyRef.current ? [bodyRef.current.selectionStart, bodyRef.current.selectionEnd] : caretRef.current)} onGo={showInBody} onClose={onClose} />\n ) : null;\n // Drawn behind the text: what open comments are attached to, and where the others are.\n const marks = [\n ...openThreads.map((th) => placeOf(content.body, th)).filter((x): x is NonNullable<typeof x> => !!x && x.end > x.start),\n ...others\n .filter((o) => o.cursor && o.selection)\n .map((o) => {\n const a = offsetOf(content.body, o.cursor!.line, o.cursor!.ch);\n const b = offsetOf(content.body, o.selection!.line, o.selection!.ch);\n return { start: Math.min(a, b), end: Math.max(a, b), tone: \"select\" as const };\n }),\n ];\n const cursors: BodyCursor[] = others\n .filter((o) => o.cursor)\n .map((o) => ({ id: o.actorId, at: offsetOf(content.body, o.cursor!.line, o.cursor!.ch), label: o.agent ?? o.label, color: personColor(o.actorId, o.kind !== \"user\" || !!o.agent) }));\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n /** Put a file at the cursor: media on a line of its own, other files as a link. */\n const insertAsset = (a: Parameters<typeof assetMarkdown>[0]) => {\n const el = bodyRef.current;\n const [at, end] = caretRef.current ?? [content.body.length, content.body.length];\n const before = content.body.slice(0, at);\n const after = content.body.slice(end);\n const md = assetMarkdown(a);\n const block = md.startsWith(\"!\");\n const lead = !block || !before || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const tail = !block || after.startsWith(\"\\n\\n\") ? \"\" : after.startsWith(\"\\n\") || !after ? \"\\n\" : \"\\n\\n\";\n setContent({ ...content, body: `${before}${lead}${md}${tail}${after}` });\n const caret = before.length + lead.length + (block ? 2 : md.length);\n requestAnimationFrame(() => {\n el?.focus();\n // An image without alt text: leave the cursor between the brackets.\n el?.setSelectionRange(block && !a.alt ? caret : before.length + lead.length + md.length, block && !a.alt ? caret : before.length + lead.length + md.length);\n });\n };\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n {canWrite && sectionCount > 1 ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" aria-pressed={outline} aria-label={t(\"sections_order\")} className={cn(\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\", outline && \"bg-muted\")} onClick={() => setOutline((v) => !v)}>\n <ArrowUpDown aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"hidden sm:inline\">{t(\"sections_order\")}</span>\n </Button>\n ) : null}\n {me?.media && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\" onClick={() => setPicking(true)}>\n <ImagePlus aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_insert_button\")}\n </Button>\n ) : null}\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n <CmsMediaPicker open={picking} onOpenChange={setPicking} onPick={insertAsset} />\n {blocks}\n {outline && sectionCount > 1 ? (\n <SectionsOrder\n body={content.body}\n className=\"min-h-[360px]\"\n onChange={(body, m) => {\n setContent({ ...content, body });\n setStatus({ text: t(\"section_moved\", { title: m.title, n: m.place, total: m.total }), tone: \"muted\" });\n }}\n onOpen={(s) => {\n const line = lineAt(content.body, s.start);\n pickLines(line, line);\n }}\n />\n ) : null}\n <div className={cn(\"relative flex min-h-[360px] flex-1 flex-col\", outline && sectionCount > 1 && \"hidden\")}>\n {marks.length || cursors.length ? <BodyBackdrop box={bodyRef} text={content.body} marks={marks} cursors={cursors} /> : null}\n <Textarea\n ref={bodyRef}\n id={bodyId}\n onSelect={(e) => {\n caretRef.current = [e.currentTarget.selectionStart, e.currentTarget.selectionEnd];\n sync.reveal(lineAt(e.currentTarget.value, e.currentTarget.selectionStart));\n }}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"relative min-h-[360px] flex-1 resize-none rounded-none border-0 bg-transparent font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0 dark:bg-transparent\"\n onChange={(e) => {\n setContent({ ...content, body: e.target.value });\n showBody();\n }}\n onScroll={showBody}\n onPaste={(e) => {\n if (!canWrite) return;\n const r = pasteAsMarkdown({ html: e.clipboardData.getData(\"text/html\"), plain: e.clipboardData.getData(\"text/plain\") });\n if (!r) return; // nothing to tidy: the browser pastes as usual\n e.preventDefault();\n const el = e.currentTarget;\n const [a, b] = [el.selectionStart, el.selectionEnd];\n // insertText keeps the browser's undo history; where it is missing, set the text directly.\n if (!(typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, r.text))) {\n setContent({ ...content, body: content.body.slice(0, a) + r.text + content.body.slice(b) });\n requestAnimationFrame(() => el.setSelectionRange(a + r.text.length, a + r.text.length));\n }\n if (r.dropped) setStatus({ text: t(\"paste_dropped\"), tone: \"muted\" });\n }}\n />\n </div>\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div ref={previewRef} className=\"flex-1 overflow-auto\" onScroll={showBody}>\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} onPickLines={pickLines} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog = (\n <>\n {previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null}\n {doc ? (\n <AddToReleaseDialog\n open={releaseOpen}\n onOpenChange={setReleaseOpen}\n collection={collection}\n slug={doc.slug}\n published={published}\n onAdded={(r) => {\n setRelease({ id: r.id, name: r.name, state: \"open\", publishAt: null });\n setStatus({ text: t(\"release_added\", { name: r.name }), tone: \"ok\" });\n }}\n />\n ) : null}\n </>\n );\n const canRelease = !!doc && canWrite && !release;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n <People people={others} max={2} />\n {publicUrl || previewAllowed || canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n {canRelease ? <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n {strips}\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n {doc && canWrite ? (\n <TabsTrigger value=\"comments\" className=\"h-6 text-xs\">\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </TabsTrigger>\n ) : null}\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n <TabsContent value=\"comments\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {comments()}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 z-10 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\", true)}</div>\n {previewDialog}\n </div>\n );\n\n // Wide screens: the editor is as tall as the window, so the text and the preview scroll side by side\n // (and follow each other). Under a top bar of your own, pass e.g. className=\"h-[calc(100dvh-4rem)]\".\n return (\n <div ref={rootRef} className={cn(\"relative flex h-dvh min-h-0 flex-none flex-col overflow-y-auto\", className)}>\n <div ref={headRef} className=\"sticky top-0 z-20 bg-background\">\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n <People people={others} className=\"mr-1\" />\n {doc && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" aria-pressed={commentsOpen} onClick={() => setCommentsOpen((v) => !v)}>\n <MessageSquare aria-hidden className=\"h-4 w-4\" />\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </Button>\n ) : null}\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n {saveButtons()}\n </PageHeader>\n </div>\n {strips}\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div ref={rowRef} className={cn(\"flex min-h-[360px] divide-x\", rowHeight === null ? \"flex-1\" : \"shrink-0\")} style={rowHeight === null ? undefined : { height: rowHeight }}>\n {bodyPane}\n {previewPane(true)}\n {commentsOpen ? comments(() => setCommentsOpen(false)) : null}\n </div>\n <div ref={footRef} className=\"sticky bottom-0 z-10 bg-background\">\n {problemsFoot}\n </div>\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [comments, setComments] = React.useState(false);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl, { comments }).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, comments, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm\">\n <input type=\"checkbox\" className=\"h-4 w-4 accent-primary\" checked={comments} onChange={(e) => setComments(e.target.checked)} />\n {t(\"pl_comments\")}\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
32
|
"path": "registry/cms/cms-field-form.tsx",
|
|
@@ -38,6 +38,11 @@
|
|
|
38
38
|
"type": "registry:component",
|
|
39
39
|
"content": "// agent-cms registry: cms-doc-editor (0.10.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The pieces of the publishing flow the editor shows: the publish button\n// with its schedule panel, the schedule and review strips, the comments\n// panel, and the \"add to a release\" dialog.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, CalendarClock, Check, ChevronDown, MessageSquare, RotateCcw, Undo2, X } from \"lucide-react\";\nimport type { CommentThread } from \"@mainsoft/agent-cms/client\";\nimport { splitSections } from \"@mainsoft/agent-cms/markdown\";\nimport type { CmsComment, CmsDoc, CmsRelease } from \"@mainsoft/agent-cms/types\";\nimport { Button } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { Segmented, StatusText } from \"./cms-parts\";\nimport { formatZoned, personColor, relativeTime, useCms, zonedParts, zonedToIso } from \"./use-cms\";\n\nexport const FLOW_SELECT = \"h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring\";\nconst FIELD = \"h-9 rounded-md border border-input bg-background px-2.5 text-sm tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring\";\n\n// ── where things are in a body ───────────────────────────────────────────────\n\nexport interface Place {\n start: number;\n end: number;\n kind: \"quote\" | \"section\" | \"doc\";\n}\n\n/** Every `#` / `##` heading of `body` with its anchor (the same anchors `splitSections` gives) and where its line starts. */\nexport function sectionStarts(body: string): { anchor: string; start: number; end: number }[] {\n const out: { anchor: string; start: number; end: number }[] = [];\n let at = 0;\n let fence = false;\n for (const line of body.split(\"\\n\")) {\n if (/^```/.test(line)) fence = !fence;\n else if (!fence && /^#{1,2}\\s+\\S/.test(line)) {\n const secs = splitSections(body.slice(0, at + line.length));\n out.push({ anchor: secs[secs.length - 1]?.anchor ?? \"\", start: at, end: at + line.length });\n }\n at += line.length + 1;\n }\n return out;\n}\n\n/** The anchor of the section the character at `offset` is in (\"\" before the first heading). */\nexport function sectionAt(body: string, offset: number): string {\n let anchor = \"\";\n for (const s of sectionStarts(body)) if (s.start <= offset) anchor = s.anchor;\n return anchor;\n}\n\n/** Where a comment sits in `body` now: on its quoted text, else on its section's heading, else nowhere (null). */\nexport function placeOf(body: string, c: Pick<CmsComment, \"anchor\" | \"quote\">): Place | null {\n if (c.quote) {\n const i = body.indexOf(c.quote);\n if (i >= 0) return { start: i, end: i + c.quote.length, kind: \"quote\" };\n }\n if (!c.anchor) return c.quote ? null : { start: 0, end: 0, kind: \"doc\" };\n const s = sectionStarts(body).find((x) => x.anchor === c.anchor);\n return s ? { start: s.start, end: s.end, kind: \"section\" } : null;\n}\n\n// ── marks behind the body ────────────────────────────────────────────────────\n\nexport interface BodyCursor {\n id: string;\n /** Character offset in the body. */\n at: number;\n label: string;\n color: string;\n}\n\n/** The character offset of a 1-based line and a column in `body` (clamped to what exists). */\nexport function offsetOf(body: string, line: number, ch: number): number {\n let at = 0;\n for (let i = 1; i < line; i++) {\n const n = body.indexOf(\"\\n\", at);\n if (n < 0) return body.length;\n at = n + 1;\n }\n const end = body.indexOf(\"\\n\", at);\n return Math.min(at + Math.max(0, ch), end < 0 ? body.length : end);\n}\n\n/**\n * Sits behind the body's text box and draws what a text box cannot: the\n * places comments are attached to, and where other people's cursors are.\n * It copies the box's font and padding and follows its scrolling, so its\n * (invisible) text lines up with the real text.\n */\nexport function BodyBackdrop({ box, text, marks, cursors }: { box: React.RefObject<HTMLTextAreaElement | null>; text: string; marks: { start: number; end: number; tone?: \"select\" }[]; cursors: BodyCursor[] }) {\n const ref = React.useRef<HTMLDivElement>(null);\n // An effect, not a layout effect: the text box is a later sibling, and its ref is not set yet when layout effects of this one run.\n React.useEffect(() => {\n const el = box.current;\n const back = ref.current;\n if (!el || !back) return;\n const fit = () => {\n const cs = getComputedStyle(el);\n const bar = el.offsetWidth - el.clientWidth;\n Object.assign(back.style, { font: cs.font, letterSpacing: cs.letterSpacing, lineHeight: cs.lineHeight, paddingTop: cs.paddingTop, paddingBottom: cs.paddingBottom, paddingLeft: cs.paddingLeft, paddingRight: `${(parseFloat(cs.paddingRight) || 0) + Math.max(0, bar)}px`, tabSize: cs.tabSize });\n back.scrollTop = el.scrollTop;\n };\n fit();\n const follow = () => (back.scrollTop = el.scrollTop);\n el.addEventListener(\"scroll\", follow);\n const ro = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(fit);\n ro?.observe(el);\n return () => {\n el.removeEventListener(\"scroll\", follow);\n ro?.disconnect();\n };\n }, [box, text]);\n\n // Cut the text at every mark edge and cursor, in order.\n const cuts = new Set<number>([0, text.length]);\n for (const m of marks) (cuts.add(Math.min(m.start, text.length)), cuts.add(Math.min(m.end, text.length)));\n for (const c of cursors) cuts.add(Math.min(c.at, text.length));\n const points = [...cuts].sort((a, b) => a - b);\n const out: React.ReactNode[] = [];\n points.forEach((from, i) => {\n for (const c of cursors.filter((x) => Math.min(x.at, text.length) === from))\n out.push(\n <span key={`c${c.id}`} data-cms-cursor={c.label} className=\"relative -mr-0.5 inline-block h-[1.15em] w-0.5 align-text-bottom\" style={{ background: c.color }}>\n <span className=\"absolute -top-3.5 left-0 whitespace-nowrap rounded-[3px] rounded-bl-none px-1 font-sans text-[10px] font-semibold leading-[15px] text-white\" style={{ background: c.color }}>\n {c.label}\n </span>\n </span>\n );\n const to = points[i + 1];\n if (to === undefined) return;\n const piece = text.slice(from, to);\n const over = marks.filter((m) => m.start <= from && m.end >= to && m.end > m.start);\n out.push(\n over.length ? (\n <mark key={from} className={cn(\"rounded-sm text-transparent\", over.some((m) => !m.tone) ? \"bg-amber-200/70\" : \"bg-neutral-500/20\")}>\n {piece}\n </mark>\n ) : (\n piece\n )\n );\n });\n return (\n <div ref={ref} aria-hidden data-cms-backdrop=\"\" className=\"pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words text-transparent\">\n {out}\n {\"\\n\"}\n </div>\n );\n}\n\n// ── publish button with the schedule panel ───────────────────────────────────\n\nexport interface PublishButtonProps {\n disabled?: boolean;\n busy?: boolean;\n /** False for a document that was never saved: there is no version to schedule yet. */\n canSchedule: boolean;\n schedule: CmsDoc[\"schedule\"];\n /** Open the panel upwards (a bar at the bottom of the screen). */\n up?: boolean;\n className?: string;\n onPublish: () => void;\n onSchedule: (when: { publishAt: string | null; unpublishAt: string | null }) => Promise<void>;\n onUnschedule: () => Promise<void>;\n}\n\n/** \"Publish\", and beside it the choice between now and a set time. Times are entered on the CMS's clock. */\nexport function PublishButton({ disabled, busy, canSchedule, schedule, up, className, onPublish, onSchedule, onUnschedule }: PublishButtonProps) {\n const { t, me } = useCms();\n const zone = me?.timeZone ?? \"UTC\";\n const [open, setOpen] = React.useState(false);\n const [mode, setMode] = React.useState<\"now\" | \"later\">(\"later\");\n const [pub, setPub] = React.useState({ date: \"\", time: \"\" });\n const [down, setDown] = React.useState({ date: \"\", time: \"\" });\n const [error, setError] = React.useState<string | null>(null);\n const [working, setWorking] = React.useState(false);\n const wrap = React.useRef<HTMLDivElement>(null);\n const toggle = React.useRef<HTMLButtonElement>(null);\n const id = React.useId();\n\n const show = () => {\n // Tomorrow at nine, unless something is already set.\n const tomorrow = zonedParts(new Date(Date.now() + 86_400_000).toISOString(), zone).date;\n setPub(schedule?.publishAt ? zonedParts(schedule.publishAt, zone) : schedule ? { date: \"\", time: \"\" } : { date: tomorrow, time: \"09:00\" });\n setDown(schedule?.unpublishAt ? zonedParts(schedule.unpublishAt, zone) : { date: \"\", time: \"\" });\n setMode(\"later\");\n setError(null);\n setOpen(true);\n };\n const close = (focus = true) => {\n setOpen(false);\n if (focus) toggle.current?.focus();\n };\n\n React.useEffect(() => {\n if (!open) return;\n const away = (e: PointerEvent) => {\n if (wrap.current && !wrap.current.contains(e.target as Node)) close(false);\n };\n document.addEventListener(\"pointerdown\", away);\n return () => document.removeEventListener(\"pointerdown\", away);\n }, [open]);\n\n const submit = async () => {\n if (mode === \"now\") {\n close();\n return onPublish();\n }\n const publishAt = pub.date ? zonedToIso(pub.date, pub.time || \"09:00\", zone) : null;\n const unpublishAt = down.date ? zonedToIso(down.date, down.time || \"09:00\", zone) : null;\n const now = Date.now();\n if ((publishAt && Date.parse(publishAt) <= now) || (unpublishAt && Date.parse(unpublishAt) <= now)) return setError(t(\"sched_past\"));\n if (publishAt && unpublishAt && Date.parse(unpublishAt) <= Date.parse(publishAt)) return setError(t(\"sched_order\"));\n setWorking(true);\n setError(null);\n try {\n await onSchedule({ publishAt, unpublishAt });\n close();\n } catch (e) {\n setError(errorMessage(e, t));\n } finally {\n setWorking(false);\n }\n };\n\n const when = (label: string, v: { date: string; time: string }, set: (x: { date: string; time: string }) => void, withZone: boolean) => (\n <fieldset className=\"grid gap-1.5\">\n <legend className=\"mb-1.5 flex w-full items-center text-xs font-medium\">\n <span className=\"flex-1\">{label}</span>\n {withZone ? <span className=\"font-normal text-muted-foreground\">{zone}</span> : null}\n </legend>\n <div className=\"flex gap-2\">\n <input type=\"date\" aria-label={`${label}: ${t(\"sched_date\")}`} className={cn(FIELD, \"min-w-0 flex-1\")} value={v.date} onChange={(e) => set({ ...v, date: e.target.value })} />\n <input type=\"time\" aria-label={`${label}: ${t(\"sched_time\")}`} className={cn(FIELD, \"w-[112px]\")} value={v.time} onChange={(e) => set({ ...v, time: e.target.value })} />\n </div>\n </fieldset>\n );\n\n return (\n <div ref={wrap} className={cn(\"relative inline-flex\", className)}>\n <Button type=\"button\" className=\"flex-1 rounded-r-none\" disabled={disabled || busy} onClick={onPublish}>\n {t(\"publish\")}\n </Button>\n <Button\n ref={toggle}\n type=\"button\"\n className=\"rounded-l-none border-l border-primary-foreground/25 px-2\"\n aria-label={t(\"publish_options\")}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n disabled={busy || !canSchedule}\n onClick={() => (open ? close() : show())}\n >\n <ChevronDown aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n {open ? (\n <div\n role=\"dialog\"\n aria-label={t(\"publish_later\")}\n className={cn(\"absolute right-0 z-50 flex w-80 max-w-[calc(100vw-1rem)] flex-col gap-3 rounded-lg border bg-background p-3.5 text-sm shadow-lg\", up ? \"bottom-full mb-1.5\" : \"top-full mt-1.5\")}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.stopPropagation();\n close();\n }\n }}\n >\n <div role=\"radiogroup\" aria-label={t(\"publish_options\")} className=\"grid gap-2.5\">\n {([\"now\", \"later\"] as const).map((m) => (\n <label key={m} className=\"flex cursor-pointer items-center gap-2\">\n <input type=\"radio\" name={`${id}-mode`} className=\"h-4 w-4 accent-primary\" checked={mode === m} disabled={m === \"now\" && !!disabled} onChange={() => setMode(m)} autoFocus={m === \"later\"} />\n {t(m === \"now\" ? \"publish_now\" : \"publish_later\")}\n </label>\n ))}\n </div>\n {mode === \"later\" ? (\n <>\n {when(t(\"sched_publish_at\"), pub, setPub, true)}\n {when(t(\"sched_unpublish_at\"), down, setDown, false)}\n </>\n ) : null}\n {error ? <StatusText tone=\"error\" className=\"text-xs\">{error}</StatusText> : null}\n <div className=\"flex items-center justify-end gap-2\">\n {schedule ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"mr-auto h-8 px-2 text-destructive hover:text-destructive\"\n disabled={working}\n onClick={() => {\n setWorking(true);\n onUnschedule().then(\n () => (setWorking(false), close()),\n (e) => (setWorking(false), setError(errorMessage(e, t)))\n );\n }}\n >\n {t(\"sched_cancel\")}\n </Button>\n ) : null}\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-8\" onClick={() => close()}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-8\" disabled={working || (mode === \"later\" && !pub.date && !down.date)} onClick={() => void submit()}>\n {mode === \"now\" ? t(\"publish\") : t(\"sched_go\")}\n </Button>\n </div>\n </div>\n ) : null}\n </div>\n );\n}\n\n// ── strips under the header ──────────────────────────────────────────────────\n\nconst STRIP = \"flex flex-wrap items-center gap-x-2.5 gap-y-1.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\";\n\n/** What is scheduled, and a warning when the document changed after that. */\nexport function ScheduleStrip({ doc, canPublish, busy, onAgain, onUnschedule }: { doc: CmsDoc; canPublish: boolean; busy?: boolean; onAgain: () => void; onUnschedule: () => void }) {\n const { t, locale, me } = useCms();\n const s = doc.schedule;\n if (!s) return null;\n const zone = me?.timeZone;\n const stale = !!s.publishAt && s.version !== doc.version;\n return (\n <div role=\"status\" className={STRIP}>\n <CalendarClock aria-hidden className=\"h-4 w-4 shrink-0\" />\n {s.publishAt ? <span>{t(\"sched_banner\", { version: s.version, time: formatZoned(s.publishAt, locale, zone) })}</span> : null}\n {s.unpublishAt ? <span>{t(\"sched_banner_down\", { time: formatZoned(s.unpublishAt, locale, zone) })}</span> : null}\n <span className=\"text-xs text-muted-foreground\">{s.byAgent ?? s.by}</span>\n {stale ? <span className=\"font-medium text-amber-700\">{t(\"sched_stale\")}</span> : null}\n <span className=\"flex-1\" />\n {canPublish ? (\n <>\n {stale ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={onAgain}>\n {t(\"sched_again\")}\n </Button>\n ) : null}\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" disabled={busy} onClick={onUnschedule}>\n {t(\"sched_cancel\")}\n </Button>\n </>\n ) : null}\n </div>\n );\n}\n\n/** \"docs-bot asked for a review of v2\", with the answer buttons for people who may publish. */\nexport function ReviewStrip({ doc, canAnswer, canWrite, busy, onApprove, onReject, onRequest }: { doc: CmsDoc; canAnswer: boolean; canWrite: boolean; busy?: boolean; onApprove: () => void; onReject: (note: string) => Promise<void>; onRequest: () => void }) {\n const { t, locale } = useCms();\n const [rejecting, setRejecting] = React.useState(false);\n const [note, setNote] = React.useState(\"\");\n const [error, setError] = React.useState<string | null>(null);\n const [working, setWorking] = React.useState(false);\n const r = doc.review;\n if (!r) return null;\n const asked = r.state === \"requested\";\n const bot = r.byKind !== \"user\" || !!r.byAgent;\n return (\n <div role=\"status\" className={STRIP}>\n {!asked ? <Undo2 aria-hidden className=\"h-4 w-4 shrink-0\" /> : bot ? <Bot aria-hidden className=\"h-4 w-4 shrink-0\" /> : null}\n <span>{asked ? t(\"review_requested_by\", { who: r.byAgent ?? r.by ?? \"\", version: r.version }) : t(\"review_changes_by\", { who: r.answeredBy ?? \"\", version: r.version })}</span>\n <span className=\"text-xs text-muted-foreground\">{relativeTime(asked ? r.at : (r.answeredAt ?? r.at), t, locale)}</span>\n {r.note ? <span className=\"min-w-0 basis-full text-[13px] text-muted-foreground md:basis-auto md:truncate\">{r.note}</span> : null}\n <span className=\"flex-1\" />\n {asked && canAnswer ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={() => (setNote(\"\"), setError(null), setRejecting(true))}>\n {t(\"review_reject\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-7\" disabled={busy} onClick={onApprove}>\n {t(\"review_approve_publish\")}\n </Button>\n </>\n ) : null}\n {!asked && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" disabled={busy} onClick={onRequest}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n <Dialog open={rejecting} onOpenChange={setRejecting}>\n <DialogContent className=\"max-w-[460px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n setWorking(true);\n onReject(note.trim()).then(\n () => (setWorking(false), setRejecting(false)),\n (err) => (setWorking(false), setError(errorMessage(err, t)))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"review_reject\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"review_requested_by\", { who: r.byAgent ?? r.by ?? \"\", version: r.version })}</DialogDescription>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-review-note\">{t(\"review_note\")}</Label>\n <Textarea id=\"cms-review-note\" autoFocus rows={4} maxLength={2000} value={note} onChange={(e) => setNote(e.target.value)} />\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setRejecting(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={working}>\n {t(\"review_reject\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n </div>\n );\n}\n\n// ── comments ─────────────────────────────────────────────────────────────────\n\nfunction Author({ c }: { c: CmsComment }) {\n const { t, locale } = useCms();\n const bot = c.authorKind === \"key\" || c.authorKind === \"system\" || !!c.authorAgent;\n const name = c.authorAgent ?? c.authorLabel ?? \"\";\n return (\n <>\n <span aria-hidden style={{ background: personColor(c.authorId ?? name, bot) }} className=\"grid h-6 w-6 shrink-0 place-items-center rounded-full text-[11px] font-semibold text-white\">\n {bot ? <Bot className=\"h-3 w-3\" /> : (name || \"?\").trim().charAt(0).toUpperCase()}\n </span>\n <span className=\"truncate font-medium\">{name}</span>\n {c.authorKind === \"guest\" ? <span className=\"shrink-0 rounded border px-1 text-[11px] text-muted-foreground\">{t(\"comment_guest\")}</span> : null}\n <span className=\"shrink-0 text-xs text-muted-foreground\">{relativeTime(c.createdAt, t, locale)}</span>\n </>\n );\n}\n\nexport interface CommentsPanelProps {\n collection: string;\n slug: string;\n /** The body as it is in the editor now (comments follow the text as it is typed). */\n body: string;\n canWrite: boolean;\n threads: CommentThread[];\n onChanged: () => void;\n /** The selection in the body, to hang a new comment on. */\n getSelection?: () => [number, number] | null;\n /** Show this part of the body (a comment's quote or heading was pressed). */\n onGo?: (start: number, end: number) => void;\n onClose?: () => void;\n className?: string;\n}\n\n/** Comments on sections and quoted text, with one level of replies. */\nexport function CommentsPanel({ collection, slug, body, canWrite, threads, onChanged, getSelection, onGo, onClose, className }: CommentsPanelProps) {\n const { client, t } = useCms();\n const [tab, setTab] = React.useState<\"open\" | \"resolved\">(\"open\");\n const [text, setText] = React.useState(\"\");\n const [replies, setReplies] = React.useState<Record<string, string>>({});\n const [error, setError] = React.useState<string | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [target, setTarget] = React.useState<{ kind: Place[\"kind\"]; quote: string; anchor: string }>({ kind: \"doc\", quote: \"\", anchor: \"\" });\n\n const act = async (fn: () => Promise<unknown>) => {\n setBusy(true);\n setError(null);\n try {\n await fn();\n onChanged();\n } catch (e) {\n setError(errorMessage(e, t));\n } finally {\n setBusy(false);\n }\n };\n /** Read where the cursor is when the person starts writing: the selection, else the section, else the whole document. */\n const aim = () => {\n const sel = getSelection?.() ?? null;\n if (!sel) return setTarget({ kind: \"doc\", quote: \"\", anchor: \"\" });\n const anchor = sectionAt(body, sel[0]);\n const quote = body.slice(sel[0], sel[1]).trim();\n setTarget(quote && !quote.includes(\"\\n\") && quote.length <= 300 ? { kind: \"quote\", quote, anchor } : { kind: anchor ? \"section\" : \"doc\", quote: \"\", anchor });\n };\n\n const open = threads.filter((x) => !x.resolvedAt);\n const done = threads.filter((x) => x.resolvedAt);\n const placed = (tab === \"open\" ? open : done).map((th) => ({ th, at: placeOf(body, th) }));\n const here = placed.filter((x) => x.at).sort((a, b) => a.at!.start - b.at!.start);\n const lost = placed.filter((x) => !x.at);\n\n const thread = ({ th, at }: { th: CommentThread; at: Place | null }) => (\n <li key={th.id} className=\"flex flex-col gap-2 border-b p-3 text-[13.5px]\">\n <div className=\"flex items-center gap-1.5\">\n <Author c={th} />\n <span className=\"flex-1\" />\n {canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-6 gap-1 px-1.5 text-xs\" disabled={busy} onClick={() => void act(() => client.resolveComment(collection, slug, th.id, !th.resolvedAt))}>\n {th.resolvedAt ? <RotateCcw aria-hidden className=\"h-3.5 w-3.5\" /> : <Check aria-hidden className=\"h-3.5 w-3.5\" />}\n {t(th.resolvedAt ? \"comment_reopen\" : \"comment_resolve\")}\n </Button>\n ) : null}\n </div>\n {th.quote || (at && at.kind === \"section\") ? (\n <button\n type=\"button\"\n disabled={!at || !onGo}\n onClick={() => at && onGo?.(at.start, at.end)}\n className=\"truncate border-l-2 pl-2 text-left font-mono text-[12.5px] text-muted-foreground outline-none enabled:hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {at?.kind === \"section\" || !th.quote ? body.slice(at!.start, at!.end) : th.quote}\n </button>\n ) : null}\n <p className=\"whitespace-pre-wrap break-words\">{th.body}</p>\n {th.replies.length ? (\n <ul className=\"ml-3.5 flex flex-col gap-2 border-l pl-3\">\n {th.replies.map((r) => (\n <li key={r.id} className=\"flex flex-col gap-1\">\n <div className=\"flex items-center gap-1.5\">\n <Author c={r} />\n </div>\n <p className=\"whitespace-pre-wrap break-words\">{r.body}</p>\n </li>\n ))}\n </ul>\n ) : null}\n {canWrite && !th.resolvedAt ? (\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const b = (replies[th.id] ?? \"\").trim();\n if (b) void act(() => client.addComment(collection, slug, { body: b, threadId: th.id }).then(() => setReplies((r) => ({ ...r, [th.id]: \"\" }))));\n }}\n >\n <Input aria-label={`${t(\"comment_reply\")}: ${th.authorAgent ?? th.authorLabel ?? \"\"}`} placeholder={t(\"comment_reply\")} className=\"h-8 text-[13px]\" maxLength={4000} value={replies[th.id] ?? \"\"} onChange={(e) => setReplies((r) => ({ ...r, [th.id]: e.target.value }))} />\n </form>\n ) : null}\n </li>\n );\n\n return (\n <aside aria-label={t(\"comments\")} className={cn(\"flex min-h-0 w-full shrink-0 flex-col md:w-80 md:border-l\", className)}>\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <MessageSquare aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"comments\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"comments_filter\")}\n value={tab}\n onChange={setTab}\n options={[\n { value: \"open\", label: t(\"comments_open\", { n: open.length }) },\n { value: \"resolved\", label: t(\"comments_resolved\", { n: done.length }) },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n {onClose ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-6 w-6\" aria-label={t(\"close\")} onClick={onClose}>\n <X aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n ) : null}\n </div>\n {canWrite && tab === \"open\" ? (\n <form\n className=\"flex flex-col gap-2 border-b p-3\"\n onSubmit={(e) => {\n e.preventDefault();\n const b = text.trim();\n if (b) void act(() => client.addComment(collection, slug, { body: b, anchor: target.anchor, quote: target.quote }).then(() => setText(\"\")));\n }}\n >\n <Textarea aria-label={t(\"comment_write\")} placeholder={t(\"comment_write\")} rows={2} maxLength={4000} className=\"min-h-[60px] resize-none text-[13px]\" value={text} onFocus={aim} onChange={(e) => setText(e.target.value)} />\n <div className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">\n {t(target.kind === \"quote\" ? \"comment_on_selection\" : target.kind === \"section\" ? \"comment_on_section\" : \"comment_on_doc\")}\n {target.quote ? <span className=\"font-mono\">: {target.quote}</span> : null}\n </span>\n <Button type=\"submit\" size=\"sm\" className=\"h-7\" disabled={busy || !text.trim()}>\n {t(\"comment_add\")}\n </Button>\n </div>\n </form>\n ) : null}\n {error ? <StatusText tone=\"error\" className=\"px-3 py-2 text-xs\">{error}</StatusText> : null}\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {!placed.length ? <p className=\"px-3 py-8 text-center text-[13px] text-muted-foreground\">{t(\"comment_empty\")}</p> : null}\n <ul>{here.map(thread)}</ul>\n {lost.length ? (\n <>\n <h3 className=\"border-b bg-muted/40 px-3 py-1.5 text-xs font-medium text-muted-foreground\">{t(\"comment_lost\")}</h3>\n <ul>{lost.map(thread)}</ul>\n </>\n ) : null}\n </div>\n </aside>\n );\n}\n\n// ── releases ─────────────────────────────────────────────────────────────────\n\n/** Put this document in an open release (or a new one), to publish or to unpublish with the rest of it. */\nexport function AddToReleaseDialog({ open, onOpenChange, collection, slug, published, onAdded }: { open: boolean; onOpenChange: (o: boolean) => void; collection: string; slug: string; published: boolean; onAdded: (r: { id: string; name: string }) => void }) {\n const { client, t } = useCms();\n const [list, setList] = React.useState<CmsRelease[] | null>(null);\n const [id, setId] = React.useState(\"\");\n const [name, setName] = React.useState(\"\");\n const [action, setAction] = React.useState<\"publish\" | \"unpublish\">(\"publish\");\n const [error, setError] = React.useState<string | null>(null);\n const [busy, setBusy] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setError(null);\n setName(\"\");\n setAction(\"publish\");\n client.releases().then(\n (all) => {\n if (!live) return;\n const openOnes = all.filter((r) => r.state !== \"published\");\n setList(openOnes);\n setId(openOnes[0]?.id ?? \"\");\n },\n (e) => live && setError(errorMessage(e, t))\n );\n return () => {\n live = false;\n };\n }, [open, client, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[420px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n (async () => {\n const target = id ? (list ?? []).find((r) => r.id === id)! : await client.createRelease(name.trim());\n await client.addToRelease(target.id, [{ collection, slug, action }]);\n return target;\n })().then(\n (r) => (setBusy(false), onAdded({ id: r.id, name: r.name }), onOpenChange(false)),\n (err) => (setBusy(false), setError(errorMessage(err, t)))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"release_add_to\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"nav_releases\")}</DialogDescription>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-rel-pick\">{t(\"nav_releases\")}</Label>\n <select id=\"cms-rel-pick\" className={FLOW_SELECT} value={id} onChange={(e) => setId(e.target.value)}>\n {(list ?? []).map((r) => (\n <option key={r.id} value={r.id}>\n {r.name}\n </option>\n ))}\n <option value=\"\">{t(\"release_new\")}</option>\n </select>\n </div>\n {!id ? (\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-rel-name\">{t(\"name\")}</Label>\n <Input id=\"cms-rel-name\" autoFocus maxLength={120} value={name} onChange={(e) => setName(e.target.value)} />\n </div>\n ) : null}\n {published ? (\n <div className=\"grid gap-1.5\">\n <span id=\"cms-rel-action\" className=\"text-sm font-medium\">\n {t(\"release_action\")}\n </span>\n <Segmented\n labelledBy=\"cms-rel-action\"\n value={action}\n onChange={setAction}\n options={[\n { value: \"publish\", label: t(\"publish\") },\n { value: \"unpublish\", label: t(\"release_unpublish\") },\n ]}\n />\n </div>\n ) : null}\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !list || (!id && !name.trim())}>\n {t(\"release_add_to\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n"
|
|
40
40
|
},
|
|
41
|
+
{
|
|
42
|
+
"path": "registry/cms/cms-body-tools.tsx",
|
|
43
|
+
"type": "registry:component",
|
|
44
|
+
"content": "// agent-cms registry: cms-doc-editor (0.11.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// What the body editor does besides typing: the order of the sections,\n// keeping the preview beside the text you are looking at, and going from a\n// block in the preview to its lines in the text.\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowDown, ArrowUp, GripVertical } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\nimport { useCms } from \"./use-cms\";\n\n// ── sections ─────────────────────────────────────────────────────────────────\n\nexport interface BodySection {\n title: string;\n level: 1 | 2;\n /** Where the heading line starts, and where the next section starts. */\n start: number;\n end: number;\n /** The first line of text under the heading. */\n excerpt: string;\n}\n\n/** The `#` / `##` sections of a body, the way `splitSections` cuts them (headings inside code fences do not count). */\nexport function bodySections(body: string): BodySection[] {\n const out: BodySection[] = [];\n let at = 0;\n let fence = false;\n for (const line of body.split(\"\\n\")) {\n if (/^```/.test(line)) fence = !fence;\n const h = fence ? null : /^(#{1,2})\\s+(.+?)\\s*#*\\s*$/.exec(line);\n if (h) {\n if (out.length) out[out.length - 1].end = at;\n out.push({ title: h[2], level: h[1].length as 1 | 2, start: at, end: body.length, excerpt: \"\" });\n } else if (out.length && !out[out.length - 1].excerpt && line.trim() && !/^(```|!\\[|---+$)/.test(line.trim())) {\n out[out.length - 1].excerpt = line\n .trim()\n .replace(/^(#{3,6}|>|[-*+]|\\d+\\.)\\s+/, \"\")\n .replace(/[*_`]|\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .slice(0, 120);\n }\n at += line.length + 1;\n }\n return out;\n}\n\n/** `body` with section `from` moved to place `to` (both count sections, 0-based). The text before the first heading stays where it is. */\nexport function moveSection(body: string, from: number, to: number): string {\n const secs = bodySections(body);\n if (from === to || !secs[from] || !secs[to]) return body;\n const parts = secs.map((s) => body.slice(s.start, s.end).replace(/\\s+$/, \"\"));\n const [moved] = parts.splice(from, 1);\n parts.splice(to, 0, moved);\n return body.slice(0, secs[0].start) + parts.join(\"\\n\\n\") + (/\\n$/.test(body) ? \"\\n\" : \"\");\n}\n\nexport interface SectionMove {\n title: string;\n /** 1-based place the section is in now. */\n place: number;\n total: number;\n}\n\nexport interface SectionsOrderProps {\n body: string;\n onChange: (body: string, moved: SectionMove) => void;\n /** Someone pressed a section's title: show it in the text. */\n onOpen?: (section: BodySection) => void;\n className?: string;\n}\n\n/**\n * The body as one card per section. Drag a card, or use its arrows, to\n * change the order. Text before the first heading is shown but stays first.\n */\nexport function SectionsOrder({ body, onChange, onOpen, className }: SectionsOrderProps) {\n const { t } = useCms();\n const secs = React.useMemo(() => bodySections(body), [body]);\n const intro = secs.length ? body.slice(0, secs[0].start).trim() : body.trim();\n const list = React.useRef<HTMLOListElement>(null);\n const [drag, setDrag] = React.useState<number | null>(null);\n const [slot, setSlot] = React.useState<number | null>(null);\n const focusNext = React.useRef<{ i: number; dir: \"up\" | \"down\" } | null>(null);\n\n // After a move by keyboard, stay on the same card's arrow (or its other arrow at either end).\n React.useEffect(() => {\n const f = focusNext.current;\n if (!f) return;\n focusNext.current = null;\n const row = list.current?.querySelector(`[data-section=\"${f.i}\"]`);\n (row?.querySelector<HTMLButtonElement>(`[data-move=\"${f.dir}\"]:not(:disabled)`) ?? row?.querySelector<HTMLButtonElement>(\"[data-move]:not(:disabled)\"))?.focus();\n }, [body]);\n\n const move = (from: number, to: number, dir?: \"up\" | \"down\") => {\n if (to < 0 || to >= secs.length || from === to) return;\n if (dir) focusNext.current = { i: to, dir };\n onChange(moveSection(body, from, to), { title: secs[from].title, place: to + 1, total: secs.length });\n };\n const drop = () => {\n // `slot` is the gap the card goes into: 0 is before the first card.\n if (drag !== null && slot !== null) move(drag, slot > drag ? slot - 1 : slot);\n setDrag(null);\n setSlot(null);\n };\n\n return (\n <ol ref={list} aria-label={t(\"sections_order\")} className={cn(\"flex min-h-0 flex-1 flex-col gap-1.5 overflow-auto p-3\", className)} onDragOver={(e) => drag !== null && e.preventDefault()} onDrop={drop}>\n {intro ? (\n <li className=\"flex items-center gap-2 rounded-md border border-dashed px-3 py-2 text-sm text-muted-foreground\">\n <span className=\"w-3.5 shrink-0\" />\n <span className=\"shrink-0 text-xs\">{t(\"section_intro\")}</span>\n <span className=\"min-w-0 flex-1 truncate\">{intro.split(\"\\n\")[0].slice(0, 120)}</span>\n </li>\n ) : null}\n {secs.map((s, i) => (\n <li\n key={`${i}:${s.title}`}\n data-section={i}\n draggable\n onDragStart={(e) => {\n setDrag(i);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", s.title);\n }}\n onDragEnd={() => {\n setDrag(null);\n setSlot(null);\n }}\n onDragOver={(e) => {\n if (drag === null) return;\n const box = e.currentTarget.getBoundingClientRect();\n setSlot(e.clientY > box.top + box.height / 2 ? i + 1 : i);\n }}\n className={cn(\n \"relative flex items-center gap-2 rounded-md border bg-background px-3 py-1.5 text-sm\",\n drag === i && \"opacity-50\",\n // A line where the card would land (not next to the card itself: that is no move).\n drag !== null && slot === i && slot !== drag && slot !== drag + 1 && \"before:absolute before:inset-x-0 before:-top-1 before:h-0.5 before:rounded-full before:bg-primary\",\n drag !== null && slot === i + 1 && i === secs.length - 1 && slot !== drag + 1 && \"after:absolute after:inset-x-0 after:-bottom-1 after:h-0.5 after:rounded-full after:bg-primary\"\n )}\n >\n <GripVertical aria-hidden className=\"h-3.5 w-3.5 shrink-0 cursor-grab text-muted-foreground\" />\n <span aria-hidden className=\"w-5 shrink-0 font-mono text-xs text-muted-foreground\">\n {s.level === 1 ? \"#\" : \"##\"}\n </span>\n <span className=\"flex min-w-0 flex-1 items-baseline gap-2\">\n {onOpen ? (\n <button type=\"button\" className=\"min-w-0 shrink truncate rounded-sm text-left font-semibold outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\" onClick={() => onOpen(s)}>\n {s.title}\n </button>\n ) : (\n <span className=\"min-w-0 shrink truncate font-semibold\">{s.title}</span>\n )}\n <span className=\"hidden min-w-0 flex-1 truncate text-xs text-muted-foreground sm:inline\">{s.excerpt}</span>\n </span>\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-7 w-7 shrink-0\" data-move=\"up\" disabled={i === 0} aria-label={t(\"section_up\", { title: s.title })} onClick={() => move(i, i - 1, \"up\")}>\n <ArrowUp aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-7 w-7 shrink-0\" data-move=\"down\" disabled={i === secs.length - 1} aria-label={t(\"section_down\", { title: s.title })} onClick={() => move(i, i + 1, \"down\")}>\n <ArrowDown aria-hidden className=\"h-3.5 w-3.5\" />\n </Button>\n </li>\n ))}\n </ol>\n );\n}\n\n// ── lines of the text box ────────────────────────────────────────────────────\n\n/** Where 1-based `line` starts in `text`, and where `endLine` ends. */\nexport function lineRange(text: string, line: number, endLine = line): [number, number] {\n let start = 0;\n for (let i = 1; i < line; i++) {\n const n = text.indexOf(\"\\n\", start);\n if (n < 0) return [text.length, text.length];\n start = n + 1;\n }\n let end = start;\n for (let i = line; i <= endLine; i++) {\n const n = text.indexOf(\"\\n\", end);\n if (n < 0) return [start, text.length];\n end = i === endLine ? n : n + 1;\n }\n return [start, end];\n}\n\n/** The 1-based line the character at `offset` is on. */\nexport function lineAt(text: string, offset: number): number {\n let n = 1;\n for (let i = text.indexOf(\"\\n\"); i >= 0 && i < offset; i = text.indexOf(\"\\n\", i + 1)) n++;\n return n;\n}\n\n/**\n * How far down (px, inside the box's scrolled content) each 1-based line\n * starts. Long lines wrap, so this lays the text out once in a hidden copy\n * with the box's font and width.\n */\nexport function lineTops(el: HTMLTextAreaElement, text: string, lines: number[]): number[] {\n const cs = getComputedStyle(el);\n const copy = document.createElement(\"div\");\n Object.assign(copy.style, {\n position: \"absolute\",\n visibility: \"hidden\",\n top: \"0\",\n left: \"-99999px\",\n boxSizing: \"border-box\",\n width: `${el.clientWidth}px`,\n font: cs.font,\n letterSpacing: cs.letterSpacing,\n lineHeight: cs.lineHeight,\n paddingTop: cs.paddingTop,\n paddingBottom: cs.paddingBottom,\n paddingLeft: cs.paddingLeft,\n paddingRight: cs.paddingRight,\n tabSize: cs.tabSize,\n whiteSpace: \"pre-wrap\",\n overflowWrap: \"break-word\",\n });\n const marks = new Map<number, HTMLSpanElement>();\n let at = 0;\n for (const l of [...new Set(lines)].sort((a, b) => a - b)) {\n const [start] = lineRange(text, l);\n copy.append(text.slice(at, start));\n const mark = document.createElement(\"span\");\n mark.textContent = \"\\u200b\";\n copy.append(mark);\n marks.set(l, mark);\n at = start;\n }\n copy.append(`${text.slice(at)}\\n`);\n document.body.append(copy);\n const tops = lines.map((l) => marks.get(l)?.offsetTop ?? 0);\n copy.remove();\n return tops;\n}\n\n// ── the preview beside the text ──────────────────────────────────────────────\n\nexport interface PreviewSync {\n /** Bring the block that holds `line` into view in the preview (after the cursor moved). */\n reveal: (line: number) => void;\n /** Select lines in the text box and bring them into view, leaving the preview where it is. */\n select: (line: number, endLine: number) => void;\n}\n\n/**\n * Keeps the text box and the preview on the same part of the document.\n * Every top-level block in the preview says which source lines it came from\n * (`data-line`); scrolling either side moves the other so the same block is\n * at the top, with the distance between two blocks stretched to fit.\n *\n * `on` turns following on scroll off (one pane at a time on a phone);\n * `select` works either way. `stamp` is anything that changes the layout\n * of the preview without changing the text (its width).\n */\nexport function usePreviewSync(box: React.RefObject<HTMLTextAreaElement | null>, pane: React.RefObject<HTMLElement | null>, text: string, on: boolean, stamp?: unknown): PreviewSync {\n const textRef = React.useRef(text);\n textRef.current = text;\n const map = React.useRef<{ a: number[]; b: number[] } | null>(null);\n const lock = React.useRef<{ who: \"box\" | \"pane\" | null; timer: number }>({ who: null, timer: 0 });\n const hold = React.useCallback((who: \"box\" | \"pane\") => {\n window.clearTimeout(lock.current.timer);\n lock.current = { who, timer: window.setTimeout(() => (lock.current.who = null), 160) };\n }, []);\n\n React.useEffect(() => {\n map.current = null;\n }, [text, stamp]);\n\n React.useEffect(() => {\n const el = box.current;\n const pv = pane.current;\n if (!on || !el || !pv) return;\n const build = () => {\n const blocks = [...pv.querySelectorAll<HTMLElement>(\"[data-line]\")];\n const zero = pv.getBoundingClientRect().top - pv.scrollTop;\n const tops = lineTops(el, textRef.current, blocks.map((m) => Number(m.dataset.line)));\n const a = [0];\n const b = [0];\n blocks.forEach((m, i) => {\n const y = m.getBoundingClientRect().top - zero;\n if (tops[i] > a[a.length - 1] && y > b[b.length - 1]) (a.push(tops[i]), b.push(y));\n });\n a.push(Math.max(a[a.length - 1] + 1, el.scrollHeight));\n b.push(Math.max(b[b.length - 1] + 1, pv.scrollHeight));\n return (map.current = { a, b });\n };\n const convert = (y: number, from: number[], to: number[], fromEnd: number, toEnd: number) => {\n if (y <= 0) return 0;\n if (y >= fromEnd - 1) return toEnd; // the two ends meet, whatever the heights\n let i = 1;\n while (i < from.length - 1 && from[i] <= y) i++;\n return to[i - 1] + ((y - from[i - 1]) / (from[i] - from[i - 1] || 1)) * (to[i] - to[i - 1]);\n };\n const onBox = () => {\n if (lock.current.who === \"pane\") return;\n const m = map.current ?? build();\n hold(\"box\");\n pv.scrollTop = convert(el.scrollTop, m.a, m.b, el.scrollHeight - el.clientHeight, pv.scrollHeight - pv.clientHeight);\n };\n const onPane = () => {\n if (lock.current.who === \"box\") return;\n const m = map.current ?? build();\n hold(\"pane\");\n el.scrollTop = convert(pv.scrollTop, m.b, m.a, pv.scrollHeight - pv.clientHeight, el.scrollHeight - el.clientHeight);\n };\n const stale = () => {\n map.current = null;\n };\n el.addEventListener(\"scroll\", onBox, { passive: true });\n pv.addEventListener(\"scroll\", onPane, { passive: true });\n pv.addEventListener(\"load\", stale, true); // a picture arrived: heights changed\n const ro = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(stale);\n ro?.observe(el);\n ro?.observe(pv);\n return () => {\n el.removeEventListener(\"scroll\", onBox);\n pv.removeEventListener(\"scroll\", onPane);\n pv.removeEventListener(\"load\", stale, true);\n ro?.disconnect();\n };\n }, [box, pane, on, hold]);\n\n return React.useMemo<PreviewSync>(\n () => ({\n reveal(line) {\n const pv = pane.current;\n if (!on || !pv) return;\n let block: HTMLElement | null = null;\n for (const m of pv.querySelectorAll<HTMLElement>(\"[data-line]\")) {\n if (Number(m.dataset.line) > line) break;\n block = m;\n }\n if (!block) return;\n const view = pv.getBoundingClientRect();\n const r = block.getBoundingClientRect();\n if (r.top >= view.top && r.top <= view.bottom - 48) return; // already in view\n hold(\"box\");\n pv.scrollTop += r.top - view.top - view.height / 4;\n },\n select(line, endLine) {\n const el = box.current;\n if (!el) return;\n const [start, end] = lineRange(textRef.current, line, endLine);\n el.focus({ preventScroll: true });\n el.setSelectionRange(start, end);\n const [top] = lineTops(el, textRef.current, [line]);\n if (top >= el.scrollTop && top <= el.scrollTop + el.clientHeight - 48) return;\n hold(\"pane\");\n el.scrollTop = Math.max(0, top - el.clientHeight / 3);\n },\n }),\n [box, pane, on, hold]\n );\n}\n"
|
|
45
|
+
},
|
|
41
46
|
{
|
|
42
47
|
"path": "registry/cms/cms-paste.ts",
|
|
43
48
|
"type": "registry:lib",
|