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): check the page before Export, with a Ready to paste row (CE-057) (#1426)
Cihanefd1a0be3b9b
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 9914f7c15..c5206098b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4250,6 +4250,22 @@"title": "Before you publish","warning": "Trust {trust}, below 60. {reason}. You can mark it ready, but {count, plural, one {fixing it} other {fixing them}} first raises Trust to about {raised}.","warningNoReason": "Trust {trust}, below 60. You can mark it ready, but Quality shows what would raise it.",+ "warningExport": "Trust {trust}, below 60. {reason}. You can export it, but {count, plural, one {fixing it} other {fixing them}} first raises Trust to about {raised}.",+ "warningNoReasonExport": "Trust {trust}, below 60. You can export it, but Quality shows what would raise it.",+ "continueExport": "Continue to export",+ "paste": {+ "title": "Ready to paste",+ "notYet": "Not ready to paste yet",+ "ok": "No placeholders, all images have alt text, all links work.",+ "placeholders": "{count, plural, one {# placeholder} other {# placeholders}} still open",+ "alt": "{count, plural, one {# image has} other {# images have}} no alt text",+ "broken": "{count, plural, one {# link doesn't} other {# links don't}} answer",+ "unread": "No placeholders, all images have alt text; {links}.",+ "reading": "{count, plural, one {# link is} other {# links are}} still being read",+ "unreadShort": "{count, plural, one {# link wasn't} other {# links weren't}} read: check {count, plural, one {it} other {them}}",+ "readingAndUnread": "{reading, plural, one {# link is} other {# links are}} still being read, {unread, plural, one {# wasn't} other {# weren't}} read: check {unread, plural, one {it} other {them}}",+ "fill": "Fill now"+ },"logged": "Mark ready anyway is logged, with this Trust.","author": {"ok": "Author for your CMS",@@ -4274,6 +4290,7 @@"datesNote": "The dates are today's: change them if the page goes out on another day.","headlineLeftOut": "The title still has a placeholder in square brackets, so the code leaves the headline out. Fill it in, and the headline comes back here.","states": {+ "ok": "done","check": "check it","missing": "missing"},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex 2c12f87ff..391c02b45 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -85,6 +85,10 @@ const onMarkReady = vi.fn();const onFixFirst = vi.fn();const writeText = vi.fn();+const clean = { placeholders: 0, imagesWithoutAlt: 0, linksBroken: 0, linksUnread: 0 };+const onContinue = vi.fn();+const onFillNow = vi.fn();+async function render(q: QualityRead,{@@ -92,6 +96,8 @@ async function render(pageType = 'blog_post' as string | null,image = 'https://cdn.acme.com/pour-over.jpg' as string | null,linksPending = 0,+ paste = clean,+ mode = 'markReady' as 'markReady' | 'export',title = 'How small teams forecast',} = {},) {@@ -99,6 +105,10 @@ async function render(root.render(<NextIntlClientProvider locale="en" messages={messages}><BeforePublish+ mode={mode}+ paste={paste}+ onFillNow={onFillNow}+ onContinue={onContinue}onClose={() => {}}quality={q}title={title}@@ -140,6 +150,8 @@ const trustRead = (over: Partial<TrustRead>): TrustRead => ({beforeEach(() => {onMarkReady.mockReset();onFixFirst.mockReset();+ onContinue.mockReset();+ onFillNow.mockReset();writeText.mockReset().mockResolvedValue(undefined);Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });container = document.createElement('div');@@ -235,6 +247,7 @@ describe('BeforePublish', () => {"Author for your CMS · check itSet Ada Lovelace as the page's author in your CMS. Its template shows the byline; nothing is added to the content.",'Visible published and updated dates · check itMost CMSs (WordPress, Webflow, Shopify) add these for you. Check your page.','Article schema with datePublished and dateModified · check itOften added by your CMS. If not, paste the code below into the page.',+ 'Ready to paste · doneNo placeholders, all images have alt text, all links work.',]);});@@ -291,11 +304,76 @@ describe('BeforePublish', () => {expect(jsonLd()).not.toHaveProperty('image');});+ it('says what keeps it from being ready to paste, with Fill now for a placeholder (CE-057)', async () => {+ await render(quality({ trust: null }), {+ paste: { placeholders: 2, imagesWithoutAlt: 1, linksBroken: 1, linksUnread: 1 },+ });+ expect(rows().at(-1)).toBe(+ "Not ready to paste yet · missing2 placeholders still open · 1 image has no alt text · 1 link doesn't answer · 1 link wasn't read: check it",+ );+ await act(async () => button('Fill now')!.click());+ expect(onFillNow).toHaveBeenCalled();+ await render(quality({ trust: null }), { paste: { ...clean, imagesWithoutAlt: 1 } });+ expect(button('Fill now')).toBeUndefined();+ });++ it('says links are still being read, or were not read, to check them', async () => {+ await render(quality({ trust: null }), {+ paste: { ...clean, linksUnread: 2 },+ linksPending: 2,+ });+ expect(rows().at(-1)).toBe(+ 'Ready to paste · check itNo placeholders, all images have alt text; 2 links are still being read.',+ );+ await render(quality({ trust: null }), { paste: { ...clean, linksUnread: 2 } });+ expect(rows().at(-1)).toBe(+ "Ready to paste · check itNo placeholders, all images have alt text; 2 links weren't read: check them.",+ );+ });++ it('tells a link still being read from one no read is coming for', async () => {+ // One read still coming; the other link's site refused its read.+ await render(quality({ trust: null }), {+ paste: { ...clean, linksUnread: 2 },+ linksPending: 1,+ });+ expect(rows().at(-1)).toBe(+ "Ready to paste · check itNo placeholders, all images have alt text; 1 link is still being read, 1 wasn't read: check it.",+ );+ await render(quality({ trust: null }), {+ paste: { ...clean, placeholders: 1, linksUnread: 3 },+ linksPending: 1,+ });+ expect(rows().at(-1)).toBe(+ "Not ready to paste yet · missing1 placeholder still open · 1 link is still being read, 2 weren't read: check them",+ );+ });++ it('goes on to Export from Export, the warning saying so, with no log', async () => {+ await render(quality(), { mode: 'export' });+ expect(alert()!.textContent).toContain('You can export it, but fixing them first');+ expect(alert()!.textContent).not.toContain('logged');+ expect(button('Mark ready anyway')).toBeUndefined();+ // The dialog moves focus in after it opens.+ await vi.waitFor(() => expect(document.activeElement).toBe(button('Continue to export')));+ await act(async () => button('Continue to export')!.click());+ expect(onContinue).toHaveBeenCalled();+ expect(onMarkReady).not.toHaveBeenCalled();+ });++ it('goes to what would raise Trust from Export too', async () => {+ await render(quality(), { mode: 'export' });+ await act(async () => button('Fix first')!.click());+ expect(onFixFirst).toHaveBeenCalledWith(expect.any(String));+ expect(onContinue).not.toHaveBeenCalled();+ });+it("gives no Article for a page that isn't one", async () => {await render(quality(), { pageType: 'product_page' });expect(rows()).toEqual([expect.stringContaining('Author for your CMS'),'Schema for this page type · check itCheck what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles.',+ expect.stringContaining('Ready to paste'),]);expect(dialog().querySelector('pre')).toBeNull();expect(button('Copy JSON-LD')).toBeUndefined();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxindex 31c1548e4..90bf36abb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -2,7 +2,7 @@import { useRef } from 'react';import { useTranslations } from 'next-intl';-import { AlertTriangle } from 'lucide-react';+import { AlertTriangle, Check } from 'lucide-react';import { Button } from '@/components/ui/button';import {Dialog,@@ -33,17 +33,39 @@ export interface ReadyAnyway {count: number | null;}-type RowState = 'missing' | 'check';+type RowState = 'ok' | 'missing' | 'check';+type Row = {+ state: RowState;+ title: string;+ detail: string;+ /** Ready to paste's Fill now, while a placeholder is open. */+ fill?: boolean;+};++/** What Ready to paste reads (Quality spec §7b): placeholders, alt text, links. */+export interface ReadyToPaste {+ placeholders: number;+ imagesWithoutAlt: number;+ linksBroken: number;+ /** Links with no read yet, or none to come: no word on whether they work. */+ linksUnread: number;+}/*** Before you publish (Content Editor Quality spec §7, CE-041), on Mark- * ready: a warning only when Trust is under 60 (nothing else blocks), what- * the CMS does for the page (its author, dates and schema), and for an- * article the JSON-LD to paste when the CMS doesn't write one, from the- * page's facts only. Mark ready anyway is logged with the Trust the page- * had. Rendered only while open.+ * ready and on Export (§7b, CE-057): a warning only when Trust is under 60+ * (nothing else blocks), what the CMS does for the page (its author, dates+ * and schema), Ready to paste (no placeholders, images with alt text, links+ * that work), and for an article the JSON-LD to paste when the CMS doesn't+ * write one, from the page's facts only. Mark ready anyway is logged with+ * the Trust the page had; on Export it goes on to Export. Rendered only+ * while open.*/export function BeforePublish({+ mode = 'markReady',+ paste,+ onFillNow,+ onContinue,onClose,quality,title,@@ -54,6 +76,13 @@ export function BeforePublish({onMarkReady,onFixFirst,}: {+ /** Opened by Mark ready, or by Export. */+ mode?: 'markReady' | 'export';+ paste: ReadyToPaste;+ /** Goes to the first placeholder, to fill it (Ready to paste's Fill now). */+ onFillNow: () => void;+ /** Export's: goes on to it. */+ onContinue?: () => void;onClose: () => void;quality: QualityRead;title: string;@@ -73,7 +102,7 @@ export function BeforePublish({const tQuality = useTranslations('contentEditor.editor.quality');const tAuthor = useTranslations('contentEditor.editor.author');const markRef = useRef<HTMLButtonElement>(null);- // Fix first moves on to the passage: focus isn't sent back to Mark ready.+ // Fix first and Fill now move on to the page: focus isn't sent back to the button.const fixing = useRef(false);const { author, brandName, siteTrust } = quality;// E-E-A-T is read with the authors: until then, who the page is by isn't known.@@ -104,7 +133,7 @@ export function BeforePublish({}),): null;- const rows: { state: RowState; title: string; detail: string }[] = [+ const rows: Row[] = [!authorsRead? { state: 'check', title: t('author.ok'), detail: t('author.unknown') }: author@@ -132,6 +161,7 @@ export function BeforePublish({},]: [{ state: 'check' as const, title: t('schema.other'), detail: t('schema.otherDetail') }]),+ { ...readyRow(t, paste, linksPending), fill: paste.placeholders > 0 },];return (@@ -153,15 +183,15 @@ export function BeforePublish({<div className="min-w-0 space-y-1"><p>{fix- ? t('warning', {+ ? t(mode === 'export' ? 'warningExport' : 'warning', {trust,reason: fix.line,count: fix.count,raised: trust + fix.gain,})- : t('warningNoReason', { trust })}+ : t(mode === 'export' ? 'warningNoReasonExport' : 'warningNoReason', { trust })}</p>- <p className="text-xs opacity-80">{t('logged')}</p>+ {mode === 'markReady' && <p className="text-xs opacity-80">{t('logged')}</p>}</div></div>)}@@ -177,12 +207,20 @@ export function BeforePublish({aria-hiddenclassName={cn('mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold',- row.state === 'missing'- ? 'bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300'- : 'bg-muted text-muted-foreground',+ row.state === 'ok'+ ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300'+ : row.state === 'missing'+ ? 'bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300'+ : 'bg-muted text-muted-foreground',)}>- {row.state === 'missing' ? '!' : '?'}+ {row.state === 'ok' ? (+ <Check className="h-3 w-3" />+ ) : row.state === 'missing' ? (+ '!'+ ) : (+ '?'+ )}</span><div className="min-w-0 flex-1"><p className="font-medium">@@ -196,6 +234,19 @@ export function BeforePublish({{row.detail}</p></div>+ {row.fill && (+ <Button+ size="sm"+ variant="outline"+ className="shrink-0"+ onClick={() => {+ fixing.current = true;+ onFillNow();+ }}+ >+ {t('paste.fill')}+ </Button>+ )}</li>))}</ul>@@ -237,19 +288,66 @@ export function BeforePublish({{t('fixFirst')}</Button>)}- <Button- ref={markRef}- onClick={() =>- onMarkReady(- below ? { trust, reason: fix?.check ?? null, count: fix?.count ?? null } : null,- )- }- >- {below ? t('markReadyAnyway') : t('markReady')}- </Button>+ {mode === 'export' ? (+ <Button ref={markRef} onClick={onContinue}>+ {t('continueExport')}+ </Button>+ ) : (+ <Button+ ref={markRef}+ onClick={() =>+ onMarkReady(+ below ? { trust, reason: fix?.check ?? null, count: fix?.count ?? null } : null,+ )+ }+ >+ {below ? t('markReadyAnyway') : t('markReady')}+ </Button>+ )}</div></DialogFooter></DialogContent></Dialog>);}++type T = ReturnType<typeof useTranslations<'contentEditor.editor.beforePublish'>>;++/**+ * Ready to paste (§7b): no placeholders, every image with alt text, every+ * link working; what is still open, named, or the links not all read yet.+ */+function readyRow(t: T, paste: ReadyToPaste, linksPending: number): Row {+ // The reads still coming are for some of the unread links at most: one the+ // site refused, one past the reads' limit or one in an HTML block gets none.+ const reading = Math.min(linksPending, paste.linksUnread);+ const notRead = paste.linksUnread - reading;+ const unread =+ reading && notRead+ ? t('paste.readingAndUnread', { reading, unread: notRead })+ : reading+ ? t('paste.reading', { count: reading })+ : notRead+ ? t('paste.unreadShort', { count: notRead })+ : null;+ const open = [+ paste.placeholders && t('paste.placeholders', { count: paste.placeholders }),+ paste.imagesWithoutAlt && t('paste.alt', { count: paste.imagesWithoutAlt }),+ paste.linksBroken && t('paste.broken', { count: paste.linksBroken }),+ ].filter((item): item is string => !!item);+ if (open.length) {+ return {+ state: 'missing',+ title: t('paste.notYet'),+ detail: [...open, ...(unread ? [unread] : [])].join(' · '),+ };+ }+ if (unread) {+ return {+ state: 'check',+ title: t('paste.title'),+ detail: t('paste.unread', { links: unread }),+ };+ }+ return { state: 'ok', title: t('paste.title'), detail: t('paste.ok') };+}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 d1911cecc..8835b8389 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@@ -76,7 +76,12 @@ import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/conteimport { JsonLd } from '@/lib/content/json-ld-node';import { firstImage } from '@/lib/content/page-schema';import { PLACEHOLDER, pagePlaceholders, placeholderIn } from '@/lib/content/placeholders';-import { exportPlaceholders, pasteChecks } from '@/lib/content/ready-to-publish';+import {+ blankCode,+ exportPlaceholders,+ pasteChecks,+ titlePlaceholders,+} from '@/lib/content/ready-to-publish';import { detectPageType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';@@ -89,7 +94,7 @@ import { useBrandStore } from '@/stores/use-brand-store';import { AgentCard } from './_agent-card';import { AgentDrafting, draftingKey } from './_agent-drafting';import { AuthorMenu } from './_author-menu';-import { BeforePublish, type ReadyAnyway } from './_before-publish';+import { BeforePublish, type ReadyAnyway, type ReadyToPaste } from './_before-publish';import { FlashBlock, findBlock, flashKey } from './_flash-block';import { useAgentRun } from './_use-agent-run';import { useLinkChecks } from './_use-link-checks';@@ -984,13 +989,14 @@ export function DraftEditor({/*** Fill now (Export, CE-057): the first placeholder, in the HTML view's- * text while it is open, else in the page; one only an HTML block holds is+ * text while it is open (where exportPlaceholders reads: not in tags,+ * styles or scripts), else in the page; one only an HTML block holds is* said to be there.*/const htmlSourceRef = useRef<HTMLTextAreaElement>(null);const fillFirstPlaceholder = () => {if (htmlSource !== null) {- const m = new RegExp(PLACEHOLDER.source, 'iu').exec(htmlSource);+ const m = new RegExp(PLACEHOLDER.source, 'iu').exec(blankCode(htmlSource, { words: true }));const area = htmlSourceRef.current;if (m && area) {area.focus();@@ -1503,12 +1509,29 @@ export function DraftEditor({}: undefined;// Before you publish (CE-041) opens on Mark ready once Quality is live,- // with the nudge to the first open to-do behind it.- const [publishOpen, setPublishOpen] = useState(false);- const openBeforePublish = () => {- setPublishOpen(true);- nudgeAt('markReady');+ // with the nudge to the first open to-do behind it, and on Export (CE-057),+ // with Ready to paste read from the page as it is then (its links as they+ // are read).+ const [publishOpen, setPublishOpen] = useState<{+ mode: 'markReady' | 'export';+ html: string;+ } | null>(null);+ const openBeforePublish = (mode: 'markReady' | 'export') => {+ setPublishOpen({ mode, html: pageToPublish() });+ if (mode === 'markReady') nudgeAt('markReady');};+ // Read once per change (a link read landing, the title), not on every render.+ const readyToPaste = useMemo((): ReadyToPaste | null => {+ if (!publishOpen) return null;+ const { html } = publishOpen;+ const { links, images } = pasteChecks(html, linkChecks);+ return {+ placeholders: exportPlaceholders(html) + titlePlaceholders(title, html),+ imagesWithoutAlt: images.withoutAlt,+ linksBroken: links.broken,+ linksUnread: links.count - links.read,+ };+ }, [publishOpen, linkChecks, title]);/** Marks it ready; past Before you publish's warning, logged with its facts. */const markReady = async (anyway?: ReadyAnyway) => {setMarking(true);@@ -1635,7 +1658,7 @@ export function DraftEditor({disabled={!editor}title={t('export.hint')}aria-label={t('export.button')}- onClick={() => openExport()}+ onClick={() => openBeforePublish('export')}><Download className="h-3.5 w-3.5" /><span className="hidden sm:inline">{t('export.button')}</span>@@ -1652,7 +1675,7 @@ export function DraftEditor({autosave.state === 'conflict' ||autosave.state === 'too_large'}- onClick={() => (quality ? openBeforePublish() : void markReady())}+ onClick={() => (quality ? openBeforePublish('markReady') : void markReady())}>{marking ? <LoadingDots /> : !canMarkReady && <Check className="h-3.5 w-3.5" />}{t('markReady')}@@ -1943,9 +1966,19 @@ export function DraftEditor({/>)}- {quality && publishOpen && (+ {quality && publishOpen && readyToPaste && (<BeforePublish- onClose={() => setPublishOpen(false)}+ mode={publishOpen.mode}+ paste={readyToPaste}+ onFillNow={() => {+ setPublishOpen(null);+ fillFirstPlaceholder();+ }}+ onContinue={() => {+ setPublishOpen(null);+ openExport();+ }}+ onClose={() => setPublishOpen(null)}quality={quality}title={title}isNew={draft.method === 'create'}@@ -1953,11 +1986,11 @@ export function DraftEditor({image={firstImage(pageHtml)}linksPending={linksPending}onMarkReady={(anyway) => {- setPublishOpen(false);+ setPublishOpen(null);void markReady(anyway ?? undefined);}}onFixFirst={(show) => {- setPublishOpen(false);+ setPublishOpen(null);openPanelTab('quality');if (show) showInPage(show, { focus: true });}}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 a3adc04ae..f74384655 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@@ -2840,16 +2840,145 @@ describe('the side panel', () => {(b) => b.textContent === name,)!;- it('opens Export with the page fields, ready to copy for the destination', async () => {- getContentDraft.mockResolvedValue(draft());+ it('opens Before you publish on Export, then Export with the page fields', async () => {+ getContentDraft.mockResolvedValue(draft({ pageType: 'blog_post' }));await renderPage();await act(async () => button('Export')!.click());+ // Before you publish first (§7): what the CMS does, and Ready to paste.+ expect(dialog()!.textContent).toContain('Before you publish');+ expect(dialog()!.textContent).toContain(+ 'Ready to paste · doneNo placeholders, all images have alt text, all links work.',+ );+ expect(markContentDraftReady).not.toHaveBeenCalled();+ await act(async () => inDialog('Continue to export').click());expect(dialog()!.textContent).toContain('Content · ready to paste');expect(dialog()!.textContent).toContain('Meta titlePipeline forecasting');expect(dialog()!.textContent).toContain('AuthorAcme Team → your CMS author field');expect(inDialog('Copy for Webflow').disabled).toBe(false);});+ it('reads Ready to paste as the links are read, a refused read as unread', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ let answer: (value: unknown) => void = () => {};+ checkDraftLinks.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ getContentDraft.mockResolvedValue(+ draft({+ bodyHtml:+ '<h1>Pipeline forecasting</h1><p>See <a href="https://research.example/r">the report</a>.</p>',+ }),+ );+ await renderPage();+ await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain(+ 'Ready to paste · check itNo placeholders, all images have alt text; 1 link is still being read.',+ );+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ await act(async () =>+ answer({+ links: [+ {+ href: 'https://research.example/r',+ status: 'unknown',+ httpStatus: 403,+ date: null,+ },+ ],+ skipped: [],+ }),+ );+ expect(dialog()!.textContent).toContain(+ "Ready to paste · check itNo placeholders, all images have alt text; 1 link wasn't read: check it.",+ );+ } finally {+ vi.useRealTimers();+ }+ });++ it('names no next step on Export, with a to-do open', async () => {+ getContentDraft.mockResolvedValue(draft({ authorId: null }));+ await renderPage();+ await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain('Before you publish');+ expect(container.querySelector('[aria-label="Your next step"]')).toBeNull();+ });++ it("counts a title that is the page's H1 once, and Fill now goes to it", async () => {+ getContentDraft.mockResolvedValue(+ draft({+ title: 'How [name of a real person] forecasts',+ bodyHtml: '<h1>How [name of a real person] forecasts</h1><p>Teams trust it.</p>',+ }),+ );+ await renderPage();+ await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain(+ 'Not ready to paste yet · missing1 placeholder still open',+ );+ await act(async () => inDialog('Fill now').click());+ expect(dialog()).toBeNull();+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ const { from, to } = editor.state.selection;+ expect(editor.state.doc.textBetween(from, to)).toBe('[name of a real person]');+ });++ it("reads a FAQPage's JSON-LD by its strings: Ready to paste is done", async () => {+ const faq = {+ '@context': 'https://schema.org',+ '@type': 'FAQPage',+ mainEntity: [+ {+ '@type': 'Question',+ name: 'How long does it take?',+ acceptedAnswer: { '@type': 'Answer', text: 'About a week.' },+ },+ ],+ sameAs: ['https://x.example/acme'],+ };+ getContentDraft.mockResolvedValue(+ draft({+ bodyHtml: `<h1>Pipeline forecasting</h1><p>Teams trust it.</p><script type="application/ld+json">${JSON.stringify(faq)}</script>`,+ }),+ );+ await renderPage();+ const ready =+ 'Ready to paste · doneNo placeholders, all images have alt text, all links work.';+ await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain(ready);+ await act(async () => inDialog('Continue to export').click());+ expect(dialog()!.querySelector('[role="alert"]')).toBeNull();+ expect(inDialog('Copy for Webflow').disabled).toBe(false);+ await act(async () => inDialog('Cancel').click());+ await act(async () => button('Mark ready')!.click());+ expect(dialog()!.textContent).toContain(ready);+ });++ it('fills in the HTML view where the count reads, past code and markup', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await act(async () => button('Edit as HTML')!.click());+ const source = container.querySelector('textarea')!;+ const html =+ '<!-- html-block -->\n<style>.cta a[href] { color: red }</style>\n<!-- /html-block -->\n' ++ '<h1 title="Pipeline">Pipeline forecasting [2026 Update]</h1>\n<p>Ask [name of a real person] how.</p>';+ const setValue = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ 'value',+ )!.set!;+ await act(async () => {+ setValue.call(source, html);+ source.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain('1 placeholder still open');+ await act(async () => inDialog('Fill now').click());+ expect(dialog()).toBeNull();+ expect(source.value.slice(source.selectionStart, source.selectionEnd)).toBe(+ '[name of a real person]',+ );+ });+it('sends Copy HTML to Export while a placeholder is open, and Fill now goes to it', async () => {const writeText = vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });@@ -2884,6 +3013,8 @@ describe('the side panel', () => {);await renderPage();await act(async () => button('Export')!.click());+ expect(dialog()!.textContent).toContain('1 placeholder still open');+ await act(async () => inDialog('Continue to export').click());expect(dialog()!.textContent).toContain('1 placeholder is still open');await act(async () => inDialog('Fill now').click());expect(toast).toHaveBeenCalledWith(diff --git a/web/src/lib/content/ready-to-publish.test.ts b/web/src/lib/content/ready-to-publish.test.tsindex ae7bbf6b3..9af58ac8c 100644--- a/web/src/lib/content/ready-to-publish.test.ts+++ b/web/src/lib/content/ready-to-publish.test.ts@@ -1,7 +1,9 @@import { describe, expect, it } from 'vitest';import type { ContentAuthor } from './authors';import type { LinkCheck } from './quality-checks';+import { PLACEHOLDER } from './placeholders';import {+ blankCode,exportPlaceholders,fragment,pageFields,@@ -83,12 +85,65 @@ describe('titlePlaceholders', () => {expect(titlePlaceholders(title, '<p>No H1.</p>')).toBe(1);});+ it('counts it with the page when a heading or the first line reads as it, H1 or not', () => {+ const title = 'How [name of a real person] forecasts';+ // An H2 with no H1 above it: the title is that heading.+ expect(titlePlaceholders(title, '<h2>How [name of a real person] forecasts</h2>')).toBe(0);+ expect(titlePlaceholders(title, '<p>Teams trust it.</p><h2>Other</h2>')).toBe(1);+ // No heading: the title is the first line's start, cut with an ellipsis.+ const line =+ 'Ask [name of a real person] how pipeline forecasting works when the quarter closes and the numbers shift.';+ expect(+ titlePlaceholders(+ 'Ask [name of a real person] how pipeline forecasting works when the quarter…',+ `<p>${line}</p>`,+ ),+ ).toBe(0);+ });+it("reads a person's brackets in the title as part of it", () => {expect(titlePlaceholders('Best CRM tools [2026 Update]', '<p>No H1.</p>')).toBe(0);expect(titlePlaceholders('The checklist [PDF]', '<h1>The checklist</h1>')).toBe(0);});});+describe('blankCode', () => {+ const matches = (text: string) => [...text.matchAll(PLACEHOLDER)];++ it('leaves only where exportPlaceholders reads, each position as in the HTML', () => {+ const html =+ '<style>a[href] { color: red }</style><script>var a = ["x y"];</script>\n' ++ '<script type="application/ld+json">{"@type":"FAQPage","sameAs":["https://x.example/"],"text":"Costs [price]."}</script>\n' ++ '<!-- [old note] -->\n<h1>Best CRM tools [2026 Update]</h1>\n' ++ '<p class="[cta]">Ask <img src="https://cdn.acme.com/a.jpg" alt="[photo of the founder]"> [name of a real person].</p>';+ const blanked = blankCode(html, { words: true });+ expect(blanked).toHaveLength(html.length);+ const found = matches(blanked).map((m) => html.slice(m.index, m.index + m[0].length));+ expect(found).toEqual(['[price]', '[photo of the founder]', '[name of a real person]']);+ expect(found).toHaveLength(exportPlaceholders(html));+ // A heading's own forms stay; a JSON-LD that doesn't parse is read for none.+ expect(+ matches(+ blankCode(+ '<h2>What [name of a real person] uses</h2><script type="application/ld+json">{"a":"[x y]",</script>',+ { words: true },+ ),+ ).map((m) => m[0]),+ ).toEqual(['[name of a real person]']);+ });++ it('blanks comments and what scripts, styles and templates hold, keeping the tags', () => {+ const html =+ '<!-- <h1>Old</h1> -->\n<script>document.write("</h1>")</script><template><h1>T</h1></template>\n<h1>Pour-over</h1>';+ const blanked = blankCode(html);+ expect(blanked).toHaveLength(html.length);+ expect(blanked.indexOf('<h1>')).toBe(html.lastIndexOf('<h1>'));+ expect(blanked.indexOf('</h1>')).toBe(html.lastIndexOf('</h1>'));+ expect(blanked).toContain('<script>');+ expect(blanked).toContain('</template>');+ });+});+describe('withoutPlaceholders', () => {it('leaves out the sentence a placeholder is in, and keeps the rest as written', () => {expect(diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.tsindex 92e0fe811..f21306bad 100644--- a/web/src/lib/content/ready-to-publish.ts+++ b/web/src/lib/content/ready-to-publish.ts@@ -2,7 +2,7 @@ import { slugify } from '@/lib/slug';import type { ContentAuthor } from './authors';import { cleanHref, jsonLdText } from './html-allowlist';import { firstImage } from './page-schema';-import { PLACEHOLDER, placeholderIn } from './placeholders';+import { AGENT_PLACEHOLDER, PLACEHOLDER, placeholderIn } from './placeholders';import type { LinkCheck } from './quality-checks';/**@@ -100,15 +100,21 @@ function otherText(root: HTMLElement): Field[] {const count = (text: string, heading = false) => text.match(placeholderIn(heading))?.length ?? 0;const inHeading = (node: Node) => !!node.parentElement?.closest(HEADINGS);+const normalized = (text: string) => text.replace(/\s+/g, ' ').trim();+/**- * The title's placeholders, when the page doesn't hold them already: a- * title that is the page's H1 is counted with the page.+ * The title's placeholders, when the page doesn't hold them already. The+ * title is read from the page (draftTitleFromDoc: its first H1, else its+ * first heading, else its first line, cut with "…"), so a heading or a+ * paragraph that starts as it reads holds them, and they are counted with+ * the page.*/export function titlePlaceholders(title: string, html: string): number {- const h1 = fragment(html).querySelector('h1');- const same =- h1 && (h1.textContent ?? '').replace(/\s+/g, ' ').trim() === title.replace(/\s+/g, ' ').trim();- return same ? 0 : count(title, true);+ const start = normalized(title).replace(/…$/, '').trimEnd();+ const held = Array.from(fragment(html).querySelectorAll(`${HEADINGS}, p`)).some((line) =>+ normalized(line.textContent ?? '').startsWith(start),+ );+ return held ? 0 : count(title, true);}/**@@ -123,6 +129,147 @@ export function exportPlaceholders(html: string): number {);}+/** One of the agent's own forms, whole. */+const AGENT_ONE = new RegExp(`^(?:${AGENT_PLACEHOLDER.source})$`, 'iu');+/** Elements whose content is code, not words: blanked, the next end tag theirs. */+const CODE = new Set(['script', 'style', 'template']);++/**+ * A tag read from its "<": where it ends (past its ">"), and where each of+ * its attributes' values is. Read by a scan, as jsonLdScripts reads one: the+ * time grows with the length only.+ */+function readTag(lower: string, open: number) {+ const values: { name: string; from: number; to: number }[] = [];+ const at = (i: number, chars: RegExp) => i < lower.length && chars.test(lower[i]);+ let i = open + 1;+ while (at(i, /[^\s/>]/)) i++;+ for (;;) {+ while (at(i, /[\s/]/)) i++;+ if (i >= lower.length) return { end: lower.length, values };+ if (lower[i] === '>') return { end: i + 1, values };+ const nameFrom = i;+ while (at(i, /[^\s/>=]/)) i++;+ const name = lower.slice(nameFrom, i);+ while (at(i, /\s/)) i++;+ if (lower[i] !== '=') continue;+ i++;+ while (at(i, /\s/)) i++;+ const quote = lower[i];+ if (quote === '"' || quote === "'") {+ const close = lower.indexOf(quote, i + 1);+ const to = close === -1 ? lower.length : close;+ values.push({ name, from: i + 1, to });+ i = to + 1;+ } else {+ const from = i;+ while (at(i, /[^\s>]/)) i++;+ values.push({ name, from, to: i });+ }+ }+}++/**+ * The HTML with its code blanked out, each character a space, so a position+ * in it is the same in the HTML: comments, and what a <script>, <style> or+ * <template> holds. With `words`, only what exportPlaceholders reads is left:+ * the words (a heading's brackets only in the agent's forms), alt and title+ * values, and a JSON-LD's strings; the tags, styles and other scripts go+ * too. For a search that must find what the page holds, not its code.+ */+export function blankCode(html: string, { words = false } = {}): string {+ // ASCII letters only: lower-casing all of it could change the length.+ const lower = html.replace(/[A-Z]+/g, (s) => s.toLowerCase());+ const out: string[] = [];+ const blank = (from: number, to: number) => out.push(' '.repeat(Math.max(0, to - from)));+ const keep = (from: number, to: number) => out.push(html.slice(from, to));+ let headings = 0;+ const text = (from: number, to: number) => {+ if (!words || !headings) return keep(from, to);+ out.push(+ html+ .slice(from, to)+ .replace(PLACEHOLDER, (m) => (AGENT_ONE.test(m) ? m : ' '.repeat(m.length))),+ );+ };+ // A tag in words: blanked, but for its alt and title values.+ const tag = (from: number, tagEnd: number, values: ReturnType<typeof readTag>['values']) => {+ if (!words) return keep(from, tagEnd);+ let at = from;+ for (const value of values) {+ if (value.name !== 'alt' && value.name !== 'title') continue;+ blank(at, value.from);+ keep(value.from, value.to);+ at = value.to;+ }+ blank(at, tagEnd);+ };+ let at = 0;+ while (at < html.length) {+ const open = html.indexOf('<', at);+ if (open === -1) break;+ text(at, open);+ if (lower.startsWith('<!--', open)) {+ const close = lower.indexOf('-->', open + 4);+ at = close === -1 ? html.length : close + 3;+ blank(open, at);+ continue;+ }+ const name = /<(\/?)([a-z][a-z0-9-]*)/y;+ name.lastIndex = open;+ const m = name.exec(lower);+ if (!m && !/[!?]/.test(lower.charAt(open + 1))) {+ // A "<" that starts no tag is a word.+ text(open, open + 1);+ at = open + 1;+ continue;+ }+ const { end, values } = readTag(lower, open);+ at = end;+ if (!m) {+ // A doctype or a processing instruction.+ blank(open, end);+ continue;+ }+ const [, closing, tagName] = m;+ if (/^h[1-6]$/.test(tagName)) headings = Math.max(0, headings + (closing ? -1 : 1));+ if (closing || !CODE.has(tagName)) {+ tag(open, end, values);+ continue;+ }+ // Code: its text is no markup, the next end tag of its kind ends it.+ const close = lower.indexOf(`</${tagName}`, end);+ const codeEnd = close === -1 ? html.length : close;+ const jsonLd =+ tagName === 'script' &&+ values.some(+ (v) => v.name === 'type' && lower.slice(v.from, v.to).trim() === 'application/ld+json',+ );+ if (words && !jsonLd) {+ blank(open, codeEnd);+ } else {+ tag(open, end, values);+ const code = html.slice(end, codeEnd);+ out.push(words ? jsonLdStrings(code) : ' '.repeat(code.length));+ }+ at = codeEnd;+ }+ text(at, html.length);+ return out.join('');+}++/** A JSON-LD's text with only its strings' insides left; all of it blanked when it doesn't parse. */+function jsonLdStrings(code: string): string {+ try {+ JSON.parse(code);+ } catch {+ return ' '.repeat(code.length);+ }+ return code.replace(/"((?:[^"\\]|\\.)*)"|[^"]+/g, (m, inner?: string) =>+ inner === undefined ? ' '.repeat(m.length) : ` ${inner} `,+ );+}+/** Lines whose text is read as sentences. */const LINES = `p, li, td, th, dd, dt, figcaption, blockquote, caption, summary, ${HEADINGS}`;