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): export the Library as CSV, Excel or Word, by tab and creation date (#1354)

Cihan0879185d59ee
diff --git a/web/messages/en.json b/web/messages/en.json
index 09f461168..64cf421ff 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3211,6 +3211,22 @@
"failed": "Agent failed"
},
"library": {
+ "export": {
+ "button": "Export",
+ "hint": "Download the drafts listed here, with their pages",
+ "csv": "Export CSV",
+ "xlsx": "Export Excel",
+ "docx": "Export Word",
+ "failed": "Couldn't export. Try again."
+ },
+ "created": {
+ "label": "Created",
+ "all": "Any time",
+ "7d": "Last 7 days",
+ "30d": "Last 30 days",
+ "90d": "Last 90 days",
+ "empty": "Nothing in this tab was created in this period."
+ },
"title": "Library",
"description": "Everything you and the agents wrote or changed.",
"selectBrand": "Select a brand to see its content.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-export.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-export.tsx
new file mode 100644
index 000000000..a63d98ed5
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-export.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { ChevronDown, Download, FileSpreadsheet, FileText, FileType, Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { BYTE_ORDER_MARK } from '@/lib/action-center/export';
+import { assigneeLabel } from '@/lib/action-center/display';
+import { getContentDraftPages, type DraftPage } from '@/lib/actions/content-drafts';
+import { publishableHtml } from '@/lib/content/clean-html';
+import {
+ draftExportBlob,
+ draftExportFileName,
+ libraryCsv,
+ libraryDocx,
+ libraryExportFileName,
+ libraryWorkbook,
+ type DraftExportFormat,
+ type LibraryExportFormat,
+ type LibraryExportItem,
+} from '@/lib/content/draft-export';
+import type { ContentDraftListItem, LibraryTab } from '@/lib/content/drafts';
+import { saveBlob } from '@/lib/download';
+
+/**
+ * The Library's Export (CE-002): the drafts listed (the tab, within the
+ * Created range) with their pages, as CSV, an Excel sheet or one Word
+ * document; and one draft from its row, as the editor's Export does.
+ */
+export function useLibraryExport(brandId: string | null) {
+ const t = useTranslations('contentEditor.library');
+ const tStatus = useTranslations('contentEditor.status');
+ const tMethod = useTranslations('contentEditor.method');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+ const [exporting, setExporting] = useState(false);
+
+ const titleOf = (draft: ContentDraftListItem) => draft.title.trim() || t('untitled');
+ const item = (draft: ContentDraftListItem, page: DraftPage): LibraryExportItem => ({
+ title: titleOf(draft),
+ status: tStatus(draft.status),
+ method: tMethod(draft.method),
+ pageType: draft.pageType
+ ? tTypes.has(draft.pageType)
+ ? tTypes(draft.pageType)
+ : draft.pageType
+ : '',
+ author:
+ draft.author === 'agent'
+ ? t('contentAgent')
+ : ((draft.createdBy && assigneeLabel(draft.createdBy)) ?? t('formerMember')),
+ createdAt: draft.createdAt,
+ updatedAt: draft.updatedAt,
+ url: page.sourceUrl,
+ html: publishableHtml(page.bodyHtml),
+ });
+
+ const exportList = async (
+ drafts: ContentDraftListItem[],
+ tab: LibraryTab,
+ format: LibraryExportFormat,
+ ) => {
+ if (!brandId || drafts.length === 0) return;
+ setExporting(true);
+ try {
+ const pages = new Map(
+ (
+ await getContentDraftPages(
+ brandId,
+ drafts.map((d) => d.id),
+ )
+ ).map((p) => [p.id, p]),
+ );
+ const items = drafts.flatMap((draft) => {
+ const page = pages.get(draft.id);
+ return page ? [item(draft, page)] : [];
+ });
+ const fileName = libraryExportFileName(tab, format, new Date());
+ if (format === 'csv') {
+ saveBlob(
+ new Blob([BYTE_ORDER_MARK, libraryCsv(items)], { type: 'text/csv;charset=utf-8;' }),
+ fileName,
+ );
+ } else if (format === 'xlsx') {
+ // Loaded on the click: the library is only needed to write the file.
+ const { default: writeXlsxFile } = await import('write-excel-file/browser');
+ await writeXlsxFile(libraryWorkbook(items)).toFile(fileName);
+ } else {
+ saveBlob(await libraryDocx(items), fileName);
+ }
+ } catch (err) {
+ console.error('Failed to export the Library:', err);
+ toast.error(t('export.failed'));
+ } finally {
+ setExporting(false);
+ }
+ };
+
+ const exportDraft = async (draft: ContentDraftListItem, format: DraftExportFormat) => {
+ if (!brandId) return;
+ try {
+ const [page] = await getContentDraftPages(brandId, [draft.id]);
+ if (!page) throw new Error('not_found');
+ const title = titleOf(draft);
+ saveBlob(
+ await draftExportBlob(format, title, publishableHtml(page.bodyHtml)),
+ draftExportFileName(title, format),
+ );
+ } catch (err) {
+ console.error('Failed to export the draft:', err);
+ toast.error(t('export.failed'));
+ }
+ };
+
+ return { exporting, exportList, exportDraft };
+}
+
+const FORMATS = [
+ { format: 'csv', icon: FileText },
+ { format: 'xlsx', icon: FileSpreadsheet },
+ { format: 'docx', icon: FileType },
+] as const satisfies readonly { format: LibraryExportFormat; icon: unknown }[];
+
+/** Export in the Library's header: the drafts listed, as CSV, Excel or Word. */
+export function LibraryExportMenu({
+ disabled,
+ exporting,
+ onExport,
+}: {
+ disabled: boolean;
+ exporting: boolean;
+ onExport: (format: LibraryExportFormat) => void;
+}) {
+ const t = useTranslations('contentEditor.library.export');
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<Button variant="outline" className="gap-2" />}
+ disabled={disabled || exporting}
+ title={t('hint')}
+ >
+ {exporting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Download className="h-4 w-4" />
+ )}
+ {t('button')}
+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ {FORMATS.map(({ format, icon: Icon }) => (
+ <DropdownMenuItem key={format} className="gap-2" onClick={() => onExport(format)}>
+ <Icon className="h-3.5 w-3.5" />
+ {t(format)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx
index 01e907e98..0868ab776 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx
@@ -6,6 +6,7 @@ import {
ArchiveRestore,
Bot,
Check,
+ Download,
FileText,
MoreHorizontal,
Trash2,
@@ -44,6 +45,7 @@ import {
type DraftStatus,
type LibraryTab,
} from '@/lib/content/drafts';
+import type { DraftExportFormat } from '@/lib/content/draft-export';
import { formatDate, formatMonthDay } from '@/lib/format';
/** A date this year as "Oct 16", an older one with its year, so the table fits at 1024 px. */
@@ -59,6 +61,8 @@ export interface LibraryRowActions {
onStatus: (draft: ContentDraftListItem, status: DraftStatus) => void;
onArchive: (draft: ContentDraftListItem, archived: boolean) => void;
onDelete: (draft: ContentDraftListItem) => void;
+ /** The draft's page as Word, HTML or Markdown, as the editor's Export. */
+ onExport: (draft: ContentDraftListItem, format: DraftExportFormat) => void;
}
/**
@@ -169,6 +173,7 @@ export function LibraryTable({
function RowMenu({ draft, actions }: { draft: ContentDraftListItem; actions: LibraryRowActions }) {
const t = useTranslations('contentEditor.library.rowMenu');
const tStatus = useTranslations('contentEditor.status');
+ const tExport = useTranslations('contentEditor.editor.export');
const title = draft.title.trim() || null;
return (
<DropdownMenu>
@@ -195,6 +200,13 @@ function RowMenu({ draft, actions }: { draft: ContentDraftListItem; actions: Lib
</DropdownMenuItem>
))}
</DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ {(['docx', 'html', 'md'] as const).map((format) => (
+ <DropdownMenuItem key={format} onClick={() => actions.onExport(draft, format)}>
+ <Download className="h-4 w-4" />
+ {tExport(format)}
+ </DropdownMenuItem>
+ ))}
{actions.canManage && (
<>
<DropdownMenuSeparator />
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 69428e59b..43ab36f9f 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
@@ -12,7 +12,9 @@ const markContentDraftReady = vi.fn();
const setContentDraftStatus = vi.fn();
const archiveContentDraft = vi.fn();
const deleteContentDraft = vi.fn();
+const getContentDraftPages = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ getContentDraftPages: (...args: unknown[]) => getContentDraftPages(...args),
// A list stands for a brand under the cap: its tabs count its rows.
getContentDrafts: async (...args: unknown[]) => {
const read = await getContentDrafts(...args);
@@ -41,6 +43,16 @@ vi.mock('@/i18n/navigation', () => ({
}));
const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));
vi.mock('sonner', () => ({ toast }));
+const saveBlob = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/download', () => ({ saveBlob }));
+
+/** jsdom's Blob has no text(): read it as a browser's FileReader would. */
+const readText = (blob: Blob) =>
+ new Promise<string>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.readAsText(blob);
+ });
const brandState = vi.hoisted(() => ({
activeBrandId: 'brand-1' as string | null,
brands: [{ id: 'brand-1', industry: 'Travel & Hospitality', shoppingModeEnabled: false }],
@@ -110,6 +122,15 @@ beforeEach(() => {
setContentDraftStatus.mockReset().mockResolvedValue(undefined);
archiveContentDraft.mockReset().mockResolvedValue(undefined);
deleteContentDraft.mockReset().mockResolvedValue(undefined);
+ getContentDraftPages.mockReset().mockImplementation(async (_brand: string, ids: string[]) =>
+ ids.map((id) => ({
+ id,
+ title: 'Pipeline forecasting',
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',
+ sourceUrl: 'https://acme.example/pricing',
+ })),
+ );
+ saveBlob.mockReset();
role.canManage = true;
});
@@ -323,6 +344,9 @@ describe('a Library row’s menu (00233)', () => {
'In review',
'Ready',
'Published',
+ 'Export Word',
+ 'Export HTML',
+ 'Export Markdown',
'Send to Archive',
'Delete',
]);
@@ -346,6 +370,9 @@ describe('a Library row’s menu (00233)', () => {
'In review',
'Ready',
'Published',
+ 'Export Word',
+ 'Export HTML',
+ 'Export Markdown',
]);
});
@@ -400,6 +427,17 @@ describe('a Library row’s menu (00233)', () => {
);
});
+ it('exports one draft’s page, as the editor’s Export', async () => {
+ getContentDrafts.mockResolvedValue([row({})]);
+ await renderPage();
+ await pick('Pipeline forecasting', 'Export Markdown');
+ await act(async () => {});
+ expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['d1']);
+ const [blob, name] = saveBlob.mock.calls[0] as [Blob, string];
+ expect(name).toBe('ansvisor_content_pipeline-forecasting.md');
+ expect(await readText(blob)).toBe('# Pipeline forecasting\n\nTeams trust it.\n');
+ });
+
it('says so when the server refuses the archive', async () => {
archiveContentDraft.mockRejectedValue(new Error('forbidden'));
getContentDrafts.mockResolvedValue([row({})]);
@@ -410,3 +448,70 @@ describe('a Library row’s menu (00233)', () => {
);
});
});
+
+describe('the Library’s Export and Created filter (CE-002)', () => {
+ const openExport = async () => {
+ const trigger = [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === 'Export',
+ )!;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ return [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ };
+
+ it('exports the drafts listed, with their pages, as CSV', async () => {
+ getContentDrafts.mockResolvedValue([
+ row({}),
+ row({ id: 'd2', title: 'Churn guide', author: 'agent', status: 'ready' }),
+ ]);
+ await renderPage();
+ const items = await openExport();
+ expect(items.map((el) => el.textContent)).toEqual([
+ 'Export CSV',
+ 'Export Excel',
+ 'Export Word',
+ ]);
+ await act(async () => items[0].click());
+ await act(async () => {});
+
+ expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['d1', 'd2']);
+ const [blob, name] = saveBlob.mock.calls[0] as [Blob, string];
+ expect(name).toMatch(/^ansvisor_content_library_all_\d{4}-\d{2}-\d{2}\.csv$/);
+ const csv = await readText(blob);
+ expect(csv).toContain(
+ 'Pipeline forecasting,In review,Optimize,Feature page,Ada Lovelace,2026-10-18',
+ );
+ expect(csv).toContain('Churn guide,Ready,Optimize,Feature page,Content Agent');
+ expect(csv).toContain('Teams trust it.');
+ });
+
+ it('lists only the drafts created in the range the URL names, and exports those', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?created=7d');
+ const recent = new Date(Date.now() - 2 * 86_400_000).toISOString();
+ getContentDrafts.mockResolvedValue([
+ row({ id: 'new', title: 'Fresh page', createdAt: recent }),
+ row({ id: 'old', title: 'Old page', createdAt: '2026-01-05T09:00:00Z' }),
+ ]);
+ await renderPage();
+ expect(container.textContent).toContain('Fresh page');
+ expect(container.textContent).not.toContain('Old page');
+
+ const items = await openExport();
+ await act(async () => items[0].click());
+ await act(async () => {});
+ expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['new']);
+ });
+
+ it('says when nothing in the tab was created in the range', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?created=30d');
+ getContentDrafts.mockResolvedValue([row({ createdAt: '2026-01-05T09:00:00Z' })]);
+ await renderPage();
+ expect(container.textContent).toContain('Nothing in this tab was created in this period.');
+ const exportButton = [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === 'Export',
+ )!;
+ expect(exportButton.disabled).toBe(true);
+ });
+});
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 8f04207f6..7e1871aca 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
@@ -14,6 +14,13 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { NewContentDialog } from '@/components/content/new-content-dialog';
import { useUserRole } from '@/hooks/use-user-role';
@@ -26,9 +33,12 @@ import {
} from '@/lib/actions/content-drafts';
import {
AGENT_POLL_MS,
+ CREATED_RANGES,
LIBRARY_TABS,
+ draftsCreatedIn,
draftsInTab,
type ContentDraftListItem,
+ type CreatedRange,
type DraftStatus,
type LibraryTab,
} from '@/lib/content/drafts';
@@ -36,6 +46,7 @@ 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';
+import { LibraryExportMenu, useLibraryExport } from './_library-export';
import { LibraryTable, type LibraryRowActions } from './_library-table';
/** A read of the brand's drafts: null until it comes back. */
@@ -59,6 +70,8 @@ export default function ContentLibraryPage() {
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));
const [tab, setTab] = useState<LibraryTab>('all');
+ // When the drafts listed (and exported) were created: ?created=30d.
+ const [created, setCreated] = useState<CreatedRange>('all');
const [read, setRead] = useState<LibraryRead | null>(null);
const [attempt, setAttempt] = useState(0);
const [starting, setStarting] = useState(false);
@@ -70,7 +83,9 @@ export default function ContentLibraryPage() {
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
setTab(readUrlChoice('tab', LIBRARY_TABS, 'all'));
+ setCreated(readUrlChoice('created', CREATED_RANGES, 'all'));
}, []);
+ const { exporting, exportList, exportDraft } = useLibraryExport(activeBrandId);
useEffect(() => {
if (!activeBrandId) return;
@@ -140,6 +155,7 @@ export default function ContentLibraryPage() {
},
onArchive: (draft, archived) => void archive(draft, archived),
onDelete: setDeleting,
+ onExport: (draft, format) => void exportDraft(draft, format),
};
const confirmDelete = async () => {
@@ -160,6 +176,10 @@ export default function ContentLibraryPage() {
setTab(next);
writeUrlParams({ tab: next }, { tab: 'all' });
};
+ const changeCreated = (next: CreatedRange) => {
+ setCreated(next);
+ writeUrlParams({ created: next }, { created: 'all' });
+ };
if (!activeBrandId) {
return (
@@ -173,7 +193,8 @@ export default function ContentLibraryPage() {
const current = read?.brandId === activeBrandId ? read : null;
const drafts = current?.drafts ?? null;
const counts = current?.counts ?? null;
- const listed = drafts ? draftsInTab(drafts, tab) : [];
+ const inTab = drafts ? draftsInTab(drafts, tab) : [];
+ const listed = draftsCreatedIn(inTab, created);
return (
<div className="space-y-6">
@@ -182,10 +203,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={() => setStarting(true)}>
- <Plus className="h-4 w-4" />
- {t('newContent')}
- </Button>
+ <div className="flex items-center gap-2">
+ <LibraryExportMenu
+ disabled={listed.length === 0}
+ exporting={exporting}
+ onExport={(format) => void exportList(listed, tab, format)}
+ />
+ <Button className="gap-2" onClick={() => setStarting(true)}>
+ <Plus className="h-4 w-4" />
+ {t('newContent')}
+ </Button>
+ </div>
</div>
<NewContentDialog
open={starting}
@@ -195,16 +223,38 @@ export default function ContentLibraryPage() {
onSent={() => setAttempt((n) => n + 1)}
/>
- <Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>
- <TabsList variant="line" aria-label={t('tabsLabel')}>
- {LIBRARY_TABS.map((id) => (
- <TabsTrigger key={id} value={id}>
- {t(`tabs.${id}`)}
- {counts && <TabCount count={counts[id]} />}
- </TabsTrigger>
- ))}
- </TabsList>
- </Tabs>
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>
+ <TabsList variant="line" aria-label={t('tabsLabel')}>
+ {LIBRARY_TABS.map((id) => (
+ <TabsTrigger key={id} value={id}>
+ {t(`tabs.${id}`)}
+ {counts && <TabCount count={counts[id]} />}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ <Select
+ value={created}
+ onValueChange={(value) => changeCreated(value as CreatedRange)}
+ items={CREATED_RANGES.map((range) => ({
+ value: range,
+ label: `${t('created.label')}: ${t(`created.${range}`)}`,
+ }))}
+ >
+ {/* On the tabs' line when it fits, else on its own, on the right. */}
+ <SelectTrigger size="sm" className="ml-auto" aria-label={t('created.label')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {CREATED_RANGES.map((range) => (
+ <SelectItem key={range} value={range}>
+ {t(`created.${range}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
<Card className="py-0">
<CardContent className="px-0">
@@ -226,6 +276,10 @@ export default function ContentLibraryPage() {
<div className="flex items-center justify-center py-12" aria-busy="true">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
+ ) : listed.length === 0 && inTab.length > 0 ? (
+ <p className="px-6 py-12 text-center text-sm text-muted-foreground">
+ {t('created.empty')}
+ </p>
) : (
<LibraryTable drafts={listed} tab={tab} actions={rowActions} />
)}
@@ -253,7 +307,7 @@ export default function ContentLibraryPage() {
</DialogFooter>
</DialogContent>
</Dialog>
- {counts && listed.length < counts[tab] && (
+ {counts && created === 'all' && listed.length < counts[tab] && (
<p className="text-xs text-muted-foreground">
{t('latestOnly', {
shown: formatNumber(listed.length),
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 0b694451e..fee72ccf2 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -241,6 +241,54 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
};
}
+/** A draft's page, for the Library's Export. */
+export interface DraftPage {
+ id: string;
+ title: string;
+ bodyHtml: string;
+ sourceUrl: string | null;
+}
+
+/** Ids read at a time: the list goes in the request's address. */
+const PAGES_PER_READ = 100;
+
+/**
+ * The Library's Export (CE-002): the stored page of each draft given, of the
+ * brand, in the order given; at most the Library's own count. A draft gone
+ * meanwhile is left out.
+ */
+export async function getContentDraftPages(brandId: string, ids: string[]): Promise<DraftPage[]> {
+ const parsed = z.array(z.guid()).max(LIBRARY_LIMIT).safeParse(ids);
+ if (!draftId.safeParse(brandId).success || !parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const chunks = [];
+ for (let i = 0; i < parsed.data.length; i += PAGES_PER_READ) {
+ chunks.push(parsed.data.slice(i, i + PAGES_PER_READ));
+ }
+ const reads = await Promise.all(
+ chunks.map((chunk) =>
+ supabase
+ .from('content_drafts')
+ .select('id, title, body_html, source_url')
+ .eq('brand_id', brandId)
+ .in('id', chunk),
+ ),
+ );
+ const byId = new Map<string, DraftPage>();
+ for (const { data, error } of reads) {
+ if (error) throw new Error(error.message);
+ for (const row of data ?? []) {
+ byId.set(row.id, {
+ id: row.id,
+ title: row.title,
+ bodyHtml: row.body_html,
+ sourceUrl: row.source_url,
+ });
+ }
+ }
+ return parsed.data.flatMap((id) => byId.get(id) ?? []);
+}
+
/** Opportunities still open to write for, the highest scored first. */
const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];
diff --git a/web/src/lib/content/draft-export.test.ts b/web/src/lib/content/draft-export.test.ts
index 2981cfdde..f449a2716 100644
--- a/web/src/lib/content/draft-export.test.ts
+++ b/web/src/lib/content/draft-export.test.ts
@@ -7,6 +7,13 @@ import {
draftExportFileName,
draftHtmlDocument,
draftMarkdown,
+ draftText,
+ libraryCsv,
+ libraryDocx,
+ libraryExportFileName,
+ libraryRows,
+ libraryWorkbook,
+ type LibraryExportItem,
} from './draft-export';
// The page as Copy HTML gives it: one block per line, an HTML block as its
@@ -169,3 +176,85 @@ describe('draftExportBlob and draftExportFileName', () => {
expect(draftExportFileName('—', 'md')).toBe('ansvisor_content_page.md');
});
});
+
+describe('the Library’s Export', () => {
+ const item = (over: Partial<LibraryExportItem> = {}): LibraryExportItem => ({
+ title: 'Pipeline forecasting',
+ status: 'In review',
+ method: 'Optimize',
+ pageType: 'Blog post',
+ author: 'Content Agent',
+ createdAt: '2026-10-20T09:00:00Z',
+ updatedAt: '2026-10-21T15:30:00Z',
+ url: 'https://acme.example/blog/forecasting',
+ html: '<h1>Pipeline forecasting</h1><p>Teams <strong>trust</strong> it.</p><ol><li>Import</li><li>Stage</li></ol>',
+ ...over,
+ });
+
+ it('reads a page as text, a block a line', () => {
+ expect(draftText('T', PAGE)).toBe(
+ [
+ 'Pipeline forecasting',
+ 'Teams trust it, every week. See our pricing.',
+ 'How it works',
+ '- Weighted stages',
+ ' - By deal size',
+ '- Rep calls',
+ '1. Import deals',
+ '2. Set the stages',
+ '> It saved us a week.',
+ 'Plan | Price',
+ 'Starter | $49 | month',
+ 'Free for 14 days',
+ ].join('\n'),
+ );
+ });
+
+ it('writes one row a draft, in the header’s order, with its page’s text', () => {
+ const csv = libraryCsv([item()]);
+ const [header, row] = csv.split('\n');
+ expect(header).toBe(
+ 'Title,Status,Method,Page type,By,Created,Updated,Page URL,Characters,Content',
+ );
+ expect(row).toContain(
+ 'Pipeline forecasting,In review,Optimize,Blog post,Content Agent,2026-10-20,2026-10-21,https://acme.example/blog/forecasting,',
+ );
+ expect(libraryRows([item()])[0]).toMatchObject({
+ Characters: 'Pipeline forecastingTeams trust it.1. Import2. Stage'.length,
+ Content: 'Pipeline forecasting\nTeams trust it.\n1. Import\n2. Stage',
+ });
+ });
+
+ it('cuts a page past a spreadsheet cell’s limit', () => {
+ const long = `<h1>T</h1><p>${'a'.repeat(40_000)}</p>`;
+ const [{ data }] = libraryWorkbook([item({ html: long })]);
+ const content = data[1][9] as string;
+ expect(content).toHaveLength(32_767);
+ expect(content.endsWith('…')).toBe(true);
+ });
+
+ it('puts every draft in one Word document, each on its own page', async () => {
+ const files = unzipSync(
+ await read(
+ await libraryDocx([
+ item(),
+ item({ title: 'Churn', html: '<h1>Churn</h1><ol><li>One</li></ol>' }),
+ ]),
+ ),
+ );
+ const xml = strFromU8(files['word/document.xml']);
+ expect(xml).toContain('In review · Optimize · Blog post · Updated 2026-10-21');
+ expect(xml).toContain('Churn');
+ // Two sections: the second starts a new page.
+ expect(xml.match(/<w:sectPr/g)).toHaveLength(2);
+ // Each draft's numbered list counts on its own.
+ const numbering = strFromU8(files['word/numbering.xml']);
+ expect(numbering.match(/<w:num w:numId=/g)!.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('names the file by tab and day', () => {
+ expect(libraryExportFileName('in_review', 'xlsx', new Date('2026-10-22T10:00:00Z'))).toBe(
+ 'ansvisor_content_library_in-review_2026-10-22.xlsx',
+ );
+ });
+});
diff --git a/web/src/lib/content/draft-export.ts b/web/src/lib/content/draft-export.ts
index 74744b892..f4c93b079 100644
--- a/web/src/lib/content/draft-export.ts
+++ b/web/src/lib/content/draft-export.ts
@@ -1,3 +1,5 @@
+import type { Sheet } from 'write-excel-file/browser';
+import { toCsv } from '@/lib/csv';
import { slugify } from '@/lib/slug';
import { safeLinkHref } from './editor';
@@ -160,9 +162,14 @@ const text = (runs: DraftRun[]) => runs.map((r) => (r.break ? '\n' : r.text)).jo
* The page as blocks. A page without an H1 opens with its title as one, so
* the file says what it is.
*/
-export function draftBlocks(title: string, html: string): DraftBlock[] {
+export function draftBlocks(
+ title: string,
+ html: string,
+ /** Shared by pages that go in one file, so each list numbers on its own. */
+ counter: { lists: number } = { lists: 0 },
+): DraftBlock[] {
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
- const blocks = blocksIn(doc.body, { lists: 0 });
+ const blocks = blocksIn(doc.body, counter);
const hasTitle = blocks.some((b) => b.kind === 'heading' && b.level === 1);
return hasTitle || !title.trim()
? blocks
@@ -246,59 +253,46 @@ export function draftMarkdown(title: string, html: string): string {
return `${parts.join('')}\n`;
}
-/** Export Word: the blocks as a document, the lists numbered and bulleted as on the page. */
-export async function draftDocx(title: string, html: string): Promise<Blob> {
- // Loaded on the click: the library is only needed to write the file.
- const {
- AlignmentType,
- Document,
- ExternalHyperlink,
- HeadingLevel,
- LevelFormat,
- Packer,
- Paragraph,
- Table,
- TableCell,
- TableRow,
- TextRun,
- WidthType,
- } = await import('docx');
- const blocks = draftBlocks(title, html);
+type Docx = typeof import('docx');
+type DocxChild = InstanceType<Docx['Paragraph']> | InstanceType<Docx['Table']>;
+
+/** The blocks as Word paragraphs and tables, the lists numbered and bulleted as on the page. */
+function docxBlocks(m: Docx, blocks: DraftBlock[]): DocxChild[] {
const HEADING = {
- 1: HeadingLevel.HEADING_1,
- 2: HeadingLevel.HEADING_2,
- 3: HeadingLevel.HEADING_3,
+ 1: m.HeadingLevel.HEADING_1,
+ 2: m.HeadingLevel.HEADING_2,
+ 3: m.HeadingLevel.HEADING_3,
} as const;
const children = (runs: DraftRun[], extra: { bold?: boolean; italics?: boolean } = {}) =>
runs.map((run) => {
- if (run.break) return new TextRun({ text: '', break: 1 });
- const textRun = new TextRun({
+ if (run.break) return new m.TextRun({ text: '', break: 1 });
+ const textRun = new m.TextRun({
text: run.text,
bold: run.bold || extra.bold,
italics: run.italics || extra.italics,
...(run.link ? { style: 'Hyperlink' } : {}),
});
- return run.link ? new ExternalHyperlink({ link: run.link, children: [textRun] }) : textRun;
+ return run.link ? new m.ExternalHyperlink({ link: run.link, children: [textRun] }) : textRun;
});
- const content = (
- list: DraftBlock[],
- ): (InstanceType<typeof Paragraph> | InstanceType<typeof Table>)[] =>
+ const content = (list: DraftBlock[]): DocxChild[] =>
list.flatMap((block) => {
switch (block.kind) {
case 'heading':
- return [new Paragraph({ heading: HEADING[block.level], children: children(block.runs) })];
+ return [
+ new m.Paragraph({ heading: HEADING[block.level], children: children(block.runs) }),
+ ];
case 'paragraph':
- return [new Paragraph({ children: children(block.runs) })];
+ return [new m.Paragraph({ children: children(block.runs) })];
case 'quote':
return block.paragraphs.map(
(p) =>
- new Paragraph({ indent: { left: 720 }, children: children(p, { italics: true }) }),
+ new m.Paragraph({ indent: { left: 720 }, children: children(p, { italics: true }) }),
);
case 'item':
return [
- new Paragraph({
+ new m.Paragraph({
children: children(block.runs),
...(block.ordered
? { numbering: { reference: 'numbered', level: block.level, instance: block.list } }
@@ -307,17 +301,17 @@ export async function draftDocx(title: string, html: string): Promise<Blob> {
];
case 'table':
return [
- new Table({
- width: { size: 100, type: WidthType.PERCENTAGE },
+ new m.Table({
+ width: { size: 100, type: m.WidthType.PERCENTAGE },
rows: block.rows.map(
(row) =>
- new TableRow({
+ new m.TableRow({
tableHeader: row.header,
children: row.cells.map(
(cell) =>
- new TableCell({
+ new m.TableCell({
children: [
- new Paragraph({ children: children(cell, { bold: row.header }) }),
+ new m.Paragraph({ children: children(cell, { bold: row.header }) }),
],
}),
),
@@ -329,26 +323,38 @@ export async function draftDocx(title: string, html: string): Promise<Blob> {
return content(block.blocks);
}
});
+ return content(blocks);
+}
- const document = new Document({
- title: title.trim() || text(blocks.find((b) => b.kind === 'heading')?.runs ?? []),
+/** A Word document of sections, each starting on a page of its own, with the lists' numbering. */
+function docxDocument(m: Docx, title: string, sections: DocxChild[][]) {
+ return new m.Document({
+ title,
numbering: {
config: [
{
reference: 'numbered',
levels: [0, 1, 2, 3].map((level) => ({
level,
- format: LevelFormat.DECIMAL,
+ format: m.LevelFormat.DECIMAL,
text: `%${level + 1}.`,
- alignment: AlignmentType.START,
+ alignment: m.AlignmentType.START,
style: { paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } } },
})),
},
],
},
- sections: [{ children: content(blocks) }],
+ sections: sections.map((children) => ({ children })),
});
- return Packer.toBlob(document);
+}
+
+/** Export Word: the blocks as a document, the lists numbered and bulleted as on the page. */
+export async function draftDocx(title: string, html: string): Promise<Blob> {
+ // Loaded on the click: the library is only needed to write the file.
+ const m = await import('docx');
+ const blocks = draftBlocks(title, html);
+ const name = title.trim() || text(blocks.find((b) => b.kind === 'heading')?.runs ?? []);
+ return m.Packer.toBlob(docxDocument(m, name, [docxBlocks(m, blocks)]));
}
/** The file for a format: Word built on the click, HTML and Markdown as UTF-8 text. */
@@ -368,3 +374,170 @@ export function draftExportFileName(title: string, format: DraftExportFormat): s
const slug = slugify(title).slice(0, 60).replace(/-+$/, '') || 'page';
return `ansvisor_content_${slug}.${format}`;
}
+
+// ─── The Library's Export (CE-002) ──────────────────────────────────────────
+
+export type LibraryExportFormat = 'csv' | 'xlsx' | 'docx';
+
+/** A draft as the Library's Export writes it: its labels as the Library shows them. */
+export interface LibraryExportItem {
+ title: string;
+ status: string;
+ method: string;
+ pageType: string;
+ author: string;
+ createdAt: string;
+ updatedAt: string;
+ /** The live page an optimize draft is for. */
+ url: string | null;
+ /** The page as Copy HTML gives it. */
+ html: string;
+}
+
+/** The CSV's and the sheet's header. */
+export const LIBRARY_EXPORT_HEADERS = [
+ 'Title',
+ 'Status',
+ 'Method',
+ 'Page type',
+ 'By',
+ 'Created',
+ 'Updated',
+ 'Page URL',
+ 'Characters',
+ 'Content',
+];
+
+/** A spreadsheet cell holds at most this many characters (Excel's limit). */
+const CELL_LIMIT = 32_767;
+
+/** "2026-10-22": a date that sorts as text. */
+const day = (iso: string) => iso.slice(0, 10);
+
+/**
+ * The page's text, a block a line: list items marked and indented, quotes
+ * with ">", a table's cells joined with " | ", an HTML block's text.
+ */
+export function draftText(title: string, html: string): string {
+ const lines: string[] = [];
+ const add = (blocks: DraftBlock[]) => {
+ for (const block of blocks) {
+ switch (block.kind) {
+ case 'heading':
+ case 'paragraph':
+ lines.push(text(block.runs));
+ break;
+ case 'quote':
+ for (const p of block.paragraphs) lines.push(`> ${text(p)}`);
+ break;
+ case 'item':
+ lines.push(
+ `${' '.repeat(block.level)}${block.ordered ? `${block.n}.` : '-'} ${text(block.runs)}`,
+ );
+ break;
+ case 'table':
+ for (const row of block.rows) lines.push(row.cells.map(text).join(' | '));
+ break;
+ case 'html':
+ add(block.blocks);
+ break;
+ }
+ }
+ };
+ add(draftBlocks(title, html));
+ return lines.join('\n');
+}
+
+/** One row a draft, in the header's order: its page's text in full. */
+export function libraryRows(items: LibraryExportItem[]): Record<string, string | number>[] {
+ return items.map((item) => {
+ const content = draftText(item.title, item.html);
+ const values: (string | number)[] = [
+ item.title,
+ item.status,
+ item.method,
+ item.pageType,
+ item.author,
+ day(item.createdAt),
+ day(item.updatedAt),
+ item.url ?? '',
+ content.replace(/\n/g, '').length,
+ content,
+ ];
+ return Object.fromEntries(LIBRARY_EXPORT_HEADERS.map((header, i) => [header, values[i]]));
+ });
+}
+
+/** Export CSV: one row a draft. */
+export function libraryCsv(items: LibraryExportItem[]): string {
+ return toCsv(libraryRows(items), LIBRARY_EXPORT_HEADERS);
+}
+
+/** Export Excel: one row a draft; a page past a cell's limit is cut, and says so. */
+export function libraryWorkbook(items: LibraryExportItem[]): Sheet<Blob>[] {
+ const bold = (value: string) => ({ value, fontWeight: 'bold' as const });
+ return [
+ {
+ sheet: 'Library',
+ columns: [
+ { width: 40 },
+ { width: 12 },
+ { width: 10 },
+ { width: 18 },
+ { width: 18 },
+ { width: 12 },
+ { width: 12 },
+ { width: 40 },
+ { width: 11 },
+ { width: 80 },
+ ],
+ data: [
+ LIBRARY_EXPORT_HEADERS.map(bold),
+ ...libraryRows(items).map((row) =>
+ LIBRARY_EXPORT_HEADERS.map((header) => {
+ const value = row[header];
+ return typeof value === 'string' && value.length > CELL_LIMIT
+ ? `${value.slice(0, CELL_LIMIT - 1)}…`
+ : value;
+ }),
+ ),
+ ],
+ },
+ ];
+}
+
+/**
+ * Export Word: every draft in one document, each from a page of its own,
+ * under a line saying where it stands.
+ */
+export async function libraryDocx(items: LibraryExportItem[]): Promise<Blob> {
+ const m = await import('docx');
+ // One count for the whole file, so a list doesn't go on from another page's.
+ const counter = { lists: 0 };
+ const sections = items.map((item) => [
+ new m.Paragraph({
+ children: [
+ new m.TextRun({
+ text: [
+ item.status,
+ item.method,
+ item.pageType,
+ `Updated ${day(item.updatedAt)}`,
+ item.url,
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ italics: true,
+ color: '666666',
+ }),
+ ],
+ }),
+ ...docxBlocks(m, draftBlocks(item.title, item.html, counter)),
+ ]);
+ return m.Packer.toBlob(docxDocument(m, 'Content Library', sections));
+}
+
+/** "ansvisor_content_library_in-review_2026-10-22.xlsx". */
+export function libraryExportFileName(tab: string, format: LibraryExportFormat, now: Date): string {
+ return `ansvisor_content_library_${tab.replace(/_/g, '-')}_${now.toISOString().slice(0, 10)}.${format}`;
+}
diff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.ts
index ae63129ad..f3d050d41 100644
--- a/web/src/lib/content/drafts.test.ts
+++ b/web/src/lib/content/drafts.test.ts
@@ -6,6 +6,7 @@ import {
WRITING_STALE_MS,
agentStateOf,
contentEditorPath,
+ draftsCreatedIn,
draftsInTab,
isPageType,
libraryTabCounts,
@@ -35,6 +36,26 @@ const drafts = [
draft('d', 'published'),
];
+describe('the Library’s Created filter', () => {
+ const at = (id: string, createdAt: string) => ({ ...draft(id, 'draft'), createdAt });
+ const now = Date.parse('2026-10-22T12:00:00Z');
+ const list = [
+ at('today', '2026-10-22T08:00:00Z'),
+ at('week', '2026-10-16T12:00:00Z'),
+ at('month', '2026-09-25T12:00:00Z'),
+ at('old', '2026-06-01T12:00:00Z'),
+ ];
+ const ids = (range: Parameters<typeof draftsCreatedIn>[1]) =>
+ draftsCreatedIn(list, range, now).map((d) => d.id);
+
+ it('keeps the drafts created in the range, counted back from now', () => {
+ expect(ids('all')).toEqual(['today', 'week', 'month', 'old']);
+ expect(ids('7d')).toEqual(['today', 'week']);
+ expect(ids('30d')).toEqual(['today', 'week', 'month']);
+ expect(ids('90d')).toEqual(['today', 'week', 'month']);
+ });
+});
+
describe('the Library tabs', () => {
it('counts every draft under All and each under its status', () => {
expect(libraryTabCounts(drafts)).toEqual({
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 897442702..a7fdd587e 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -230,6 +230,21 @@ export interface DraftStartOptions {
topics: { id: string; name: string; promptCount: number }[];
}
+/** The Library's Created filter (CE-002): any time, or the last 7, 30 or 90 days. */
+export const CREATED_RANGES = ['all', '7d', '30d', '90d'] as const;
+export type CreatedRange = (typeof CREATED_RANGES)[number];
+
+/** The drafts created in the range, counted back from `now`. */
+export function draftsCreatedIn(
+ drafts: ContentDraftListItem[],
+ range: CreatedRange,
+ now: number = Date.now(),
+): ContentDraftListItem[] {
+ if (range === 'all') return drafts;
+ const since = now - Number.parseInt(range, 10) * 86_400_000;
+ return drafts.filter((d) => new Date(d.createdAt).getTime() >= since);
+}
+
export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {
if (tab === 'archived') return drafts.filter((d) => d.archivedAt !== null);
const live = drafts.filter((d) => d.archivedAt === null);