Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): export the page from the Content Editor as Word, HTML or Markdown (#1348)
Cihan03ff150e8ad5
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 185a87b98..e1d127218 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3864,6 +3864,14 @@"failed": "Couldn't save the brief. Try again."}},+ "export": {+ "button": "Export",+ "hint": "Download the page as it is now",+ "docx": "Export Word",+ "html": "Export HTML",+ "md": "Export Markdown",+ "failed": "Couldn't export the page. Try again."+ },"rulesChip": "Rules {met}/{total}","rulesChipHint": "Rules this page meets now. Open the Rules tab.","rules": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 612783b0d..e81788fe3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -42,6 +42,11 @@ import {type PageType,} from '@/lib/content/drafts';import { CITED_DAYS, MAX_PASSAGES, type CitedPassage } from '@/lib/content/cited-passages';+import {+ draftExportBlob,+ draftExportFileName,+ type DraftExportFormat,+} from '@/lib/content/draft-export';import type { DraftVersion } from '@/lib/content/history';import type { DraftSuggestion, SuggestionStatus } from '@/lib/content/suggestions';import {@@ -54,6 +59,7 @@ import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/conteimport { JsonLd } from '@/lib/content/json-ld-node';import { detectPageType } from '@/lib/content/page-types';import { aiTracesFound } from '@/lib/content/rules';+import { saveBlob } from '@/lib/download';import { cn } from '@/lib/utils';import { AgentBar } from './_agent-bar';import { DropOverlay, useAttachments } from './_attach';@@ -65,6 +71,7 @@ import {lockedPassageCount,type HeldEdit,} from './_cited-passages';+import { ExportMenu } from './_export-menu';import { HistoryMenu } from './_history-menu';import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';@@ -682,6 +689,21 @@ export function DraftEditor({);};+ /** Export: the page as Copy HTML gives it, as a Word, HTML or Markdown file. */+ const exportPage = async (format: DraftExportFormat) => {+ if (!editor) return;+ const html = publishableHtml(+ htmlSource !== null ? htmlFromSource(htmlSource) : editor.getHTML(),+ );+ const name = title.trim() || t('untitled');+ try {+ saveBlob(await draftExportBlob(format, name, html), draftExportFileName(name, format));+ } catch (err) {+ console.error('Failed to export the page:', err);+ toast.error(t('export.failed'));+ }+ };+/*** Try again: the agent takes the page as saved now, with the rules in* effect here, and the page waits for it.@@ -814,7 +836,7 @@ export function DraftEditor({<h1 className="min-w-0 truncate text-sm font-medium" title={title.trim() || undefined}>{title.trim() || t('untitled')}</h1>- <div className="ml-auto flex shrink-0 items-center gap-3">+ <div className="ml-auto flex shrink-0 items-center gap-1.5 sm:gap-3"><SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} /><HistoryMenudraftId={draft.id}@@ -837,6 +859,7 @@ export function DraftEditor({<Copy className="h-3.5 w-3.5" /><span className="hidden xl:inline">{t('copyHtml')}</span></Button>+ <ExportMenu disabled={!editor} onExport={(format) => void exportPage(format)} /><Buttonsize="sm"// A page that can't be saved can't be marked ready; the save state says why.diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-menu.tsxnew file mode 100644index 000000000..3a454daf3--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-menu.tsx@@ -0,0 +1,55 @@+'use client';++import { useTranslations } from 'next-intl';+import { ChevronDown, Download, FileCode, FileText, FileType } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import type { DraftExportFormat } from '@/lib/content/draft-export';++const FORMATS = [+ { format: 'docx', icon: FileType },+ { format: 'html', icon: FileCode },+ { format: 'md', icon: FileText },+] as const satisfies readonly { format: DraftExportFormat; icon: unknown }[];++/**+ * Export in the editor's header: the page as written now, as Word, HTML or+ * Markdown. Labelled from a tablet's width up, so it is there to find; an+ * icon on a phone, where the header's one row has no room for the word.+ */+export function ExportMenu({+ disabled,+ onExport,+}: {+ disabled: boolean;+ onExport: (format: DraftExportFormat) => void;+}) {+ const t = useTranslations('contentEditor.editor.export');+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Button variant="outline" size="sm" />}+ disabled={disabled}+ title={t('hint')}+ aria-label={t('button')}+ >+ <Download className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">{t('button')}</span>+ <ChevronDown className="hidden h-3.5 w-3.5 text-muted-foreground sm:block" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ {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/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex ddf2070a6..27d2507e8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -81,6 +81,8 @@ vi.mock('mammoth', () => ({},}));vi.mock('sonner', () => ({ toast }));+const saveBlob = vi.hoisted(() => vi.fn());+vi.mock('@/lib/download', () => ({ saveBlob }));(globalThis as typeof globalThis & {@@ -187,6 +189,7 @@ beforeEach(() => {root = createRoot(container);getContentDraft.mockReset();markContentDraftReady.mockReset();+ saveBlob.mockReset();setContentDraftPageType.mockReset().mockResolvedValue(undefined);saveContentDraft.mockReset()@@ -1217,6 +1220,38 @@ describe('the content editor', () => {expect(toast.success).toHaveBeenLastCalledWith('HTML copied');});+ it('exports the page from the header, as Markdown here', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams <strong>trust</strong> it.</p>' }),+ );+ await renderPage();+ const trigger = [...container.querySelectorAll<HTMLButtonElement>('header button')].find(+ (b) => b.textContent === 'Export',+ )!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ expect(items.map((i) => i.textContent)).toEqual([+ 'Export Word',+ 'Export HTML',+ 'Export Markdown',+ ]);+ await act(async () => items[2].click());+ await act(async () => {});++ expect(saveBlob).toHaveBeenCalledTimes(1);+ const [blob, name] = saveBlob.mock.calls[0] as [Blob, string];+ expect(name).toBe('ansvisor_content_pipeline-forecasting.md');+ const text = await new Promise<string>((resolve) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsText(blob);+ });+ expect(text).toBe('# Pipeline forecasting\n\nTeams **trust** it.\n');+ });+it('shows the link the cursor is in, to open in a new tab', async () => {getContentDraft.mockResolvedValue(draft({ bodyHtml: '<p><a href="https://gartner.com/x">Gartner</a> says so.</p>' }),diff --git a/web/src/lib/content/draft-export.test.ts b/web/src/lib/content/draft-export.test.tsnew file mode 100644index 000000000..2981cfdde--- /dev/null+++ b/web/src/lib/content/draft-export.test.ts@@ -0,0 +1,171 @@+import { strFromU8, unzipSync } from 'fflate';+import { describe, expect, it } from 'vitest';+import {+ draftBlocks,+ draftDocx,+ draftExportBlob,+ draftExportFileName,+ draftHtmlDocument,+ draftMarkdown,+} from './draft-export';++// The page as Copy HTML gives it: one block per line, an HTML block as its+// code, the schema JSON-LD as its script.+const PAGE = [+ '<h1>Pipeline forecasting</h1>',+ '<p>Teams <strong>trust</strong> it, <em>every</em> week. See <a href="https://acme.example/pricing">our pricing</a>.</p>',+ '<h2>How it works</h2>',+ '<ul><li>Weighted stages<ul><li>By deal size</li></ul></li><li>Rep calls</li></ul>',+ '<ol><li>Import deals</li><li>Set the stages</li></ol>',+ '<blockquote><p>It saved us a week.</p></blockquote>',+ '<table><tbody><tr><th>Plan</th><th>Price</th></tr><tr><td>Starter</td><td>$49 | month</td></tr></tbody></table>',+ '<div class="callout"><p>Free for 14 days</p></div>',+ '<script type="application/ld+json">{"@type":"Article"}</script>',+].join('\n');++/** jsdom's Blob has no text() or arrayBuffer(): read it as a browser's FileReader would. */+function read(blob: Blob): Promise<Uint8Array> {+ return new Promise((resolve) => {+ const reader = new FileReader();+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));+ reader.readAsArrayBuffer(blob);+ });+}++describe('draftBlocks', () => {+ it('reads the page as headings, paragraphs, lists, a quote, a table and an HTML block', () => {+ const blocks = draftBlocks('Pipeline forecasting', PAGE);+ expect(blocks.map((b) => b.kind)).toEqual([+ 'heading',+ 'paragraph',+ 'heading',+ 'item',+ 'item',+ 'item',+ 'item',+ 'item',+ 'quote',+ 'table',+ 'html',+ ]);+ expect(blocks[1]).toEqual({+ kind: 'paragraph',+ runs: [+ { text: 'Teams ' },+ { text: 'trust', bold: true },+ { text: ' it, ' },+ { text: 'every', italics: true },+ { text: ' week. See ' },+ { text: 'our pricing', link: 'https://acme.example/pricing' },+ { text: '.' },+ ],+ });+ // The nested item one level down, in its parent's place.+ expect(blocks.slice(3, 6)).toMatchObject([+ { ordered: false, level: 0, n: 1, runs: [{ text: 'Weighted stages' }] },+ { ordered: false, level: 1, n: 1, runs: [{ text: 'By deal size' }] },+ { ordered: false, level: 0, n: 2, runs: [{ text: 'Rep calls' }] },+ ]);+ });++ it('opens with the title when the page has no H1', () => {+ expect(draftBlocks('Pipeline forecasting', '<p>Body</p>')[0]).toEqual({+ kind: 'heading',+ level: 1,+ runs: [{ text: 'Pipeline forecasting' }],+ });+ expect(draftBlocks('', '<p>Body</p>').map((b) => b.kind)).toEqual(['paragraph']);+ });++ it('drops a link to an unsafe address, and keeps its text', () => {+ const [block] = draftBlocks(+ 'T',+ '<h1>T</h1><p><a href="javascript:alert(1)">click</a></p>',+ ).slice(1);+ expect(block).toEqual({ kind: 'paragraph', runs: [{ text: 'click' }] });+ });+});++describe('draftMarkdown', () => {+ it('writes the page as Markdown, an HTML block as HTML, without the JSON-LD', () => {+ expect(draftMarkdown('Pipeline forecasting', PAGE)).toBe(+ [+ '# Pipeline forecasting',+ '',+ 'Teams **trust** it, *every* week. See [our pricing](https://acme.example/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 |',+ '',+ '<div class="callout"><p>Free for 14 days</p></div>',+ '',+ ].join('\n'),+ );+ });++ it('escapes what Markdown would read as its own', () => {+ expect(draftMarkdown('', '<p>2 * 3 = 6 and [not] a_link</p><p># not a heading</p>')).toBe(+ '2 \\* 3 = 6 and \\[not\\] a\\_link\n\n\\# not a heading\n',+ );+ });+});++describe('draftHtmlDocument', () => {+ it("wraps Copy HTML's page in a titled document", () => {+ const doc = draftHtmlDocument('Pricing <2026>', '<h1>Pricing</h1>');+ expect(doc).toContain('<!doctype html>');+ expect(doc).toContain('<meta charset="utf-8">');+ expect(doc).toContain('<title>Pricing <2026></title>');+ expect(doc).toContain('<body>\n<h1>Pricing</h1>\n</body>');+ });+});++describe('draftDocx', () => {+ it('writes a Word document with the headings, text, links, lists and table', async () => {+ const files = unzipSync(await read(await draftDocx('Pipeline forecasting', PAGE)));+ const xml = strFromU8(files['word/document.xml']);+ for (const text of [+ 'Pipeline forecasting',+ 'How it works',+ 'trust',+ 'our pricing',+ 'By deal size',+ 'Set the stages',+ 'It saved us a week.',+ '$49 | month',+ 'Free for 14 days',+ ]) {+ expect(xml).toContain(text);+ }+ expect(xml).toContain('<w:tbl>');+ expect(xml).not.toContain('@type');+ // The link points at the page's address.+ expect(strFromU8(files['word/_rels/document.xml.rels'])).toContain(+ 'https://acme.example/pricing',+ );+ });+});++describe('draftExportBlob and draftExportFileName', () => {+ it('gives each format its file', async () => {+ const md = await draftExportBlob('md', 'T', '<h1>T</h1>');+ expect(md.type).toBe('text/markdown;charset=utf-8');+ expect(strFromU8(await read(md))).toBe('# T\n');+ expect((await draftExportBlob('html', 'T', '<h1>T</h1>')).type).toBe('text/html;charset=utf-8');+ expect(draftExportFileName('Pipeline forecasting: a guide', 'docx')).toBe(+ 'ansvisor_content_pipeline-forecasting-a-guide.docx',+ );+ expect(draftExportFileName('—', 'md')).toBe('ansvisor_content_page.md');+ });+});diff --git a/web/src/lib/content/draft-export.ts b/web/src/lib/content/draft-export.tsnew file mode 100644index 000000000..74744b892--- /dev/null+++ b/web/src/lib/content/draft-export.ts@@ -0,0 +1,370 @@+import { slugify } from '@/lib/slug';+import { safeLinkHref } from './editor';++/**+ * Export in the Content Editor: the page as Word, HTML or Markdown, from the+ * HTML Copy HTML gives (publishableHtml). HTML is that page as a document of+ * its own. Word and Markdown read it as blocks first: headings, paragraphs,+ * quotes, lists, tables, and anything else an HTML block holds. Markdown keeps+ * that last as HTML, Word keeps its text. The schema JSON-LD is the page's+ * markup, not its text, so only the HTML file carries it.+ */++export type DraftExportFormat = 'docx' | 'html' | 'md';++/** A stretch of text with one format; a link carries its address. */+export interface DraftRun {+ text: string;+ bold?: boolean;+ italics?: boolean;+ link?: string;+ /** A line break (a <br>), with no text. */+ break?: boolean;+}++export type DraftBlock =+ | { kind: 'heading'; level: 1 | 2 | 3; runs: DraftRun[] }+ | { kind: 'paragraph'; runs: DraftRun[] }+ | { kind: 'quote'; paragraphs: DraftRun[][] }+ /** One list item; `list` tells a numbered list's items from the next list's. */+ | { kind: 'item'; ordered: boolean; level: number; list: number; n: number; runs: DraftRun[] }+ | { kind: 'table'; rows: { header: boolean; cells: DraftRun[][] }[] }+ /** Anything else, as an HTML block holds it: its HTML, and the blocks inside it. */+ | { kind: 'html'; html: string; blocks: DraftBlock[] };++const childrenOf = (el: Element) => Array.from(el.childNodes);++const HEADINGS: Record<string, 1 | 2 | 3> = { h1: 1, h2: 2, h3: 3, h4: 3, h5: 3, h6: 3 };+const SKIPPED = new Set(['script', 'style', 'template', 'noscript']);++function sameFormat(a: DraftRun, b: DraftRun) {+ return !a.break && !b.break && a.bold === b.bold && a.italics === b.italics && a.link === b.link;+}++/** The runs in some nodes: whitespace collapsed as a browser shows it, trimmed at the ends. */+function inlineRuns(nodes: Node[]): DraftRun[] {+ const runs: DraftRun[] = [];+ const walk = (node: Node, format: Omit<DraftRun, 'text'>) => {+ if (node.nodeType === Node.TEXT_NODE) {+ const text = (node.textContent ?? '').replace(/\s+/g, ' ');+ if (!text) return;+ const last = runs.at(-1);+ if (last && sameFormat(last, { text, ...format })) last.text += text;+ else runs.push({ text, ...format });+ return;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) return;+ const el = node as Element;+ const tag = el.tagName.toLowerCase();+ if (SKIPPED.has(tag)) return;+ if (tag === 'br') {+ runs.push({ text: '', break: true });+ return;+ }+ if (tag === 'img') {+ const src = safeLinkHref(el.getAttribute('src') ?? '');+ const alt = el.getAttribute('alt')?.trim() || 'Image';+ runs.push({ text: `[${alt}]`, ...format, ...(src ? { link: src } : {}) });+ return;+ }+ const next = { ...format };+ if (tag === 'strong' || tag === 'b') next.bold = true;+ if (tag === 'em' || tag === 'i') next.italics = true;+ if (tag === 'a') {+ const href = safeLinkHref(el.getAttribute('href') ?? '');+ if (href) next.link = href;+ }+ el.childNodes.forEach((child) => walk(child, next));+ };+ nodes.forEach((node) => walk(node, {}));+ // Trimmed at the ends, as a browser shows a block's text.+ while (runs.length && !runs[0].break && !runs[0].text.trim()) runs.shift();+ while (runs.length && !runs.at(-1)!.break && !runs.at(-1)!.text.trim()) runs.pop();+ if (runs.length && !runs[0].break) runs[0].text = runs[0].text.trimStart();+ if (runs.length && !runs.at(-1)!.break) runs.at(-1)!.text = runs.at(-1)!.text.trimEnd();+ return runs;+}++/** A list's items in order, a nested list's one level down. */+function listItems(list: Element, level: number, counter: { lists: number }): DraftBlock[] {+ const ordered = list.tagName.toLowerCase() === 'ol';+ const id = counter.lists++;+ const items: DraftBlock[] = [];+ let n = 0;+ for (const li of Array.from(list.children)) {+ if (li.tagName.toLowerCase() !== 'li') continue;+ n += 1;+ // The item's own text, without the lists nested in it.+ const own = li.cloneNode(true) as Element;+ own.querySelectorAll('ul, ol').forEach((nested) => nested.remove());+ items.push({ kind: 'item', ordered, level, list: id, n, runs: inlineRuns(childrenOf(own)) });+ for (const nested of Array.from(li.children)) {+ const tag = nested.tagName.toLowerCase();+ if (tag === 'ul' || tag === 'ol') items.push(...listItems(nested, level + 1, counter));+ }+ }+ return items;+}++function tableRows(table: Element): Extract<DraftBlock, { kind: 'table' }>['rows'] {+ return Array.from(table.querySelectorAll('tr'))+ .filter((tr) => tr.closest('table') === table)+ .map((tr) => {+ const cells = Array.from(tr.children).filter((c) => /^t[hd]$/i.test(c.tagName));+ return {+ header: cells.length > 0 && cells.every((c) => c.tagName.toLowerCase() === 'th'),+ cells: cells.map((c) => inlineRuns(childrenOf(c))),+ };+ });+}++function blocksIn(parent: Element, counter: { lists: number }): DraftBlock[] {+ const blocks: DraftBlock[] = [];+ for (const node of Array.from(parent.childNodes)) {+ if (node.nodeType === Node.TEXT_NODE) {+ // Loose text between blocks, as an HTML block may leave it.+ const runs = inlineRuns([node]);+ if (runs.length) blocks.push({ kind: 'paragraph', runs });+ continue;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) continue;+ const el = node as Element;+ const tag = el.tagName.toLowerCase();+ if (SKIPPED.has(tag)) continue;+ if (tag in HEADINGS) {+ blocks.push({ kind: 'heading', level: HEADINGS[tag], runs: inlineRuns(childrenOf(el)) });+ } else if (tag === 'p') {+ const runs = inlineRuns(childrenOf(el));+ if (runs.length) blocks.push({ kind: 'paragraph', runs });+ } else if (tag === 'blockquote') {+ const inner = el.querySelector('p') ? Array.from(el.querySelectorAll('p')) : [el];+ const paragraphs = inner.map((p) => inlineRuns(childrenOf(p))).filter((runs) => runs.length);+ if (paragraphs.length) blocks.push({ kind: 'quote', paragraphs });+ } else if (tag === 'ul' || tag === 'ol') {+ blocks.push(...listItems(el, 0, counter));+ } else if (tag === 'table') {+ const rows = tableRows(el);+ if (rows.length) blocks.push({ kind: 'table', rows });+ } else if (tag === 'img') {+ blocks.push({ kind: 'paragraph', runs: inlineRuns([el]) });+ } else {+ blocks.push({ kind: 'html', html: el.outerHTML, blocks: blocksIn(el, counter) });+ }+ }+ return blocks;+}++const text = (runs: DraftRun[]) => runs.map((r) => (r.break ? '\n' : r.text)).join('');++/**+ * 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[] {+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');+ const blocks = blocksIn(doc.body, { lists: 0 });+ const hasTitle = blocks.some((b) => b.kind === 'heading' && b.level === 1);+ return hasTitle || !title.trim()+ ? blocks+ : [{ kind: 'heading', level: 1, runs: [{ text: title.trim() }] }, ...blocks];+}++const escapeHtml = (value: string) =>+ value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');++/** Export HTML: Copy HTML's page as a document of its own, titled. */+export function draftHtmlDocument(title: string, html: string): string {+ return [+ '<!doctype html>',+ '<html lang="en">',+ '<head>',+ '<meta charset="utf-8">',+ `<title>${escapeHtml(title.trim())}</title>`,+ '</head>',+ '<body>',+ html.trim(),+ '</body>',+ '</html>',+ '',+ ].join('\n');+}++/** Characters Markdown would read as its own: escaped, so the text reads as written. */+function escapeMarkdown(value: string): string {+ return value.replace(/([\\`*_[\]<>|])/g, '\\$1').replace(/^(\s*)([#+-]|\d+\.)(?=\s)/, '$1\\$2');+}++function markdownRuns(runs: DraftRun[], lineBreak: string): string {+ return runs+ .map((run) => {+ if (run.break) return lineBreak;+ if (!run.text.trim()) return run.text;+ // The marks hug the words: "**bold** text", not "** bold **text".+ const lead = run.text.match(/^\s*/)![0];+ const tail = run.text.match(/\s*$/)![0];+ let out = escapeMarkdown(run.text.trim());+ if (run.bold) out = `**${out}**`;+ if (run.italics) out = `*${out}*`;+ if (run.link) out = `[${out}](${run.link.replace(/[()\s]/g, encodeURIComponent)})`;+ return lead + out + tail;+ })+ .join('');+}++function markdownBlock(block: DraftBlock): string {+ switch (block.kind) {+ case 'heading':+ return `${'#'.repeat(block.level)} ${markdownRuns(block.runs, ' ')}`;+ case 'paragraph':+ return markdownRuns(block.runs, ' \n');+ case 'quote':+ return block.paragraphs.map((p) => `> ${markdownRuns(p, ' \n> ')}`).join('\n>\n');+ case 'item':+ return `${' '.repeat(block.level)}${block.ordered ? `${block.n}.` : '-'} ${markdownRuns(block.runs, ' ')}`;+ case 'table': {+ const width = Math.max(...block.rows.map((r) => r.cells.length));+ const line = (cells: string[]) =>+ `| ${Array.from({ length: width }, (_, i) => cells[i] ?? '').join(' | ')} |`;+ const rows = block.rows.map((r) => r.cells.map((c) => markdownRuns(c, '<br>')));+ return [line(rows[0]), line(Array(width).fill('---')), ...rows.slice(1).map(line)].join('\n');+ }+ case 'html':+ return block.html;+ }+}++/** Export Markdown: headings, emphasis, links, lists, quotes and tables; an HTML block as HTML. */+export function draftMarkdown(title: string, html: string): string {+ const blocks = draftBlocks(title, html);+ const parts: string[] = [];+ blocks.forEach((block, i) => {+ // A list's items one under the other; a blank line between other blocks.+ const prev = blocks[i - 1];+ if (i > 0) parts.push(block.kind === 'item' && prev?.kind === 'item' ? '\n' : '\n\n');+ parts.push(markdownBlock(block));+ });+ 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);+ const HEADING = {+ 1: HeadingLevel.HEADING_1,+ 2: HeadingLevel.HEADING_2,+ 3: 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({+ 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;+ });++ const content = (+ list: DraftBlock[],+ ): (InstanceType<typeof Paragraph> | InstanceType<typeof Table>)[] =>+ list.flatMap((block) => {+ switch (block.kind) {+ case 'heading':+ return [new Paragraph({ heading: HEADING[block.level], children: children(block.runs) })];+ case 'paragraph':+ return [new Paragraph({ children: children(block.runs) })];+ case 'quote':+ return block.paragraphs.map(+ (p) =>+ new Paragraph({ indent: { left: 720 }, children: children(p, { italics: true }) }),+ );+ case 'item':+ return [+ new Paragraph({+ children: children(block.runs),+ ...(block.ordered+ ? { numbering: { reference: 'numbered', level: block.level, instance: block.list } }+ : { bullet: { level: block.level } }),+ }),+ ];+ case 'table':+ return [+ new Table({+ width: { size: 100, type: WidthType.PERCENTAGE },+ rows: block.rows.map(+ (row) =>+ new TableRow({+ tableHeader: row.header,+ children: row.cells.map(+ (cell) =>+ new TableCell({+ children: [+ new Paragraph({ children: children(cell, { bold: row.header }) }),+ ],+ }),+ ),+ }),+ ),+ }),+ ];+ case 'html':+ return content(block.blocks);+ }+ });++ const document = new Document({+ title: title.trim() || text(blocks.find((b) => b.kind === 'heading')?.runs ?? []),+ numbering: {+ config: [+ {+ reference: 'numbered',+ levels: [0, 1, 2, 3].map((level) => ({+ level,+ format: LevelFormat.DECIMAL,+ text: `%${level + 1}.`,+ alignment: AlignmentType.START,+ style: { paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } } },+ })),+ },+ ],+ },+ sections: [{ children: content(blocks) }],+ });+ return Packer.toBlob(document);+}++/** The file for a format: Word built on the click, HTML and Markdown as UTF-8 text. */+export async function draftExportBlob(+ format: DraftExportFormat,+ title: string,+ html: string,+): Promise<Blob> {+ if (format === 'docx') return draftDocx(title, html);+ return format === 'html'+ ? new Blob([draftHtmlDocument(title, html)], { type: 'text/html;charset=utf-8' })+ : new Blob([draftMarkdown(title, html)], { type: 'text/markdown;charset=utf-8' });+}++/** "ansvisor_content_pipeline-forecasting.docx". */+export function draftExportFileName(title: string, format: DraftExportFormat): string {+ const slug = slugify(title).slice(0, 60).replace(/-+$/, '') || 'page';+ return `ansvisor_content_${slug}.${format}`;+}