Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): write and save drafts in the content editor (#1258)
Cihan98a6cb8736c7
diff --git a/web/messages/en.json b/web/messages/en.jsonindex acbf59e52..271d6f2d4 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3102,7 +3102,73 @@"published": "Nothing published yet."},"loadError": "Couldn't load the Library.",- "retry": "Try again"+ "retry": "Try again",+ "newContent": "New content",+ "createFailed": "Couldn't start a draft. Try again."+ },+ "editor": {+ "back": "Back to the Library",+ "untitled": "Untitled",+ "newPage": "New page",+ "placeholder": "Start with the page's H1, then write…",+ "documentLabel": "Page content",+ "markReady": "Mark ready",+ "markedReady": "Marked ready. Publish it on your site when you're ready.",+ "markReadyFailed": "Couldn't mark it ready. Try again.",+ "markReadyUnsaved": "The page has changes that aren't saved, so it wasn't marked ready.",+ "loadError": "Couldn't open this draft.",+ "notFound": "This draft doesn't exist, or it belongs to another workspace.",+ "retryLoad": "Try again",+ "save": {+ "saved": "Saved",+ "unsaved": "Unsaved changes",+ "saving": "Saving…",+ "failed": "Couldn't save.",+ "retry": "Retry",+ "conflict": "Changed elsewhere.",+ "conflictHint": "Someone else changed this page since you opened it, so your latest changes weren't saved over theirs. Reload to see their version.",+ "reload": "Reload",+ "tooLarge": "Too long to save.",+ "tooLargeHint": "The page is over the size limit. Shorten it (a big table, for example) and it saves again."+ },+ "toolbar": {+ "label": "Formatting",+ "h1": "Heading 1",+ "h2": "Heading 2",+ "h3": "Heading 3",+ "bold": "Bold",+ "italic": "Italic",+ "link": "Link",+ "bulletList": "Bulleted list",+ "orderedList": "Numbered list",+ "quote": "Quote",+ "table": "Insert a table",+ "image": "Insert an image",+ "addRow": "Add a row below",+ "addColumn": "Add a column to the right",+ "deleteTable": "Delete the table",+ "openLink": "Open the link in a new tab (or ⌘/Ctrl + click it in the page)",+ "counter": "{count} / {target} characters"+ },+ "link": {+ "title": "Add a link",+ "editTitle": "Edit the link",+ "label": "Address",+ "placeholder": "https://… or /a-page-on-your-site",+ "invalid": "Enter a web address (https://…), a path on your site (/…) or an e-mail (mailto:…).",+ "remove": "Remove the link",+ "cancel": "Cancel",+ "apply": "Apply"+ },+ "image": {+ "title": "Insert an image",+ "srcLabel": "Image address",+ "altLabel": "Alt text",+ "altPlaceholder": "What the image shows",+ "invalid": "Enter the image's web address (https://…).",+ "cancel": "Cancel",+ "insert": "Insert"+ }},"status": {"draft": "Draft",diff --git a/web/package.json b/web/package.jsonindex 94cbc07f2..afb349bcb 100644--- a/web/package.json+++ b/web/package.json@@ -30,6 +30,13 @@"@stripe/stripe-js": "^9.1.0","@supabase/ssr": "^0.9.0","@supabase/supabase-js": "^2.99.0",+ "@tiptap/core": "3.31.4",+ "@tiptap/extension-image": "3.31.4",+ "@tiptap/extension-table": "3.31.4",+ "@tiptap/extensions": "3.31.4",+ "@tiptap/pm": "3.31.4",+ "@tiptap/react": "3.31.4",+ "@tiptap/starter-kit": "3.31.4","@vercel/analytics": "^2.0.1","ai": "^6.0.116","class-variance-authority": "^0.7.1",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxnew file mode 100644index 000000000..193d673c3--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -0,0 +1,227 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { EditorContent, useEditor } from '@tiptap/react';+import StarterKit from '@tiptap/starter-kit';+import { TableKit } from '@tiptap/extension-table';+import Image from '@tiptap/extension-image';+import { CharacterCount, Placeholder } from '@tiptap/extensions';+import { ArrowLeft, Check, Loader2 } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';+import { markContentDraftReady } from '@/lib/actions/content-drafts';+import { CONTENT_LIBRARY_PATH, isPageType, type ContentDraft } from '@/lib/content/drafts';+import { draftTitleFromDoc, lengthTarget, safeLinkHref } from '@/lib/content/editor';+import { cn } from '@/lib/utils';+import { EditorToolbar } from './_toolbar';+import { useDraftAutosave, type SaveState } from './_use-autosave';++/**+ * The page as it reads: the app's prose type, links blue and underlined so+ * they read as links, tables with cell borders, a placeholder while empty,+ * and the selected table cells and images marked.+ */+const DOCUMENT_CLASS = cn(+ 'prose prose-neutral max-w-none dark:prose-invert min-h-[50vh] focus:outline-none',+ 'prose-a:font-normal prose-a:text-blue-600 prose-a:underline prose-a:underline-offset-2 dark:prose-a:text-blue-400',+ 'prose-h1:text-3xl prose-h1:tracking-tight prose-h2:tracking-tight',+ '[&_table]:my-4 [&_table]:w-full [&_table]:table-fixed [&_td]:border [&_td]:px-2 [&_td]:py-1.5 [&_th]:border [&_th]:bg-muted/50 [&_th]:px-2 [&_th]:py-1.5 [&_th]:text-left',+ // Cells and list items hold paragraphs; their margins would pad every row.+ '[&_td>p]:my-0 [&_th>p]:my-0 [&_li>p]:my-0 prose-li:my-1',+ '[&_.selectedCell]:bg-primary/10 [&_img]:rounded-md [&_.ProseMirror-selectednode]:ring-2 [&_.ProseMirror-selectednode]:ring-ring/50',+ '[&_.is-editor-empty:first-child]:before:pointer-events-none [&_.is-editor-empty:first-child]:before:float-left [&_.is-editor-empty:first-child]:before:h-0 [&_.is-editor-empty:first-child]:before:text-muted-foreground [&_.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]',+);++/**+ * The content editor (Content Editor, CE-004, spec §6): a header with the+ * draft's title, page type and method, whether it's saved, and Mark ready;+ * the toolbar; and the page itself, rich text that saves as you write. The+ * draft's title is its first heading, as the Library lists it.+ */+export function DraftEditor({ draft }: { draft: ContentDraft }) {+ const t = useTranslations('contentEditor.editor');+ const tTypes = useTranslations('contentEditor.pageTypes');+ const autosave = useDraftAutosave(draft.id, draft);+ const [title, setTitle] = useState(draft.title);+ const [status, setStatus] = useState(draft.status);+ const [marking, setMarking] = useState(false);++ const editor = useEditor({+ extensions: [+ StarterKit.configure({+ heading: { levels: [1, 2, 3] },+ // Pages, not code: the toolbar has no code or rules.+ code: false,+ codeBlock: false,+ horizontalRule: false,+ link: {+ openOnClick: false,+ defaultProtocol: 'https',+ isAllowedUri: (url) => safeLinkHref(url) !== null,+ },+ }),+ TableKit.configure({ table: { resizable: false } }),+ Image,+ CharacterCount,+ Placeholder.configure({ placeholder: t('placeholder') }),+ ],+ content: draft.bodyHtml,+ // Rendered on the client only, so the server's HTML can't disagree with it.+ immediatelyRender: false,+ editorProps: {+ attributes: { class: DOCUMENT_CLASS, 'aria-label': t('documentLabel') },+ // A click on a link puts the cursor in it, to edit it; ⌘/Ctrl + click+ // opens it, as in other editors. A path on the brand's own site has no+ // address here to open.+ handleClick: (_view, _pos, event) => {+ if (!event.metaKey && !event.ctrlKey) return false;+ const href = (event.target as HTMLElement).closest('a')?.getAttribute('href');+ if (!href || !/^https?:/.test(safeLinkHref(href) ?? '')) return false;+ window.open(href, '_blank', 'noopener,noreferrer');+ return true;+ },+ },+ onUpdate: ({ editor: e }) => {+ const next = draftTitleFromDoc(e.getJSON());+ setTitle(next);+ autosave.schedule({ title: next, bodyHtml: e.getHTML() });+ },+ });++ const canMarkReady = status === 'draft' || status === 'in_review';+ const markReady = async () => {+ setMarking(true);+ try {+ // What's waiting goes out first, so the ready draft is the one on screen;+ // a page that can't be saved isn't marked ready.+ try {+ await autosave.settle();+ } catch {+ toast.error(t('markReadyUnsaved'));+ return;+ }+ const next = await markContentDraftReady(draft.id);+ setStatus(next);+ toast.success(t('markedReady'));+ } catch (err) {+ console.error('Failed to mark the draft ready:', err);+ toast.error(t('markReadyFailed'));+ } finally {+ setMarking(false);+ }+ };++ const typeLabel = isPageType(draft.pageType) ? tTypes(draft.pageType) : null;+ const pageTag = [typeLabel, draft.method === 'create' ? t('newPage') : null]+ .filter(Boolean)+ .join(' · ');++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {/* One line at any width: the title shortens, the tags give way on a+ narrow window, and the save state and Mark ready never move. */}+ <header className="flex items-center gap-2.5 border-b px-4 py-2.5">+ <Link+ href={CONTENT_LIBRARY_PATH}+ aria-label={t('back')}+ title={t('back')}+ className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}+ >+ <ArrowLeft className="h-4 w-4" />+ </Link>+ <h1 className="min-w-0 truncate text-sm font-medium" title={title.trim() || undefined}>+ {title.trim() || t('untitled')}+ </h1>+ <div className="hidden shrink-0 items-center gap-2 lg:flex">+ {pageTag && (+ <Badge variant="outline" className="font-normal">+ {pageTag}+ </Badge>+ )}+ <DraftMethodBadge method={draft.method} />+ </div>+ <span className="shrink-0">+ <DraftStatusBadge status={status} />+ </span>+ <div className="ml-auto flex shrink-0 items-center gap-3">+ <SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} />+ <Button+ size="sm"+ // A page that can't be saved can't be marked ready; the save state says why.+ disabled={+ !canMarkReady ||+ marking ||+ autosave.state === 'conflict' ||+ autosave.state === 'too_large'+ }+ onClick={markReady}+ >+ {marking ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ !canMarkReady && <Check className="h-3.5 w-3.5" />+ )}+ {t('markReady')}+ </Button>+ </div>+ </header>++ {editor && <EditorToolbar editor={editor} target={lengthTarget(draft.pageType)} />}++ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="mx-auto max-w-[720px] px-7 pt-7 pb-20">+ <EditorContent editor={editor} />+ </div>+ </div>+ </div>+ );+}++function SaveIndicator({ state, onRetry }: { state: SaveState; onRetry: () => void }) {+ const t = useTranslations('contentEditor.editor.save');+ if (state === 'conflict') {+ return (+ <span+ className="flex items-center gap-1.5 text-xs text-destructive"+ role="status"+ title={t('conflictHint')}+ >+ {t('conflict')}+ <button+ type="button"+ className="font-medium underline"+ onClick={() => window.location.reload()}+ >+ {t('reload')}+ </button>+ </span>+ );+ }+ if (state === 'too_large') {+ return (+ <span className="text-xs text-destructive" role="status" title={t('tooLargeHint')}>+ {t('tooLarge')}+ </span>+ );+ }+ if (state === 'failed') {+ return (+ <span className="flex items-center gap-1.5 text-xs text-destructive" role="status">+ {t('failed')}+ <button type="button" className="font-medium underline" onClick={onRetry}>+ {t('retry')}+ </button>+ </span>+ );+ }+ return (+ <span className="text-xs text-muted-foreground" role="status">+ {t(state)}+ </span>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsxnew file mode 100644index 000000000..a027a1b68--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx@@ -0,0 +1,380 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { useEditorState, type Editor } from '@tiptap/react';+import {+ Bold,+ ExternalLink,+ Columns3,+ Heading1,+ Heading2,+ Heading3,+ ImagePlus,+ Italic,+ Link2,+ List,+ ListOrdered,+ Quote,+ Rows3,+ Table2,+ Trash2,+} from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { formatNumber } from '@/lib/format';+import { safeImageSrc, safeLinkHref } from '@/lib/content/editor';+import { cn } from '@/lib/utils';++/**+ * The editor's toolbar (CE-004, spec §6): H1 H2 H3 · B I link · lists,+ * quote · table, image, and the length counter against the page type's+ * target. Inside a table it adds a row, a column, or removes the table.+ */+export function EditorToolbar({ editor, target }: { editor: Editor; target: number }) {+ const t = useTranslations('contentEditor.editor.toolbar');+ const [dialog, setDialog] = useState<'link' | 'image' | null>(null);++ // Re-read only what the toolbar shows, not on every keystroke's render.+ const state = useEditorState({+ editor,+ selector: ({ editor: e }) => ({+ h1: e.isActive('heading', { level: 1 }),+ h2: e.isActive('heading', { level: 2 }),+ h3: e.isActive('heading', { level: 3 }),+ bold: e.isActive('bold'),+ italic: e.isActive('italic'),+ link: e.isActive('link'),+ href: e.isActive('link')+ ? ((e.getAttributes('link').href as string | undefined) ?? null)+ : null,+ bulletList: e.isActive('bulletList'),+ orderedList: e.isActive('orderedList'),+ blockquote: e.isActive('blockquote'),+ inTable: e.isActive('table'),+ characters: e.storage.characterCount.characters() as number,+ }),+ });++ const chain = () => editor.chain().focus();+ const tools = [+ [+ {+ key: 'h1',+ icon: Heading1,+ on: state.h1,+ run: () => chain().toggleHeading({ level: 1 }).run(),+ },+ {+ key: 'h2',+ icon: Heading2,+ on: state.h2,+ run: () => chain().toggleHeading({ level: 2 }).run(),+ },+ {+ key: 'h3',+ icon: Heading3,+ on: state.h3,+ run: () => chain().toggleHeading({ level: 3 }).run(),+ },+ ],+ [+ { key: 'bold', icon: Bold, on: state.bold, run: () => chain().toggleBold().run() },+ { key: 'italic', icon: Italic, on: state.italic, run: () => chain().toggleItalic().run() },+ { key: 'link', icon: Link2, on: state.link, run: () => setDialog('link') },+ ],+ [+ {+ key: 'bulletList',+ icon: List,+ on: state.bulletList,+ run: () => chain().toggleBulletList().run(),+ },+ {+ key: 'orderedList',+ icon: ListOrdered,+ on: state.orderedList,+ run: () => chain().toggleOrderedList().run(),+ },+ {+ key: 'quote',+ icon: Quote,+ on: state.blockquote,+ run: () => chain().toggleBlockquote().run(),+ },+ ],+ [+ {+ key: 'table',+ icon: Table2,+ on: state.inTable,+ run: () => chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),+ },+ { key: 'image', icon: ImagePlus, on: false, run: () => setDialog('image') },+ ],+ ];+ const tableTools = [+ { key: 'addRow', icon: Rows3, run: () => chain().addRowAfter().run() },+ { key: 'addColumn', icon: Columns3, run: () => chain().addColumnAfter().run() },+ { key: 'deleteTable', icon: Trash2, run: () => chain().deleteTable().run() },+ ];++ return (+ <div+ role="toolbar"+ aria-label={t('label')}+ className="flex flex-wrap items-center gap-0.5 border-b px-4 py-1.5"+ >+ {tools.map((group, i) => (+ <div key={i} className="flex items-center gap-0.5">+ {i > 0 && <span aria-hidden="true" className="mx-1.5 h-5 w-px bg-border" />}+ {group.map((tool) => (+ <ToolButton key={tool.key} label={t(tool.key)} pressed={tool.on} onClick={tool.run}>+ <tool.icon className="h-4 w-4" />+ </ToolButton>+ ))}+ </div>+ ))}+ {state.href && <LinkTarget href={state.href} />}+ {state.inTable && (+ <div className="flex items-center gap-0.5">+ <span aria-hidden="true" className="mx-1.5 h-5 w-px bg-border" />+ {tableTools.map((tool) => (+ <ToolButton key={tool.key} label={t(tool.key)} onClick={tool.run}>+ <tool.icon className="h-4 w-4" />+ </ToolButton>+ ))}+ </div>+ )}+ <span+ className={cn(+ 'ml-auto text-xs font-medium tabular-nums text-muted-foreground',+ state.characters > target && 'text-amber-700 dark:text-amber-400',+ )}+ >+ {t('counter', {+ count: formatNumber(state.characters),+ target: formatNumber(target),+ })}+ </span>++ {/* Mounted while open, so each opening starts from the selection. */}+ {dialog === 'link' && <LinkDialog editor={editor} onClose={() => setDialog(null)} />}+ {dialog === 'image' && <ImageDialog editor={editor} onClose={() => setDialog(null)} />}+ </div>+ );+}++/**+ * The link the cursor is in: its address, and a way to open it in a new tab+ * (a path on the brand's own site has no address here to open).+ */+function LinkTarget({ href }: { href: string }) {+ const t = useTranslations('contentEditor.editor.toolbar');+ const safe = safeLinkHref(href);+ const label = href.replace(/^https?:\/\//, '').replace(/\/$/, '');+ const className =+ 'ml-1 flex max-w-[240px] items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-blue-600 dark:text-blue-400';+ if (!safe || !/^https?:/.test(safe)) {+ return (+ <span className={cn(className, 'text-muted-foreground dark:text-muted-foreground')}>+ <span className="truncate">{label}</span>+ </span>+ );+ }+ return (+ <a+ href={safe}+ target="_blank"+ rel="noopener noreferrer"+ title={t('openLink')}+ className={cn(className, 'hover:bg-muted hover:underline')}+ >+ <span className="truncate">{label}</span>+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />+ </a>+ );+}++function ToolButton({+ label,+ pressed,+ onClick,+ children,+}: {+ label: string;+ pressed?: boolean;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ title={label}+ aria-label={label}+ aria-pressed={pressed}+ // Keep the editor's selection: a click on the toolbar mustn't move focus first.+ onMouseDown={(e) => e.preventDefault()}+ onClick={onClick}+ className={cn(+ 'flex h-7 min-w-7 items-center justify-center rounded-md px-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ pressed && 'bg-muted text-foreground',+ )}+ >+ {children}+ </button>+ );+}++/** Set, change or remove the link on the selection. */+function LinkDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) {+ const t = useTranslations('contentEditor.editor.link');+ const [current] = useState(() => editor.getAttributes('link').href as string | undefined);+ const [value, setValue] = useState(current ?? '');+ const [invalid, setInvalid] = useState(false);++ const apply = () => {+ const href = safeLinkHref(value);+ if (!href) {+ setInvalid(true);+ return;+ }+ if (editor.state.selection.empty && !current) {+ // Nothing selected: the address goes in as its own link text.+ editor+ .chain()+ .focus()+ .insertContent({ type: 'text', text: href, marks: [{ type: 'link', attrs: { href } }] })+ .run();+ } else {+ editor.chain().focus().extendMarkRange('link').setLink({ href }).run();+ }+ onClose();+ };++ return (+ <Dialog open onOpenChange={(next) => !next && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{current ? t('editTitle') : t('title')}</DialogTitle>+ </DialogHeader>+ <form+ className="space-y-2"+ onSubmit={(e) => {+ e.preventDefault();+ apply();+ }}+ >+ <Label htmlFor="content-link-href">{t('label')}</Label>+ <Input+ id="content-link-href"+ autoFocus+ value={value}+ placeholder={t('placeholder')}+ aria-invalid={invalid}+ onChange={(e) => {+ setValue(e.target.value);+ setInvalid(false);+ }}+ />+ {invalid && <p className="text-xs text-destructive">{t('invalid')}</p>}+ </form>+ <DialogFooter>+ {current && (+ <Button+ variant="ghost"+ className="mr-auto text-muted-foreground"+ onClick={() => {+ editor.chain().focus().extendMarkRange('link').unsetLink().run();+ onClose();+ }}+ >+ {t('remove')}+ </Button>+ )}+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>+ <Button onClick={apply}>{t('apply')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/** Insert an image by its address; uploads come with attachments (CE-006). */+function ImageDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) {+ const t = useTranslations('contentEditor.editor.image');+ const [src, setSrc] = useState('');+ const [alt, setAlt] = useState('');+ const [invalid, setInvalid] = useState(false);++ const insert = () => {+ const safe = safeImageSrc(src);+ if (!safe) {+ setInvalid(true);+ return;+ }+ editor+ .chain()+ .focus()+ .setImage({ src: safe, alt: alt.trim() || undefined })+ .run();+ onClose();+ };++ return (+ <Dialog open onOpenChange={(next) => !next && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ </DialogHeader>+ <form+ className="space-y-3"+ onSubmit={(e) => {+ e.preventDefault();+ insert();+ }}+ >+ <div className="space-y-2">+ <Label htmlFor="content-image-src">{t('srcLabel')}</Label>+ <Input+ id="content-image-src"+ autoFocus+ value={src}+ placeholder="https://"+ aria-invalid={invalid}+ onChange={(e) => {+ setSrc(e.target.value);+ setInvalid(false);+ }}+ />+ {invalid && <p className="text-xs text-destructive">{t('invalid')}</p>}+ </div>+ <div className="space-y-2">+ <Label htmlFor="content-image-alt">{t('altLabel')}</Label>+ <Input+ id="content-image-alt"+ value={alt}+ placeholder={t('altPlaceholder')}+ onChange={(e) => setAlt(e.target.value)}+ />+ </div>+ {/* Enter in either field inserts. */}+ <button type="submit" hidden />+ </form>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>+ <Button onClick={insert}>{t('insert')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsxnew file mode 100644index 000000000..9ce10e1d0--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx@@ -0,0 +1,198 @@+import { act, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useDraftAutosave } from './_use-autosave';++const saveContentDraft = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),+}));+// A fingerprint that settles in a microtask, so fake timers drive the saves.+vi.mock('@/lib/content/editor', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/content/editor')>()),+ bodyHash: async (html: string) => `hash:${html}`,+}));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const LOADED = { updatedAt: 't0', bodyHtml: '<p>loaded</p>' };+const BIG = `<p>${'x'.repeat(500_000)}</p>`;+const BODIES = ['<p>a</p>', '<p>ab</p>', '<p>1</p>', '<p>12</p>', '<p>x</p>', '<p>last</p>'];++/** The hook behind buttons, as the editor drives it: one per text, Retry, and settle. */+function Harness() {+ const autosave = useDraftAutosave('d1', LOADED);+ const [settled, setSettled] = useState('');+ return (+ <div>+ <output>{autosave.state}</output>+ <span data-settled>{settled}</span>+ {BODIES.map((body) => (+ <button key={body} data-body={body} onClick={() => autosave.schedule(content(body))} />+ ))}+ <button data-big onClick={() => autosave.schedule(content(BIG))} />+ <button data-retry onClick={() => void autosave.retry()} />+ <button+ data-settle+ onClick={() =>+ void autosave.settle().then(+ () => setSettled('saved'),+ () => setSettled('unsaved'),+ )+ }+ />+ </div>+ );+}++let container: HTMLDivElement;+let root: Root;+function content(bodyHtml: string) {+ return { title: 'T', bodyHtml };+}+const loadedBase = { updatedAt: 't0', bodyHash: 'hash:<p>loaded</p>' };+const saved = (updatedAt = 'now', bodyHash = 'h1') => ({ ok: true, updatedAt, bodyHash });+const state = () => container.querySelector('output')!.textContent;+const settled = () => container.querySelector('[data-settled]')!.textContent;+const edit = (body: string) =>+ act(() => container.querySelector<HTMLButtonElement>(`[data-body="${body}"]`)!.click());+const retry = () =>+ act(async () => container.querySelector<HTMLButtonElement>('[data-retry]')!.click());+const settle = () =>+ act(async () => container.querySelector<HTMLButtonElement>('[data-settle]')!.click());++beforeEach(async () => {+ vi.useFakeTimers();+ saveContentDraft.mockReset().mockResolvedValue(saved());+ container = document.createElement('div');+ root = createRoot(container);+ await act(async () => root.render(<Harness />));+});++afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});++describe('the editor’s autosave', () => {+ it('saves once typing pauses, with the latest text, over the version it loaded', async () => {+ edit('<p>a</p>');+ edit('<p>ab</p>');+ expect(state()).toBe('unsaved');+ expect(saveContentDraft).not.toHaveBeenCalled();++ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft).toHaveBeenCalledTimes(1);+ expect(saveContentDraft).toHaveBeenCalledWith('d1', {+ ...content('<p>ab</p>'),+ base: loadedBase,+ });+ expect(state()).toBe('saved');+ });++ it('sends a change made during a save after it, over the version that save made', async () => {+ let finish!: () => void;+ saveContentDraft.mockImplementationOnce(+ () => new Promise((resolve) => (finish = () => resolve(saved('t1', 'h1')))),+ );+ edit('<p>1</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(state()).toBe('saving');++ edit('<p>12</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft).toHaveBeenCalledTimes(1);++ await act(async () => finish());+ expect(state()).toBe('unsaved');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft).toHaveBeenCalledTimes(2);+ expect(saveContentDraft).toHaveBeenLastCalledWith('d1', {+ ...content('<p>12</p>'),+ base: { updatedAt: 't1', bodyHash: 'h1' },+ });+ expect(state()).toBe('saved');+ });++ it('keeps the text after a failed save, and Retry sends it', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ saveContentDraft.mockRejectedValueOnce(new Error('offline'));+ edit('<p>x</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(state()).toBe('failed');++ await retry();+ expect(saveContentDraft).toHaveBeenCalledTimes(2);+ expect(saveContentDraft).toHaveBeenLastCalledWith('d1', {+ ...content('<p>x</p>'),+ base: loadedBase,+ });+ expect(state()).toBe('saved');+ error.mockRestore();+ });++ it('stops saving when the page was changed elsewhere, rather than overwriting it', async () => {+ saveContentDraft.mockResolvedValueOnce({ ok: false, reason: 'conflict' });+ edit('<p>x</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(state()).toBe('conflict');++ edit('<p>last</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ await retry();+ expect(saveContentDraft).toHaveBeenCalledTimes(1);+ expect(state()).toBe('conflict');+ });++ it('doesn’t send a page over the size limit, and saves again once it is shorter', async () => {+ act(() => container.querySelector<HTMLButtonElement>('[data-big]')!.click());+ expect(state()).toBe('too_large');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft).not.toHaveBeenCalled();++ edit('<p>x</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft).toHaveBeenCalledTimes(1);+ expect(state()).toBe('saved');+ });++ it('settles: saves what is waiting first, and says when the page can’t be saved', async () => {+ edit('<p>x</p>');+ await settle();+ expect(saveContentDraft).toHaveBeenCalledTimes(1);+ expect(settled()).toBe('saved');++ saveContentDraft.mockResolvedValueOnce({ ok: false, reason: 'conflict' });+ edit('<p>last</p>');+ await settle();+ expect(settled()).toBe('unsaved');+ });++ it('asks before leaving the page while something is unsaved', async () => {+ const leave = () => {+ const event = new Event('beforeunload', { cancelable: true });+ window.dispatchEvent(event);+ return event.defaultPrevented;+ };+ expect(leave()).toBe(false);+ edit('<p>x</p>');+ expect(leave()).toBe(true);+ await act(async () => vi.advanceTimersByTime(1500));+ expect(leave()).toBe(false);+ });++ it('saves what is waiting when the editor closes', async () => {+ edit('<p>last</p>');+ act(() => root.unmount());+ await act(async () => {});+ expect(saveContentDraft).toHaveBeenCalledWith('d1', {+ ...content('<p>last</p>'),+ base: loadedBase,+ });+ root = createRoot(container);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.tsnew file mode 100644index 000000000..44d07b164--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts@@ -0,0 +1,165 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';+import { saveContentDraft } from '@/lib/actions/content-drafts';+import { AUTOSAVE_DELAY_MS, MAX_BODY_HTML_LENGTH, bodyHash } from '@/lib/content/editor';++/**+ * Where the page stands: conflict when someone else changed it meanwhile+ * (nothing more saves until it's reloaded), too_large when it's over the+ * limit (nothing saves until it's shorter).+ */+export type SaveState = 'saved' | 'unsaved' | 'saving' | 'failed' | 'conflict' | 'too_large';++/** How long settle() waits for saves before giving up. */+const SETTLE_TIMEOUT_MS = 15_000;++interface DraftContent {+ title: string;+ bodyHtml: string;+}++/**+ * The editor's autosave (CE-004). Each change waits for typing to pause,+ * then saves; a change made while a save runs goes out right after it, so+ * saves never overlap and the last one is always the newest text. A failed+ * save keeps the text pending: Retry, or the next change, sends it again.+ * While anything is unsaved, leaving the page asks first.+ *+ * Each save goes only over the version this editor loaded or last saved, so+ * a page someone else changed meanwhile is never overwritten: the editor says+ * so and stops saving until it's reloaded. A page over the size limit isn't+ * sent at all.+ *+ * Before a step that reads the saved page (Mark ready), settle() saves what+ * is waiting and waits for a save under way, and throws when the page isn't+ * saved.+ */+export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bodyHtml: string }) {+ const [state, setState] = useState<SaveState>('saved');+ const pending = useRef<DraftContent | null>(null);+ const saving = useRef(false);+ const failed = useRef(false);+ // Changed elsewhere: nothing more is saved over it.+ const stopped = useRef(false);+ const timer = useRef<ReturnType<typeof setTimeout>>(undefined);+ // The version saves go over; its hash is worked out at the first save.+ const base = useRef<{ updatedAt: string; bodyHash: string | null }>({+ updatedAt: loaded.updatedAt,+ bodyHash: null,+ });+ const loadedBody = useRef(loaded.bodyHtml);++ const baseVersion = useCallback(async () => {+ base.current.bodyHash ??= await bodyHash(loadedBody.current);+ return { updatedAt: base.current.updatedAt, bodyHash: base.current.bodyHash };+ }, []);++ const flush = useCallback(async () => {+ clearTimeout(timer.current);+ if (stopped.current || saving.current || !pending.current) return;+ const content = pending.current;+ if (content.bodyHtml.length > MAX_BODY_HTML_LENGTH) {+ failed.current = true;+ setState('too_large');+ return;+ }+ pending.current = null;+ saving.current = true;+ setState('saving');+ try {+ const result = await saveContentDraft(draftId, { ...content, base: await baseVersion() });+ saving.current = false;+ if (!result.ok) {+ // Unless something newer is waiting, this text is still to save.+ pending.current ??= content;+ failed.current = true;+ if (result.reason === 'conflict') stopped.current = true;+ setState(+ result.reason === 'conflict'+ ? 'conflict'+ : result.reason === 'too_large'+ ? 'too_large'+ : 'failed',+ );+ return;+ }+ base.current = { updatedAt: result.updatedAt, bodyHash: result.bodyHash };+ failed.current = false;+ if (pending.current) {+ // Typed while it saved: that waits for its own pause.+ setState('unsaved');+ timer.current = setTimeout(() => void flush(), AUTOSAVE_DELAY_MS);+ } else {+ setState('saved');+ }+ } catch (err) {+ console.error('Failed to save the draft:', err);+ saving.current = false;+ failed.current = true;+ pending.current ??= content;+ setState('failed');+ }+ }, [draftId, baseVersion]);++ const schedule = useCallback(+ (content: DraftContent) => {+ pending.current = content;+ if (stopped.current) return;+ clearTimeout(timer.current);+ if (content.bodyHtml.length > MAX_BODY_HTML_LENGTH) {+ // Nothing to send until it's shorter.+ failed.current = true;+ if (!saving.current) setState('too_large');+ return;+ }+ if (!saving.current) setState('unsaved');+ timer.current = setTimeout(() => void flush(), AUTOSAVE_DELAY_MS);+ },+ [flush],+ );++ /** Saves what is waiting and waits for a save under way; throws when the page isn't saved. */+ const settle = useCallback(async () => {+ const deadline = Date.now() + SETTLE_TIMEOUT_MS;+ while (saving.current || pending.current) {+ if (stopped.current || Date.now() > deadline) throw new Error('unsaved');+ if (saving.current) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ continue;+ }+ await flush();+ if (failed.current) throw new Error('unsaved');+ }+ }, [flush]);++ const unsaved = state !== 'saved';+ useEffect(() => {+ if (!unsaved) return;+ const warn = (e: BeforeUnloadEvent) => e.preventDefault();+ window.addEventListener('beforeunload', warn);+ return () => window.removeEventListener('beforeunload', warn);+ }, [unsaved]);++ // Leaving the editor inside the app saves what is waiting.+ useEffect(+ () => () => {+ clearTimeout(timer.current);+ const content = pending.current;+ if (+ !content ||+ saving.current ||+ stopped.current ||+ content.bodyHtml.length > MAX_BODY_HTML_LENGTH+ ) {+ return;+ }+ void baseVersion()+ .then((version) => saveContentDraft(draftId, { ...content, base: version }))+ .catch((err) => console.error('Failed to save the draft on leaving:', err));+ },+ [draftId, baseVersion],+ );++ return { state, schedule, retry: flush, settle };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxnew file mode 100644index 000000000..c25e0371b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -0,0 +1,173 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { ContentDraft } from '@/lib/content/drafts';+import ContentEditorPage from './page';++const getContentDraft = vi.fn();+const markContentDraftReady = vi.fn();+const saveContentDraft = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ getContentDraft: (...args: unknown[]) => getContentDraft(...args),+ markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),+ saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),+}));+vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));+const brandState = vi.hoisted(() => ({+ activeBrandId: 'b1' as string | null,+ brands: [{ id: 'b1' }, { id: 'b2' }],+ setActiveBrand: vi.fn(),+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({+ id: 'd1',+ brandId: 'b1',+ title: 'Pipeline forecasting',+ pageType: 'feature_page',+ method: 'optimize',+ status: 'in_review',+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',+ author: 'agent',+ updatedAt: '2026-10-20T10:00:00Z',+ ...over,+});++let container: HTMLDivElement;+let root: Root;++async function renderPage() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <ContentEditorPage />+ </NextIntlClientProvider>,+ );+ });+ // The editor mounts on the client after the first render.+ await act(async () => {});+}++const button = (name: string) =>+ [...container.querySelectorAll('button')].find(+ (b) => b.getAttribute('aria-label') === name || b.textContent === name,+ );++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ getContentDraft.mockReset();+ markContentDraftReady.mockReset();+ saveContentDraft.mockReset();+ brandState.activeBrandId = 'b1';+ brandState.setActiveBrand.mockReset();+ toast.success.mockReset();+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('the content editor', () => {+ it('opens the draft with its title, type, method, status and length', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();++ expect(getContentDraft).toHaveBeenCalledWith('d1');+ const header = container.querySelector('header')!;+ expect(header.querySelector('h1')!.textContent).toBe('Pipeline forecasting');+ expect(header.textContent).toContain('Feature page');+ expect(header.textContent).toContain('Optimize');+ expect(header.textContent).toContain('In review');+ expect(header.textContent).toContain('Saved');+ expect(container.querySelector('a[href="/dashboard/content/library"]')).not.toBeNull();++ // The page's text, against a feature page's 3,000-character target.+ expect(container.querySelector('[role="toolbar"]')!.textContent).toContain(+ '35 / 3,000 characters',+ );+ for (const name of ['Heading 1', 'Bold', 'Link', 'Numbered list', 'Insert a table']) {+ expect(button(name)).toBeDefined();+ }+ expect(container.querySelector('.ProseMirror h1')!.textContent).toBe('Pipeline forecasting');+ });++ it('tags a new page as one', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ method: 'create',+ pageType: 'product_page',+ status: 'draft',+ title: '',+ bodyHtml: '',+ }),+ );+ await renderPage();+ const header = container.querySelector('header')!;+ expect(header.textContent).toContain('Product page · New page');+ expect(header.querySelector('h1')!.textContent).toBe('Untitled');+ expect(container.querySelector('[role="toolbar"]')!.textContent).toContain(+ '0 / 1,200 characters',+ );+ });++ it('marks the draft ready once', async () => {+ getContentDraft.mockResolvedValue(draft());+ markContentDraftReady.mockResolvedValue('ready');+ await renderPage();++ await act(async () => button('Mark ready')!.click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(toast.success).toHaveBeenCalled();+ expect(container.querySelector('header')!.textContent).toContain('Ready');+ expect(button('Mark ready')!.disabled).toBe(true);+ });++ it('shows the link the cursor is in, to open in a new tab', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<p><a href="https://gartner.com/x">Gartner</a> says so.</p>' }),+ );+ await renderPage();+ const target = container.querySelector<HTMLAnchorElement>('[role="toolbar"] a')!;+ expect(target.getAttribute('href')).toBe('https://gartner.com/x');+ expect(target.target).toBe('_blank');+ expect(target.rel).toBe('noopener noreferrer');+ expect(target.textContent).toBe('gartner.com/x');+ });++ it('follows the draft’s brand in the sidebar', async () => {+ getContentDraft.mockResolvedValue(draft({ brandId: 'b2' }));+ await renderPage();+ expect(brandState.setActiveBrand).toHaveBeenCalledWith('b2');+ });++ it('says when the draft can’t be opened', async () => {+ getContentDraft.mockResolvedValue(null);+ await renderPage();+ expect(container.textContent).toContain(+ "This draft doesn't exist, or it belongs to another workspace.",+ );+ expect(container.querySelector('a[href="/dashboard/content/library"]')).not.toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsxnew file mode 100644index 000000000..dffb899df--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx@@ -0,0 +1,98 @@+'use client';++import { useEffect, useState } from 'react';+import { useParams } from 'next/navigation';+import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { getContentDraft } from '@/lib/actions/content-drafts';+import { CONTENT_LIBRARY_PATH, type ContentDraft } from '@/lib/content/drafts';+import { useBrandStore } from '@/stores/use-brand-store';+import { DraftEditor } from './_draft-editor';++type DraftRead = { id: string; draft: ContentDraft } | { id: string; draft: null; failed: boolean };++/**+ * A draft in the editor (Content Editor, CE-004), opened from the Library.+ * Full height, as Chat is: the editor scrolls inside, under its header.+ */+export default function ContentEditorPage() {+ const t = useTranslations('contentEditor.editor');+ const { draftId } = useParams<{ draftId: string }>();+ const [read, setRead] = useState<DraftRead | null>(null);+ const [attempt, setAttempt] = useState(0);+ const brands = useBrandStore((s) => s.brands);+ const activeBrandId = useBrandStore((s) => s.activeBrandId);+ const setActiveBrand = useBrandStore((s) => s.setActiveBrand);++ useEffect(() => {+ let cancelled = false;+ getContentDraft(draftId)+ .then((draft) => {+ if (cancelled) return;+ setRead(draft ? { id: draftId, draft } : { id: draftId, draft: null, failed: false });+ })+ .catch((err) => {+ console.error('Failed to open the draft:', err);+ if (!cancelled) setRead({ id: draftId, draft: null, failed: true });+ });+ return () => {+ cancelled = true;+ };+ }, [draftId, attempt]);++ // A draft opened from a link to another of the member's brands: the+ // sidebar follows it, so the rest of the app shows the same brand.+ const draftBrandId = read?.draft?.brandId;+ useEffect(() => {+ if (+ draftBrandId &&+ draftBrandId !== activeBrandId &&+ brands.some((b) => b.id === draftBrandId)+ ) {+ setActiveBrand(draftBrandId);+ }+ }, [draftBrandId, activeBrandId, brands, setActiveBrand]);++ const current = read?.id === draftId ? read : null;++ return (+ <div className="-m-6 flex h-[calc(100vh-4rem)] flex-col md:h-screen">+ {!current ? (+ <div className="flex flex-1 items-center justify-center" aria-busy="true">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ ) : current.draft ? (+ <DraftEditor key={current.draft.id} draft={current.draft} />+ ) : (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center">+ <p className="text-sm text-muted-foreground">+ {current.failed ? t('loadError') : t('notFound')}+ </p>+ <div className="flex gap-2">+ {current.failed && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setRead(null);+ setAttempt((n) => n + 1);+ }}+ >+ {t('retryLoad')}+ </Button>+ )}+ <Link+ href={CONTENT_LIBRARY_PATH}+ className={buttonVariants({ variant: 'outline', size: 'sm' })}+ >+ {t('back')}+ </Link>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex b90927a0f..d3a88d369 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -7,16 +7,22 @@ import type { ContentDraftListItem } from '@/lib/content/drafts';import ContentLibraryPage from './page';const getContentDrafts = vi.fn();+const createContentDraft = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({getContentDrafts: (...args: unknown[]) => getContentDrafts(...args),+ createContentDraft: (...args: unknown[]) => createContentDraft(...args),}));+const push = vi.fn();vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (<a href={href} {...props}>{children}</a>),+ useRouter: () => ({ push }),}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));const brandState = vi.hoisted(() => ({ activeBrandId: 'brand-1' as string | null }));vi.mock('@/stores/use-brand-store', () => ({useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),@@ -68,6 +74,9 @@ beforeEach(() => {document.body.appendChild(container);root = createRoot(container);getContentDrafts.mockReset();+ createContentDraft.mockReset();+ push.mockReset();+ toast.error.mockReset();});afterEach(() => {@@ -185,6 +194,33 @@ describe('the Content Library', () => {error.mockRestore();});+ it('starts a blank draft and opens it in the editor', async () => {+ getContentDrafts.mockResolvedValue([]);+ createContentDraft.mockResolvedValue('d9');+ await renderPage();+ const newContent = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'New content',+ )!;+ await act(async () => newContent.click());+ expect(createContentDraft).toHaveBeenCalledWith('brand-1');+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d9');+ });++ it('says so when a draft can’t be started', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ getContentDrafts.mockResolvedValue([]);+ createContentDraft.mockRejectedValue(new Error('denied'));+ await renderPage();+ const newContent = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'New content',+ )!;+ await act(async () => newContent.click());+ expect(push).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalledWith("Couldn't start a draft. Try again.");+ expect(newContent.disabled).toBe(false);+ error.mockRestore();+ });+it('asks for a brand when none is selected', async () => {brandState.activeBrandId = null;await renderPage();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 930ce1612..1e0b6902c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -2,13 +2,16 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';-import { Loader2 } from 'lucide-react';+import { toast } from 'sonner';+import { Loader2, Plus } from 'lucide-react';+import { useRouter } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';-import { getContentDrafts } from '@/lib/actions/content-drafts';+import { createContentDraft, getContentDrafts } from '@/lib/actions/content-drafts';import {LIBRARY_TABS,+ contentEditorPath,draftsInTab,libraryTabCounts,type ContentDraftListItem,@@ -37,6 +40,8 @@ export default function ContentLibraryPage() {const [tab, setTab] = useState<LibraryTab>('all');const [read, setRead] = useState<LibraryRead | null>(null);const [attempt, setAttempt] = useState(0);+ const [creating, setCreating] = useState(false);+ const router = useRouter();useEffect(() => {// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount@@ -59,6 +64,21 @@ export default function ContentLibraryPage() {};}, [activeBrandId, attempt]);+ // New content opens a blank draft in the editor; the Start screen (CE-015)+ // takes this over, asking for the page type and checking overlaps first.+ const newContent = async () => {+ if (!activeBrandId) return;+ setCreating(true);+ try {+ const id = await createContentDraft(activeBrandId);+ router.push(contentEditorPath(id));+ } catch (err) {+ console.error('Failed to start a draft:', err);+ toast.error(t('createFailed'));+ setCreating(false);+ }+ };+const changeTab = (next: LibraryTab) => {setTab(next);writeUrlParams({ tab: next }, { tab: 'all' });@@ -79,9 +99,15 @@ export default function ContentLibraryPage() {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <Button className="gap-2" onClick={newContent} disabled={creating}>+ {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}+ {t('newContent')}+ </Button></div><Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.tsindex 360c5a78b..ff29db535 100644--- a/web/src/config/dashboard.ts+++ b/web/src/config/dashboard.ts@@ -28,6 +28,8 @@ export type BrandPrefKey = 'shoppingModeEnabled';export interface NavChild {title: string;href: string;+ /** Other routes that belong to this entry, e.g. the editor to the Library. */+ activeFor?: string[];}export interface NavItem {@@ -91,7 +93,12 @@ export const dashboardNav: NavGroup[] = [requiredFeature: 'content_optimization',children: [{ title: 'Opportunities', href: '/dashboard/content' },- { title: 'Library', href: '/dashboard/content/library' },+ // A draft opens in the editor from the Library (CE-004).+ {+ title: 'Library',+ href: '/dashboard/content/library',+ activeFor: ['/dashboard/content/editor'],+ },],},{diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsnew file mode 100644index 000000000..00cecfdab--- /dev/null+++ b/web/src/lib/actions/content-drafts.test.ts@@ -0,0 +1,176 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The editor's writes (CE-004): a save or Mark ready that RLS turns away+ * matches no row without an error, so each reads its row back and says so.+ */++const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';++interface Call {+ op: string;+ value?: unknown;+ filters: [string, string, unknown][];+}+let calls: Call[];+// What the next update returns: its row, or none (RLS, or not found).+let updated: Record<string, unknown> | null;+// Or, update by update, when a test needs more than one.+let updates: (Record<string, unknown> | null)[];+let row: Record<string, unknown> | null;++vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));+vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },+ from: () => {+ const call: Call = { op: 'select', filters: [] };+ calls.push(call);+ const result = () =>+ call.op === 'update'+ ? { data: updates.length ? updates.shift()! : updated, error: null }+ : call.op === 'insert'+ ? { data: { id: 'new-draft' }, error: null }+ : { data: row, error: null };+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: (col: string, v: unknown) => (call.filters.push(['eq', col, v]), chain),+ in: (col: string, v: unknown) => (call.filters.push(['in', col, v]), chain),+ update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),+ insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),+ maybeSingle: async () => result(),+ single: async () => result(),+ };+ return chain;+ },+ })),+}));++const { createContentDraft, getContentDraft, markContentDraftReady, saveContentDraft } =+ await import('./content-drafts');+const { bodyHash } = await import('@/lib/content/editor');++beforeEach(() => {+ calls = [];+ updated = null;+ updates = [];+ row = null;+});++describe('saveContentDraft', () => {+ const LOADED = '<h1>Pipeline</h1>';+ const base = async (html = LOADED) => ({+ updatedAt: '2026-10-20T14:00:00Z',+ bodyHash: await bodyHash(html),+ });++ it('saves the body and the title over the version the editor last saw', async () => {+ updated = { updated_at: '2026-10-20T15:00:00Z' };+ await expect(+ saveContentDraft(DRAFT, {+ title: 'Pipeline forecasting',+ bodyHtml: '<h1>Pipeline forecasting</h1>',+ base: await base(),+ }),+ ).resolves.toEqual({+ ok: true,+ updatedAt: '2026-10-20T15:00:00Z',+ bodyHash: await bodyHash('<h1>Pipeline forecasting</h1>'),+ });+ expect(calls[0]).toMatchObject({+ op: 'update',+ value: { title: 'Pipeline forecasting', body_html: '<h1>Pipeline forecasting</h1>' },+ filters: [+ ['eq', 'id', DRAFT],+ ['eq', 'updated_at', '2026-10-20T14:00:00Z'],+ ],+ });+ });++ it('goes over a change to the draft’s other columns, the page being the same', async () => {+ // Marked ready meanwhile: a newer updated_at, the page as the editor saw it.+ updates = [null, { updated_at: '2026-10-20T15:01:00Z' }];+ row = { updated_at: '2026-10-20T14:30:00Z', body_html: LOADED };+ const result = await saveContentDraft(DRAFT, {+ title: 'Pipeline',+ bodyHtml: '<h1>Pipeline</h1><p>More</p>',+ base: await base(),+ });+ expect(result).toMatchObject({ ok: true, updatedAt: '2026-10-20T15:01:00Z' });+ expect(calls.map((c) => c.op)).toEqual(['update', 'select', 'update']);+ expect(calls[2].filters).toContainEqual(['eq', 'updated_at', '2026-10-20T14:30:00Z']);+ });++ it('doesn’t overwrite a page someone else changed', async () => {+ row = { updated_at: '2026-10-20T14:30:00Z', body_html: '<h1>Their version</h1>' };+ await expect(+ saveContentDraft(DRAFT, { title: 'Mine', bodyHtml: '<h1>Mine</h1>', base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'conflict' });+ expect(calls.map((c) => c.op)).toEqual(['update', 'select']);+ });++ it('says so when the draft is gone or not the member’s, rather than reporting it saved', async () => {+ await expect(+ saveContentDraft(DRAFT, { title: '', bodyHtml: '', base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'not_found' });+ });++ it('says a body over the limit is too large, and refuses a bad title or id, before writing', async () => {+ await expect(+ saveContentDraft(DRAFT, { title: '', bodyHtml: 'x'.repeat(500_001), base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'too_large' });+ await expect(+ saveContentDraft(DRAFT, { title: 'x'.repeat(301), bodyHtml: '', base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'invalid' });+ await expect(+ saveContentDraft('nope', { title: '', bodyHtml: '', base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'invalid' });+ expect(calls).toEqual([]);+ });+});++describe('markContentDraftReady', () => {+ it('moves a draft or an agent draft in review to ready', async () => {+ updated = { status: 'ready' };+ await expect(markContentDraftReady(DRAFT)).resolves.toBe('ready');+ expect(calls[0]).toMatchObject({+ op: 'update',+ value: { status: 'ready' },+ filters: [+ ['eq', 'id', DRAFT],+ ['in', 'status', ['draft', 'in_review']],+ ],+ });+ });++ it('leaves a published draft published', async () => {+ row = {+ id: DRAFT,+ brand_id: 'b1',+ title: '',+ page_type: null,+ method: 'create',+ status: 'published',+ body_html: '',+ author: 'user',+ updated_at: '2026-10-20T15:00:00Z',+ };+ await expect(markContentDraftReady(DRAFT)).resolves.toBe('published');+ });++ it('says so when the draft isn’t the member’s', async () => {+ await expect(markContentDraftReady(DRAFT)).rejects.toThrow('not_found');+ });+});++describe('getContentDraft and createContentDraft', () => {+ it('reads nothing for a malformed id', async () => {+ await expect(getContentDraft('../etc')).resolves.toBeNull();+ expect(calls).toEqual([]);+ });++ it('starts a blank draft as the signed-in member', async () => {+ await expect(createContentDraft('b1')).resolves.toBe('new-draft');+ expect(calls[0]).toMatchObject({ op: 'insert', value: { brand_id: 'b1', created_by: 'u1' } });+ });+});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 5de8a83eb..22f4fe2f7 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -1,13 +1,21 @@'use server';+import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import { readAssignees } from '@/lib/action-center/assignees';import {DRAFT_STATUSES,+ type ContentDraft,type ContentDraftListItem,type DraftMethod,type DraftStatus,} from '@/lib/content/drafts';+import {+ MAX_BODY_HTML_LENGTH,+ MAX_TITLE_LENGTH,+ bodyHash,+ type SaveDraftResult,+} from '@/lib/content/editor';/*** Content drafts (Content Editor, CE-002), read through the signed-in member's@@ -48,9 +56,7 @@ export async function getContentDrafts(brandId: string): Promise<ContentDraftListitle: row.title,pageType: row.page_type,method: row.method as DraftMethod,- status: (DRAFT_STATUSES as readonly string[]).includes(row.status)- ? (row.status as DraftStatus)- : 'draft',+ status: draftStatus(row.status),author: row.author === 'agent' ? 'agent' : 'user',createdBy: row.created_by ? (people.get(row.created_by) ?? null) : null,isMine: me !== null && row.created_by === me,@@ -59,3 +65,135 @@ export async function getContentDrafts(brandId: string): Promise<ContentDraftLisupdatedAt: row.updated_at,}));}++function draftStatus(value: string): DraftStatus {+ return (DRAFT_STATUSES as readonly string[]).includes(value) ? (value as DraftStatus) : 'draft';+}++const draftId = z.guid();++/** One draft for the editor (CE-004), or null when it isn't the member's to read. */+export async function getContentDraft(id: string): Promise<ContentDraft | null> {+ if (!draftId.safeParse(id).success) return null;+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .select('id, brand_id, title, page_type, method, status, body_html, author, updated_at')+ .eq('id', id)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) return null;+ return {+ id: data.id,+ brandId: data.brand_id,+ title: data.title,+ pageType: data.page_type,+ method: data.method as DraftMethod,+ status: draftStatus(data.status),+ bodyHtml: data.body_html,+ author: data.author === 'agent' ? 'agent' : 'user',+ updatedAt: data.updated_at,+ };+}++/**+ * A blank draft of a new page, started by the signed-in member: what the+ * Library's New content opens until the Start screen (CE-015) asks for the+ * page type and checks for overlaps first.+ */+export async function createContentDraft(brandId: string): Promise<string> {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) throw new Error('unauthorized');+ const { data, error } = await supabase+ .from('content_drafts')+ .insert({ brand_id: brandId, created_by: user.id })+ .select('id')+ .single();+ if (error) throw new Error(error.message);+ return data.id;+}++const saveInput = z.object({+ title: z.string().max(MAX_TITLE_LENGTH),+ bodyHtml: z.string(),+ base: z.object({+ updatedAt: z.string().min(1),+ bodyHash: z.string().regex(/^[0-9a-f]{64}$/),+ }),+});++/** Saves that find the draft written meanwhile, then try again over it. */+const SAVE_ATTEMPTS = 3;++/**+ * The editor's autosave: the body and the title read from it, written only+ * over the version the editor last saw (`base`). When another write came+ * first, the page tells which kind: the same page means only the draft's+ * other columns changed (Mark ready, its type), and the save goes over them;+ * another page means someone else changed it (another tab, a teammate, the+ * Content Agent), and nothing is overwritten. A save RLS refused, or of a+ * draft that no longer exists, comes back not_found rather than saved.+ */+export async function saveContentDraft(+ id: string,+ input: { title: string; bodyHtml: string; base: { updatedAt: string; bodyHash: string } },+): Promise<SaveDraftResult> {+ if (typeof input?.bodyHtml === 'string' && input.bodyHtml.length > MAX_BODY_HTML_LENGTH) {+ return { ok: false, reason: 'too_large' };+ }+ const parsed = saveInput.safeParse(input);+ if (!draftId.safeParse(id).success || !parsed.success) return { ok: false, reason: 'invalid' };+ const { title, bodyHtml, base } = parsed.data;+ const supabase = await createClient();+ let expected = base.updatedAt;+ for (let attempt = 0; attempt < SAVE_ATTEMPTS; attempt++) {+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ title, body_html: bodyHtml })+ .eq('id', id)+ .eq('updated_at', expected)+ .select('updated_at')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (data) return { ok: true, updatedAt: data.updated_at, bodyHash: await bodyHash(bodyHtml) };++ const { data: current, error: readError } = await supabase+ .from('content_drafts')+ .select('updated_at, body_html')+ .eq('id', id)+ .maybeSingle();+ if (readError) throw new Error(readError.message);+ if (!current) return { ok: false, reason: 'not_found' };+ if ((await bodyHash(current.body_html)) !== base.bodyHash) {+ return { ok: false, reason: 'conflict' };+ }+ expected = current.updated_at;+ }+ return { ok: false, reason: 'conflict' };+}++/**+ * Mark ready: a draft, or an agent's draft in review, is ready to publish.+ * Ansvisor never publishes it; the person does (CE-013 records the URL).+ * Returns the status the draft has after, so a draft already ready or+ * published keeps its own.+ */+export async function markContentDraftReady(id: string): Promise<DraftStatus> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ status: 'ready' })+ .eq('id', id)+ .in('status', ['draft', 'in_review'])+ .select('status')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (data) return draftStatus(data.status);+ const current = await getContentDraft(id);+ if (!current) throw new Error('not_found');+ return current.status;+}diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex 72f351500..6b281cfb4 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -76,6 +76,19 @@ export interface ContentDraftListItem {updatedAt: string;}+/** A draft as the editor opens it. */+export interface ContentDraft {+ id: string;+ brandId: string;+ title: string;+ pageType: string | null;+ method: DraftMethod;+ status: DraftStatus;+ bodyHtml: string;+ author: 'user' | 'agent';+ updatedAt: string;+}+export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {return tab === 'all' ? drafts : drafts.filter((d) => d.status === tab);}diff --git a/web/src/lib/content/editor.test.ts b/web/src/lib/content/editor.test.tsnew file mode 100644index 000000000..14f58dc72--- /dev/null+++ b/web/src/lib/content/editor.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';+import {+ draftTitleFromDoc,+ lengthTarget,+ safeImageSrc,+ safeLinkHref,+ type EditorJsonNode,+} from './editor';++const doc = (...content: EditorJsonNode[]): EditorJsonNode => ({ type: 'doc', content });+const heading = (level: number, text: string): EditorJsonNode => ({+ type: 'heading',+ attrs: { level },+ content: [{ type: 'text', text }],+});+const paragraph = (...texts: string[]): EditorJsonNode => ({+ type: 'paragraph',+ content: texts.map((text) => ({ type: 'text', text })),+});++describe('draftTitleFromDoc', () => {+ it('names the draft by its first H1, wherever it is', () => {+ expect(+ draftTitleFromDoc(+ doc(paragraph('Intro'), heading(2, 'How it works'), heading(1, 'Pipeline forecasting')),+ ),+ ).toBe('Pipeline forecasting');+ });++ it('takes the first heading when there is no H1, then the first text', () => {+ expect(draftTitleFromDoc(doc(paragraph(''), heading(2, 'FAQ')))).toBe('FAQ');+ expect(draftTitleFromDoc(doc(paragraph('Lisbon ', 'in winter')))).toBe('Lisbon in winter');+ });++ it('cuts a long first paragraph at a word', () => {+ const title = draftTitleFromDoc(+ doc(+ paragraph(+ 'Northwind forecasts each deal from real activity: emails, meetings and stage changes, every week.',+ ),+ ),+ );+ expect(title).toBe(+ 'Northwind forecasts each deal from real activity: emails, meetings and stage…',+ );+ });++ it('is empty for an empty page, and keeps a heading to the column’s limit', () => {+ expect(draftTitleFromDoc(doc(paragraph()))).toBe('');+ expect(draftTitleFromDoc({ type: 'doc' })).toBe('');+ expect(draftTitleFromDoc(doc(heading(1, 'x'.repeat(400))))).toHaveLength(300);+ });+});++describe('lengthTarget', () => {+ it('follows the spec’s default Length rule per page type', () => {+ expect(lengthTarget('product_page')).toBe(1200);+ expect(lengthTarget('category_page')).toBe(800);+ expect(lengthTarget('blog_post')).toBe(3000);+ expect(lengthTarget(null)).toBe(3000);+ });+});++describe('safeLinkHref', () => {+ it('keeps web addresses, e-mail and paths on the brand’s site', () => {+ expect(safeLinkHref('https://gartner.com/en/sales')).toBe('https://gartner.com/en/sales');+ expect(safeLinkHref(' example.com/pricing ')).toBe('https://example.com/pricing');+ expect(safeLinkHref('mailto:[email protected]')).toBe('mailto:[email protected]');+ expect(safeLinkHref('/features/email-sync')).toBe('/features/email-sync');+ });++ it('refuses scripts and anything that isn’t a link', () => {+ expect(safeLinkHref('javascript:alert(1)')).toBeNull();+ expect(safeLinkHref('data:text/html,hi')).toBeNull();+ expect(safeLinkHref('//evil.com')).toBeNull();+ expect(safeLinkHref('/\\evil.com')).toBeNull();+ expect(safeLinkHref('hello')).toBeNull();+ expect(safeLinkHref('')).toBeNull();+ });+});++describe('safeImageSrc', () => {+ it('takes only http(s) addresses', () => {+ expect(safeImageSrc('https://cdn.acme.com/a.png')).toBe('https://cdn.acme.com/a.png');+ expect(safeImageSrc('/a.png')).toBeNull();+ expect(safeImageSrc('mailto:[email protected]')).toBeNull();+ });+});diff --git a/web/src/lib/content/editor.ts b/web/src/lib/content/editor.tsnew file mode 100644index 000000000..cedf3f9a3--- /dev/null+++ b/web/src/lib/content/editor.ts@@ -0,0 +1,118 @@+/**+ * The content editor's rules that don't need the editor itself (Content+ * Editor, CE-004): the draft's title, the length target the counter shows,+ * and which links the toolbar accepts.+ */++/** How long typing pauses before the draft saves itself. */+export const AUTOSAVE_DELAY_MS = 1500;++/** The largest body a draft saves, in characters of HTML (about 100 pages). */+export const MAX_BODY_HTML_LENGTH = 500_000;++/** content_drafts.title's limit (00204). */+export const MAX_TITLE_LENGTH = 300;++/** The saved page the editor last saw: a save only goes over this version. */+export interface SavedVersion {+ updatedAt: string;+ bodyHash: string;+}++/**+ * What a save came to. Typed rather than thrown: in production Next.js hides+ * a server action's error message, and the editor says something different+ * for each.+ * - conflict: someone else changed the page since (another tab, a teammate,+ * the Content Agent), and it wasn't overwritten;+ * - too_large: over MAX_BODY_HTML_LENGTH, which no retry can save;+ * - not_found: the draft is gone, or isn't the member's.+ */+export type SaveDraftResult =+ | ({ ok: true } & SavedVersion)+ | { ok: false; reason: 'conflict' | 'too_large' | 'not_found' | 'invalid' };++/**+ * A fingerprint of a page (SHA-256 of its HTML, in hex), the same in the+ * browser and on the server. A save sends the one it last saw, so the server+ * can tell a page someone else changed from a draft where only another+ * column changed (its status, its type).+ */+export async function bodyHash(html: string): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(html));+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');+}++/**+ * The counter's target until the Rules tab (CE-009) lets it be changed: the+ * spec's default Length rule, 3,000 characters, 1,200 for a product page and+ * 800 for a category page.+ */+export function lengthTarget(pageType: string | null): number {+ if (pageType === 'product_page') return 1200;+ if (pageType === 'category_page') return 800;+ return 3000;+}++/** The parts of the editor's JSON (TipTap's getJSON) a title is read from. */+export interface EditorJsonNode {+ type?: string;+ attrs?: Record<string, unknown>;+ text?: string;+ content?: EditorJsonNode[];+}++function textOf(node: EditorJsonNode): string {+ if (node.text) return node.text;+ return (node.content ?? []).map(textOf).join('');+}++/**+ * A draft is named by its page's H1, as the Library lists it: the first H1,+ * else the first heading, else the start of the first text. Empty while the+ * page is.+ */+export function draftTitleFromDoc(doc: EditorJsonNode): string {+ const blocks = (doc.content ?? []).filter((node) => textOf(node).trim());+ const pick =+ blocks.find((node) => node.type === 'heading' && node.attrs?.level === 1) ??+ blocks.find((node) => node.type === 'heading') ??+ blocks[0];+ if (!pick) return '';+ const text = textOf(pick).replace(/\s+/g, ' ').trim();+ if (pick.type === 'heading' || text.length <= 80) return text.slice(0, MAX_TITLE_LENGTH);+ // A first paragraph as the title: cut at a word, with an ellipsis.+ const cut = text.slice(0, 80);+ return `${cut.slice(0, cut.lastIndexOf(' ') > 40 ? cut.lastIndexOf(' ') : 80)}…`;+}++/**+ * A link the toolbar sets: a path on the brand's own site (an internal+ * link), or an http(s) or mailto address, so a pasted "javascript:" never+ * becomes a link. A bare domain gets https://. Null when it isn't a link.+ */+export function safeLinkHref(input: string): string | null {+ const value = input.trim();+ if (!value) return null;+ // "//host" (and "/\host", which browsers read the same) is another site's+ // address with no scheme to check.+ if (/^\/[/\\]/.test(value)) return null;+ if (value.startsWith('/')) return value;+ const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(value) ? value : `https://${value}`;+ try {+ const url = new URL(withScheme);+ if (url.protocol === 'mailto:') return url.href;+ if ((url.protocol === 'http:' || url.protocol === 'https:') && url.hostname.includes('.')) {+ return url.href;+ }+ } catch {+ // Not a URL.+ }+ return null;+}++/** An image the toolbar inserts by address: http(s) only. */+export function safeImageSrc(input: string): string | null {+ const href = safeLinkHref(input);+ return href && /^https?:/.test(href) ? href : null;+}diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.tsindex 6f8919061..a840a5afc 100644--- a/web/src/lib/dashboard-navigation.test.ts+++ b/web/src/lib/dashboard-navigation.test.ts@@ -48,7 +48,11 @@ describe('getDashboardNavLabel', () => {expect(content.href).toBe('/dashboard/content');expect(content.children).toEqual([{ title: 'Opportunities', href: '/dashboard/content' },- { title: 'Library', href: '/dashboard/content/library' },+ {+ title: 'Library',+ href: '/dashboard/content/library',+ activeFor: ['/dashboard/content/editor'],+ },]);});@@ -134,6 +138,15 @@ describe('activeChildHref', () => {);});+ it('marks the Library while a draft is open in the editor', () => {+ const items = dashboardNav.flatMap((group) => group.items);+ const children = items.find((item) => item.title === 'Content')!.children!;+ expect(activeChildHref(children, '/dashboard/content/editor/d1')).toBe(+ '/dashboard/content/library',+ );+ expect(activeChildHref(children, '/dashboard/content/3f2a')).toBe('/dashboard/content');+ });+it('keeps an opportunity’s own page under Opportunities', () => {expect(activeChildHref(content, '/dashboard/content')).toBe('/dashboard/content');expect(activeChildHref(content, '/dashboard/content/3f2a')).toBe('/dashboard/content');diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.tsindex b8fd23e3a..12339a26e 100644--- a/web/src/lib/dashboard-navigation.ts+++ b/web/src/lib/dashboard-navigation.ts@@ -50,16 +50,23 @@ export function getDashboardNavLabel(title: string, t: Translator, tBrands: Tran}/**- * The submenu entry the current page belongs to: its own route or a page- * under it (a topic's page sits under Topics). When one entry's route holds- * another's (Opportunities is /dashboard/content, the Library is- * /dashboard/content/library), the longer one wins, so only one is current.+ * The submenu entry the current page belongs to: its own route, one it is+ * `activeFor` (the editor, for the Library), or a page under either (a+ * topic's page sits under Topics). When one entry's route holds another's+ * (Opportunities is /dashboard/content, the Library is+ * /dashboard/content/library), the longer match wins, so only one is current.*/export function activeChildHref(children: NavChild[], pathname: string): string | null {let best: string | null = null;+ let bestLength = -1;for (const child of children) {- const matches = pathname === child.href || pathname.startsWith(`${child.href}/`);- if (matches && (best === null || child.href.length > best.length)) best = child.href;+ for (const route of [child.href, ...(child.activeFor ?? [])]) {+ const matches = pathname === route || pathname.startsWith(`${route}/`);+ if (matches && route.length > bestLength) {+ best = child.href;+ bestLength = route.length;+ }+ }}return best;}diff --git a/web/yarn.lock b/web/yarn.lockindex a4fbf87ff..1a9da1cdc 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -625,6 +625,21 @@dependencies:"@floating-ui/utils" "^0.2.11"+"@floating-ui/core@^1.8.0":+ version "1.8.0"+ resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-1.8.0.tgz#d01c0bbea02e4a57f6fd7d5de6fc2c5c7dca40e1"+ integrity sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==+ dependencies:+ "@floating-ui/utils" "^0.2.12"++"@floating-ui/dom@^1.0.0":+ version "1.8.0"+ resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-1.8.0.tgz#8a20e6facbe2456afdbeb6c8b968a72df689cf63"+ integrity sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==+ dependencies:+ "@floating-ui/core" "^1.8.0"+ "@floating-ui/utils" "^0.2.12"+"@floating-ui/dom@^1.7.6":version "1.7.6"resolved "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz"@@ -645,6 +660,11 @@resolved "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz"integrity sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==+"@floating-ui/utils@^0.2.12":+ version "0.2.12"+ resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.12.tgz#afefe785949f16ac4cdd1e695935a321572dd56a"+ integrity sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==+"@formatjs/[email protected]":version "3.1.1"resolved "https://registry.npmjs.org/@formatjs/ecma402-abstract/-/ecma402-abstract-3.1.1.tgz"@@ -2114,6 +2134,206 @@dependencies:postcss-selector-parser "6.0.10"+"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/core/-/core-3.31.4.tgz#6deb89d6a7db4e20a7e12ca50784328ed826b410"+ integrity sha512-cIVUQYBycighzsk6GbmCef8ZiEDVxoT5EuAe4xg2q9dNkDqCXVqI4YGr9aavCQEiAS4uHiRwqvcsPqJHipFDfg==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-blockquote/-/extension-blockquote-3.31.4.tgz#5911721e9328b60964819926fd51cf0aaee5679b"+ integrity sha512-FHnbvCIW0eDKgUUFjmvEB0ax9YUBW7/Unm+38qpuQROvU872yRqhnDtycKT9IKk46jNdjM4A4fAGUbge10CrAA==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bold/-/extension-bold-3.31.4.tgz#d059630d72f0088505e4066c65922b3f5ffc2477"+ integrity sha512-QX1xoXvO0gz6uVsoLegumqQ4MJXL7lcUDQZ4J7la7LBqiIh4efrCmp2EXbhpr37M/YQL7w8q3g7H/VovSh7xIg==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.31.4.tgz#412b5c56f77d0511bc465666f8e89658e4cf68d4"+ integrity sha512-Ml/yswuys+3QkOMajfXyAGlUKCxEbT3dMyF8vHwQ5mDk9MDm+dqp10It5CrDBkUT/KkVTa6AJI3kb0TXZJZiAA==+ dependencies:+ "@floating-ui/dom" "^1.0.0"++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bullet-list/-/extension-bullet-list-3.31.4.tgz#90d0748f01e27835edebabdf10cd4892909eb404"+ integrity sha512-gHn1RDR4olCnmKpH+G9x+f8R+iKPNVdLlvbFkIpR/stjabZi7fB4Rr5GiHWsulbtxAjdQrNjnVeNdGM4rBxApw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code-block/-/extension-code-block-3.31.4.tgz#a3b6161b83161fc88625f76e0bb87e4516c42675"+ integrity sha512-su/B/cfQ1HpiHl6JfJ6wa+RVEptiYsV4dCntE8XQNj2dUcII4y6w6PQbbswOoDrU79uXHsAvpy44215rghG4LA==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code/-/extension-code-3.31.4.tgz#0da4874c90aa708ead8b9719edc6e8f645529c78"+ integrity sha512-pzi8GNDs5J1DEoO1HNYiJ5WZpgOZzlc/2VIa77mMpEuD4hZxuK0BQzlF/O6Ps/O5P1lGJT4xS0Yowpzb9mD9RA==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-document/-/extension-document-3.31.4.tgz#49c53a2c2b1b2a319b7d20f28cb7413dc3bd834d"+ integrity sha512-vT20u62RWR+BLIyNJ54e24MPUY4zm8VF7tcgJnxQXi7BgVJWcNMtMWWDIkPJ4JNXwfoIznKh3jzYsaYmbCJgQQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-dropcursor/-/extension-dropcursor-3.31.4.tgz#deef7743648eff12ae2afbf33d75378d6a8202a0"+ integrity sha512-5TbCPCC4RL+QT1NYHjXCYDBHBtVqYOFvFEnk3v98lvXCM2PNL13ofXUfJPuykAVy1OdTAx4DlZOQAD9WKy/IdQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-floating-menu/-/extension-floating-menu-3.31.4.tgz#3889c994c86ca86d9425f8dc666734e70747a0dc"+ integrity sha512-pKzulkDmolpVt7IP9FSPsC5pKbXQ5pyeqkaAYr8cyOVW+KUObpPRIzAuXvEso8PCjWgwJ1f2qyishOEMw8MbfQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-gapcursor/-/extension-gapcursor-3.31.4.tgz#407e640910cc97db91b420b2bd109fde57703f75"+ integrity sha512-hBogUAepQH6IQUhaePhPWzQ1Oeu+yqlJVMKO06Eue5m36uRy1PZZAQ780pCGT0SC4R5MH2td1N8EUQ7bupQdDA==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-hard-break/-/extension-hard-break-3.31.4.tgz#1f1bbb8102cb46d845c99289bab95975e074fb1e"+ integrity sha512-oLNajLyUvRMg1qtzFgKGduygTlpaHFB9PU+M+pUWdA4sa1bRnxS2Y++Ao4lHYopJ7nxatLndrYoCIHkotqkPDQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-heading/-/extension-heading-3.31.4.tgz#227cbe95012a4bfa9872960a8844ed330a5adc10"+ integrity sha512-KqlSeLathpdxCc3kVHBCA/RkHvb+V7u5vgiSEu1Cv3L70r7F19COMGODav/k1AGYBgEXKL6lM9cy8cloE5/28g==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.31.4.tgz#d48fee5d0317d3761dc193b81191c53e1a6a24f8"+ integrity sha512-ws0Kh8kfHL7ESILSXj0HJAXs8G10ewlW1sedXKm8dm0op9L8il+xl8bEJVoqG/jMf77900Fc2CaQldcCGRpF1g==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-image/-/extension-image-3.31.4.tgz#6d7f629c02151b045a271f89d034d82c3a042b0b"+ integrity sha512-vtD+rK73abJnPRKOjU37sQTCa5Auyg451yhqZD/3lZKiFJDBHAZKI7lQARkXBQYK289hBhK6yMIwofoqCBvi3g==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-italic/-/extension-italic-3.31.4.tgz#bed5bdf17e65a1e6d8a34f592ff84b3a73d52af1"+ integrity sha512-pftTQBPYZocNDAj/u6OyDIp7YxmN0+N895cQPogJQ6qMHdLiRhzgawiEewJkniyN1w8k3Wx/Etp8pTKrxaOOBQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-link/-/extension-link-3.31.4.tgz#9fdfc30f684c0f502943a5228c93c1ba74586139"+ integrity sha512-LLxW3qfeL9gvDdMPVdxYFYZ0zZSjsoIDhOqjJ5U2UfaK3U2iwkKTBgV2qT+FWf3uUHmBRjBZ08q3dRPmWBAD5g==+ dependencies:+ linkifyjs "^4.3.3"++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list-item/-/extension-list-item-3.31.4.tgz#c986b451d476174702045302d2a214f8207461c3"+ integrity sha512-ao8XAPvhOrtGFILs+fKtOM91omDSpUC8X19m44gbaq5xJDVpIMZ0rP+NAVUS72G7LskhcHa0bu/Pm022bUVjVw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list-keymap/-/extension-list-keymap-3.31.4.tgz#a73c1c32731c31c3cbdc292fca6a71d30458ac47"+ integrity sha512-etdkl/YnYfwtALDxecJ+4WYgJAez1fn1vzzZqJklZBpgqiZtny3NxpvWS7/JhsltNG84Wo/oovpfJgVmzhddrw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list/-/extension-list-3.31.4.tgz#7b339e7c1fbc590cdb475eaca4823a8b90c31484"+ integrity sha512-Wd4YRYxOdf+TtF33/QsRo1RK1CecVxjYGjUBIKNGHAywfh8tghgV4YOUCiV1iJqYt2IBs+RWlIqTmdIPzBrd4A==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-ordered-list/-/extension-ordered-list-3.31.4.tgz#5b47a963d452e6258946519a2271965ebcbb34e8"+ integrity sha512-UNWyF+Dhm08znszIMnT8Y2kJ1lvtiCvUGs1aG7m9cPHxDa7VycWnOqdtXWkc+6xRLNiC0zgWCFWgLLHduV8pRQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-paragraph/-/extension-paragraph-3.31.4.tgz#b90574a72ae832b8ed76cf7d08a44d71ea0d80ae"+ integrity sha512-WZlBgw+XVKXerRlmEsoQ7x1PwSU+dh3X+b70+ViZsLebdfsmmYBIaNDrvIGwG9UQr5eLnddJnZplMSTI2YKs+g==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-strike/-/extension-strike-3.31.4.tgz#99bf79b26cdb38c62056c8c06c4aed0ce98574f9"+ integrity sha512-4MBr63TJIMqxCjE+gAPdlY1IdELgvbAP516K3Ntn/BkcpEbEoPMEYVz+XTxULyHQEuARDO6jsXPPxRXpA74jaw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-table/-/extension-table-3.31.4.tgz#ded2536323240281ed6f4f67e7c365528a5b985a"+ integrity sha512-ai7DLwg/xmhlUas3LgWaPQdPlZ8StliY6Dn+iUH6eyZ/TQqRDY/oeIsKWaHpXq22T5M5dMlZPTg172ZdtwKswQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-text/-/extension-text-3.31.4.tgz#f51ed21ef44197c35f08b903795236deb1908c2c"+ integrity sha512-WL2ZRpFksgQcXJN05/UQH09YCH9LlhdLrSEcviASvEH/aAfsKiJlDrouN8PET+YAWK/F5xFc5/Q1z0xj+I23jw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-underline/-/extension-underline-3.31.4.tgz#e893adfc2d0d2c4694bbc2331b6f9c48f73ef844"+ integrity sha512-0iFGPIqmqGkCrOFh1OPo7Dzv5s86dVN3bZaugsz0jK04otkb8bn04ZDKP2/6Wq+lcK0M9DfJ0QqfW5hC2nBZxQ==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/extensions/-/extensions-3.31.4.tgz#ac29dfeb89f78434936e21d3daa8bf54089afe81"+ integrity sha512-nIupIne/sHpV2Kw1M4MOmr4+G454KI8BXM5+LWKOU2EpzfALZWVSy7koF9lVRna4Zp5Gv8hfg5Z8kvmrYQvhkw==++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/pm/-/pm-3.31.4.tgz#f76cbacc32038921e41f0530a44fa1c40a818dce"+ integrity sha512-x7dwth79cQp4QGae66/RJqMDJQv0+n7b7dD7cyFQBWqzPFLJxN/4paHY4qbWedZjNLhRyIOAD9a5q4AYM1zmPA==+ dependencies:+ prosemirror-changeset "^2.4.1"+ prosemirror-commands "^1.7.1"+ prosemirror-dropcursor "^1.8.2"+ prosemirror-gapcursor "^1.4.1"+ prosemirror-history "^1.5.0"+ prosemirror-inputrules "^1.5.1"+ prosemirror-keymap "^1.2.3"+ prosemirror-model "^1.25.11"+ prosemirror-schema-list "^1.5.1"+ prosemirror-state "^1.4.4"+ prosemirror-tables "^1.8.5"+ prosemirror-transform "^1.12.0"+ prosemirror-view "^1.42.3"++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/react/-/react-3.31.4.tgz#bc27a1965c0040b82200915d411f0e74853c19f7"+ integrity sha512-mBvvXgdPhMinT1NPfwHvFK1dFdMXHVWMSeNn0IPj7/zV0XBmOnASkEOwoIvl8NluKYEtpZBE1yA+6pN2enLa5g==+ dependencies:+ "@types/use-sync-external-store" "^0.0.6"+ fast-equals "^5.3.3"+ use-sync-external-store "^1.4.0"+ optionalDependencies:+ "@tiptap/extension-bubble-menu" "3.31.4"+ "@tiptap/extension-floating-menu" "3.31.4"++"@tiptap/[email protected]":+ version "3.31.4"+ resolved "https://registry.yarnpkg.com/@tiptap/starter-kit/-/starter-kit-3.31.4.tgz#95edc876d390cf4757de291b525628515c4b5c6e"+ integrity sha512-u7HIJ9vK6kFe4S4J2CIcDLrhRZzoTMSyU0XxjQ6lUNF7pWW3rMi//pvi8RcsZmxGjyb8CpXAqYgNl7f9WyaUeA==+ dependencies:+ "@tiptap/core" "3.31.4"+ "@tiptap/extension-blockquote" "3.31.4"+ "@tiptap/extension-bold" "3.31.4"+ "@tiptap/extension-bullet-list" "3.31.4"+ "@tiptap/extension-code" "3.31.4"+ "@tiptap/extension-code-block" "3.31.4"+ "@tiptap/extension-document" "3.31.4"+ "@tiptap/extension-dropcursor" "3.31.4"+ "@tiptap/extension-gapcursor" "3.31.4"+ "@tiptap/extension-hard-break" "3.31.4"+ "@tiptap/extension-heading" "3.31.4"+ "@tiptap/extension-horizontal-rule" "3.31.4"+ "@tiptap/extension-italic" "3.31.4"+ "@tiptap/extension-link" "3.31.4"+ "@tiptap/extension-list" "3.31.4"+ "@tiptap/extension-list-item" "3.31.4"+ "@tiptap/extension-list-keymap" "3.31.4"+ "@tiptap/extension-ordered-list" "3.31.4"+ "@tiptap/extension-paragraph" "3.31.4"+ "@tiptap/extension-strike" "3.31.4"+ "@tiptap/extension-text" "3.31.4"+ "@tiptap/extension-underline" "3.31.4"+ "@tiptap/extensions" "3.31.4"+ "@tiptap/pm" "3.31.4"+"@ts-morph/common@~0.27.0":version "0.27.0"resolved "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz"@@ -4090,6 +4310,11 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz"integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==+fast-equals@^5.3.3:+ version "5.4.5"+ resolved "https://registry.yarnpkg.com/fast-equals/-/fast-equals-5.4.5.tgz#df1401ad0b25f38ceccd94008173576a5bc8f320"+ integrity sha512-yKEpcFuRPu/pTQL2VB8YKE2yFldrLlIsoWtJeBnAdqEhvu21OgkFT0C8njf/xYc2LSZGEr3K9JGjthHJxnVLvQ==+version "3.3.1"resolved "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz"@@ -5299,6 +5524,11 @@ lines-and-columns@^1.1.6:resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz"integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==+linkifyjs@^4.3.3:+ version "4.3.3"+ resolved "https://registry.yarnpkg.com/linkifyjs/-/linkifyjs-4.3.3.tgz#da08f0eeb4d89a24541d09591fbdcc211eb8fef0"+ integrity sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==+locate-path@^6.0.0:version "6.0.0"resolved "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz"@@ -6238,6 +6468,11 @@ ora@^8.2.0:string-width "^7.2.0"strip-ansi "^7.1.0"+orderedmap@^2.0.0:+ version "2.1.1"+ resolved "https://registry.yarnpkg.com/orderedmap/-/orderedmap-2.1.1.tgz#61481269c44031c449915497bf5a4ad273c512d2"+ integrity sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==+outvariant@^1.4.0, outvariant@^1.4.3:version "1.4.3"resolved "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz"@@ -6527,6 +6762,119 @@ property-information@^7.0.0:resolved "https://registry.yarnpkg.com/property-information/-/property-information-7.1.0.tgz#b622e8646e02b580205415586b40804d3e8bfd5d"integrity sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==+prosemirror-changeset@^2.4.1:+ version "2.4.4"+ resolved "https://registry.yarnpkg.com/prosemirror-changeset/-/prosemirror-changeset-2.4.4.tgz#406dc360110f16d4eebfb0c28abf72a84e51663e"+ integrity sha512-Gyuz9jYdrAeA9I7AholyOes9KUmv/lEwsC5O9s5xF5VB3EgTPsXMGUxz4+H1B+wKVPdZbvRcg1Cp3x8qX+8ofA==+ dependencies:+ prosemirror-transform "^1.0.0"++prosemirror-commands@^1.7.1:+ version "1.7.2"+ resolved "https://registry.yarnpkg.com/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz#cbef3b0d722dc51e71cc936c87c4ca27d81df3a6"+ integrity sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.10.2"++prosemirror-dropcursor@^1.8.2:+ version "1.8.4"+ resolved "https://registry.yarnpkg.com/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.4.tgz#cf570b932f993c897e8b0bdfda438ee208f9c535"+ integrity sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg==+ dependencies:+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.1.0"+ prosemirror-view "^1.1.0"++prosemirror-gapcursor@^1.4.1:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz#da33c905fece147df577342c06f4929b25d365ee"+ integrity sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==+ dependencies:+ prosemirror-keymap "^1.0.0"+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-view "^1.0.0"++prosemirror-history@^1.5.0:+ version "1.5.1"+ resolved "https://registry.yarnpkg.com/prosemirror-history/-/prosemirror-history-1.5.1.tgz#200fa741bc775c04a563d1208d0a0b4385f4efcb"+ integrity sha512-onlwnqKvgtFg6srZOmDOAhlAy1FIHQpOExORybX0S+DvJepE5tPALrB9iGet/2sqqqrelSnB10OoiOJqAvu2DA==+ dependencies:+ prosemirror-state "^1.2.2"+ prosemirror-transform "^1.0.0"+ prosemirror-view "^1.31.0"+ rope-sequence "^1.3.0"++prosemirror-inputrules@^1.5.1:+ version "1.5.1"+ resolved "https://registry.yarnpkg.com/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz#d2e935f6086e3801486b09222638f61dae89a570"+ integrity sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==+ dependencies:+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.0.0"++prosemirror-keymap@^1.0.0, prosemirror-keymap@^1.2.3:+ version "1.2.3"+ resolved "https://registry.yarnpkg.com/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz#c0f6ab95f75c0b82c97e44eb6aaf29cbfc150472"+ integrity sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==+ dependencies:+ prosemirror-state "^1.0.0"+ w3c-keyname "^2.2.0"++prosemirror-model@^1.0.0, prosemirror-model@^1.21.0, prosemirror-model@^1.25.11, prosemirror-model@^1.25.12, prosemirror-model@^1.25.4:+ version "1.25.12"+ resolved "https://registry.yarnpkg.com/prosemirror-model/-/prosemirror-model-1.25.12.tgz#00232836bf4f5bdfdfe8300d00706564515bfc28"+ integrity sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg==+ dependencies:+ orderedmap "^2.0.0"++prosemirror-schema-list@^1.5.1:+ version "1.5.1"+ resolved "https://registry.yarnpkg.com/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz#5869c8f749e8745c394548bb11820b0feb1e32f5"+ integrity sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.7.3"++prosemirror-state@^1.0.0, prosemirror-state@^1.2.2, prosemirror-state@^1.4.4:+ version "1.4.4"+ resolved "https://registry.yarnpkg.com/prosemirror-state/-/prosemirror-state-1.4.4.tgz#72b5e926f9e92dcee12b62a05fcc8a2de3bf5b39"+ integrity sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-transform "^1.0.0"+ prosemirror-view "^1.27.0"++prosemirror-tables@^1.8.5:+ version "1.8.5"+ resolved "https://registry.yarnpkg.com/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz#104427012e5a5da1d2a38c122efee8d66bdd5104"+ integrity sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==+ dependencies:+ prosemirror-keymap "^1.2.3"+ prosemirror-model "^1.25.4"+ prosemirror-state "^1.4.4"+ prosemirror-transform "^1.10.5"+ prosemirror-view "^1.41.4"++prosemirror-transform@^1.0.0, prosemirror-transform@^1.1.0, prosemirror-transform@^1.10.2, prosemirror-transform@^1.10.5, prosemirror-transform@^1.12.0, prosemirror-transform@^1.7.3:+ version "1.12.2"+ resolved "https://registry.yarnpkg.com/prosemirror-transform/-/prosemirror-transform-1.12.2.tgz#3c4291e8468f0d98941180245412f26974553a5b"+ integrity sha512-PE/aY0HEY4zczvmqrilgkUK/WautF0chvMqkmM/iN5/aPHvwrCWaQZjS6CIZp+K84YrvPFqrL+YArrfJX8xX7g==+ dependencies:+ prosemirror-model "^1.21.0"++prosemirror-view@^1.0.0, prosemirror-view@^1.1.0, prosemirror-view@^1.27.0, prosemirror-view@^1.31.0, prosemirror-view@^1.41.4, prosemirror-view@^1.42.3:+ version "1.42.6"+ resolved "https://registry.yarnpkg.com/prosemirror-view/-/prosemirror-view-1.42.6.tgz#d72d3ddafdc9c97db870f051f5cdd7c872eb53fc"+ integrity sha512-3g25f6hKV2bBxo3puH3EcYWmmVNSH0iWmNsMVT7sugDSpA025jgpOLarcDWr39SdzPjYMaiYtRdNtXialPSjEQ==+ dependencies:+ prosemirror-model "^1.25.12"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.1.0"+protobufjs@^7.3.0:version "7.5.8"resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-7.5.8.tgz#51b153a06da6e47153a1aa6800cb1253bc502436"@@ -6891,6 +7239,11 @@ rollup@^4.43.0:"@rollup/rollup-win32-x64-msvc" "4.61.1"fsevents "~2.3.2"+rope-sequence@^1.3.0:+ version "1.3.4"+ resolved "https://registry.yarnpkg.com/rope-sequence/-/rope-sequence-1.3.4.tgz#df85711aaecd32f1e756f76e43a415171235d425"+ integrity sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==+router@^2.2.0:version "2.2.0"resolved "https://registry.npmjs.org/router/-/router-2.2.0.tgz"@@ -8053,6 +8406,11 @@ vitest@^3.0.0:vite-node "3.2.4"why-is-node-running "^2.3.0"+w3c-keyname@^2.2.0:+ version "2.2.8"+ resolved "https://registry.yarnpkg.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz#7b17c8c6883d4e8b86ac8aba79d39e880f8869c5"+ integrity sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==+w3c-xmlserializer@^5.0.0:version "5.0.0"resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz#f925ba26855158594d907313cedd1476c5967f6c"