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.

fix(content): show where a page's placeholders are and step through them, the hidden ones included (#1619)

Cihan698f2254648f
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdx
index 2908d7c42..8142267e0 100644
--- a/docs/guides/content-editor.mdx
+++ b/docs/guides/content-editor.mdx
@@ -120,6 +120,8 @@ The header shows the title, the page type, a **Rules** chip with how many rules
The page starts with its H1, which is also its title. A page has one H1: the toolbar won't add a second one. A paste is cleaned on the way in: headings, lists, links and tables stay; fonts, colors and styles go. Press ⌘/Ctrl + Shift + V to paste plain text. **Attach a file** inserts Excel, CSV, Word, Markdown, HTML or text, up to 10 MB each; a sheet comes in as a table.
+Words in square brackets, such as `[figure, source]` or `[competitor]`, are placeholders: the Content Agent leaves one where a real name, quote or number goes. Each is tinted amber in the page, and the toolbar counts those left to fill. Click the count or the arrows beside it to go to the next or the previous one, already selected, so you type over it. A placeholder in an image's alt text, the JSON-LD or an HTML block isn't in the page's text: it's counted too, and **Show in HTML** selects it in the HTML view. Export and Send to CMS wait until none is left.
+
### Side panel
The panel opens on **Rules**. Its tabs are **Rules · Brief · Sources · Live page**.
diff --git a/docs/guides/send-to-cms.mdx b/docs/guides/send-to-cms.mdx
index f217900b8..fd146e7dd 100644
--- a/docs/guides/send-to-cms.mdx
+++ b/docs/guides/send-to-cms.mdx
@@ -73,7 +73,7 @@ Once you publish it in Webflow, the page becomes **Published** at its address on
The page goes as **Export** makes it: the HTML without its H1 (your CMS's title field carries it), with the byline line if your brand adds the byline to its content. Ansvisor holds the send while:
-- a placeholder such as `[figure, source]` is still open (**Fill now** goes to it);
+- a placeholder such as `[figure, source]` is still open: **Fill now** selects the first one, in the page or, when it's in an image's alt text, the JSON-LD or an HTML block, in the HTML view. The editor's toolbar counts those left and steps through them;
- the page has no title, or nothing under its title;
- the slug can't be used.
diff --git a/web/messages/en.json b/web/messages/en.json
index 39d28f109..a78db8c14 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5000,11 +5000,20 @@
"copied": "Copied for {destination}: paste it in.",
"copiedHtml": "HTML copied.",
"copiedAsHtml": "Copied as HTML: paste it into the editor's HTML or code view.",
- "inHtmlBlock": "The placeholders are in an HTML block: open it with {html} to fill them.",
"copyFailed": "Couldn't copy. Open the HTML view and copy it from there.",
"failed": "Couldn't export the page. Try again.",
"cancel": "Cancel"
},
+ "placeholders": {
+ "label": "Placeholders to fill",
+ "left": "{count, plural, =0 {No placeholders left to fill} one {# placeholder to fill} other {# placeholders to fill}}",
+ "onOf": "Placeholder {on} of {count}",
+ "previous": "Previous placeholder",
+ "next": "Next placeholder",
+ "showHidden": "Show in HTML",
+ "hiddenHint": "In an image's alt text, the JSON-LD or an HTML block: the page doesn't show them.",
+ "inHtmlView": "This placeholder is in an image's alt text, the JSON-LD or an HTML block. It's selected in the HTML view ({html}): type over it, then apply."
+ },
"beforePublish": {
"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}.",
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.tsx
index 4b649318b..05d95283b 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
@@ -109,7 +109,7 @@ import {
listedProducts,
MIN_LISTED,
} from '@/lib/content/page-schema';
-import { PLACEHOLDER, pagePlaceholders, placeholderIn } from '@/lib/content/placeholders';
+import { PLACEHOLDER, pagePlaceholders } from '@/lib/content/placeholders';
import { HANDOFF_KEYS, handOffItems } from '@/lib/content/hand-off';
import {
blankCode,
@@ -205,6 +205,7 @@ import { AuthorMenu, MANAGE_AUTHORS_PATH } from './_author-menu';
import { ReviewerMenu } from './_reviewer-menu';
import { BeforePublish, TRUST_GATE, type ReadyAnyway, type ReadyToPaste } from './_before-publish';
import { FlashBlock, findBlock, flashKey } from './_flash-block';
+import { PlaceholderMarks, placeholderRanges, selectPlaceholder } from './_placeholder-marks';
import { useAgentRun } from './_use-agent-run';
import { useAutoHandOff } from './_use-auto-hand-off';
import { useLinkChecks } from './_use-link-checks';
@@ -613,6 +614,7 @@ export function DraftEditor({
OneH1,
AgentDrafting,
FlashBlock,
+ PlaceholderMarks,
PageInfoStrip,
WeakSourcesMarks,
ClaimMarksExtension,
@@ -1437,6 +1439,18 @@ export function DraftEditor({
);
const [hadPlaceholders, setHadPlaceholders] = useState(false);
if (placeholderCount > 0 && !hadPlaceholders) setHadPlaceholders(true);
+ // The placeholders a send or an export finds that the page's text doesn't
+ // show: in an image's alt text, the JSON-LD, an HTML block, or a title the
+ // page doesn't hold. The toolbar counts them with the page's (a code
+ // block's too, which the marks hold and pagePlaceholders doesn't read).
+ const hiddenPlaceholders = useMemo(() => {
+ const html = publishableHtml(pageHtml);
+ const found = exportPlaceholders(html) + titlePlaceholders(title, html);
+ const code = Array.from(
+ new DOMParser().parseFromString(pageHtml, 'text/html').querySelectorAll('pre'),
+ ).reduce((sum, pre) => sum + (pre.textContent?.match(PLACEHOLDER)?.length ?? 0), 0);
+ return Math.max(0, found - pagePlaceholders(pageHtml).count - code);
+ }, [pageHtml, title]);
// Who may edit the page's author: only they get Edit author (CE-037's rule).
const canEditPageAuthor =
!!pageAuthor && !!authorsRead && canEditAuthor(pageAuthor, authorsRead.me);
@@ -2156,40 +2170,10 @@ export function DraftEditor({
*/
const showFirstPlaceholder = (): boolean => {
if (!editor) return false;
- let found: { from: number; to: number; block: { from: number; to: number } } | null = null;
- editor.state.doc.descendants((block, pos) => {
- if (found) return false;
- if (!block.isTextblock) return true;
- // The line's text, with where each piece of it starts in the page.
- let text = '';
- const pieces: { at: number; pos: number }[] = [];
- block.forEach((child, offset) => {
- if (!child.isText) return;
- pieces.push({ at: text.length, pos: pos + 1 + offset });
- text += child.text;
- });
- const m = new RegExp(placeholderIn(block.type.name === 'heading').source, 'iu').exec(text);
- if (!m) return false;
- const posOf = (i: number) => {
- const piece = pieces.findLast((p) => p.at <= i)!;
- return piece.pos + (i - piece.at);
- };
- found = {
- from: posOf(m.index),
- to: posOf(m.index + m[0].length - 1) + 1,
- block: { from: pos, to: pos + block.nodeSize },
- };
- return false;
- });
- if (!found) return false;
- const { from, to, block } = found;
- editor
- .chain()
- .setTextSelection({ from, to })
- .scrollIntoView()
- .focus(undefined, { scrollIntoView: false })
- .run();
- editor.view.dispatch(editor.state.tr.setMeta(flashKey, block));
+ const [first] = placeholderRanges(editor.state.doc);
+ if (!first) return false;
+ selectPlaceholder(editor, first);
+ editor.view.dispatch(editor.state.tr.setMeta(flashKey, first.block));
setTimeout(() => {
if (!editor.isDestroyed) editor.view.dispatch(editor.state.tr.setMeta(flashKey, null));
}, 1200);
@@ -2197,10 +2181,11 @@ export function DraftEditor({
};
/**
- * Fill now (Export, CE-057): the first placeholder, in the HTML view's
- * 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.
+ * Fill now (Export, CE-057; Send to CMS; Before you publish): the first
+ * placeholder, in the HTML view's text while it is open (where
+ * exportPlaceholders reads: not in tags, styles or scripts), else in the
+ * page. One the page's text doesn't show (an image's alt text, the
+ * JSON-LD, an HTML block) is selected in the HTML view, opened for it.
*/
const htmlSourceRef = useRef<HTMLTextAreaElement>(null);
// The disclosure line Before you publish offers (CE-050), and whether the
@@ -2271,17 +2256,33 @@ export function DraftEditor({
)
.run();
};
+ // Fill now for a placeholder the page's text doesn't show, and the
+ // toolbar's Show in HTML: once the HTML view is open (Show in HTML's, the
+ // first the page's text doesn't show).
+ const [fillInHtml, setFillInHtml] = useState<null | { hidden: boolean }>(null);
+ useEffect(() => {
+ if (!fillInHtml || htmlSource === null) return;
+ setFillInHtml(null);
+ selectHtmlPlaceholder(htmlSourceRef.current, htmlSource, fillInHtml);
+ }, [fillInHtml, htmlSource]);
const fillFirstPlaceholder = () => {
if (htmlSource !== null) {
- const m = new RegExp(PLACEHOLDER.source, 'iu').exec(blankCode(htmlSource, { words: true }));
- const area = htmlSourceRef.current;
- if (m && area) {
- area.focus();
- area.setSelectionRange(m.index, m.index + m[0].length);
- }
+ selectHtmlPlaceholder(htmlSourceRef.current, htmlSource);
+ return;
+ }
+ if (showFirstPlaceholder()) return;
+ if (openHtmlView()) {
+ setFillInHtml({ hidden: false });
+ toast(t('placeholders.inHtmlView', { html: '</>' }));
+ }
+ };
+ // Show in HTML: straight to the HTML view, past the page's own placeholders.
+ const showHiddenPlaceholder = () => {
+ if (htmlSource !== null) {
+ selectHtmlPlaceholder(htmlSourceRef.current, htmlSource, { hidden: true });
return;
}
- if (!showFirstPlaceholder()) toast(t('exportDialog.inHtmlBlock', { html: '</>' }));
+ if (openHtmlView()) setFillInHtml({ hidden: true });
};
/**
@@ -2833,15 +2834,17 @@ export function DraftEditor({
},
};
- const openHtmlView = () => {
- if (!editor) return;
+ /** Opens the HTML view; whether it opened. */
+ const openHtmlView = (): boolean => {
+ if (!editor) return false;
// The cards aren't in the HTML: decide them first.
if (openSuggestions > 0) {
toast(t('suggestions.htmlBlocked', { count: openSuggestions }));
- return;
+ return false;
}
setHtmlSource(formatHtmlSource(editor.getHTML()));
setHtmlEdited(false);
+ return true;
};
const applyHtmlView = () => {
if (!editor || htmlSource === null) return;
@@ -4141,6 +4144,7 @@ export function DraftEditor({
onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
onAttach={attachments.open}
linkRequest={linkRequest}
+ placeholders={{ hidden: hiddenPlaceholders, onShowHidden: showHiddenPlaceholder }}
// + Insert › Products, from an online shop's catalog (shopping path, part 5).
productsBrandId={siteType === 'ecommerce' ? draft.brandId : null}
/>
@@ -4423,6 +4427,45 @@ export function DraftEditor({
);
}
+/**
+ * Where the page's text shows a placeholder in the HTML view's source: in
+ * its words, not an alt or title value, the JSON-LD, or an HTML block's code
+ * (between its markers).
+ */
+function shownPlaceholderAt(source: string): Set<number> {
+ const blocks = [...source.matchAll(/<!-- html-block -->[\s\S]*?<!-- \/html-block -->/g)];
+ const inBlock = (i: number) => blocks.some((b) => i > b.index && i < b.index + b[0].length);
+ const words = blankCode(source, { words: true, fields: false });
+ return new Set(
+ [...words.matchAll(new RegExp(PLACEHOLDER.source, 'giu'))]
+ .map((m) => m.index)
+ .filter((i) => !inBlock(i)),
+ );
+}
+
+/**
+ * The HTML view's first placeholder, selected and scrolled to. With
+ * `hidden`, the first the page's text doesn't show (an image's alt text,
+ * the JSON-LD, an HTML block), when there is one.
+ */
+function selectHtmlPlaceholder(
+ area: HTMLTextAreaElement | null,
+ source: string,
+ { hidden = false } = {},
+) {
+ const found = [
+ ...blankCode(source, { words: true }).matchAll(new RegExp(PLACEHOLDER.source, 'giu')),
+ ];
+ const shown = hidden ? shownPlaceholderAt(source) : null;
+ const m = found.find((f) => !shown?.has(f.index)) ?? found[0];
+ if (!m || !area) return;
+ area.focus();
+ area.setSelectionRange(m.index, m.index + m[0].length);
+ // A textarea scrolls to its selection on focus, not on a new range.
+ area.blur();
+ area.focus();
+}
+
function SaveIndicator({ state, onRetry }: { state: SaveState; onRetry: () => void }) {
const t = useTranslations('contentEditor.editor.save');
if (state === 'conflict') {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx
index 5c2c61cab..c050e482c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx
@@ -222,6 +222,12 @@ export function ExportDialog({
const [platformsOpen, setPlatformsOpen] = useState(() => isPlatform(destination));
const platformsId = useId();
const radios = useRef<Partial<Record<ExportDestination, HTMLButtonElement | null>>>({});
+ // Fill now: the editor selects the placeholder, so focus stays there.
+ const filling = useRef(false);
+ const fillNow = () => {
+ filling.current = true;
+ onFillNow();
+ };
const placeholders = useMemo(
() => exportPlaceholders(html) + titlePlaceholders(title, html),
[html, title],
@@ -443,6 +449,7 @@ export function ExportDialog({
// Focus starts on the destination picked, as a radio group's does:
// Enter or Space then keeps it, not the first file's.
initialFocus={() => radios.current[destination] ?? true}
+ finalFocus={() => !filling.current}
>
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
@@ -506,7 +513,7 @@ export function ExportDialog({
: t('placeholders.headings', { count: left })}
</span>
{!ready && (
- <Button variant="outline" size="sm" className="h-7" onClick={onFillNow}>
+ <Button variant="outline" size="sm" className="h-7" onClick={fillNow}>
{t('placeholders.fill')}
</Button>
)}
@@ -526,7 +533,7 @@ export function ExportDialog({
<AlertTriangle aria-hidden className="mt-0.5 h-4 w-4 shrink-0" />
<p className="min-w-0 flex-1">{t('placeholders.open', { count: placeholders })}</p>
<div className="flex w-full justify-end gap-2">
- <Button variant="outline" size="sm" className="h-7" onClick={onFillNow}>
+ <Button variant="outline" size="sm" className="h-7" onClick={fillNow}>
{t('placeholders.fill')}
</Button>
<Button
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.test.ts
new file mode 100644
index 000000000..b06c6009c
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.test.ts
@@ -0,0 +1,137 @@
+import { Editor } from '@tiptap/core';
+import StarterKit from '@tiptap/starter-kit';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ PlaceholderMarks,
+ placeholderIndexAt,
+ placeholderMarksKey,
+ placeholderRanges,
+ selectPlaceholder,
+ stepPlaceholder,
+} from './_placeholder-marks';
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+});
+
+const open = (content: string) => {
+ editor = new Editor({ extensions: [StarterKit, PlaceholderMarks], content });
+ return editor;
+};
+
+/** Each placeholder's text, as the page reads. */
+const texts = (e: Editor) =>
+ placeholderRanges(e.state.doc).map((r) => e.state.doc.textBetween(r.from, r.to));
+
+/** The page's placeholders (CE-044), marked and stepped through. */
+describe('placeholderRanges', () => {
+ it("finds every placeholder in order, in paragraphs and lists, across a line's marks", () => {
+ const e = open(
+ '<h1>Title</h1><p>Rivals like [competitor] lead. Ensure your <strong>[About]</strong> and [Documentation] pages.</p>' +
+ '<ul><li><p>Check [OpenAI release notes]</p></li></ul><p>Not [1], [x] or [docs](https://a.example).</p>',
+ );
+ expect(texts(e)).toEqual([
+ '[competitor]',
+ '[About]',
+ '[Documentation]',
+ '[OpenAI release notes]',
+ ]);
+ });
+
+ it("reads a heading's only in the agent's own forms", () => {
+ const e = open(
+ '<h2>Best CRM tools [2026 Update]</h2><h2>Grew [figure, source] last year</h2><p>[price]</p>',
+ );
+ expect(texts(e)).toEqual(['[figure, source]', '[price]']);
+ });
+
+ it('finds two that read the same as two', () => {
+ const e = open('<p>See [notes].</p><h2>FAQ</h2><p>Also in [notes].</p>');
+ expect(texts(e)).toEqual(['[notes]', '[notes]']);
+ });
+});
+
+describe('PlaceholderMarks', () => {
+ it('tints each placeholder, and follows the page as it changes', () => {
+ const e = open('<p>Rivals like [competitor] and [partner] lead.</p>');
+ const marks = () =>
+ [...e.view.dom.querySelectorAll('[data-placeholder-mark]')].map((m) => m.textContent);
+ expect(marks()).toEqual(['[competitor]', '[partner]']);
+ expect(placeholderMarksKey.getState(e.state)?.ranges).toHaveLength(2);
+
+ const [first] = placeholderRanges(e.state.doc);
+ e.chain().setTextSelection({ from: first.from, to: first.to }).insertContent('Acme').run();
+ expect(marks()).toEqual(['[partner]']);
+ expect(placeholderMarksKey.getState(e.state)?.ranges).toHaveLength(1);
+ });
+});
+
+describe('stepPlaceholder', () => {
+ const ranges = [
+ { from: 5, to: 10, block: { from: 0, to: 20 } },
+ { from: 25, to: 30, block: { from: 20, to: 40 } },
+ { from: 45, to: 50, block: { from: 40, to: 60 } },
+ ];
+
+ it('goes to the next one after the cursor, and round to the first past the last', () => {
+ expect(stepPlaceholder(ranges, 0, 1)).toBe(ranges[0]);
+ expect(stepPlaceholder(ranges, 7, 1)).toBe(ranges[1]);
+ expect(stepPlaceholder(ranges, 12, 1)).toBe(ranges[1]);
+ expect(stepPlaceholder(ranges, 47, 1)).toBe(ranges[0]);
+ expect(stepPlaceholder(ranges, 55, 1)).toBe(ranges[0]);
+ });
+
+ it('goes to the one before, and round to the last before the first', () => {
+ expect(stepPlaceholder(ranges, 27, -1)).toBe(ranges[0]);
+ expect(stepPlaceholder(ranges, 40, -1)).toBe(ranges[1]);
+ expect(stepPlaceholder(ranges, 7, -1)).toBe(ranges[2]);
+ expect(stepPlaceholder(ranges, 0, -1)).toBe(ranges[2]);
+ });
+
+ it('finds none in a page without one', () => {
+ expect(stepPlaceholder([], 3, 1)).toBeNull();
+ });
+
+ it('goes on past two that touch, the second selected starting where the first ends', () => {
+ const e = open('<p>Call [ab][cd] or [ef].</p>');
+ const found = placeholderRanges(e.state.doc);
+ expect(found.map((r) => e.state.doc.textBetween(r.from, r.to))).toEqual([
+ '[ab]',
+ '[cd]',
+ '[ef]',
+ ]);
+ expect(found[0].to).toBe(found[1].from);
+ // On the second (its start is the first's end), Next is the third, not the second again.
+ expect(placeholderIndexAt(found, found[1].from)).toBe(1);
+ expect(stepPlaceholder(found, found[1].from, 1)).toBe(found[2]);
+ expect(stepPlaceholder(found, found[1].from, -1)).toBe(found[0]);
+ // On the first, Next is the second.
+ expect(stepPlaceholder(found, found[0].from, 1)).toBe(found[1]);
+ });
+});
+
+describe('placeholderIndexAt', () => {
+ const ranges = [
+ { from: 5, to: 10, block: { from: 0, to: 30 } },
+ { from: 10, to: 15, block: { from: 0, to: 30 } },
+ { from: 20, to: 25, block: { from: 0, to: 30 } },
+ ];
+
+ it('reads the one the cursor is in, at its end too, and the second where two touch', () => {
+ expect(placeholderIndexAt(ranges, 7)).toBe(0);
+ expect(placeholderIndexAt(ranges, 10)).toBe(1);
+ expect(placeholderIndexAt(ranges, 25)).toBe(2);
+ expect(placeholderIndexAt(ranges, 17)).toBe(-1);
+ });
+});
+
+describe('selectPlaceholder', () => {
+ it('selects the placeholder, to type over', () => {
+ const e = open('<p>Rivals like [competitor] lead.</p>');
+ selectPlaceholder(e, placeholderRanges(e.state.doc)[0]);
+ const { from, to } = e.state.selection;
+ expect(e.state.doc.textBetween(from, to)).toBe('[competitor]');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.ts
new file mode 100644
index 000000000..740073731
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-marks.ts
@@ -0,0 +1,134 @@
+import { Extension, type Editor } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { placeholderIn } from '@/lib/content/placeholders';
+
+/**
+ * The page's placeholders (CE-044), marked where they are: what the Content
+ * Agent leaves in square brackets for the person to fill, and what holds a
+ * send to a CMS or an export until they do. Each one is tinted amber, so the
+ * person sees them as they read; the toolbar counts them and steps from one
+ * to the next (PlaceholderNav). A heading's are the agent's own forms only
+ * (AGENT_PLACEHOLDER), as everywhere else.
+ */
+
+/** A placeholder in the page, and the block (a paragraph or a heading) holding it. */
+export interface PlaceholderRange {
+ from: number;
+ to: number;
+ block: { from: number; to: number };
+}
+
+/** The page's placeholders, in order: each line read once, across the marks in it. */
+export function placeholderRanges(doc: PmNode): PlaceholderRange[] {
+ const found: PlaceholderRange[] = [];
+ doc.descendants((block, pos) => {
+ if (!block.isTextblock) return true;
+ // The line's text, with where each piece of it starts in the page.
+ let text = '';
+ const pieces: { at: number; pos: number }[] = [];
+ block.forEach((child, offset) => {
+ if (!child.isText) return;
+ pieces.push({ at: text.length, pos: pos + 1 + offset });
+ text += child.text;
+ });
+ const posOf = (i: number) => {
+ const piece = pieces.findLast((p) => p.at <= i)!;
+ return piece.pos + (i - piece.at);
+ };
+ for (const m of text.matchAll(placeholderIn(block.type.name === 'heading'))) {
+ found.push({
+ from: posOf(m.index),
+ to: posOf(m.index + m[0].length - 1) + 1,
+ block: { from: pos, to: pos + block.nodeSize },
+ });
+ }
+ return false;
+ });
+ return found;
+}
+
+/**
+ * Which placeholder the cursor at `at` is on (-1 for none): the last one
+ * holding it, so where two touch ("[ab][cd]") the end of the first, which
+ * is where the second starts, is the second's.
+ */
+export function placeholderIndexAt(ranges: readonly PlaceholderRange[], at: number): number {
+ return ranges.findLastIndex((r) => at >= r.from && at <= r.to);
+}
+
+/**
+ * The placeholder after (or before) the cursor at `at`, round to the first
+ * (or the last) past the end: from inside one, its neighbour.
+ */
+export function stepPlaceholder(
+ ranges: readonly PlaceholderRange[],
+ at: number,
+ direction: 1 | -1,
+): PlaceholderRange | null {
+ if (!ranges.length) return null;
+ const here = placeholderIndexAt(ranges, at);
+ if (direction === 1) {
+ const next = here >= 0 ? here + 1 : ranges.findIndex((r) => r.from > at);
+ return ranges[next >= 0 && next < ranges.length ? next : 0];
+ }
+ const previous = here >= 0 ? here - 1 : ranges.findLastIndex((r) => r.to < at);
+ return ranges[previous >= 0 ? previous : ranges.length - 1];
+}
+
+/** Selects a placeholder to type over, scrolled to. */
+export function selectPlaceholder(editor: Editor, range: PlaceholderRange) {
+ editor
+ .chain()
+ .setTextSelection({ from: range.from, to: range.to })
+ .scrollIntoView()
+ .focus(undefined, { scrollIntoView: false })
+ .run();
+}
+
+/** The tint, in the light and the dark theme. */
+export const PLACEHOLDER_MARK_CLASS =
+ 'rounded-sm bg-amber-100 text-amber-900 dark:bg-amber-500/25 dark:text-amber-100';
+
+interface MarksState {
+ ranges: PlaceholderRange[];
+ decorations: DecorationSet;
+}
+
+function read(doc: PmNode): MarksState {
+ const ranges = placeholderRanges(doc);
+ return {
+ ranges,
+ decorations: DecorationSet.create(
+ doc,
+ ranges.map((r) =>
+ Decoration.inline(r.from, r.to, {
+ class: PLACEHOLDER_MARK_CLASS,
+ 'data-placeholder-mark': '',
+ }),
+ ),
+ ),
+ };
+}
+
+export const placeholderMarksKey = new PluginKey<MarksState>('placeholderMarks');
+
+export const PlaceholderMarks = Extension.create({
+ name: 'placeholderMarks',
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin<MarksState>({
+ key: placeholderMarksKey,
+ state: {
+ init: (_, state) => read(state.doc),
+ apply: (tr, previous) => (tr.docChanged ? read(tr.doc) : previous),
+ },
+ props: {
+ decorations: (state) => placeholderMarksKey.getState(state)?.decorations ?? null,
+ },
+ }),
+ ];
+ },
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.test.tsx
new file mode 100644
index 000000000..bdbb8ce04
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.test.tsx
@@ -0,0 +1,150 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { Editor } from '@tiptap/react';
+import StarterKit from '@tiptap/starter-kit';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import { PlaceholderMarks } from './_placeholder-marks';
+import { PlaceholderNav } from './_placeholder-nav';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+let editor: Editor;
+
+async function render(content: string, hidden = 0, onShowHidden = vi.fn()) {
+ editor = new Editor({ extensions: [StarterKit, PlaceholderMarks], content });
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <PlaceholderNav editor={editor} hidden={hidden} onShowHidden={onShowHidden} />
+ </NextIntlClientProvider>,
+ );
+ });
+ return onShowHidden;
+}
+
+const button = (label: string) =>
+ [...container.querySelectorAll('button')].find(
+ (b) => b.getAttribute('aria-label') === label || b.textContent === label,
+ )!;
+const status = () => container.querySelector('[role="status"]')!.textContent;
+const selected = () => {
+ const { from, to } = editor.state.selection;
+ return editor.state.doc.textBetween(from, to);
+};
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ editor.destroy();
+ container.remove();
+});
+
+/** The toolbar's placeholders (CE-044): how many are left, and the way through them. */
+describe('PlaceholderNav', () => {
+ it('counts the placeholders left and steps through them, round from the last', async () => {
+ await render(
+ '<p>Rivals like [competitor] lead.</p><h2>FAQ</h2><p>See [notes] and [notes].</p>',
+ );
+ expect(container.textContent).toContain('3 placeholders to fill');
+
+ await act(async () => button('Next placeholder').click());
+ expect(selected()).toBe('[competitor]');
+ expect(container.textContent).toContain('Placeholder 1 of 3');
+
+ await act(async () => button('Next placeholder').click());
+ await act(async () => button('Next placeholder').click());
+ expect(container.textContent).toContain('Placeholder 3 of 3');
+ await act(async () => button('Next placeholder').click());
+ expect(container.textContent).toContain('Placeholder 1 of 3');
+
+ await act(async () => button('Previous placeholder').click());
+ expect(container.textContent).toContain('Placeholder 3 of 3');
+ });
+
+ it('goes on to the next one once one is filled, and leaves once none is left', async () => {
+ await render('<p>Rivals like [competitor] and [partner] lead.</p>');
+ await act(async () => button('Next placeholder').click());
+ await act(async () => {
+ editor.commands.insertContent('Acme');
+ });
+ expect(container.textContent).toContain('1 placeholder to fill');
+ await act(async () => button('1 placeholder to fill').click());
+ expect(selected()).toBe('[partner]');
+ await act(async () => {
+ editor.commands.insertContent('Beta');
+ });
+ expect(container.querySelector('[role="group"]')).toBeNull();
+ expect(container.querySelectorAll('button')).toHaveLength(0);
+ // A screen reader hears that the last one is filled.
+ expect(status()).toBe('No placeholders left to fill');
+ });
+
+ it('steps past two that touch, on to the second and then the next', async () => {
+ await render('<p>Call [ab][cd] or [ef].</p>');
+ await act(async () => button('Next placeholder').click());
+ expect(selected()).toBe('[ab]');
+ await act(async () => button('Next placeholder').click());
+ expect(selected()).toBe('[cd]');
+ expect(container.textContent).toContain('Placeholder 2 of 3');
+ await act(async () => button('Next placeholder').click());
+ expect(selected()).toBe('[ef]');
+ expect(container.textContent).toContain('Placeholder 3 of 3');
+ });
+
+ it('says the count as it changes, in a polite status', async () => {
+ await render('<p>Rivals like [competitor] and [partner] lead.</p>');
+ expect(container.querySelector('[role="status"]')!.getAttribute('aria-live')).toBe('polite');
+ expect(status()).toBe('2 placeholders to fill');
+ await act(async () => button('Next placeholder').click());
+ // Stepping doesn't change it: only a fill does.
+ expect(status()).toBe('2 placeholders to fill');
+ await act(async () => {
+ editor.commands.insertContent('Acme');
+ });
+ expect(status()).toBe('1 placeholder to fill');
+ });
+
+ it('counts the ones the page doesn’t show, and offers Show in HTML for them all along', async () => {
+ const onShowHidden = await render('<p>Rivals like [competitor] lead.</p>', 1);
+ expect(container.textContent).toContain('2 placeholders to fill');
+ // The arrows step through the page's only: Show in HTML is there for the hidden one.
+ expect(button('Show in HTML')).toBeTruthy();
+ await act(async () => button('Next placeholder').click());
+ expect(container.textContent).toContain('Placeholder 1 of 2');
+ expect(button('Show in HTML')).toBeTruthy();
+ await act(async () => {
+ editor.commands.insertContent('Acme');
+ });
+ expect(container.textContent).toContain('1 placeholder to fill');
+ await act(async () => button('Show in HTML').click());
+ expect(onShowHidden).toHaveBeenCalledOnce();
+ });
+
+ it('says where the hidden ones are to a screen reader, not only in a tooltip', async () => {
+ await render('<p>Nothing to fill.</p>', 2);
+ const show = button('Show in HTML');
+ const hint = document.getElementById(show.getAttribute('aria-describedby')!)!;
+ expect(hint.textContent).toBe(
+ "In an image's alt text, the JSON-LD or an HTML block: the page doesn't show them.",
+ );
+ });
+
+ it('shows nothing for a page without one', async () => {
+ await render('<p>Nothing to fill.</p>');
+ expect(container.textContent).toBe('');
+ expect(container.querySelectorAll('button')).toHaveLength(0);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.tsx
new file mode 100644
index 000000000..82810617c
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_placeholder-nav.tsx
@@ -0,0 +1,127 @@
+'use client';
+
+import { useId, useState } from 'react';
+import { useEditorState, type Editor } from '@tiptap/react';
+import { useTranslations } from 'next-intl';
+import { ChevronLeft, ChevronRight, Code2 } from 'lucide-react';
+import {
+ placeholderIndexAt,
+ placeholderMarksKey,
+ selectPlaceholder,
+ stepPlaceholder,
+} from './_placeholder-marks';
+
+/**
+ * The toolbar's placeholders (CE-044): how many are left to fill, and the
+ * way from one to the next, as long as one is left. A send to a CMS or an
+ * export waits for all of them, so the person never has to search the page.
+ * Those the page doesn't show (`hidden`: in an image's alt text, the
+ * JSON-LD or an HTML block) are counted too, and Show in HTML, there while
+ * one is left, opens the first of them: the arrows step through the page's
+ * only. A screen reader hears the count as it changes, down to none left.
+ */
+export function PlaceholderNav({
+ editor,
+ hidden,
+ onShowHidden,
+}: {
+ editor: Editor;
+ /** Placeholders a send or an export finds outside the page's text. */
+ hidden: number;
+ onShowHidden: () => void;
+}) {
+ const t = useTranslations('contentEditor.editor.placeholders');
+ const state = useEditorState({
+ editor,
+ selector: ({ editor: e }) => {
+ const ranges = placeholderMarksKey.getState(e.state)?.ranges ?? [];
+ const at = e.state.selection.from;
+ return {
+ count: ranges.length,
+ // Which one the cursor is on, from 1; 0 for none.
+ on: placeholderIndexAt(ranges, at) + 1,
+ };
+ },
+ });
+ const total = state.count + hidden;
+ const hintId = useId();
+ // Whether the page had one: then the last filled is said too.
+ const [had, setHad] = useState(false);
+ if (total > 0 && !had) setHad(true);
+ const status = (
+ <span role="status" aria-live="polite" className="sr-only">
+ {total > 0 || had ? t('left', { count: total }) : ''}
+ </span>
+ );
+ if (total === 0) return status;
+
+ const step = (direction: 1 | -1) => {
+ const ranges = placeholderMarksKey.getState(editor.state)?.ranges ?? [];
+ const range = stepPlaceholder(ranges, editor.state.selection.from, direction);
+ if (range) selectPlaceholder(editor, range);
+ };
+ const arrow =
+ 'inline-flex h-6 w-6 items-center justify-center rounded-full hover:bg-amber-200/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 dark:hover:bg-amber-500/30';
+
+ return (
+ <>
+ {status}
+ <div
+ role="group"
+ aria-label={t('label')}
+ className="flex items-center gap-0.5 rounded-full border border-amber-300 bg-amber-50 py-0.5 pl-2.5 pr-0.5 text-xs font-medium text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-300"
+ >
+ {state.count > 0 ? (
+ <>
+ <button
+ type="button"
+ onClick={() => step(1)}
+ className="whitespace-nowrap rounded-full pr-1 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ {state.on > 0
+ ? t('onOf', { on: state.on, count: total })
+ : t('left', { count: total })}
+ </button>
+ <button
+ type="button"
+ className={arrow}
+ aria-label={t('previous')}
+ title={t('previous')}
+ onClick={() => step(-1)}
+ >
+ <ChevronLeft aria-hidden className="h-3.5 w-3.5" />
+ </button>
+ <button
+ type="button"
+ className={arrow}
+ aria-label={t('next')}
+ title={t('next')}
+ onClick={() => step(1)}
+ >
+ <ChevronRight aria-hidden className="h-3.5 w-3.5" />
+ </button>
+ </>
+ ) : (
+ <span className="whitespace-nowrap pr-1">{t('left', { count: total })}</span>
+ )}
+ {hidden > 0 && (
+ <>
+ <button
+ type="button"
+ className="inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-full px-2 hover:bg-amber-200/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 dark:hover:bg-amber-500/30"
+ title={t('hiddenHint')}
+ aria-describedby={hintId}
+ onClick={onShowHidden}
+ >
+ <Code2 aria-hidden className="h-3.5 w-3.5" />
+ {t('showHidden')}
+ </button>
+ <span id={hintId} className="sr-only">
+ {t('hiddenHint')}
+ </span>
+ </>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
index 4e8939484..1e84ed607 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
@@ -44,6 +44,7 @@ import { cn } from '@/lib/utils';
import { HtmlBlockDialog } from './_html-block';
import { ProductBlockDialog } from './_product-block-dialog';
import { h1Positions } from './_one-h1';
+import { PlaceholderNav } from './_placeholder-nav';
/**
* Where the insert menu shows: the cursor on an empty paragraph between the
@@ -63,8 +64,8 @@ export function onEmptyLine(editor: Editor, state: EditorState): boolean {
/**
* The editor's toolbar (CE-004, spec §6): H1 H2 H3 · B I link · lists,
- * quote · table, image, Add HTML, attach a file · </> HTML, and the length counter against the page
- * type's target. Inside a table it adds a row, a column, or removes the
+ * quote · table, image, Add HTML, attach a file · </> HTML, the placeholders left to fill
+ * (PlaceholderNav) and the length counter against the page type's target. Inside a table it adds a row, a column, or removes the
* table. While the HTML view is open, only its own button works. On an empty
* line, a small menu offers an HTML block, a table or an image there. With
* `productsBrandId` (an online shop's draft), both offer products from its
@@ -78,6 +79,7 @@ export function EditorToolbar({
onToggleHtml,
onAttach,
linkRequest = 0,
+ placeholders,
productsBrandId = null,
}: {
editor: Editor;
@@ -92,6 +94,8 @@ export function EditorToolbar({
* source, its claim selected (CE-045).
*/
linkRequest?: number;
+ /** The placeholders a send or an export finds outside the page's text, and how to show them. */
+ placeholders?: { hidden: number; onShowHidden: () => void };
/** The brand whose catalog + Insert › Products picks from; null hides it. */
productsBrandId?: string | null;
}) {
@@ -259,18 +263,27 @@ export function EditorToolbar({
))}
</div>
)}
- <span
- className={cn(
- 'ml-auto text-xs font-medium tabular-nums text-muted-foreground',
- lengthWarning && 'text-amber-700 dark:text-amber-400',
+ <div className="ml-auto flex items-center gap-3">
+ {placeholders && !htmlView && (
+ <PlaceholderNav
+ editor={editor}
+ hidden={placeholders.hidden}
+ onShowHidden={placeholders.onShowHidden}
+ />
)}
- >
- {t('counter', {
- count: formatNumber(state.characters),
- target: formatNumber(target),
- words: state.words,
- })}
- </span>
+ <span
+ className={cn(
+ 'text-xs font-medium tabular-nums text-muted-foreground',
+ lengthWarning && 'text-amber-700 dark:text-amber-400',
+ )}
+ >
+ {t('counter', {
+ count: formatNumber(state.characters),
+ target: formatNumber(target),
+ words: state.words,
+ })}
+ </span>
+ </div>
{/* On an empty line, what can go there, as Webflow offers between
blocks; not on an empty page, which shows its placeholder. */}
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.tsx
index 3c98d74f4..2be7dd99e 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
@@ -6093,6 +6093,30 @@ describe('the side panel', () => {
await act(async () => inDialog('Cancel').click());
});
+ it('keeps the focus on the placeholder Fill now selects in the HTML view, not on the header’s button', async () => {
+ const { htmlBlockElement } = await import('@/lib/content/html-allowlist');
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml:
+ '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>' +
+ htmlBlockElement('<div class="cta">Call [phone number]</div>'),
+ }),
+ );
+ await renderPage();
+ // Opened from the header's button, where a closing dialog gives the focus back.
+ button('Send to CMS')!.focus();
+ await act(async () => button('Send to CMS')!.click());
+ await act(async () => {});
+ await act(async () => inDialog('Fill now').click());
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
+ expect(dialog()).toBeNull();
+ const area = [...container.querySelectorAll('textarea')].find((a) =>
+ a.value.includes('[phone number]'),
+ )!;
+ expect(area.value.slice(area.selectionStart, area.selectionEnd)).toBe('[phone number]');
+ expect(document.activeElement).toBe(area);
+ });
+
it('is for admins and managers only', async () => {
getContentDraft.mockResolvedValue(draft());
await renderPage('analyst');
@@ -6317,7 +6341,7 @@ describe('the side panel', () => {
expect(editor.state.doc.textBetween(from, to)).toBe('[name of a real person]');
});
- it('says where a placeholder only an HTML block holds is', async () => {
+ it('keeps the focus on the placeholder Export’s Fill now selects in the HTML view, not on the header’s button', async () => {
const { htmlBlockElement } = await import('@/lib/content/html-allowlist');
getContentDraft.mockResolvedValue(
draft({
@@ -6327,6 +6351,32 @@ describe('the side panel', () => {
}),
);
await renderPage();
+ // Opened from the header's button, where a closing dialog gives the focus back.
+ button('Export')!.focus();
+ await act(async () => button('Export')!.click());
+ await act(async () => inDialog('Fill now').click());
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
+ expect(dialog()).toBeNull();
+ const area = [...container.querySelectorAll('textarea')].find((a) =>
+ a.value.includes('[phone number]'),
+ )!;
+ expect(area.value.slice(area.selectionStart, area.selectionEnd)).toBe('[phone number]');
+ expect(document.activeElement).toBe(area);
+ });
+
+ it('selects a placeholder only an HTML block holds in the HTML view, and says where it is', async () => {
+ const { htmlBlockElement } = await import('@/lib/content/html-allowlist');
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml:
+ '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>' +
+ htmlBlockElement('<div class="cta">Call [phone number]</div>'),
+ }),
+ );
+ await renderPage();
+ // The toolbar counts it, though the page doesn't show it.
+ expect(container.textContent).toContain('1 placeholder to fill');
+ expect(button('Show in HTML')).toBeTruthy();
await act(async () => button('Export')!.click());
expect(dialog()!.textContent).toContain('1 placeholder is still open');
await act(async () => inDialog('Review').click());
@@ -6335,8 +6385,48 @@ describe('the side panel', () => {
expect(dialog()!.textContent).toContain('1 placeholder is still open');
await act(async () => inDialog('Fill now').click());
expect(toast).toHaveBeenCalledWith(
- 'The placeholders are in an HTML block: open it with </> to fill them.',
+ "This placeholder is in an image's alt text, the JSON-LD or an HTML block. It's selected in the HTML view (</>): type over it, then apply.",
+ );
+ const area = [...container.querySelectorAll('textarea')].find((a) =>
+ a.value.includes('[phone number]'),
+ )!;
+ expect(area.value.slice(area.selectionStart, area.selectionEnd)).toBe('[phone number]');
+ });
+
+ it('opens the HTML view at the placeholder the page hides from Show in HTML, past the five it shows', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml:
+ '<h1>Pipeline forecasting</h1>' +
+ '<p>Ask [competitor] and [name of a real person].</p>' +
+ '<p><img src="https://cdn.example.com/a.jpg" alt="[photo of the founder]"></p>' +
+ '<p>Costs [price], since [year], at [city].</p>',
+ }),
);
+ await renderPage();
+ expect(container.textContent).toContain('6 placeholders to fill');
+ await act(async () => button('Show in HTML')!.click());
+ const area = [...container.querySelectorAll('textarea')].find((a) =>
+ a.value.includes('[photo of the founder]'),
+ )!;
+ expect(area).toBeTruthy();
+ expect(area.value.slice(area.selectionStart, area.selectionEnd)).toBe(
+ '[photo of the founder]',
+ );
+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })
+ .editor;
+ expect(editor.state.selection.empty).toBe(true);
+ });
+
+ it("counts a code block's placeholder once in the toolbar", async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml: '<h1>Pipeline forecasting</h1><pre><code>token = "[api key]"</code></pre>',
+ }),
+ );
+ await renderPage();
+ expect(container.textContent).toContain('1 placeholder to fill');
+ expect(button('Show in HTML')).toBeFalsy();
});
it('puts the byline under the H1 for a brand that adds it to content, and says so', async () => {
diff --git a/web/src/components/content/send-to-cms-dialog.tsx b/web/src/components/content/send-to-cms-dialog.tsx
index 7143e3ec2..5a47b6f85 100644
--- a/web/src/components/content/send-to-cms-dialog.tsx
+++ b/web/src/components/content/send-to-cms-dialog.tsx
@@ -97,6 +97,8 @@ export function SendDialog({
// or the CMS could get the page twice).
const touched = useRef(new Set<keyof CmsFields>());
const [sending, setSending] = useState(false);
+ // Fill now: the editor selects the placeholder, so focus stays there.
+ const filling = useRef(false);
const [problem, setProblem] = useState<
| { code: CmsSendError; field: string | null }
| { status: number }
@@ -238,7 +240,10 @@ export function SendDialog({
return (
<Dialog open onOpenChange={(open) => !open && !sending && onClose()}>
- <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg">
+ <DialogContent
+ className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg"
+ finalFocus={() => !filling.current}
+ >
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>
@@ -276,7 +281,14 @@ export function SendDialog({
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />
<span className="min-w-0 flex-1">{t('placeholders', { count: placeholders })}</span>
- <Button size="sm" variant="outline" onClick={onFillNow}>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ filling.current = true;
+ onFillNow();
+ }}
+ >
{t('fillNow')}
</Button>
</div>
diff --git a/web/src/lib/content/ready-to-publish.test.ts b/web/src/lib/content/ready-to-publish.test.ts
index 51045e0f5..af9eda0c8 100644
--- a/web/src/lib/content/ready-to-publish.test.ts
+++ b/web/src/lib/content/ready-to-publish.test.ts
@@ -136,6 +136,17 @@ describe('blankCode', () => {
).toEqual(['[name of a real person]']);
});
+ it('without fields, leaves only the words the page shows: no alt, title or JSON-LD', () => {
+ const html =
+ '<script type="application/ld+json">{"text":"Costs [price]."}</script>\n' +
+ '<p title="[tip]">Ask <img src="a.jpg" alt="[photo of the founder]"> [name of a real person].</p>';
+ const blanked = blankCode(html, { words: true, fields: false });
+ expect(blanked).toHaveLength(html.length);
+ expect(matches(blanked).map((m) => html.slice(m.index, m.index + m[0].length))).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>';
diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.ts
index 3a0a5c4fa..193ab0293 100644
--- a/web/src/lib/content/ready-to-publish.ts
+++ b/web/src/lib/content/ready-to-publish.ts
@@ -176,9 +176,11 @@ function readTag(lower: string, open: number) {
* <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.
+ * too. For a search that must find what the page holds, not its code. With
+ * `words` and not `fields`, the alt and title values and the JSON-LD go as
+ * well: only the words the page's text shows are left.
*/
-export function blankCode(html: string, { words = false } = {}): string {
+export function blankCode(html: string, { words = false, fields = true } = {}): 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[] = [];
@@ -198,7 +200,7 @@ export function blankCode(html: string, { words = false } = {}): string {
if (!words) return keep(from, tagEnd);
let at = from;
for (const value of values) {
- if (value.name !== 'alt' && value.name !== 'title') continue;
+ if (!fields || (value.name !== 'alt' && value.name !== 'title')) continue;
blank(at, value.from);
keep(value.from, value.to);
at = value.to;
@@ -246,7 +248,7 @@ export function blankCode(html: string, { words = false } = {}): string {
values.some(
(v) => v.name === 'type' && lower.slice(v.from, v.to).trim() === 'application/ld+json',
);
- if (words && !jsonLd) {
+ if (words && (!jsonLd || !fields)) {
blank(open, codeEnd);
} else {
tag(open, end, values);