Skip to content

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.

feat(content): start a draft from New content and Start (#1286)

Cihancb8039a173b9
diff --git a/supabase/migrations/00206_content_draft_start.sql b/supabase/migrations/00206_content_draft_start.sql
new file mode 100644
index 000000000..f4d381f25
--- /dev/null
+++ b/supabase/migrations/00206_content_draft_start.sql
@@ -0,0 +1,105 @@
+-- ============================================================================
+-- 00206: what a draft was started for (Content Editor, CE-003 / CE-015)
+-- ============================================================================
+-- New content starts a draft from an opportunity, a tracked prompt or a
+-- topic, or from content to optimize (Content Editor spec v2 §5, §9). The
+-- draft keeps what it is for:
+--
+-- * opportunity_id: the Content Opportunity it was started from, if any.
+-- * prompt_ids: the tracked prompts the page should answer: the
+-- opportunity's, the one prompt picked, or a topic's active prompts. The
+-- overlap check, Impact and the brief read them.
+--
+-- Both must belong to the draft's brand: a check trigger turns away another
+-- brand's opportunity or prompts, which the foreign key alone would accept.
+-- It checks only the prompt ids a write adds, and a deleted prompt leaves
+-- every draft's prompt_ids (it has no foreign key to do that), so a draft
+-- that had one can still take more.
+
+alter table public.content_drafts
+ add column if not exists opportunity_id uuid
+ references public.content_opportunities(id) on delete set null,
+ add column if not exists prompt_ids uuid[] not null default '{}'
+ check (cardinality(prompt_ids) <= 500);
+
+comment on column public.content_drafts.opportunity_id is
+ 'Content Editor (CE-003): the Content Opportunity the draft was started from.';
+comment on column public.content_drafts.prompt_ids is
+ 'Content Editor (CE-003): the tracked prompts the page should answer.';
+
+create index if not exists content_drafts_opportunity_idx
+ on public.content_drafts (opportunity_id)
+ where opportunity_id is not null;
+
+-- Runs as the writer: a member sees only their organization's opportunities
+-- and prompts, so another brand's ids read as missing and are refused.
+create or replace function public.check_content_draft_links()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if new.opportunity_id is not null
+ and (tg_op = 'INSERT' or new.opportunity_id is distinct from old.opportunity_id)
+ and not exists (
+ select 1
+ from public.content_opportunities o
+ where o.id = new.opportunity_id and o.brand_id = new.brand_id
+ )
+ then
+ raise exception 'content draft opportunity belongs to another brand'
+ using errcode = '23514';
+ end if;
+
+ if cardinality(new.prompt_ids) > 0
+ and (tg_op = 'INSERT' or new.prompt_ids is distinct from old.prompt_ids)
+ and exists (
+ select 1
+ from unnest(new.prompt_ids) as wanted(id)
+ -- Only what this write adds: the ids already there were checked.
+ where wanted.id <> all(case when tg_op = 'UPDATE' then old.prompt_ids else '{}' end)
+ and not exists (
+ select 1
+ from public.prompts p
+ join public.prompt_sets s on s.id = p.prompt_set_id
+ where p.id = wanted.id and s.brand_id = new.brand_id
+ )
+ )
+ then
+ raise exception 'content draft prompt belongs to another brand'
+ using errcode = '23514';
+ end if;
+ return new;
+end;
+$$;
+
+create or replace trigger content_drafts_check_links
+ before insert or update on public.content_drafts
+ for each row execute function public.check_content_draft_links();
+
+-- A deleted prompt leaves the drafts that had it, in one update per delete
+-- statement (a topic's prompts go together). Definer: the drafts may be ones
+-- the deleting member can't write, and the deletion is theirs to make.
+create or replace function public.forget_deleted_draft_prompts()
+returns trigger
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_gone uuid[];
+begin
+ select coalesce(array_agg(id), '{}') into v_gone from deleted_prompts;
+ update public.content_drafts d
+ set prompt_ids = array(select x from unnest(d.prompt_ids) as x where x <> all(v_gone))
+ where d.prompt_ids && v_gone;
+ return null;
+end;
+$$;
+
+revoke execute on function public.forget_deleted_draft_prompts() from public, anon, authenticated;
+
+create or replace trigger prompts_forget_in_content_drafts
+ after delete on public.prompts
+ referencing old table as deleted_prompts
+ for each statement execute function public.forget_deleted_draft_prompts();
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8b0024f9f..14c9bb703 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -28825,3 +28825,112 @@ alter table public.content_drafts
comment on column public.content_drafts.page_type_source is
'Content Editor (CE-023): detected = page_type follows the page as it changes; user = a person picked it.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00206_content_draft_start.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00206: what a draft was started for (Content Editor, CE-003 / CE-015)
+-- ============================================================================
+-- New content starts a draft from an opportunity, a tracked prompt or a
+-- topic, or from content to optimize (Content Editor spec v2 §5, §9). The
+-- draft keeps what it is for:
+--
+-- * opportunity_id: the Content Opportunity it was started from, if any.
+-- * prompt_ids: the tracked prompts the page should answer: the
+-- opportunity's, the one prompt picked, or a topic's active prompts. The
+-- overlap check, Impact and the brief read them.
+--
+-- Both must belong to the draft's brand: a check trigger turns away another
+-- brand's opportunity or prompts, which the foreign key alone would accept.
+-- It checks only the prompt ids a write adds, and a deleted prompt leaves
+-- every draft's prompt_ids (it has no foreign key to do that), so a draft
+-- that had one can still take more.
+
+alter table public.content_drafts
+ add column if not exists opportunity_id uuid
+ references public.content_opportunities(id) on delete set null,
+ add column if not exists prompt_ids uuid[] not null default '{}'
+ check (cardinality(prompt_ids) <= 500);
+
+comment on column public.content_drafts.opportunity_id is
+ 'Content Editor (CE-003): the Content Opportunity the draft was started from.';
+comment on column public.content_drafts.prompt_ids is
+ 'Content Editor (CE-003): the tracked prompts the page should answer.';
+
+create index if not exists content_drafts_opportunity_idx
+ on public.content_drafts (opportunity_id)
+ where opportunity_id is not null;
+
+-- Runs as the writer: a member sees only their organization's opportunities
+-- and prompts, so another brand's ids read as missing and are refused.
+create or replace function public.check_content_draft_links()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if new.opportunity_id is not null
+ and (tg_op = 'INSERT' or new.opportunity_id is distinct from old.opportunity_id)
+ and not exists (
+ select 1
+ from public.content_opportunities o
+ where o.id = new.opportunity_id and o.brand_id = new.brand_id
+ )
+ then
+ raise exception 'content draft opportunity belongs to another brand'
+ using errcode = '23514';
+ end if;
+
+ if cardinality(new.prompt_ids) > 0
+ and (tg_op = 'INSERT' or new.prompt_ids is distinct from old.prompt_ids)
+ and exists (
+ select 1
+ from unnest(new.prompt_ids) as wanted(id)
+ -- Only what this write adds: the ids already there were checked.
+ where wanted.id <> all(case when tg_op = 'UPDATE' then old.prompt_ids else '{}' end)
+ and not exists (
+ select 1
+ from public.prompts p
+ join public.prompt_sets s on s.id = p.prompt_set_id
+ where p.id = wanted.id and s.brand_id = new.brand_id
+ )
+ )
+ then
+ raise exception 'content draft prompt belongs to another brand'
+ using errcode = '23514';
+ end if;
+ return new;
+end;
+$$;
+
+create or replace trigger content_drafts_check_links
+ before insert or update on public.content_drafts
+ for each row execute function public.check_content_draft_links();
+
+-- A deleted prompt leaves the drafts that had it, in one update per delete
+-- statement (a topic's prompts go together). Definer: the drafts may be ones
+-- the deleting member can't write, and the deletion is theirs to make.
+create or replace function public.forget_deleted_draft_prompts()
+returns trigger
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_gone uuid[];
+begin
+ select coalesce(array_agg(id), '{}') into v_gone from deleted_prompts;
+ update public.content_drafts d
+ set prompt_ids = array(select x from unnest(d.prompt_ids) as x where x <> all(v_gone))
+ where d.prompt_ids && v_gone;
+ return null;
+end;
+$$;
+
+revoke execute on function public.forget_deleted_draft_prompts() from public, anon, authenticated;
+
+create or replace trigger prompts_forget_in_content_drafts
+ after delete on public.prompts
+ referencing old table as deleted_prompts
+ for each statement execute function public.forget_deleted_draft_prompts();
+
diff --git a/web/messages/en.json b/web/messages/en.json
index a2ffda2ce..498f59bf2 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3103,8 +3103,76 @@
},
"loadError": "Couldn't load the Library.",
"retry": "Try again",
- "newContent": "New content",
- "createFailed": "Couldn't start a draft. Try again."
+ "newContent": "New content"
+ },
+ "newContent": {
+ "title": "New content",
+ "description": "Pick how you want to start.",
+ "methodLabel": "How to start",
+ "methods": {
+ "create": {
+ "title": "Create from scratch",
+ "hint": "From an opportunity, a prompt or a topic"
+ },
+ "optimize": {
+ "title": "Optimize content",
+ "hint": "Pasted text or a file"
+ }
+ },
+ "startFrom": "Start from",
+ "sources": {
+ "opportunity": {
+ "tab": "Opportunity",
+ "placeholder": "Pick an opportunity",
+ "search": "Search opportunities",
+ "empty": "No open opportunities."
+ },
+ "prompt": {
+ "tab": "Prompt",
+ "placeholder": "Pick a tracked prompt",
+ "search": "Search prompts",
+ "empty": "No tracked prompts."
+ },
+ "topic": {
+ "tab": "Topic",
+ "placeholder": "Pick a topic",
+ "search": "Search topics",
+ "empty": "No topics with tracked prompts."
+ }
+ },
+ "topicPrompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "loading": "Loading…",
+ "loadError": "Couldn't load what to start from.",
+ "retry": "Try again",
+ "content": {
+ "label": "Content",
+ "paste": "Paste text",
+ "file": "Upload file",
+ "pastePlaceholder": "Paste from Word, Google Docs or a web page. Headings, lists, links and tables are kept.",
+ "choose": "Choose a file or drop it here",
+ "fileHint": "Word, Markdown, HTML or text · up to 10 MB",
+ "summary": "{headings, plural, =0 {No headings} one {# heading} other {# headings}} · {characters} characters",
+ "imagesLeftOut": "{count, plural, one {# image} other {# images}} left out",
+ "clear": "Remove this content",
+ "empty": "There's no text in it to optimize.",
+ "tooLarge": "{name} is over 10 MB.",
+ "unsupported": "{name} isn't a file this reads: use Word, Markdown, HTML or text.",
+ "readFailed": "Couldn't read {name}."
+ },
+ "cancel": "Cancel",
+ "continue": "Continue",
+ "back": "Back",
+ "start": {
+ "titleCreate": "Create: {title}",
+ "titleOptimize": "Optimize: {title}",
+ "untitled": "Untitled",
+ "description": "Pick what kind of page this is. You can change it later in the editor.",
+ "pageType": "Page type",
+ "detectedTitle": "Picked from the title.",
+ "detectedContent": "Picked from the content.",
+ "openEditor": "Open editor",
+ "failed": "Couldn't start the draft. Try again."
+ }
},
"editor": {
"back": "Back to the Library",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_attach.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_attach.tsx
index ad2756aa7..9e7bb6eee 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_attach.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_attach.tsx
@@ -22,7 +22,6 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import { cleanHtml } from '@/lib/content/clean-html';
import {
ATTACHMENT_ACCEPT,
CONFIRM_TABLE_ROWS,
@@ -31,9 +30,9 @@ import {
rowsThatFit,
tableHtml,
tableRows,
- textToHtml,
} from '@/lib/content/attachments';
import { MAX_BODY_HTML_LENGTH } from '@/lib/content/editor';
+import { readDocumentFile } from '@/lib/content/import-document';
import { formatNumber } from '@/lib/format';
import { cellsToText, parseCsv } from '@/lib/prompt-import';
@@ -114,33 +113,17 @@ export function useAttachments(editor: Editor | null) {
else setQueue((q) => [...q, { name, sheets: [{ name, rows }] }]);
return;
}
- case 'markdown': {
- const { marked } = await import('marked');
- insert(cleanHtml(await marked.parse(await file.text()), { keepImages: true }).html, name);
- return;
- }
- case 'html': {
- const cleaned = cleanHtml(await file.text(), { keepImages: true });
- insert(
- cleaned.html,
- name,
- cleaned.unsafeRemoved ? t('unsafeRemoved', { count: cleaned.unsafeRemoved }) : undefined,
- );
- return;
- }
+ case 'markdown':
+ case 'html':
case 'text':
- insert(textToHtml(await file.text()), name);
- return;
case 'word': {
- const { default: mammoth } = await import('mammoth');
- const { value } = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
- // Word's images are embedded data: they wait for file storage.
- const cleaned = cleanHtml(value, { keepImages: false });
- insert(
- cleaned.html,
- name,
- cleaned.imagesRemoved ? t('imagesLeftOut', { count: cleaned.imagesRemoved }) : undefined,
- );
+ const doc = (await readDocumentFile(file))!;
+ const note = doc.unsafeRemoved
+ ? t('unsafeRemoved', { count: doc.unsafeRemoved })
+ : doc.imagesRemoved
+ ? t('imagesLeftOut', { count: doc.imagesRemoved })
+ : undefined;
+ insert(doc.html, name, note);
return;
}
case 'image':
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.tsx
index d3a88d369..996e0ace2 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,10 +7,11 @@ import type { ContentDraftListItem } from '@/lib/content/drafts';
import ContentLibraryPage from './page';
const getContentDrafts = vi.fn();
-const createContentDraft = vi.fn();
+const getContentStartOptions = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
getContentDrafts: (...args: unknown[]) => getContentDrafts(...args),
- createContentDraft: (...args: unknown[]) => createContentDraft(...args),
+ getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),
+ createContentDraft: vi.fn(),
}));
const push = vi.fn();
vi.mock('@/i18n/navigation', () => ({
@@ -23,7 +24,10 @@ vi.mock('@/i18n/navigation', () => ({
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('sonner', () => ({ toast }));
-const brandState = vi.hoisted(() => ({ activeBrandId: 'brand-1' as string | null }));
+const brandState = vi.hoisted(() => ({
+ activeBrandId: 'brand-1' as string | null,
+ brands: [{ id: 'brand-1', industry: 'Travel & Hospitality', shoppingModeEnabled: false }],
+}));
vi.mock('@/stores/use-brand-store', () => ({
useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),
}));
@@ -74,7 +78,11 @@ beforeEach(() => {
document.body.appendChild(container);
root = createRoot(container);
getContentDrafts.mockReset();
- createContentDraft.mockReset();
+ getContentStartOptions.mockReset().mockResolvedValue({
+ opportunities: [],
+ prompts: [],
+ topics: [],
+ });
push.mockReset();
toast.error.mockReset();
});
@@ -194,31 +202,16 @@ 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(() => {});
+ it('opens New content for the brand', async () => {
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(getContentStartOptions).toHaveBeenCalledWith('brand-1');
+ expect(document.body.textContent).toContain('Pick how you want to start.');
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 () => {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
index 1e0b6902c..7b7205448 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
@@ -2,21 +2,20 @@
import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
-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 { createContentDraft, getContentDrafts } from '@/lib/actions/content-drafts';
+import { NewContentDialog } from '@/components/content/new-content-dialog';
+import { getContentDrafts } from '@/lib/actions/content-drafts';
import {
LIBRARY_TABS,
- contentEditorPath,
draftsInTab,
libraryTabCounts,
type ContentDraftListItem,
type LibraryTab,
} from '@/lib/content/drafts';
+import { siteTypeOf } from '@/lib/content/page-types';
import { formatNumber } from '@/lib/format';
import { readUrlChoice, writeUrlParams } from '@/lib/url-state';
import { useBrandStore } from '@/stores/use-brand-store';
@@ -37,11 +36,11 @@ interface LibraryRead {
export default function ContentLibraryPage() {
const t = useTranslations('contentEditor.library');
const activeBrandId = useBrandStore((s) => s.activeBrandId);
+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));
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();
+ const [starting, setStarting] = useState(false);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
@@ -64,21 +63,6 @@ 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' });
@@ -104,11 +88,17 @@ export default function ContentLibraryPage() {
<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" />}
+ <Button className="gap-2" onClick={() => setStarting(true)}>
+ <Plus className="h-4 w-4" />
{t('newContent')}
</Button>
</div>
+ <NewContentDialog
+ open={starting}
+ onOpenChange={setStarting}
+ brandId={activeBrandId}
+ siteType={siteTypeOf(activeBrand ?? {})}
+ />
<Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>
<TabsList variant="line" aria-label={t('tabsLabel')}>
diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsx
new file mode 100644
index 000000000..f2ee10c0a
--- /dev/null
+++ b/web/src/components/content/new-content-dialog.test.tsx
@@ -0,0 +1,228 @@
+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 { SiteType } from '@/lib/content/page-types';
+import { NewContentDialog } from './new-content-dialog';
+
+const getContentStartOptions = vi.fn();
+const createContentDraft = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),
+ createContentDraft: (...args: unknown[]) => createContentDraft(...args),
+}));
+const push = vi.fn();
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// jsdom's files can't be read as text, as browsers' can.
+if (!('text' in Blob.prototype)) {
+ Object.assign(Blob.prototype, {
+ text(this: Blob) {
+ return new Promise<string>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.readAsText(this);
+ });
+ },
+ });
+}
+
+const OPTIONS = {
+ opportunities: [
+ { id: 'o1', title: 'Northwind vs HubSpot', decision: 'create', pageTitle: null },
+ {
+ id: 'o2',
+ title: 'Create a page for realtors',
+ decision: 'create',
+ pageTitle: 'CRM for real estate teams',
+ },
+ ],
+ prompts: [{ id: 'p1', text: 'best crm for realtors' }],
+ topics: [{ id: 't1', name: 'Real estate', promptCount: 3 }],
+};
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(siteType: SiteType = 'b2b') {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <NewContentDialog open onOpenChange={vi.fn()} brandId="b1" siteType={siteType} />
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const button = (name: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name || b.getAttribute('aria-label') === name,
+ );
+const radio = (name: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="radio"]')].find((r) =>
+ r.textContent?.startsWith(name),
+ )!;
+const click = async (el: Element | undefined) => {
+ await act(async () => {
+ el!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ (el as HTMLElement).click();
+ });
+};
+const checkedType = () =>
+ document.querySelector('[aria-labelledby="start-page-type"] [aria-checked="true"]')?.textContent;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getContentStartOptions.mockReset().mockResolvedValue(OPTIONS);
+ createContentDraft.mockReset().mockResolvedValue('d9');
+ push.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+});
+
+describe('New content', () => {
+ it('starts a new page from an opportunity, the page type picked from its title', async () => {
+ await render();
+ expect(getContentStartOptions).toHaveBeenCalledWith('b1');
+ expect(button('Continue')!.disabled).toBe(true);
+
+ await click(button('Pick an opportunity'));
+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (o) => o.textContent === 'Northwind vs HubSpot',
+ );
+ await click(option);
+ await click(button('Continue'));
+
+ expect(document.body.textContent).toContain('Create: Northwind vs HubSpot');
+ expect(checkedType()).toBe('Comparison');
+ expect(document.body.textContent).toContain('Picked from the title.');
+
+ await click(radio('Guide'));
+ expect(checkedType()).toBe('Guide');
+ await click(button('Open editor'));
+ expect(createContentDraft).toHaveBeenCalledWith('b1', {
+ method: 'create',
+ title: 'Northwind vs HubSpot',
+ pageType: 'guide',
+ // Picked, so it stays; Start's guess would follow the page.
+ typePicked: true,
+ source: { kind: 'opportunity', id: 'o1' },
+ bodyHtml: undefined,
+ });
+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d9');
+ });
+
+ it('names the page by the opportunity’s brief title when it has one', async () => {
+ await render();
+ await click(button('Pick an opportunity'));
+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (o) => o.textContent === 'Create a page for realtors',
+ );
+ await click(option);
+ await click(button('Continue'));
+ expect(document.body.textContent).toContain('Create: CRM for real estate teams');
+ expect(checkedType()).toBe('Solution page');
+ });
+
+ it('optimizes pasted content, cleaned, and reads its page type from it', async () => {
+ await render('ecommerce');
+ await click(radio('Optimize content'));
+ const box = document.querySelector('textarea')!;
+ const paste = new Event('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(paste, 'clipboardData', {
+ value: {
+ getData: (type: string) =>
+ type === 'text/html'
+ ? '<h2 style="color:red">Returns policy</h2><p>30 days.</p><script>x()</script>'
+ : '',
+ },
+ });
+ await act(async () => box.dispatchEvent(paste));
+
+ expect(document.body.textContent).toContain('Returns policy');
+ expect(document.body.textContent).toContain('1 heading · 23 characters');
+ await click(button('Continue'));
+ expect(document.body.textContent).toContain('Optimize: Returns policy');
+ expect(checkedType()).toBe('Policy');
+ expect(document.body.textContent).toContain('Picked from the content.');
+
+ await click(button('Open editor'));
+ expect(createContentDraft).toHaveBeenCalledWith('b1', {
+ method: 'optimize',
+ title: 'Returns policy',
+ pageType: 'policy',
+ typePicked: false,
+ source: { kind: 'content' },
+ bodyHtml: '<h2>Returns policy</h2><p>30 days.</p>',
+ });
+ });
+
+ it('takes typed plain text as paragraphs, and a blog post when nothing tells the type', async () => {
+ await render();
+ await click(radio('Optimize content'));
+ const box = document.querySelector('textarea')!;
+ const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setValue.call(box, 'Our onboarding checklist\n\nStep one.');
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await click(button('Continue'));
+ expect(checkedType()).toBe('Blog post');
+ expect(document.body.textContent).not.toContain('Picked from');
+ await click(button('Open editor'));
+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({
+ title: 'Our onboarding checklist',
+ bodyHtml: '<p>Our onboarding checklist</p><p>Step one.</p>',
+ });
+ });
+
+ it('reads an uploaded Markdown file, and refuses a spreadsheet', async () => {
+ await render();
+ await click(radio('Optimize content'));
+ await click(
+ [...document.querySelectorAll('[role="tab"]')].find((t) => t.textContent === 'Upload file'),
+ );
+ const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const upload = async (file: File) => {
+ Object.defineProperty(input, 'files', { value: [file], configurable: true });
+ await act(async () => input.dispatchEvent(new Event('change', { bubbles: true })));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
+ };
+
+ await upload(new File(['a,b'], 'keywords.csv'));
+ expect(toast.error).toHaveBeenCalledWith(
+ "keywords.csv isn't a file this reads: use Word, Markdown, HTML or text.",
+ );
+ await upload(new File(['# Pipeline forecasting\n\nTeams trust it.'], 'forecast.md'));
+ expect(document.body.textContent).toContain('Pipeline forecasting');
+ expect(document.body.textContent).toContain('forecast.md · 1 heading');
+ expect(button('Continue')!.disabled).toBe(false);
+ });
+
+ it('says so when what to start from can’t be read, and tries again', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getContentStartOptions.mockRejectedValueOnce(new Error('down'));
+ await render();
+ expect(document.body.textContent).toContain("Couldn't load what to start from.");
+ await click(button('Try again'));
+ expect(getContentStartOptions).toHaveBeenCalledTimes(2);
+ expect(button('Pick an opportunity')).toBeDefined();
+ });
+});
diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsx
new file mode 100644
index 000000000..61e434a28
--- /dev/null
+++ b/web/src/components/content/new-content-dialog.tsx
@@ -0,0 +1,540 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { ArrowLeft, FileText, Loader2, X } from 'lucide-react';
+import { useRouter } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import {
+ Combobox,
+ ComboboxCollection,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ ComboboxValue,
+} from '@/components/ui/combobox';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Label } from '@/components/ui/label';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { Textarea } from '@/components/ui/textarea';
+import { createContentDraft, getContentStartOptions } from '@/lib/actions/content-drafts';
+import { MAX_ATTACHMENT_BYTES, textToHtml } from '@/lib/content/attachments';
+import { cleanHtml } from '@/lib/content/clean-html';
+import {
+ contentEditorPath,
+ type DraftMethod,
+ type DraftSource,
+ type DraftStartOptions,
+ type PageType,
+} from '@/lib/content/drafts';
+import { DOCUMENT_ACCEPT, readDocumentFile } from '@/lib/content/import-document';
+import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';
+import {
+ fileTitle,
+ startPageType,
+ summarizeContent,
+ type ContentSummary,
+} from '@/lib/content/start';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+
+type SourceKind = 'opportunity' | 'prompt' | 'topic';
+const SOURCE_KINDS: SourceKind[] = ['opportunity', 'prompt', 'topic'];
+
+interface PickerItem {
+ value: string;
+ label: string;
+ meta?: string;
+ /** The page's title, when it isn't the label (an opportunity's brief title). */
+ pageTitle?: string;
+}
+
+/** Content brought to optimize: cleaned HTML, what it holds, and where it came from. */
+interface BroughtContent extends ContentSummary {
+ html: string;
+ /** The file's name; none for a paste. */
+ fileName?: string;
+ imagesRemoved: number;
+}
+
+/** What Start opens the editor with. */
+interface StartChoice {
+ method: DraftMethod;
+ title: string;
+ source: DraftSource;
+ bodyHtml?: string;
+ pageType: PageType;
+ detected: boolean;
+ /** The person picked the type from the chips. */
+ picked: boolean;
+}
+
+/**
+ * New content and Start (Content Editor CE-003, CE-015; spec §5, §9). First,
+ * how the page starts: a new page from an opportunity, a tracked prompt or a
+ * topic, or content to optimize, pasted or from a file. Then Start: the page
+ * type, picked first from what the title or content shows, and Open editor.
+ */
+export function NewContentDialog({
+ open,
+ onOpenChange,
+ brandId,
+ siteType,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ brandId: string;
+ siteType: SiteType;
+}) {
+ const t = useTranslations('contentEditor.newContent');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+ const router = useRouter();
+
+ const [options, setOptions] = useState<DraftStartOptions | null>(null);
+ const [optionsFailed, setOptionsFailed] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+
+ const [method, setMethod] = useState<DraftMethod>('create');
+ const [kind, setKind] = useState<SourceKind>('opportunity');
+ const [picked, setPicked] = useState<PickerItem | null>(null);
+ const [from, setFrom] = useState<'paste' | 'file'>('paste');
+ const [pastedText, setPastedText] = useState('');
+ const [content, setContent] = useState<BroughtContent | null>(null);
+ const [reading, setReading] = useState(false);
+ const [start, setStart] = useState<StartChoice | null>(null);
+ const [opening, setOpening] = useState(false);
+ const fileRef = useRef<HTMLInputElement>(null);
+
+ // Each opening starts over and reads what there is to start from.
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ getContentStartOptions(brandId)
+ .then((read) => {
+ if (cancelled) return;
+ setOptions(read);
+ setOptionsFailed(false);
+ })
+ .catch((err) => {
+ console.error('Failed to load what New content starts from:', err);
+ if (!cancelled) setOptionsFailed(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, brandId, attempt]);
+
+ const reset = () => {
+ setMethod('create');
+ setKind('opportunity');
+ setPicked(null);
+ setFrom('paste');
+ setPastedText('');
+ setContent(null);
+ setStart(null);
+ setOpening(false);
+ };
+ const changeOpen = (next: boolean) => {
+ if (!next) reset();
+ onOpenChange(next);
+ };
+
+ const items: PickerItem[] = !options
+ ? []
+ : kind === 'opportunity'
+ ? options.opportunities.map((o) => ({
+ value: o.id,
+ label: o.title,
+ pageTitle: o.pageTitle ?? undefined,
+ }))
+ : kind === 'prompt'
+ ? options.prompts.map((p) => ({ value: p.id, label: p.text }))
+ : options.topics.map((topic) => ({
+ value: topic.id,
+ label: topic.name,
+ meta: t('topicPrompts', { count: topic.promptCount }),
+ }));
+
+ const bring = (html: string, imagesRemoved: number, fileName?: string) => {
+ const summary = summarizeContent(html, fileName ? fileTitle(fileName) : '');
+ if (!summary.characters) {
+ toast.error(t('content.empty'));
+ return;
+ }
+ setContent({ ...summary, html, fileName, imagesRemoved });
+ };
+
+ const onPaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
+ const html = e.clipboardData.getData('text/html');
+ // Plain text goes into the box as typed text would; formatted text is
+ // cleaned like a paste in the editor and shown as what it holds.
+ if (!html) return;
+ e.preventDefault();
+ const cleaned = cleanHtml(html, { keepImages: false });
+ bring(cleaned.html, cleaned.imagesRemoved);
+ };
+
+ const readFile = async (file: File | undefined) => {
+ if (!file) return;
+ if (file.size > MAX_ATTACHMENT_BYTES) {
+ toast.error(t('content.tooLarge', { name: file.name }));
+ return;
+ }
+ setReading(true);
+ try {
+ const doc = await readDocumentFile(file);
+ if (!doc) toast.error(t('content.unsupported', { name: file.name }));
+ else bring(doc.html, doc.imagesRemoved, file.name);
+ } catch (err) {
+ console.error('Failed to read a file for New content:', err);
+ toast.error(t('content.readFailed', { name: file.name }));
+ } finally {
+ setReading(false);
+ }
+ };
+
+ const typed = pastedText.trim();
+ const canContinue =
+ method === 'create' ? picked !== null : content !== null || (from === 'paste' && !!typed);
+
+ const toStart = () => {
+ if (method === 'create') {
+ if (!picked) return;
+ const title = picked.pageTitle ?? picked.label;
+ const type = startPageType({ title }, siteType);
+ setStart({
+ method,
+ title,
+ source: { kind, id: picked.value },
+ ...type,
+ picked: false,
+ });
+ return;
+ }
+ const brought =
+ content ??
+ (typed ? { ...summarizeContent(textToHtml(typed)), html: textToHtml(typed) } : null);
+ if (!brought) return;
+ const type = startPageType({ title: brought.title, html: brought.html }, siteType);
+ setStart({
+ method,
+ title: brought.title,
+ source: { kind: 'content' },
+ bodyHtml: brought.html,
+ ...type,
+ picked: false,
+ });
+ };
+
+ const openEditor = async () => {
+ if (!start) return;
+ setOpening(true);
+ try {
+ const id = await createContentDraft(brandId, {
+ method: start.method,
+ title: start.title,
+ pageType: start.pageType,
+ typePicked: start.picked,
+ source: start.source,
+ bodyHtml: start.bodyHtml,
+ });
+ router.push(contentEditorPath(id));
+ } catch (err) {
+ console.error('Failed to start a draft:', err);
+ toast.error(t('start.failed'));
+ setOpening(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={changeOpen}>
+ <DialogContent className="sm:max-w-xl">
+ {start ? (
+ <>
+ <DialogHeader>
+ <DialogTitle className="truncate pr-8" title={start.title}>
+ {t(start.method === 'create' ? 'start.titleCreate' : 'start.titleOptimize', {
+ title: start.title || t('start.untitled'),
+ })}
+ </DialogTitle>
+ <DialogDescription>{t('start.description')}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label id="start-page-type">{t('start.pageType')}</Label>
+ <div
+ role="radiogroup"
+ aria-labelledby="start-page-type"
+ className="flex flex-wrap gap-1.5"
+ >
+ {SITE_PAGE_TYPES[siteType].map((type) => (
+ <ChoiceChip
+ key={type}
+ selected={start.pageType === type}
+ onSelect={() =>
+ setStart({ ...start, pageType: type, detected: false, picked: true })
+ }
+ >
+ {tTypes(type)}
+ </ChoiceChip>
+ ))}
+ </div>
+ {start.detected && (
+ <p className="text-xs text-muted-foreground">
+ {t(start.bodyHtml ? 'start.detectedContent' : 'start.detectedTitle')}
+ </p>
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setStart(null)} disabled={opening}>
+ <ArrowLeft className="h-4 w-4" />
+ {t('back')}
+ </Button>
+ <Button onClick={() => void openEditor()} disabled={opening}>
+ {opening && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t('start.openEditor')}
+ </Button>
+ </DialogFooter>
+ </>
+ ) : (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t('title')}</DialogTitle>
+ <DialogDescription>{t('description')}</DialogDescription>
+ </DialogHeader>
+
+ <div role="radiogroup" aria-label={t('methodLabel')} className="grid grid-cols-2 gap-2">
+ {(['create', 'optimize'] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ role="radio"
+ aria-checked={method === value}
+ onClick={() => setMethod(value)}
+ className={cn(
+ 'rounded-xl border px-3 py-2.5 text-left transition-colors hover:bg-muted/50',
+ method === value && 'border-foreground ring-1 ring-inset ring-foreground',
+ )}
+ >
+ <span className="block text-sm font-medium">{t(`methods.${value}.title`)}</span>
+ <span className="block text-xs text-muted-foreground">
+ {t(`methods.${value}.hint`)}
+ </span>
+ </button>
+ ))}
+ </div>
+
+ {method === 'create' ? (
+ <div className="space-y-2">
+ <Label>{t('startFrom')}</Label>
+ <Tabs
+ value={kind}
+ onValueChange={(value) => {
+ setKind(value as SourceKind);
+ setPicked(null);
+ }}
+ >
+ <TabsList>
+ {SOURCE_KINDS.map((value) => (
+ <TabsTrigger key={value} value={value}>
+ {t(`sources.${value}.tab`)}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ {optionsFailed ? (
+ <div className="flex items-center gap-2 text-xs text-destructive">
+ {t('loadError')}
+ <button
+ type="button"
+ className="font-medium underline"
+ onClick={() => setAttempt((n) => n + 1)}
+ >
+ {t('retry')}
+ </button>
+ </div>
+ ) : (
+ <Combobox
+ items={items}
+ value={picked}
+ onValueChange={(item: PickerItem | null) => setPicked(item)}
+ disabled={!options}
+ >
+ <ComboboxTrigger
+ className="w-full"
+ aria-label={t(`sources.${kind}.placeholder`)}
+ title={picked?.label}
+ >
+ {options ? (
+ <ComboboxValue placeholder={t(`sources.${kind}.placeholder`)} />
+ ) : (
+ <span className="flex items-center gap-2 text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t('loading')}
+ </span>
+ )}
+ </ComboboxTrigger>
+ <ComboboxContent>
+ <ComboboxInput placeholder={t(`sources.${kind}.search`)} />
+ <ComboboxList>
+ <ComboboxEmpty>{t(`sources.${kind}.empty`)}</ComboboxEmpty>
+ <ComboboxCollection>
+ {(item: PickerItem) => (
+ <ComboboxItem key={item.value} value={item} title={item.label}>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ {item.meta && (
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {item.meta}
+ </span>
+ )}
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <Label>{t('content.label')}</Label>
+ <Tabs
+ value={from}
+ onValueChange={(value) => {
+ setFrom(value as 'paste' | 'file');
+ setContent(null);
+ }}
+ >
+ <TabsList>
+ <TabsTrigger value="paste">{t('content.paste')}</TabsTrigger>
+ <TabsTrigger value="file">{t('content.file')}</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ {content ? (
+ <div className="flex items-start gap-3 rounded-lg border bg-muted/30 px-3 py-2.5">
+ <FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium" title={content.title}>
+ {content.title}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {[
+ content.fileName,
+ t('content.summary', {
+ headings: content.headings,
+ characters: formatNumber(content.characters),
+ }),
+ content.imagesRemoved
+ ? t('content.imagesLeftOut', { count: content.imagesRemoved })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('content.clear')}
+ title={t('content.clear')}
+ onClick={() => {
+ setContent(null);
+ setPastedText('');
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ) : from === 'paste' ? (
+ <Textarea
+ value={pastedText}
+ onChange={(e) => setPastedText(e.target.value)}
+ onPaste={onPaste}
+ rows={5}
+ aria-label={t('content.paste')}
+ placeholder={t('content.pastePlaceholder')}
+ />
+ ) : (
+ <>
+ <input
+ ref={fileRef}
+ type="file"
+ accept={DOCUMENT_ACCEPT}
+ className="hidden"
+ onChange={(e) => {
+ void readFile(e.target.files?.[0]);
+ e.target.value = '';
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => fileRef.current?.click()}
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ void readFile(e.dataTransfer.files[0]);
+ }}
+ disabled={reading}
+ className="flex w-full flex-col items-center gap-1 rounded-lg border border-dashed px-3 py-6 text-center text-sm transition-colors hover:bg-muted/50"
+ >
+ {reading ? (
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ ) : (
+ <span className="font-medium">{t('content.choose')}</span>
+ )}
+ <span className="text-xs text-muted-foreground">{t('content.fileHint')}</span>
+ </button>
+ </>
+ )}
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => changeOpen(false)}>
+ {t('cancel')}
+ </Button>
+ <Button onClick={toStart} disabled={!canContinue}>
+ {t('continue')}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ChoiceChip({
+ selected,
+ onSelect,
+ children,
+}: {
+ selected: boolean;
+ onSelect: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ 'rounded-lg border px-2.5 py-1 text-sm transition-colors hover:bg-muted/50',
+ selected && 'border-foreground font-medium ring-1 ring-inset ring-foreground',
+ )}
+ >
+ {children}
+ </button>
+ );
+}
diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.ts
new file mode 100644
index 000000000..b3462769d
--- /dev/null
+++ b/web/src/lib/actions/content-drafts-start.test.ts
@@ -0,0 +1,237 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { DraftStart } from '@/lib/content/drafts';
+
+/**
+ * New content and Start (CE-003, CE-015): what a page can start from, and
+ * the draft each start opens, with the prompts it should answer.
+ */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const OPPORTUNITY = '44444444-4444-4444-4444-444444444444';
+const PROMPT = '55555555-5555-5555-5555-555555555555';
+const TOPIC = '66666666-6666-6666-6666-666666666666';
+
+interface Call {
+ table: string;
+ op: string;
+ value?: unknown;
+ filters: [string, string, unknown][];
+}
+let calls: Call[];
+// What a read of each table returns: a row for maybeSingle, rows otherwise.
+let reads: Record<string, unknown>;
+
+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: (table: string) => {
+ const call: Call = { table, op: 'select', filters: [] };
+ calls.push(call);
+ const result = () =>
+ call.op === 'insert'
+ ? { data: { id: 'new-draft' }, error: null }
+ : { data: reads[table] ?? null, 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),
+ order: () => chain,
+ limit: () => chain,
+ insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),
+ maybeSingle: async () => result(),
+ single: async () => result(),
+ then: (resolve: (r: unknown) => void) => resolve(result()),
+ };
+ return chain;
+ },
+ })),
+}));
+
+const { createContentDraft, getContentStartOptions } = await import('./content-drafts');
+
+const inserted = () => calls.find((call) => call.op === 'insert')?.value as Record<string, unknown>;
+
+beforeEach(() => {
+ calls = [];
+ reads = {};
+});
+
+describe('getContentStartOptions', () => {
+ it('lists open opportunities, active prompts and the topics that have some', async () => {
+ reads = {
+ content_opportunities: [
+ {
+ id: OPPORTUNITY,
+ title: 'Create a CRM page for real estate',
+ decision: 'create',
+ brief: { suggestedTitle: ' CRM for real estate teams ' },
+ },
+ { id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', brief: null },
+ ],
+ prompts: [
+ { id: PROMPT, text: 'best crm for realtors', topic_id: TOPIC },
+ { id: 'p2', text: 'crm pricing', topic_id: null },
+ ],
+ topics: [
+ { id: TOPIC, name: 'Real estate' },
+ { id: 't2', name: 'Empty topic' },
+ ],
+ };
+ await expect(getContentStartOptions(BRAND)).resolves.toEqual({
+ opportunities: [
+ {
+ id: OPPORTUNITY,
+ title: 'Create a CRM page for real estate',
+ decision: 'create',
+ pageTitle: 'CRM for real estate teams',
+ },
+ { id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', pageTitle: null },
+ ],
+ prompts: [
+ { id: PROMPT, text: 'best crm for realtors' },
+ { id: 'p2', text: 'crm pricing' },
+ ],
+ topics: [{ id: TOPIC, name: 'Real estate', promptCount: 1 }],
+ });
+ expect(calls.find((call) => call.table === 'content_opportunities')!.filters).toEqual([
+ ['eq', 'brand_id', BRAND],
+ ['in', 'status', ['new', 'reviewed', 'sent', 'in_progress']],
+ ]);
+ expect(calls.find((call) => call.table === 'prompts')!.filters).toEqual([
+ ['eq', 'prompt_sets.brand_id', BRAND],
+ ['eq', 'is_active', true],
+ ]);
+ });
+});
+
+describe('createContentDraft', () => {
+ const start = (over: Partial<DraftStart> = {}): DraftStart => ({
+ method: 'create',
+ title: 'CRM for real estate teams',
+ pageType: 'solution_page',
+ source: { kind: 'opportunity', id: OPPORTUNITY },
+ ...over,
+ });
+
+ it('starts a new page from an opportunity, with its clusters’ prompts and the title as H1', async () => {
+ reads = {
+ content_opportunities: {
+ id: OPPORTUNITY,
+ prompt_id: null,
+ cluster_id: 'c1',
+ related_cluster_ids: ['c2'],
+ },
+ prompt_cluster_members: [{ prompt_id: PROMPT }, { prompt_id: 'p2' }, { prompt_id: PROMPT }],
+ };
+ await expect(createContentDraft(BRAND, start({ title: 'CRM <for> agents' }))).resolves.toBe(
+ 'new-draft',
+ );
+ expect(calls.find((call) => call.table === 'content_opportunities')!.filters).toEqual([
+ ['eq', 'id', OPPORTUNITY],
+ ['eq', 'brand_id', BRAND],
+ ]);
+ expect(calls.find((call) => call.table === 'prompt_cluster_members')!.filters).toEqual([
+ ['in', 'cluster_id', ['c1', 'c2']],
+ ]);
+ expect(inserted()).toEqual({
+ brand_id: BRAND,
+ created_by: 'u1',
+ method: 'create',
+ title: 'CRM <for> agents',
+ page_type: 'solution_page',
+ // Start's guess: it follows the page until someone picks a type.
+ page_type_source: 'detected',
+ body_html: '<h1>CRM &lt;for&gt; agents</h1>',
+ opportunity_id: OPPORTUNITY,
+ prompt_ids: [PROMPT, 'p2'],
+ });
+ });
+
+ it('keeps a type the person picked as theirs', async () => {
+ reads = {
+ content_opportunities: {
+ id: OPPORTUNITY,
+ prompt_id: PROMPT,
+ cluster_id: null,
+ related_cluster_ids: [],
+ },
+ };
+ await createContentDraft(BRAND, start({ typePicked: true }));
+ expect(inserted()).toMatchObject({ page_type: 'solution_page', page_type_source: 'user' });
+ });
+
+ it('takes the one prompt of an opportunity with no clusters', async () => {
+ reads = {
+ content_opportunities: {
+ id: OPPORTUNITY,
+ prompt_id: PROMPT,
+ cluster_id: null,
+ related_cluster_ids: [],
+ },
+ };
+ await createContentDraft(BRAND, start());
+ expect(calls.some((call) => call.table === 'prompt_cluster_members')).toBe(false);
+ expect(inserted()).toMatchObject({ opportunity_id: OPPORTUNITY, prompt_ids: [PROMPT] });
+ });
+
+ it('starts from a prompt of the brand’s, its long text cut to a title', async () => {
+ reads = { prompts: { id: PROMPT } };
+ await createContentDraft(
+ BRAND,
+ start({ title: `${'word '.repeat(80)}end`, source: { kind: 'prompt', id: PROMPT } }),
+ );
+ expect(calls[0]).toMatchObject({
+ table: 'prompts',
+ filters: [
+ ['eq', 'prompt_sets.brand_id', BRAND],
+ ['eq', 'id', PROMPT],
+ ],
+ });
+ const row = inserted();
+ expect((row.title as string).length).toBeLessThanOrEqual(300);
+ expect(row).toMatchObject({ opportunity_id: null, prompt_ids: [PROMPT] });
+ });
+
+ it('starts from a topic, with its active prompts', async () => {
+ reads = { prompts: [{ id: PROMPT }, { id: 'p2' }] };
+ await createContentDraft(BRAND, start({ source: { kind: 'topic', id: TOPIC } }));
+ expect(calls[0].filters).toEqual([
+ ['eq', 'prompt_sets.brand_id', BRAND],
+ ['eq', 'topic_id', TOPIC],
+ ['eq', 'is_active', true],
+ ]);
+ expect(inserted()).toMatchObject({ prompt_ids: [PROMPT, 'p2'] });
+ });
+
+ it('opens content to optimize as checked against the draft allow-list', async () => {
+ await createContentDraft(
+ BRAND,
+ start({
+ method: 'optimize',
+ title: 'Pricing',
+ pageType: 'pricing',
+ source: { kind: 'content' },
+ bodyHtml: '<h1>Pricing</h1><p onclick="x()">Plans</p><script>alert(1)</script>',
+ }),
+ );
+ expect(inserted()).toMatchObject({
+ method: 'optimize',
+ body_html: '<h1>Pricing</h1><p>Plans</p>',
+ opportunity_id: null,
+ prompt_ids: [],
+ });
+ });
+
+ it('writes nothing for a source the member can’t read, or a start that isn’t valid', async () => {
+ await expect(createContentDraft(BRAND, start())).rejects.toThrow('not_found');
+ await expect(
+ createContentDraft(BRAND, start({ source: { kind: 'topic', id: TOPIC } })),
+ ).rejects.toThrow('not_found');
+ await expect(
+ createContentDraft(BRAND, start({ pageType: 'landing' as DraftStart['pageType'] })),
+ ).rejects.toThrow('invalid');
+ await expect(createContentDraft('nope', start())).rejects.toThrow('invalid');
+ expect(calls.some((call) => call.op === 'insert')).toBe(false);
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index 827c2fe32..c9691bf28 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -46,13 +46,8 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const {
- createContentDraft,
- getContentDraft,
- markContentDraftReady,
- saveContentDraft,
- setContentDraftPageType,
-} = await import('./content-drafts');
+const { getContentDraft, markContentDraftReady, saveContentDraft, setContentDraftPageType } =
+ await import('./content-drafts');
const { bodyHash } = await import('@/lib/content/editor');
beforeEach(() => {
@@ -177,6 +172,21 @@ describe('the page type on save (CE-023)', () => {
});
});
+ it('keeps the type it had when the page shows none, as Start’s guess', async () => {
+ updated = {
+ updated_at: '2026-10-20T15:00:00Z',
+ page_type: 'blog_post',
+ page_type_source: 'detected',
+ brands: shop,
+ };
+ await saveContentDraft(DRAFT, {
+ title: 'Our spring update',
+ bodyHtml: '<h1>Our spring update</h1>',
+ base,
+ });
+ expect(calls.map((call) => call.op)).toEqual(['update']);
+ });
+
it('writes nothing more when the type is unchanged, or the person picked it', async () => {
updated = {
updated_at: '2026-10-20T15:00:00Z',
@@ -256,7 +266,7 @@ describe('markContentDraftReady', () => {
});
});
-describe('getContentDraft and createContentDraft', () => {
+describe('getContentDraft', () => {
it('opens a draft with its brand’s site type, chosen or guessed', async () => {
const base = {
id: DRAFT,
@@ -290,9 +300,4 @@ describe('getContentDraft and createContentDraft', () => {
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.ts
index 855e97572..75df83934 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -9,9 +9,12 @@ import {
type ContentDraft,
type ContentDraftListItem,
type DraftMethod,
+ type DraftStart,
+ type DraftStartOptions,
type DraftStatus,
type PageType,
} from '@/lib/content/drafts';
+import { escapeHtml } from '@/lib/content/attachments';
import {
MAX_BODY_HTML_LENGTH,
MAX_TITLE_LENGTH,
@@ -121,20 +124,178 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
};
}
+/** Opportunities still open to write for, the highest scored first. */
+const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];
+
+/** How many of each New content lists to pick from. */
+const START_LIMIT = 500;
+
/**
- * 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.
+ * What New content (CE-003) offers to start a new page from: the brand's
+ * open Content Opportunities, its active tracked prompts and its topics.
*/
-export async function createContentDraft(brandId: string): Promise<string> {
+export async function getContentStartOptions(brandId: string): Promise<DraftStartOptions> {
+ const supabase = await createClient();
+ const [opportunities, prompts, topics] = await Promise.all([
+ supabase
+ .from('content_opportunities')
+ .select('id, title, decision, brief')
+ .eq('brand_id', brandId)
+ .in('status', OPEN_OPPORTUNITY_STATUSES)
+ .order('opportunity_score', { ascending: false, nullsFirst: false })
+ .limit(START_LIMIT),
+ supabase
+ .from('prompts')
+ .select('id, text, topic_id, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .eq('is_active', true)
+ .order('text')
+ .limit(START_LIMIT),
+ supabase
+ .from('topics')
+ .select('id, name')
+ .eq('brand_id', brandId)
+ .eq('is_active', true)
+ .order('name'),
+ ]);
+ const failed = opportunities.error ?? prompts.error ?? topics.error;
+ if (failed) throw new Error(failed.message);
+
+ const perTopic = new Map<string, number>();
+ for (const p of prompts.data ?? []) {
+ if (p.topic_id) perTopic.set(p.topic_id, (perTopic.get(p.topic_id) ?? 0) + 1);
+ }
+ return {
+ opportunities: (opportunities.data ?? []).map((o) => {
+ const suggested = (o.brief as { suggestedTitle?: unknown } | null)?.suggestedTitle;
+ return {
+ id: o.id,
+ title: o.title,
+ decision: o.decision,
+ pageTitle: typeof suggested === 'string' && suggested.trim() ? suggested.trim() : null,
+ };
+ }),
+ prompts: (prompts.data ?? []).map((p) => ({ id: p.id, text: p.text })),
+ // A topic with no active prompt has nothing for a page to answer.
+ topics: (topics.data ?? [])
+ .map((topic) => ({
+ id: topic.id,
+ name: topic.name,
+ promptCount: perTopic.get(topic.id) ?? 0,
+ }))
+ .filter((topic) => topic.promptCount > 0),
+ };
+}
+
+const startInput = z.object({
+ method: z.enum(['create', 'optimize']),
+ // A prompt's text can run longer than a title: cut to fit, not refused.
+ title: z.string().max(5_000),
+ pageType: z.enum(PAGE_TYPES),
+ typePicked: z.boolean().default(false),
+ source: z.discriminatedUnion('kind', [
+ z.object({ kind: z.enum(['opportunity', 'prompt', 'topic']), id: z.guid() }),
+ z.object({ kind: z.literal('content') }),
+ ]),
+ bodyHtml: z.string().max(MAX_BODY_HTML_LENGTH).optional(),
+});
+
+/** The most prompt ids a draft keeps (00206). */
+const MAX_DRAFT_PROMPTS = 500;
+
+/**
+ * The tracked prompts a page started from this source should answer: an
+ * opportunity's (its clusters', or its one prompt), the prompt picked, or a
+ * topic's active prompts. Throws 'not_found' for one the member can't read.
+ */
+async function promptsFor(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ source: DraftStart['source'],
+): Promise<{ promptIds: string[]; opportunityId: string | null }> {
+ if (source.kind === 'content') return { promptIds: [], opportunityId: null };
+
+ if (source.kind === 'opportunity') {
+ const { data, error } = await supabase
+ .from('content_opportunities')
+ .select('id, prompt_id, cluster_id, related_cluster_ids')
+ .eq('id', source.id)
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ const clusterIds = [data.cluster_id, ...(data.related_cluster_ids ?? [])].filter(
+ (id): id is string => typeof id === 'string',
+ );
+ if (!clusterIds.length) {
+ return { promptIds: data.prompt_id ? [data.prompt_id] : [], opportunityId: data.id };
+ }
+ const members = await supabase
+ .from('prompt_cluster_members')
+ .select('prompt_id')
+ .in('cluster_id', clusterIds)
+ .limit(MAX_DRAFT_PROMPTS);
+ if (members.error) throw new Error(members.error.message);
+ return { promptIds: (members.data ?? []).map((m) => m.prompt_id), opportunityId: data.id };
+ }
+
+ const query = supabase
+ .from('prompts')
+ .select('id, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId);
+ if (source.kind === 'prompt') {
+ const { data, error } = await query.eq('id', source.id).maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ return { promptIds: [data.id], opportunityId: null };
+ }
+ const { data, error } = await query
+ .eq('topic_id', source.id)
+ .eq('is_active', true)
+ .limit(MAX_DRAFT_PROMPTS);
+ if (error) throw new Error(error.message);
+ if (!data?.length) throw new Error('not_found');
+ return { promptIds: data.map((p) => p.id), opportunityId: null };
+}
+
+/**
+ * A draft started from New content and Start (CE-003, CE-015), by the
+ * signed-in member: its page type, what it is for, and its first text. A new
+ * page starts with its title as the H1; content to optimize is checked
+ * against the draft allow-list, as a save is. A type the person picked stays;
+ * Start's guess is stored as detected, so it follows the page (CE-023).
+ */
+export async function createContentDraft(brandId: string, start: DraftStart): Promise<string> {
+ const parsed = startInput.safeParse(start);
+ if (!draftId.safeParse(brandId).success || !parsed.success) throw new Error('invalid');
+ const { method, pageType, typePicked, source, bodyHtml } = parsed.data;
+ const title = parsed.data.title.trim().slice(0, MAX_TITLE_LENGTH).trim();
+
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) throw new Error('unauthorized');
+ const { promptIds, opportunityId } = await promptsFor(supabase, brandId, source);
+
const { data, error } = await supabase
.from('content_drafts')
- .insert({ brand_id: brandId, created_by: user.id })
+ .insert({
+ brand_id: brandId,
+ created_by: user.id,
+ method,
+ title,
+ page_type: pageType,
+ page_type_source: typePicked ? 'user' : 'detected',
+ body_html:
+ method === 'optimize'
+ ? sanitizeDraftHtml(bodyHtml ?? '')
+ : title
+ ? `<h1>${escapeHtml(title)}</h1>`
+ : '',
+ opportunity_id: opportunityId,
+ prompt_ids: [...new Set(promptIds)].slice(0, MAX_DRAFT_PROMPTS),
+ })
.select('id')
.single();
if (error) throw new Error(error.message);
@@ -194,7 +355,8 @@ export async function saveContentDraft(
let updatedAt: string = data.updated_at;
if (data.page_type_source === 'detected') {
const detected = detectPageType({ title, html: bodyHtml }, brandSiteType(data.brands));
- if (detected !== data.page_type) {
+ // A page that shows no type keeps the one it had (Start's guess).
+ if (detected && detected !== data.page_type) {
const { data: typed, error: typeError } = await supabase
.from('content_drafts')
.update({ page_type: detected })
diff --git a/web/src/lib/content/attachments.ts b/web/src/lib/content/attachments.ts
index 7829855b5..f8c074370 100644
--- a/web/src/lib/content/attachments.ts
+++ b/web/src/lib/content/attachments.ts
@@ -55,7 +55,8 @@ export function attachmentKind(fileName: string): AttachmentKind {
/** What the file picker offers. */
export const ATTACHMENT_ACCEPT = '.xlsx,.csv,.md,.markdown,.html,.htm,.txt,.docx';
-function escapeHtml(text: string) {
+/** Text safe to put in HTML. */
+export function escapeHtml(text: string) {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 8d37024e7..4d3e2676e 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -100,6 +100,37 @@ export interface ContentDraft {
updatedAt: string;
}
+/**
+ * What New content starts a page from (CE-003): an opportunity, a tracked
+ * prompt or a topic for a new page, or content to optimize.
+ */
+export type DraftSource =
+ | { kind: 'opportunity' | 'prompt' | 'topic'; id: string }
+ | { kind: 'content' };
+
+/** A draft as Start opens it (CE-015). */
+export interface DraftStart {
+ method: DraftMethod;
+ title: string;
+ pageType: PageType;
+ /** The person picked the type; otherwise it was Start's guess, and follows the page. */
+ typePicked?: boolean;
+ source: DraftSource;
+ /** The content to optimize, as HTML. */
+ bodyHtml?: string;
+}
+
+/** What New content offers to start a page from. */
+export interface DraftStartOptions {
+ /**
+ * pageTitle: the page title its brief suggests, once one is generated;
+ * the opportunity's own title says what to do, not what to call the page.
+ */
+ opportunities: { id: string; title: string; decision: string | null; pageTitle: string | null }[];
+ prompts: { id: string; text: string }[];
+ topics: { id: string; name: string; promptCount: number }[];
+}
+
export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {
return tab === 'all' ? drafts : drafts.filter((d) => d.status === tab);
}
diff --git a/web/src/lib/content/import-document.ts b/web/src/lib/content/import-document.ts
new file mode 100644
index 000000000..4deed5c30
--- /dev/null
+++ b/web/src/lib/content/import-document.ts
@@ -0,0 +1,44 @@
+import { attachmentKind, textToHtml } from './attachments';
+import { cleanHtml } from './clean-html';
+
+/** A document file as page content, and what its cleaning took out. */
+export interface ImportedDocument {
+ html: string;
+ /** Scripts and other unsafe tags removed from an HTML file. */
+ unsafeRemoved: number;
+ /** Images left out of a Word file: they wait for file storage. */
+ imagesRemoved: number;
+}
+
+/** The file kinds read as page content (not spreadsheets or images). */
+export const DOCUMENT_ACCEPT = '.docx,.md,.markdown,.html,.htm,.txt';
+
+/**
+ * A Markdown, HTML, Word (.docx) or text file as page content, cleaned like a
+ * paste (CE-006); null for any other kind. The Markdown and Word readers load
+ * on demand: they are only needed when someone brings a file.
+ */
+export async function readDocumentFile(file: File): Promise<ImportedDocument | null> {
+ switch (attachmentKind(file.name)) {
+ case 'markdown': {
+ const { marked } = await import('marked');
+ const cleaned = cleanHtml(await marked.parse(await file.text()), { keepImages: true });
+ return { html: cleaned.html, unsafeRemoved: 0, imagesRemoved: 0 };
+ }
+ case 'html': {
+ const cleaned = cleanHtml(await file.text(), { keepImages: true });
+ return { html: cleaned.html, unsafeRemoved: cleaned.unsafeRemoved, imagesRemoved: 0 };
+ }
+ case 'text':
+ return { html: textToHtml(await file.text()), unsafeRemoved: 0, imagesRemoved: 0 };
+ case 'word': {
+ const { default: mammoth } = await import('mammoth');
+ const { value } = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
+ // Word's images are embedded data: they wait for file storage.
+ const cleaned = cleanHtml(value, { keepImages: false });
+ return { html: cleaned.html, unsafeRemoved: 0, imagesRemoved: cleaned.imagesRemoved };
+ }
+ default:
+ return null;
+ }
+}
diff --git a/web/src/lib/content/start.test.ts b/web/src/lib/content/start.test.ts
new file mode 100644
index 000000000..aec2f6897
--- /dev/null
+++ b/web/src/lib/content/start.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import { fileTitle, startPageType, summarizeContent } from './start';
+
+describe('summarizeContent', () => {
+ it('names content by its first heading, and counts headings and text', () => {
+ expect(
+ summarizeContent('<p>Intro</p><h2>Returns policy</h2><p>30 days.</p><h3>Refunds</h3>'),
+ ).toEqual({
+ title: 'Returns policy',
+ headings: 2,
+ characters: 'Intro Returns policy 30 days. Refunds'.length,
+ });
+ });
+
+ it('falls back to the file’s name, then the first paragraph, cut at a word', () => {
+ expect(summarizeContent('<p>Plans start at $9.</p>', 'Pricing notes').title).toBe(
+ 'Pricing notes',
+ );
+ expect(summarizeContent('<p>Short one</p><p>Next</p>').title).toBe('Short one');
+ const long = summarizeContent(`<p>${'word '.repeat(30)}</p>`).title;
+ expect(long.endsWith('word…')).toBe(true);
+ expect(long.length).toBeLessThanOrEqual(81);
+ });
+
+ it('keeps words from running together across blocks', () => {
+ expect(summarizeContent('<p>One</p><ul><li>two</li><li>three</li></ul>').characters).toBe(
+ 'One two three'.length,
+ );
+ });
+});
+
+describe('fileTitle', () => {
+ it('drops the extension', () => {
+ expect(fileTitle('Q3 brief.docx')).toBe('Q3 brief');
+ expect(fileTitle('notes')).toBe('notes');
+ });
+});
+
+describe('startPageType', () => {
+ it('picks the type the title or content shows, else a blog post', () => {
+ expect(startPageType({ title: 'Northwind vs HubSpot' }, 'b2b')).toEqual({
+ pageType: 'comparison',
+ detected: true,
+ });
+ expect(
+ startPageType(
+ {
+ title: 'Trail Runner X',
+ html: '<script type="application/ld+json">{"@type":"Product"}</script>',
+ },
+ 'ecommerce',
+ ),
+ ).toEqual({ pageType: 'product_page', detected: true });
+ expect(startPageType({ title: 'Our story' }, 'b2c')).toEqual({
+ pageType: 'blog_post',
+ detected: false,
+ });
+ });
+});
diff --git a/web/src/lib/content/start.ts b/web/src/lib/content/start.ts
new file mode 100644
index 000000000..3ace5ff4b
--- /dev/null
+++ b/web/src/lib/content/start.ts
@@ -0,0 +1,61 @@
+import type { PageType } from './drafts';
+import { SITE_PAGE_TYPES, detectPageType, type SiteType } from './page-types';
+
+/** Content brought to optimize, as New content shows it before the editor. */
+export interface ContentSummary {
+ /** Its first heading, or what stands in for one. */
+ title: string;
+ headings: number;
+ characters: number;
+}
+
+/** Elements that end a line of text: their words don't run into the next. */
+const BLOCKS = 'p, h1, h2, h3, h4, h5, h6, li, td, th, blockquote, div, br';
+
+/**
+ * What pasted or uploaded content holds (CE-003): its title (the first
+ * heading, else the file's name, else its first paragraph), how many
+ * headings and how much text. Read in the browser, from HTML already cleaned.
+ */
+export function summarizeContent(html: string, fallbackTitle = ''): ContentSummary {
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const textOf = (el: Element | null) => (el?.textContent ?? '').replace(/\s+/g, ' ').trim();
+ const heading = textOf(doc.querySelector('h1, h2, h3'));
+ const firstBlock = textOf(doc.querySelector('p, li, td, blockquote'));
+ for (const block of doc.body.querySelectorAll(BLOCKS)) block.append(' ');
+ const text = textOf(doc.body);
+ return {
+ title: heading || fallbackTitle || openingWords(firstBlock || text),
+ headings: doc.querySelectorAll('h1, h2, h3').length,
+ characters: text.length,
+ };
+}
+
+/** The first words of a text, cut at a word near 80 characters. */
+function openingWords(text: string, max = 80): string {
+ if (text.length <= max) return text;
+ const cut = text.slice(0, max);
+ const space = cut.lastIndexOf(' ');
+ return `${space > 40 ? cut.slice(0, space) : cut}…`;
+}
+
+/** "Q3 brief.docx" → "Q3 brief". */
+export function fileTitle(name: string): string {
+ return name.replace(/\.[a-z0-9]+$/i, '').trim();
+}
+
+/**
+ * The page type Start picks first (CE-015): the one the title or content
+ * shows, else a blog post, which every kind of site writes.
+ */
+export function startPageType(
+ page: { title: string; html?: string },
+ siteType: SiteType,
+): { pageType: PageType; detected: boolean } {
+ const detected = detectPageType(page, siteType);
+ if (detected) return { pageType: detected, detected: true };
+ const fallback: PageType = SITE_PAGE_TYPES[siteType].includes('blog_post')
+ ? 'blog_post'
+ : SITE_PAGE_TYPES[siteType][0];
+ return { pageType: fallback, detected: false };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 8a0bdb226..81f900103 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -834,8 +834,10 @@ export type Database = {
created_by: string | null
id: string
method: string
+ opportunity_id: string | null
page_type: string | null
page_type_source: string
+ prompt_ids: string[]
score_after: number | null
score_before: number | null
status: string
@@ -850,8 +852,10 @@ export type Database = {
created_by?: string | null
id?: string
method?: string
+ opportunity_id?: string | null
page_type?: string | null
page_type_source?: string
+ prompt_ids?: string[]
score_after?: number | null
score_before?: number | null
status?: string
@@ -866,8 +870,10 @@ export type Database = {
created_by?: string | null
id?: string
method?: string
+ opportunity_id?: string | null
page_type?: string | null
page_type_source?: string
+ prompt_ids?: string[]
score_after?: number | null
score_before?: number | null
status?: string
@@ -875,6 +881,13 @@ export type Database = {
updated_at?: string
}
Relationships: [
+ {
+ foreignKeyName: "content_drafts_opportunity_id_fkey"
+ columns: ["opportunity_id"]
+ isOneToOne: false
+ referencedRelation: "content_opportunities"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "content_drafts_brand_id_fkey"
columns: ["brand_id"]
@@ -895,12 +908,15 @@ export type Database = {
Row: {
brand_id: string
brief: Json | null
+ cluster_id: string | null
created_at: string | null
+ decision: string | null
description: string | null
id: string
impact: string
opportunity_score: number | null
prompt_id: string | null
+ related_cluster_ids: string[]
source_data: Json | null
status: string
title: string
@@ -912,12 +928,15 @@ export type Database = {
Insert: {
brand_id: string
brief?: Json | null
+ cluster_id?: string | null
created_at?: string | null
+ decision?: string | null
description?: string | null
id?: string
impact?: string
opportunity_score?: number | null
prompt_id?: string | null
+ related_cluster_ids?: string[]
source_data?: Json | null
status?: string
title: string
@@ -929,12 +948,15 @@ export type Database = {
Update: {
brand_id?: string
brief?: Json | null
+ cluster_id?: string | null
created_at?: string | null
+ decision?: string | null
description?: string | null
id?: string
impact?: string
opportunity_score?: number | null
prompt_id?: string | null
+ related_cluster_ids?: string[]
source_data?: Json | null
status?: string
title?: string
@@ -1915,6 +1937,29 @@ export type Database = {
},
]
}
+ prompt_cluster_members: {
+ Row: {
+ cluster_id: string
+ prompt_id: string
+ }
+ Insert: {
+ cluster_id: string
+ prompt_id: string
+ }
+ Update: {
+ cluster_id?: string
+ prompt_id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "prompt_cluster_members_prompt_id_fkey"
+ columns: ["prompt_id"]
+ isOneToOne: true
+ referencedRelation: "prompts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
prompt_notes: {
Row: {
author_id: string | null