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-editor): show visual proof spots in the draft's margin, with Add image (CE-049, part c) (#1469)
Cihan3527707aafca
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 1ad69a9fd..ee37da110 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3999,6 +3999,26 @@"cancel": "Cancel","apply": "Apply"},+ "proofSpots": {+ "title": "Visual proof",+ "add": "Add image",+ "for": "For: “{passage}”",+ "addFor": "Add image for “{passage}”",+ "marker": "Visual proof: {image}",+ "dialog": {+ "title": "Add visual proof",+ "srcLabel": "Image address",+ "srcHint": "An image you host: your own screenshot or photo, not a stock one.",+ "invalid": "Enter the image's web address (https://…).",+ "altLabel": "Alt text",+ "altHint": "What the image shows, for readers who can't see it. Drafted from the passage: edit it to match your image.",+ "altRequired": "Add alt text: what the image shows.",+ "captionLabel": "Caption (optional)",+ "cancel": "Cancel",+ "insert": "Add image",+ "gone": "That passage isn't on the page any more, so the image wasn't added."+ }+ },"image": {"title": "Insert an image","srcLabel": "Image address",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 a882fed25..fa4ca02d1 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 {import { proofKey, qualityTodos } from '@/lib/content/quality-todos';import { readability, sentencesOf } from '@/lib/content/readability';import { brandFactsPath, factMismatches } from '@/lib/content/brand-facts';-import { MAX_PROOF_TODOS, proofsOnPage } from '@/lib/content/page-read';+import { MAX_PROOF_TODOS, proofsOnPage, type ProofSpot } from '@/lib/content/page-read';import {liveSkips,nextStep,@@ -160,6 +160,8 @@ import { NextNudge, useNextNudge } from './_next-nudge';import { PageInfoStrip, pageInfoKey } from './_page-info';import { WeakSourcesMarks, weakSourcesKey } from './_weak-sources';import { ClaimMarksExtension, claimMarksKey, textRanges, writingBlock } from './_claim-marks';+import { ProofImageDialog } from './_proof-image-dialog';+import { ProofSpotsExtension, proofSpotsKey } from './_proof-spots';import { useClaims } from './_use-claims';import { useBrandFacts } from './_use-brand-facts';import { usePageRead } from './_use-page-read';@@ -207,7 +209,8 @@ import { useDraftAutosave, type SaveState } from './_use-autosave';* and the selected table cells and images marked.*/const DOCUMENT_CLASS = cn(- 'prose prose-neutral max-w-none dark:prose-invert min-h-[50vh] focus:outline-none',+ // Relative: the visual proof spots sit beside their paragraphs, in its margin (CE-049).+ 'relative prose prose-neutral max-w-none dark:prose-invert min-h-[50vh] focus:outline-none','prose-a:font-normal prose-a:text-blue-600 prose-a:underline prose-a:underline-offset-2 dark:prose-a:text-blue-400',// A weak source's amber wavy line takes the place of its link's (CE-046).'prose-a:has-[.quality-weak-source]:no-underline!',@@ -436,6 +439,7 @@ export function DraftEditor({PageInfoStrip,WeakSourcesMarks,ClaimMarksExtension,+ ProofSpotsExtension,],content: draft.bodyHtml,// Rendered on the client only, so the server's HTML can't disagree with it.@@ -1661,6 +1665,31 @@ export function DraftEditor({if (wasBusy.current && !agentBusy) refreshAiUsage();wasBusy.current = agentBusy;}, [agentBusy, refreshAiUsage]);+ // The page read's visual proof spots (CE-049), in the draft's margin: not+ // while the agent changes the page. Add image opens their dialog.+ const [spotFor, setSpotFor] = useState<ProofSpot | null>(null);+ const spotList = sourcesOn && !agentBusy ? (pageRead.read?.spots ?? null) : null;+ useEffect(() => {+ if (!editor || editor.isDestroyed) return;+ editor.view.dispatch(+ editor.state.tr+ .setMeta(+ proofSpotsKey,+ spotList?.length+ ? {+ spots: spotList,+ title: t('proofSpots.title'),+ add: t('proofSpots.add'),+ forPassage: (passage: string) => t('proofSpots.for', { passage }),+ addFor: (passage: string) => t('proofSpots.addFor', { passage }),+ marker: (image: string) => t('proofSpots.marker', { image }),+ onAdd: setSpotFor,+ }+ : null,+ )+ .setMeta('addToHistory', false),+ );+ }, [editor, spotList, t]);const agentFix: AgentFix = {run: (only) => void fixRules(only),running: fixing,@@ -2760,7 +2789,8 @@ export function DraftEditor({)}<div className="relative min-h-0 flex-1" {...dropHandlers}>- <div className="h-full overflow-y-auto">+ {/* A container: the visual proof spots are cards from 1120 px, markers below. */}+ <div className="@container h-full overflow-y-auto">{htmlSource !== null && (<textarearef={htmlSourceRef}@@ -2841,6 +2871,9 @@ export function DraftEditor({)}</div>+ {editor && spotFor && (+ <ProofImageDialog editor={editor} spot={spotFor} onClose={() => setSpotFor(null)} />+ )}{quality && exportOpen && exportChecks && (<ExportDialogonClose={() => setExportOpen(null)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.test.tsxnew file mode 100644index 000000000..bcb87491e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.test.tsx@@ -0,0 +1,129 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { Editor } from '@tiptap/core';+import Image from '@tiptap/extension-image';+import StarterKit from '@tiptap/starter-kit';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { ProofSpot } from '@/lib/content/page-read';+import { ProofImageDialog, insertProofImage } from './_proof-image-dialog';++const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * A visual proof spot's Add image (Quality CE-049): the image goes in right+ * after its passage's block, with its alt text and an optional caption.+ */++const SPOT: ProofSpot = {+ passage: 'keeps your gear dry in any weather',+ block: 'The Ridge 28 keeps your gear dry in any weather.',+ image: 'A photo of the Ridge 28 on a real hike in the rain',+ alt: 'A hiker with the Ridge 28 on a wet trail',+};+const SRC = 'https://cdn.trailmade.example/ridge-rain.jpg';++let editor: Editor;+let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ toast.error.mockReset();+ editor = new Editor({+ extensions: [StarterKit, Image],+ content: `<h1>Ridge 28</h1><p>${SPOT.block}</p><p>Next paragraph.</p>`,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+ editor.destroy();+});++const setValue = (el: HTMLInputElement, value: string) => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(el, value);+ el.dispatchEvent(new Event('input', { bubbles: true }));+};+const input = (id: string) => document.querySelector<HTMLInputElement>(`#${id}`)!;+const button = (name: string) =>+ [...document.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === name)!;+const onClose = vi.fn();+const render = () =>+ act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ProofImageDialog editor={editor} spot={SPOT} onClose={onClose} />+ </NextIntlClientProvider>,+ ),+ );++describe('insertProofImage', () => {+ it('puts the image right after the passage’s block, with a caption under it', () => {+ expect(+ insertProofImage(editor, SPOT, { src: SRC, alt: 'Rain test', caption: ' On the GR20. ' }),+ ).toBe(true);+ expect(editor.getHTML()).toBe(+ `<h1>Ridge 28</h1><p>${SPOT.block}</p><img src="${SRC}" alt="Rain test"><p><em>On the GR20.</em></p><p>Next paragraph.</p>`,+ );+ });++ it('puts it after a list whole, and says when the passage is gone', () => {+ editor.commands.setContent(+ `<ul><li><p>${SPOT.block}</p></li><li><p>Two.</p></li></ul><p>After.</p>`,+ );+ insertProofImage(editor, SPOT, { src: SRC, alt: 'Rain', caption: '' });+ expect(editor.getHTML()).toBe(+ `<ul><li><p>${SPOT.block}</p></li><li><p>Two.</p></li></ul><img src="${SRC}" alt="Rain"><p>After.</p>`,+ );+ editor.commands.setContent('<p>Written over.</p>');+ expect(insertProofImage(editor, SPOT, { src: SRC, alt: 'Rain', caption: '' })).toBe(false);+ });+});++describe('ProofImageDialog', () => {+ it('names the image to take, drafts its alt text, and adds it', async () => {+ onClose.mockReset();+ await render();+ expect(document.body.textContent).toContain(SPOT.image);+ expect(input('proof-image-alt').value).toBe(SPOT.alt);+ // Not an image address; then no alt text.+ await act(async () => setValue(input('proof-image-src'), 'javascript:alert(1)'));+ await act(async () => button('Add image').click());+ expect(document.body.textContent).toContain("Enter the image's web address");+ // http: an https page may not show it.+ await act(async () => setValue(input('proof-image-src'), 'http://cdn.example/rain.jpg'));+ await act(async () => button('Add image').click());+ expect(onClose).not.toHaveBeenCalled();+ expect(input('proof-image-src').maxLength).toBe(2048);+ await act(async () => setValue(input('proof-image-src'), SRC));+ await act(async () => setValue(input('proof-image-alt'), ' '));+ await act(async () => button('Add image').click());+ expect(document.body.textContent).toContain('Add alt text');+ expect(onClose).not.toHaveBeenCalled();++ await act(async () => setValue(input('proof-image-alt'), 'The Ridge 28 after a rain test'));+ await act(async () => button('Add image').click());+ expect(onClose).toHaveBeenCalled();+ expect(editor.getHTML()).toContain(`<img src="${SRC}" alt="The Ridge 28 after a rain test">`);+ });++ it('says so when the passage left the page meanwhile', async () => {+ await render();+ editor.commands.setContent('<p>Written over.</p>');+ await act(async () => setValue(input('proof-image-src'), SRC));+ await act(async () => button('Add image').click());+ expect(toast.error).toHaveBeenCalledWith(+ "That passage isn't on the page any more, so the image wasn't added.",+ );+ expect(editor.getHTML()).toBe('<p>Written over.</p>');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.tsxnew file mode 100644index 000000000..f4f434296--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-image-dialog.tsx@@ -0,0 +1,171 @@+'use client';++import { useRef, useState } from 'react';+import type { Editor } from '@tiptap/core';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { safeImageSrc } from '@/lib/content/editor';+import type { ProofSpot } from '@/lib/content/page-read';+import { textRanges } from './_claim-marks';++/** The longest image address the dialog takes, as the database keeps an own image's (00270). */+const MAX_IMAGE_SRC_LENGTH = 2048;++/**+ * A visual proof spot's Add image (Quality spec §4b, CE-049): the image by+ * its address (one the business hosts), its alt text drafted from the+ * passage, and an optional caption, put in right after the passage's+ * block (its list or quote, whole). The caption is an italic paragraph+ * under it. A passage gone from the page meanwhile says so.+ */+export function insertProofImage(+ editor: Editor,+ spot: ProofSpot,+ image: { src: string; alt: string; caption: string },+): boolean {+ const [range] = textRanges(editor.state.doc, spot.passage, spot.block);+ if (!range) return false;+ const at = editor.state.doc.resolve(range.from).after(1);+ const caption = image.caption.trim();+ return editor+ .chain()+ .focus()+ .insertContentAt(at, [+ { type: 'image', attrs: { src: image.src, alt: image.alt } },+ ...(caption+ ? [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: caption, marks: [{ type: 'italic' }] }],+ },+ ]+ : []),+ ])+ .run();+}++export function ProofImageDialog({+ editor,+ spot,+ onClose,+}: {+ editor: Editor;+ spot: ProofSpot;+ onClose: () => void;+}) {+ const t = useTranslations('contentEditor.editor.proofSpots.dialog');+ const [src, setSrc] = useState('');+ const [alt, setAlt] = useState(spot.alt);+ const [caption, setCaption] = useState('');+ const [invalid, setInvalid] = useState<'src' | 'alt' | null>(null);+ const fieldRef = useRef<HTMLInputElement>(null);++ const insert = () => {+ // https only (an http image on an https page may not show), as the page keeps addresses.+ const checked = safeImageSrc(src.trim());+ const safe =+ checked?.startsWith('https:') && checked.length <= MAX_IMAGE_SRC_LENGTH ? checked : null;+ if (!safe) {+ setInvalid('src');+ return;+ }+ if (!alt.trim()) {+ setInvalid('alt');+ return;+ }+ if (!insertProofImage(editor, spot, { src: safe, alt: alt.trim(), caption })) {+ toast.error(t('gone'));+ }+ onClose();+ };++ return (+ <Dialog open onOpenChange={(next) => !next && onClose()}>+ <DialogContent className="sm:max-w-md" initialFocus={fieldRef}>+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription className="[overflow-wrap:anywhere]">{spot.image}</DialogDescription>+ </DialogHeader>+ <form+ className="space-y-3"+ onSubmit={(e) => {+ e.preventDefault();+ insert();+ }}+ >+ <div className="space-y-1.5">+ <Label htmlFor="proof-image-src">{t('srcLabel')}</Label>+ <Input+ id="proof-image-src"+ ref={fieldRef}+ value={src}+ maxLength={MAX_IMAGE_SRC_LENGTH}+ placeholder="https://"+ aria-invalid={invalid === 'src'}+ aria-describedby="proof-image-src-hint"+ onChange={(e) => {+ setSrc(e.target.value);+ setInvalid(null);+ }}+ />+ <p id="proof-image-src-hint" className="text-xs text-muted-foreground">+ {invalid === 'src' ? (+ <span className="text-destructive">{t('invalid')}</span>+ ) : (+ t('srcHint')+ )}+ </p>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="proof-image-alt">{t('altLabel')}</Label>+ <Input+ id="proof-image-alt"+ value={alt}+ maxLength={125}+ aria-invalid={invalid === 'alt'}+ aria-describedby="proof-image-alt-hint"+ onChange={(e) => {+ setAlt(e.target.value);+ setInvalid(null);+ }}+ />+ <p id="proof-image-alt-hint" className="text-xs text-muted-foreground">+ {invalid === 'alt' ? (+ <span className="text-destructive">{t('altRequired')}</span>+ ) : (+ t('altHint')+ )}+ </p>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="proof-image-caption">{t('captionLabel')}</Label>+ <Input+ id="proof-image-caption"+ value={caption}+ maxLength={200}+ onChange={(e) => setCaption(e.target.value)}+ />+ </div>+ {/* Enter in any field adds it. */}+ <button type="submit" hidden />+ </form>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>+ <Button onClick={insert}>{t('insert')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.test.tsnew file mode 100644index 000000000..3d1527b6d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.test.ts@@ -0,0 +1,107 @@+import { Editor } from '@tiptap/core';+import Image from '@tiptap/extension-image';+import StarterKit from '@tiptap/starter-kit';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { ProofSpot } from '@/lib/content/page-read';+import { ProofSpotsExtension, openSpotPlaces, proofSpotsKey } from './_proof-spots';++let editor: Editor | null = null;+afterEach(() => {+ editor?.destroy();+ editor = null;+});++const open = (content: string) => {+ editor = new Editor({ extensions: [StarterKit, Image, ProofSpotsExtension], content });+ return editor;+};++const RAIN: ProofSpot = {+ passage: 'keeps your gear dry in any weather',+ block: 'The Ridge 28 keeps your gear dry in any weather.',+ image: 'A photo of the Ridge 28 on a real hike in the rain',+ alt: 'A hiker with the Ridge 28 on a wet trail',+};+const SEAMS: ProofSpot = {+ passage: 'welded seams',+ block: 'Every seam is welded seams-first and taped.',+ image: 'A close-up of the welded seams',+ alt: 'Close-up of the seams',+};++const show = (e: Editor, spots: ProofSpot[], onAdd = vi.fn()) => {+ e.view.dispatch(+ e.state.tr.setMeta(proofSpotsKey, {+ spots,+ title: 'Visual proof',+ add: 'Add image',+ forPassage: (passage: string) => `For: “${passage}”`,+ addFor: (passage: string) => `Add image for “${passage}”`,+ marker: (image: string) => `Visual proof: ${image}`,+ onAdd,+ }),+ );+ return onAdd;+};+const spots = (e: Editor) => [...e.view.dom.querySelectorAll<HTMLElement>('[data-proof-spot]')];++/** Visual proof spots (Quality CE-049): editor-only, beside their passages. */+describe('ProofSpotsExtension', () => {+ it('shows a spot at the start of its passage’s paragraph, outside the page', () => {+ const e = open(`<h1>Ridge 28</h1><p>${RAIN.block}</p><p>More words.</p>`);+ const onAdd = show(e, [RAIN]);+ const [spot] = spots(e);+ expect(spot.parentElement?.tagName).toBe('P');+ expect(spot.parentElement?.textContent).toContain(RAIN.block);+ expect(spot.contentEditable).toBe('false');+ expect(spot.textContent).toContain('Visual proof');+ expect(spot.textContent).toContain(RAIN.image);+ expect(spot.textContent).toContain(`For: “${RAIN.passage}”`);+ // The card's button and the narrow width's marker both add an image.+ const buttons = spot.querySelectorAll('button');+ expect([...buttons].map((b) => b.getAttribute('aria-label'))).toEqual([+ `Add image for “${RAIN.passage}”`,+ `Add image for “${RAIN.passage}”`,+ ]);+ expect(buttons[1].title).toBe(`Visual proof: ${RAIN.image}`);+ // Its own group, not the paragraph's words.+ expect(spot.getAttribute('role')).toBe('group');+ expect(spot.getAttribute('aria-label')).toBe('Visual proof');+ buttons[1].click();+ expect(onAdd).toHaveBeenCalledWith(RAIN);+ // No save, export, Copy HTML or HTML view has it.+ expect(e.getHTML()).toBe(`<h1>Ridge 28</h1><p>${RAIN.block}</p><p>More words.</p>`);+ expect(e.getText()).not.toContain('Visual proof');+ });++ it('leaves a spot out once an image follows its block, or its passage is gone', () => {+ const e = open(+ `<p>${RAIN.block}</p><img src="https://cdn.example/rain.jpg" alt="Rain"><ul><li><p>${SEAMS.block}</p></li></ul>`,+ );+ show(e, [RAIN, SEAMS]);+ expect(spots(e)).toHaveLength(1);+ expect(spots(e)[0].closest('li')).not.toBeNull();+ expect(openSpotPlaces(e.state.doc, [RAIN, SEAMS]).map((p) => p.spot)).toEqual([SEAMS]);++ // Written over: no spot.+ e.commands.setContent(`<p>The Ridge 28 is light.</p><ul><li><p>${SEAMS.block}</p></li></ul>`);+ expect(openSpotPlaces(e.state.doc, [RAIN])).toEqual([]);+ });++ it('follows the read, and leaves with none to show', () => {+ const e = open(`<p>${RAIN.block}</p>`);+ show(e, [RAIN]);+ // Placed once: a cursor move doesn't place them again.+ const placed = proofSpotsKey.getState(e.state)!.decorations;+ e.commands.setTextSelection(3);+ expect(proofSpotsKey.getState(e.state)!.decorations).toBe(placed);+ // A new read of the same spot with other alt text: its Add image has the new one.+ const onAdd = show(e, [{ ...RAIN, alt: 'The Ridge 28 dry inside after rain' }]);+ spots(e)[0].querySelector('button')!.click();+ expect(onAdd).toHaveBeenCalledWith({ ...RAIN, alt: 'The Ridge 28 dry inside after rain' });+ e.commands.insertContentAt(e.state.doc.content.size, '<p>Typing on.</p>');+ expect(spots(e)).toHaveLength(1);+ e.view.dispatch(e.state.tr.setMeta(proofSpotsKey, null));+ expect(spots(e)).toHaveLength(0);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.tsnew file mode 100644index 000000000..ab9ede3ab--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_proof-spots.ts@@ -0,0 +1,170 @@+import { Extension } 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 type { ProofSpot } from '@/lib/content/page-read';+import { textRanges } from './_claim-marks';++/**+ * Visual proof spots in the draft's left margin (Quality spec §4b, CE-049):+ * where one specific image the business can take itself would prove a+ * passage, with "For: “{passage}”" and Add image. A decoration, never the+ * page's, so no save, export, Copy, Copy HTML or CMS push has it. Wide+ * (the page's scroll area 1120 px and up), a card beside the paragraph;+ * narrower, a small marker in its padding that opens the same dialog.+ */++export interface ProofSpotsMeta {+ /** The page read's spots, in its order. */+ spots: readonly ProofSpot[];+ /** "Visual proof". */+ title: string;+ /** "Add image". */+ add: string;+ /** "For: “{passage}”". */+ forPassage: (passage: string) => string;+ /** "Add image for “{passage}”": the button's and the marker's name. */+ addFor: (passage: string) => string;+ /** "Visual proof: {image}": the marker's tooltip. */+ marker: (image: string) => string;+ /** Opens the image dialog for a spot. */+ onAdd: (spot: ProofSpot) => void;+}++interface SpotsState {+ meta: ProofSpotsMeta | null;+ decorations: DecorationSet;+}++export const proofSpotsKey = new PluginKey<SpotsState>('proofSpots');++/** A spot on the page: where its passage's paragraph starts. */+export interface PlacedSpot {+ spot: ProofSpot;+ /** The start of its passage's paragraph's text. */+ at: number;+}++/**+ * The spots still open on the page, each where its passage's paragraph+ * starts: one whose passage is gone, or whose paragraph's top-level block+ * an image already follows (its spot was filled), isn't.+ */+export function openSpotPlaces(doc: PmNode, spots: readonly ProofSpot[]): PlacedSpot[] {+ return spots.flatMap((spot) => {+ const [range] = textRanges(doc, spot.passage, spot.block);+ if (!range) return [];+ const $from = doc.resolve(range.from);+ if (doc.maybeChild($from.index(0) + 1)?.type.name === 'image') return [];+ return [{ spot, at: $from.start() }];+ });+}++function el<K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = '') {+ const node = document.createElement(tag);+ node.className = className;+ if (text) node.textContent = text;+ return node;+}++const CAMERA =+ '<svg aria-hidden="true" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>';++/** The card (wide) and the marker (narrow), absolutely beside the paragraph. */+function spotView(spot: ProofSpot, meta: ProofSpotsMeta): HTMLElement {+ // Not the paragraph's words: a group of its own, in the page's plain type+ // (a quote's italics aren't the card's).+ const box = el('span', 'not-prose font-normal not-italic');+ box.contentEditable = 'false';+ box.dataset.proofSpot = '';+ box.setAttribute('role', 'group');+ box.setAttribute('aria-label', meta.title);+ const add = (e: Event) => {+ e.preventDefault();+ meta.onAdd(spot);+ };++ const card = el(+ 'span',+ 'absolute right-full mr-5 hidden w-[200px] flex-col gap-1 rounded-lg border border-dashed border-sky-300 bg-sky-50/60 p-2.5 text-left leading-snug select-none @min-[1120px]:flex dark:border-sky-800 dark:bg-sky-950/30',+ );+ card.append(+ el(+ 'span',+ 'text-[10.5px] font-semibold tracking-wide text-sky-700 uppercase dark:text-sky-300',+ meta.title,+ ),+ el('span', 'line-clamp-4 text-[12.5px] text-foreground', spot.image),+ el(+ 'span',+ 'line-clamp-2 text-[11.5px] text-muted-foreground [overflow-wrap:anywhere]',+ meta.forPassage(spot.passage),+ ),+ );+ const button = el(+ 'button',+ 'mt-1 self-start rounded-md border bg-background px-2 py-0.5 text-[12px] font-medium text-foreground hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none',+ meta.add,+ );+ button.type = 'button';+ button.setAttribute('aria-label', meta.addFor(spot.passage));+ button.addEventListener('mousedown', (e) => e.preventDefault());+ button.addEventListener('click', add);+ card.append(button);++ const marker = el(+ 'button',+ 'absolute right-full mt-1 mr-1.5 inline-flex h-5 w-5 items-center justify-center rounded-full border border-dashed border-sky-400 bg-background text-sky-700 hover:bg-sky-50 focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none @min-[1120px]:hidden dark:border-sky-700 dark:text-sky-300 dark:hover:bg-sky-950/40',+ );+ marker.type = 'button';+ marker.innerHTML = CAMERA;+ marker.title = meta.marker(spot.image);+ marker.setAttribute('aria-label', meta.addFor(spot.passage));+ marker.addEventListener('mousedown', (e) => e.preventDefault());+ marker.addEventListener('click', add);++ box.append(card, marker);+ return box;+}++function place(doc: PmNode, meta: ProofSpotsMeta | null): DecorationSet {+ if (!meta?.spots.length) return DecorationSet.empty;+ return DecorationSet.create(+ doc,+ openSpotPlaces(doc, meta.spots).map(({ spot, at }) =>+ Decoration.widget(at, () => spotView(spot, meta), {+ // All the card shows and acts on: a change draws it again.+ key: `proof-spot:${spot.passage}:${spot.block}:${spot.image}:${spot.alt}:${meta.title}`,+ side: -1,+ ignoreSelection: true,+ stopEvent: () => true,+ }),+ ),+ );+}++export const ProofSpotsExtension = Extension.create({+ name: 'proofSpots',++ addProseMirrorPlugins() {+ return [+ new Plugin<SpotsState>({+ key: proofSpotsKey,+ state: {+ init: () => ({ meta: null, decorations: DecorationSet.empty }),+ // Placed again when the spots change or the page does (a spot+ // filled or written over goes), not on a cursor move.+ apply: (tr, prev) => {+ const next = tr.getMeta(proofSpotsKey) as ProofSpotsMeta | null | undefined;+ const meta = next === undefined ? prev.meta : next;+ if (next === undefined && !tr.docChanged) return prev;+ return { meta, decorations: place(tr.doc, meta) };+ },+ },+ props: {+ decorations: (state) => proofSpotsKey.getState(state)?.decorations ?? null,+ },+ }),+ ];+ },+});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 91ce66626..34d707eaa 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@@ -3068,6 +3068,63 @@ describe('the side panel', () => {expect(done.textContent).toContain('The proof is linked');});+ it('shows a visual proof spot beside its passage, and Add image puts the image after it (CE-049)', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const block = `${said} It is easy to set up for any team.`;+ readDraftPage.mockResolvedValue({+ spots: [+ {+ passage: 'the fastest forecasting app',+ block,+ image: 'A screenshot of a real forecast run, timed',+ alt: 'A forecast run finishing in 4 seconds',+ },+ ],+ proofs: [],+ regulated: null,+ pending: false,+ limited: false,+ paused: false,+ });+ getContentDraft.mockResolvedValue(claimed);+ window.innerWidth = 1440;+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ const spot = container.querySelector<HTMLElement>('.ProseMirror [data-proof-spot]')!;+ expect(spot.textContent).toContain('A screenshot of a real forecast run, timed');+ expect(spot.textContent).toContain('For: “the fastest forecasting app”');+ await act(async () =>+ spot.querySelector<HTMLButtonElement>('button[aria-label^="Add image for"]')!.click(),+ );+ const src = document.querySelector<HTMLInputElement>('#proof-image-src')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(+ src,+ 'https://cdn.acme.com/forecast-run.png',+ );+ src.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () =>+ [...document.querySelectorAll('button')]+ .find((b) => b.textContent === 'Add image' && !b.closest('[data-proof-spot]'))!+ .click(),+ );+ const image = container.querySelector<HTMLImageElement>(+ '.ProseMirror img[src="https://cdn.acme.com/forecast-run.png"]',+ )!;+ expect(image.alt).toBe('A forecast run finishing in 4 seconds');+ expect(image.previousElementSibling?.textContent).toContain(said);+ // Filled: the spot goes; Undo takes the image out and brings it back.+ expect(container.querySelector('.ProseMirror [data-proof-spot]')).toBeNull();+ const { editor: pm } = container.querySelector('.ProseMirror') as HTMLElement & {+ editor: Editor;+ };+ await act(async () => void pm.commands.undo());+ expect(container.querySelector('.ProseMirror img')).toBeNull();+ expect(container.querySelector('.ProseMirror [data-proof-spot]')).not.toBeNull();+ });+it('takes the claim’s sentence out on Remove', async () => {process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });