From 7aa85fd7745694431ef9d89df7af4489816b71b7 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Mon, 9 Nov 2026 13:06:07 -0800 Subject: [PATCH 01/13] =?UTF-8?q?feat(canvas):=20cut=20frames=20and=20elem?= =?UTF-8?q?ents=20with=20=E2=8C=98X=20and=20the=20context=20menus=20(#468)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(canvas): cut frames and elements with ⌘X and the context menus ⌘X (the native cut event, so the desktop Edit menu's Cut works too) copies the picked elements, else the selected frames, and removes what ⌫ would once the clipboard took the copy. The frame and element context menus gain Cut; their asynchronous clipboard write deletes only after it succeeds, so a denied write loses nothing. Locked frames and layers are copied but stay. Fixes kgoedecke/doop#333 Co-Authored-By: Claude Opus 5.5 * fix(canvas): copy the live frames a menu cut deletes Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit b0b11db47b6b53fcf0d63a511f81f5a7db2180a8) --- src/components/ElementContextMenu.tsx | 28 +++++++++ src/components/FrameContextMenu.tsx | 28 +++++++++ src/lib/canvasClipboard.ts | 7 ++- src/lib/i18n/en/common.ts | 1 + src/lib/i18n/en/stage.ts | 1 + src/lib/i18n/pt-BR/common.ts | 1 + src/lib/i18n/pt-BR/stage.ts | 1 + src/pages/CanvasPage.tsx | 32 +++++++++-- tests/canvasClipboardBrowser.test.ts | 82 ++++++++++++++++++++++++++- 9 files changed, 171 insertions(+), 10 deletions(-) diff --git a/src/components/ElementContextMenu.tsx b/src/components/ElementContextMenu.tsx index d4d9352e7..debbadb6b 100644 --- a/src/components/ElementContextMenu.tsx +++ b/src/components/ElementContextMenu.tsx @@ -9,6 +9,7 @@ import { hasFrameClip, pasteFrameCentered } from '../lib/frameClipboard' import { deleteLayer, duplicateLayer, setLayerHidden, setLayerLocked, shiftLayer } from '../lib/layerEdits' import { buildLayerTree, elementHtml, findLayer, isElementHidden, isElementLocked, layerName } from '../lib/layers' import { MOD_KEY } from '../lib/keys' +import { canEditOpenCanvas, useStore } from '../lib/store' import { useT } from '../lib/i18n' import { useStore } from '../lib/store' import { @@ -77,6 +78,21 @@ export function ElementContextMenu({ frame, selector, hit, onRename }: ElementMe ) } +/** Copy the element, then remove it once the clipboard took the copy. The + * menu writes the clipboard asynchronously; a selector is a position in the + * frame's HTML, so if the frame changed meanwhile the element stays, rather + * than deleting whatever now sits at that position. */ +function cutLayer(frame: Frame, selector: string) { + writeCanvasClipboard( + () => copyPicked(frame, [selector]), + undefined, + () => { + const live = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) + if (live?.html === frame.html) deleteLayer(live, selector) + }, + ) +} + /** Radix mounts these children only while the menu is open. Closed layer * rows must not parse their frame HTML just to render a dormant menu. */ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementItemsProps) { @@ -92,8 +108,20 @@ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementI /* a copied standalone shape is a frame on the clipboard: its paste lands a second element on the canvas, as ⌘V does, not a layer in this frame */ const frameClip = hasFrameClip() + const readOnly = useStore((s) => !canEditOpenCanvas(s)) return ( <> + {!readOnly && ( + { + if (selector) cutLayer(frame, selector) + }} + > + {t('common.cut')} + {MOD_KEY}X + + )} { diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index 8ad660ed3..a3e9f6af1 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -73,6 +73,28 @@ export function FrameContextMenu({ /* locked frames stay, as they do on ⌫ */ deleteFramesTracked(groupFrames().filter((f) => !f.locked)) } + /* Cut copies the group, then removes what Delete would once the clipboard + took it. The menu writes the clipboard asynchronously, so the frames are + read again by id when it lands, and that one read is both what is copied + and what is deleted: an edit made meanwhile rides along in the copy, and + a frame deleted meanwhile is not deleted twice. */ + function cutSelection() { + const ids = new Set(groupFrames().map((f) => f.id)) + if (!ids.size) return + let live: Frame[] = [] + writeCanvasClipboard( + () => { + live = (useStore.getState().canvas?.frames ?? []).filter((f) => ids.has(f.id)) + if (!live.length) return false + copyFrames(live) + }, + undefined, + () => { + const cut = live.filter((f) => !f.locked) + if (cut.length) deleteFramesTracked(cut) + }, + ) + } const allReady = useStore((s) => { const ids = s.selectedIds.includes(frame.id) ? s.selectedIds : [frame.id] const group = s.canvas?.frames.filter((f) => ids.includes(f.id)) ?? [frame] @@ -100,6 +122,12 @@ export function FrameContextMenu({ if (exportFrames || historyOpen) event.preventDefault() }} > + {!readOnly && ( + + {groupSize > 1 ? t('stage.cutFrames', { count: groupSize }) : t('common.cut')} + {MOD_KEY}X + + )} { const frames = groupFrames() diff --git a/src/lib/canvasClipboard.ts b/src/lib/canvasClipboard.ts index 790ce2ac1..18fdc8a4c 100644 --- a/src/lib/canvasClipboard.ts +++ b/src/lib/canvasClipboard.ts @@ -4,8 +4,10 @@ import { t } from './i18n' const TOKEN_KEY = 'doop:clipboard-token' -/** Replace the saved selection only after the system clipboard accepts the write. */ -export function writeCanvasClipboard(copy: () => boolean | void, data?: DataTransfer): boolean { +/** Replace the saved selection only after the system clipboard accepts the write. + * `onWritten` runs once the copy has landed (a cut removes the original + * there), never when the clipboard refused it, so a failed cut loses nothing. */ +export function writeCanvasClipboard(copy: () => boolean | void, data?: DataTransfer, onWritten?: () => void): boolean { const token = `doop:clipboard:${nanoid()}` const failed = () => { useStore.getState().pushNotice(t('stage.copyClipboardFailed')) @@ -13,6 +15,7 @@ export function writeCanvasClipboard(copy: () => boolean | void, data?: DataTran const commit = () => { if (copy() === false) return false localStorage.setItem(TOKEN_KEY, token) + onWritten?.() return true } try { diff --git a/src/lib/i18n/en/common.ts b/src/lib/i18n/en/common.ts index cc0674ce7..6ac080686 100644 --- a/src/lib/i18n/en/common.ts +++ b/src/lib/i18n/en/common.ts @@ -5,6 +5,7 @@ export const common = { delete: 'Delete', close: 'Close', copy: 'Copy', + cut: 'Cut', copied: 'Copied', back: 'Back', loading: 'Loading…', diff --git a/src/lib/i18n/en/stage.ts b/src/lib/i18n/en/stage.ts index b9e07d59a..757978fc4 100644 --- a/src/lib/i18n/en/stage.ts +++ b/src/lib/i18n/en/stage.ts @@ -75,6 +75,7 @@ export const stage = { deleteElement: 'Delete element', deleteFrame: 'Delete frame', copyFrames: 'Copy {count} frames', + cutFrames: 'Cut {count} frames', duplicateFrames: 'Duplicate {count} frames', showFrames: 'Show {count} frames', hideFrames: 'Hide {count} frames', diff --git a/src/lib/i18n/pt-BR/common.ts b/src/lib/i18n/pt-BR/common.ts index a40eff00c..3d4a56e0c 100644 --- a/src/lib/i18n/pt-BR/common.ts +++ b/src/lib/i18n/pt-BR/common.ts @@ -6,6 +6,7 @@ export const common: Catalog['common'] = { delete: 'Excluir', close: 'Fechar', copy: 'Copiar', + cut: 'Recortar', copied: 'Copiado', back: 'Voltar', loading: 'Carregando…', diff --git a/src/lib/i18n/pt-BR/stage.ts b/src/lib/i18n/pt-BR/stage.ts index 6fae83f63..665448fdc 100644 --- a/src/lib/i18n/pt-BR/stage.ts +++ b/src/lib/i18n/pt-BR/stage.ts @@ -75,6 +75,7 @@ export const stage: Catalog['stage'] = { deleteElement: 'Excluir elemento', deleteFrame: 'Excluir frame', copyFrames: 'Copiar {count} frames', + cutFrames: 'Recortar {count} frames', duplicateFrames: 'Duplicar {count} frames', showFrames: 'Mostrar {count} frames', hideFrames: 'Ocultar {count} frames', diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index c758a7ef8..f7e0d186d 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -408,6 +408,12 @@ export function CanvasPage({ const typing = isTypingTarget(e.target) if (dispatchActionKey(e, typing)) return if (typing) return + /* a held ⌘X cuts once: the auto-repeat would cut the frame left + selected around a cut element next, as a held ⌫ would */ + if ((e.metaKey || e.ctrlKey) && e.repeat && e.key.toLowerCase() === 'x') { + e.preventDefault() + return + } /* a picked element (from the canvas or the layers tree) is what ⌫ removes — the frame it lives in only goes when nothing inside it is selected. Auto-repeat is ignored: a held key must not take the @@ -449,25 +455,37 @@ export function CanvasPage({ return () => window.removeEventListener('keydown', onKey) }, [canvasId, presenting]) // eslint-disable-line react-hooks/exhaustive-deps - /* Native copy/paste events let us write the selection's token and read + /* Native copy/cut/paste events let us write the selection's token and read clipboard images without asking for clipboard-read permission. */ useEffect(() => { - function onCopy(e: ClipboardEvent) { - if (isTypingTarget(e.target) || window.getSelection()?.toString() || !e.clipboardData) return + /* the picked elements, else the selected frames, onto the clipboard; + false when there is nothing of the canvas's to take (text selected on + the page, a field focused, nothing selected) */ + function writeSelection(e: ClipboardEvent, onWritten?: () => void): boolean { + if (isTypingTarget(e.target) || window.getSelection()?.toString() || !e.clipboardData) return false const state = useStore.getState() const picked = state.selectedElement const frame = state.canvas?.frames.find((f) => f.id === picked?.frameId) let copy: () => boolean | void if (picked) { - if (!frame) return + if (!frame) return false const selectors = pickedSelectors(state) copy = () => copyPicked(frame, selectors) } else { const frames = state.canvas?.frames.filter((f) => state.selectedIds.includes(f.id)) ?? [] - if (!frames.length) return + if (!frames.length) return false copy = () => copyFrames(frames) } - if (writeCanvasClipboard(copy, e.clipboardData)) e.preventDefault() + return writeCanvasClipboard(copy, e.clipboardData, onWritten) + } + function onCopy(e: ClipboardEvent) { + if (writeSelection(e)) e.preventDefault() + } + /* ⌘X: copy, then remove what ⌫ would. Locked frames and layers stay put, + as they do on ⌫, so cutting one only copies it; a reader's cut copies. */ + function onCut(e: ClipboardEvent) { + const remove = canEditOpenCanvas(useStore.getState()) ? () => void deleteSelection() : undefined + if (writeSelection(e, remove)) e.preventDefault() } function onPaste(e: ClipboardEvent) { if (isTypingTarget(e.target)) return @@ -502,9 +520,11 @@ export function CanvasPage({ } } window.addEventListener('copy', onCopy) + window.addEventListener('cut', onCut) window.addEventListener('paste', onPaste) return () => { window.removeEventListener('copy', onCopy) + window.removeEventListener('cut', onCut) window.removeEventListener('paste', onPaste) } }, [canvasId]) diff --git a/tests/canvasClipboardBrowser.test.ts b/tests/canvasClipboardBrowser.test.ts index e5890540d..7f6be430e 100644 --- a/tests/canvasClipboardBrowser.test.ts +++ b/tests/canvasClipboardBrowser.test.ts @@ -47,14 +47,15 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard let page: Page let created: Partial[] = [] let uploads = 0 + let deleted: string[] = [] const errors: string[] = [] /* Headless Chromium on macOS binds copy and paste in the OS menu, not in Blink, so a key chord alone never fires the clipboard events there; the editing command goes along with the key (a macOS-only CDP option). */ - async function chord(key: 'c' | 'v') { + async function chord(key: 'c' | 'x' | 'v') { const mod = process.platform === 'darwin' ? 'Meta' : 'Control' - const commands = process.platform === 'darwin' ? [key === 'c' ? 'copy' : 'paste'] : undefined + const commands = process.platform === 'darwin' ? [{ c: 'copy', x: 'cut', v: 'paste' }[key]] : undefined await page.keyboard.down(mod) await page.keyboard.press(key, { commands }) await page.keyboard.up(mod) @@ -119,6 +120,7 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard beforeEach(async () => { created = [] uploads = 0 + deleted = [] page = await pages.open() page.setDefaultTimeout(4_000) await page.setViewport({ width: 1200, height: 900 }) @@ -136,6 +138,8 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard await page.setRequestInterception(true) page.on('request', async (request) => { const path = new URL(request.url()).pathname + if (path.startsWith('/api/frames/') && request.method() === 'DELETE') + deleted.push(path.slice('/api/frames/'.length)) if (path === '/api/canvases/c/frames' && request.method() === 'POST') { const frame: Partial = JSON.parse(request.postData()!) created.push(frame) @@ -264,6 +268,80 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard expect(uploads).toBe(0) }) + it('cuts the picked element and pastes it back as one undo step each', async () => { + await page.evaluate(() => window.canvasClipboardHarness.pick('#card')) + await chord('x') + await expect.poll(() => count('section')).toBe(0) + expect(await count('#other')).toBe(1) + await page.evaluate(() => window.canvasClipboardHarness.pick('#other')) + await chord('v') + await expect.poll(() => count('section')).toBe(1) + expect(await count('section h1, section button')).toBe(2) + await page.evaluate(() => window.canvasClipboardHarness.undo()) + expect(await count('section')).toBe(0) + await page.evaluate(() => window.canvasClipboardHarness.undo()) + expect(await count('section')).toBe(1) + }) + + it('cuts a selected frame and pastes it as a new frame', async () => { + await clickFrameTitle() + await chord('x') + /* the server's broadcast removes the frame from the store; this harness + has no room, so the delete request is what shows the cut */ + await expect.poll(() => deleted).toEqual(['f']) + await chord('v') + await expect.poll(() => created.length).toBe(1) + expect(created[0]).toMatchObject({ html: HTML, width: 400, height: 300 }) + }) + + it('copies a locked element on cut and leaves it in place', async () => { + await page.evaluate((frame) => { + window.canvasClipboardHarness.seed([ + { ...frame, html: frame.html.replace('id="card"', 'id="card" data-doop-locked="true"') }, + ]) + window.canvasClipboardHarness.pick('#card') + }, FRAME) + await chord('x') + expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('doop:clipboard:') + expect(await count('section')).toBe(1) + }) + + it('cuts through the element menu', async () => { + const doc = (await (await page.$('iframe[data-doop-frame]'))!.contentFrame())! + await doc.click('h1', { button: 'right' }) + await choose('Cut') + await expect.poll(() => count('h1')).toBe(0) + expect(await count('section button')).toBe(1) + await page.evaluate(() => window.canvasClipboardHarness.pick('#card')) + await chord('v') + await expect.poll(() => count('h1')).toBe(1) + }) + + it('cuts a frame through its menu', async () => { + await clickFrameTitle('right') + await choose('Cut') + /* the server's broadcast removes the frame from the store; this harness + has no room, so the delete request is what shows the cut */ + await expect.poll(() => deleted).toEqual(['f']) + await chord('v') + await expect.poll(() => created.length).toBe(1) + expect(created[0]).toMatchObject({ html: HTML, width: 400, height: 300 }) + }) + + it('keeps the element when the menu cut is denied by the clipboard', async () => { + await page.evaluate(() => + Object.defineProperty(navigator.clipboard, 'writeText', { + configurable: true, + value: () => Promise.reject(new DOMException('Clipboard denied', 'NotAllowedError')), + }), + ) + const doc = (await (await page.$('iframe[data-doop-frame]'))!.contentFrame())! + await doc.click('h1', { button: 'right' }) + await choose('Cut') + await page.waitForFunction(() => window.canvasClipboardHarness.notice()?.includes('Couldn’t copy')) + expect(await count('h1')).toBe(1) + }) + it('copies a frame through its menu and pastes with the keyboard', async () => { await copyImage() await clickFrameTitle('right') From 545e1f782be891d8f4e2ca260e377df90644ee0e Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 15 Nov 2026 22:44:42 -0800 Subject: [PATCH 02/13] feat(mcp): inspect_frame for MCP agents, with a layout problems report (#566) * feat(mcp): inspect_frame for MCP agents, with a layout problems report The resident agent's inspect_frame reaches MCP agents: the rendered frame as data (design summary, element outline with boxes and computed styles), now with selectors to report on chosen elements and a problems list: content past the frame's edge (everything below its height as one line), text cut off by its box, and text or controls overlapping, measured on what clipping ancestors leave visible and per line for wrapped inline text. Co-Authored-By: Claude Opus 5.5 * fix(mcp): inspect_frame reports text cut off vertically, and every asked-for match Two gaps from review. A fixed-height text box with overflow hidden lost lines without a problem, since only horizontal overflow of the box's own text was checked. And asked-for selectors shared the outline's 64-element limit, so later selectors could come back empty without appearing in unmatched: each now gets its own 20. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 8f20caf2ca8b51f33286b6be436cd50ad60676c2) --- server/guide.ts | 5 + server/mcp.ts | 36 ++- server/resident.ts | 15 +- server/screenshot.ts | 565 ++++++++++++++++++++++++++----------- tests/inspectFrame.test.ts | 122 ++++++++ 5 files changed, 567 insertions(+), 176 deletions(-) create mode 100644 tests/inspectFrame.test.ts diff --git a/server/guide.ts b/server/guide.ts index 5787118c6..b6aa4c63b 100644 --- a/server/guide.ts +++ b/server/guide.ts @@ -373,6 +373,11 @@ and fix real issues before moving on: that is not a ? A hex, font or size that a token already names? Make the component or use the token. +For Fit and overlaps, inspect_frame measures what the eye estimates: its \`problems\` list +content past the frame's edge, text cut off by its box and text or controls on top of each +other, with each element's selector and box. Pass selectors to read exact boxes and computed +styles of the elements you are fixing. Judge its findings against the screenshot. + Prefer targeted fixes over rewrites. Never delete and restart a mostly-good frame — the humans watching lose work they may have been reacting to. diff --git a/server/mcp.ts b/server/mcp.ts index ebd0fc960..98d303bdd 100644 --- a/server/mcp.ts +++ b/server/mcp.ts @@ -40,7 +40,7 @@ import * as workspaces from './workspaces.ts' import { auth, getUserName, isBanned } from './auth.ts' import { capture, captureThrottled } from './analytics.ts' import { captureFeature, captureTokenResults } from './featureEvents.ts' -import { renderFrame } from './screenshot.ts' +import { inspectFrame, renderFrame } from './screenshot.ts' import { imagesForFrames } from './assets.ts' import type { FrameImage } from '../shared/imageDescriptions.ts' import { renderedHeight } from './renderLimits.ts' @@ -2315,6 +2315,40 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st }, ) + server.registerTool( + 'inspect_frame', + { + title: 'Inspect a rendered frame', + description: + "Render a frame and read it as data rather than pixels: the design in use (colours, backgrounds, fonts, sizes, radii, shadows, CSS variables), an outline of its key elements with text, box (design px) and computed style, and `problems`: content past the frame's edge, text cut off by its box, and text or controls overlapping. Problems are candidates to check against the screenshot: a deliberate overlap (stacked avatars, a label on a photo) or a clipped preview is fine as it is. Pass selectors to report on those elements instead of the automatic outline (a data-doop-id, a class, any CSS selector). Use it with get_frame_screenshot to pin down what looks wrong, and before editing a large frame.", + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + inputSchema: { + frame_id: z.string(), + selectors: z + .array(z.string()) + .max(20) + .optional() + .describe('CSS selectors to report on (up to 20 matches each) instead of the automatic outline'), + agent_name: agentName.optional(), + }, + }, + async ({ frame_id, selectors, agent_name }) => { + const f = frameFor(frame_id, 'view') + if (!f) return noFrame(frame_id) + arrive(f.canvasId, agent_name) + try { + const inspection = await inspectFrame({ ...f }, { selectors }) + return withFeedbackNotice( + text({ ...inspection, approvalStatus: f.approval?.status ?? 'draft' }), + f.canvasId, + agent_name ? actorFrom(agent_name) : undefined, + ) + } catch (e) { + return err(e instanceof Error ? e.message : 'inspection failed') + } + }, + ) + server.registerTool( 'get_frame_screenshot', { diff --git a/server/resident.ts b/server/resident.ts index 15ffd8386..eb524d3ec 100644 --- a/server/resident.ts +++ b/server/resident.ts @@ -1224,10 +1224,17 @@ const TOOLS: Anthropic.Tool[] = [ { name: 'inspect_frame', description: - 'Inspect the rendered page without relying on class names. Returns a compact semantic element outline, visible text, geometry, computed colors, typography, radii, shadows, and CSS variables. Use this before working with large frames and for cross-frame visual references.', + "Inspect the rendered page without relying on class names. Returns a compact semantic element outline, visible text, geometry, computed colors, typography, radii, shadows, and CSS variables, plus `problems`: content past the frame's edge, text cut off by its box, and text or controls overlapping (candidates to check against the screenshot; a deliberate overlap is fine). Pass selectors to report on those elements instead of the automatic outline. Use this before working with large frames, for cross-frame visual references and to pin down layout faults.", input_schema: { type: 'object', - properties: { frame_id: { type: 'string' } }, + properties: { + frame_id: { type: 'string' }, + selectors: { + type: 'array', + items: { type: 'string' }, + description: 'CSS selectors to report on (up to 20 matches each) instead of the automatic outline', + }, + }, required: ['frame_id'], }, }, @@ -1955,7 +1962,9 @@ async function runResidentTool( case 'inspect_frame': { const f = store.getFrame(input.frame_id) if (!f || f.canvasId !== canvasId) return fail('frame not found on this canvas') - const inspection = await inspectFrame(f) + const asked = (input as Record).selectors + const selectors = Array.isArray(asked) ? asked.filter((x): x is string => typeof x === 'string') : undefined + const inspection = await inspectFrame(f, { selectors }) return ok( JSON.stringify({ ...inspection, diff --git a/server/screenshot.ts b/server/screenshot.ts index a4932382a..f06aa99f7 100644 --- a/server/screenshot.ts +++ b/server/screenshot.ts @@ -215,204 +215,422 @@ export interface FrameInspection { } elements: Array<{ selector: string + /** the selector asked for that found this element (inspect with `selectors`) */ + matched?: string tag: string role?: string text?: string rect: { x: number; y: number; width: number; height: number } style: { color: string; background: string; font: string; fontSize: string; fontWeight: string } }> + /** asked-for selectors that matched nothing visible, or are not valid CSS */ + unmatched?: Array<{ selector: string; reason: 'no visible match' | 'invalid selector' }> + /** layout faults a reviewer would flag, at most MAX_PROBLEMS of them */ + problems: InspectionProblem[] + problemCount: number +} + +export interface InspectionProblem { + /** off-frame: past the frame's edge, where the canvas cuts it off; clipped: content cut + * off by its own box (overflow hidden, an ellipsis); overlap: two pieces of text or + * controls on top of each other */ + type: 'off-frame' | 'clipped' | 'overlap' + selector: string + /** the other element of an overlap */ + other?: string + text?: string + rect: { x: number; y: number; width: number; height: number } + detail: string +} + +export interface InspectOptions { + /** CSS selectors to report on instead of the automatic outline (up to 20 matches each) */ + selectors?: string[] } /** A compact, rendered representation for agents. It intentionally relies on * visible text, semantics, geometry and computed styles rather than classes. */ -export function inspectFrame(frame: Frame): Promise { - return renderer.withPage('inspecting the frame', RENDER_TIMEOUT_MS, (page) => inspectOn(page, frame)) +export function inspectFrame(frame: Frame, options: InspectOptions = {}): Promise { + return renderer.withPage('inspecting the frame', RENDER_TIMEOUT_MS, (page) => inspectOn(page, frame, options)) } -async function inspectOn(page: Page, frame: Frame): Promise { +const MAX_PROBLEMS = 30 + +async function inspectOn(page: Page, frame: Frame, options: InspectOptions): Promise { await loadFrameInto(page, frame) { /* tsx/esbuild annotates nested functions with __name; page.evaluate serializes the callback without that runtime helper. A tiny in-page identity shim keeps the evaluated code independent of the loader. */ await page.evaluate('globalThis.__name = (target) => target') - const inspection = await page.evaluate(() => { - const MAX_ELEMENTS = 64 - const MAX_STYLE_SAMPLES = 500 - const semanticTags = new Set([ - 'header', - 'nav', - 'main', - 'section', - 'article', - 'aside', - 'footer', - 'h1', - 'h2', - 'h3', - 'h4', - 'h5', - 'h6', - 'p', - 'a', - 'button', - 'input', - 'textarea', - 'select', - 'form', - 'img', - 'ul', - 'ol', - 'table', - ]) - - function visible(el: Element): el is HTMLElement { - if (!(el instanceof HTMLElement)) return false - const style = getComputedStyle(el) - const rect = el.getBoundingClientRect() - return ( - style.display !== 'none' && - style.visibility !== 'hidden' && - Number(style.opacity) > 0 && - rect.width > 1 && - rect.height > 1 + const inspection = await page.evaluate( + ({ asked, frameWidth, frameHeight, maxProblems }) => { + const MAX_ELEMENTS = 64 + const MAX_STYLE_SAMPLES = 500 + const semanticTags = new Set([ + 'header', + 'nav', + 'main', + 'section', + 'article', + 'aside', + 'footer', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'p', + 'a', + 'button', + 'input', + 'textarea', + 'select', + 'form', + 'img', + 'ul', + 'ol', + 'table', + ]) + + function visible(el: Element): el is HTMLElement { + if (!(el instanceof HTMLElement)) return false + const style = getComputedStyle(el) + const rect = el.getBoundingClientRect() + return ( + style.display !== 'none' && + style.visibility !== 'hidden' && + Number(style.opacity) > 0 && + rect.width > 1 && + rect.height > 1 + ) + } + + function selectorFor(el: Element): string { + const doopId = el.getAttribute('data-doop-id') + if (doopId) return `[data-doop-id="${doopId}"]` + if (el.id && el.id.length < 80) return `#${CSS.escape(el.id)}` + const parts: string[] = [] + let node: Element | null = el + while (node && node !== document.body && parts.length < 7) { + const tag = node.tagName.toLowerCase() + const parent: Element | null = node.parentElement + if (!parent) { + parts.unshift(tag) + break + } + const sameTag = Array.from(parent.children).filter((child: Element) => child.tagName === node!.tagName) + const suffix = sameTag.length > 1 ? `:nth-of-type(${sameTag.indexOf(node) + 1})` : '' + parts.unshift(tag + suffix) + node = parent + } + return `body > ${parts.join(' > ')}` + } + + function cleanText(value: string | null | undefined, max = 180): string | undefined { + const text = (value || '').replace(/\s+/g, ' ').trim() + if (!text) return undefined + return text.length > max ? `${text.slice(0, max - 1)}…` : text + } + + function normalizedColor(value: string): string | undefined { + if (!value || value === 'rgba(0, 0, 0, 0)' || value === 'transparent') return undefined + return value + } + + const counts = { + colors: new Map(), + backgrounds: new Map(), + fonts: new Map(), + fontSizes: new Map(), + radii: new Map(), + shadows: new Map(), + } + const bump = (map: Map, value?: string) => { + if (value) map.set(value, (map.get(value) || 0) + 1) + } + + const all = Array.from(document.body.querySelectorAll('*')).filter(visible) + for (const el of all.slice(0, MAX_STYLE_SAMPLES)) { + const style = getComputedStyle(el) + bump(counts.colors, normalizedColor(style.color)) + bump(counts.backgrounds, normalizedColor(style.backgroundColor)) + bump(counts.fonts, style.fontFamily) + bump(counts.fontSizes, style.fontSize) + if (style.borderRadius !== '0px') bump(counts.radii, style.borderRadius) + if (style.boxShadow !== 'none') bump(counts.shadows, style.boxShadow) + } + + const semantic = all + .filter((el) => semanticTags.has(el.tagName.toLowerCase()) || !!el.getAttribute('role')) + .sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top) + const candidates: HTMLElement[] = [] + const selected = new Set() + const take = (limit: number, predicate: (el: HTMLElement) => boolean) => { + for (const el of semantic) { + if (candidates.length >= MAX_ELEMENTS || limit <= 0) break + if (selected.has(el) || !predicate(el)) continue + selected.add(el) + candidates.push(el) + limit-- + } + } + take(18, (el) => + ['header', 'nav', 'main', 'section', 'article', 'aside', 'footer'].includes(el.tagName.toLowerCase()), ) - } - - function selectorFor(el: Element): string { - const doopId = el.getAttribute('data-doop-id') - if (doopId) return `[data-doop-id="${doopId}"]` - if (el.id && el.id.length < 80) return `#${CSS.escape(el.id)}` - const parts: string[] = [] - let node: Element | null = el - while (node && node !== document.body && parts.length < 7) { - const tag = node.tagName.toLowerCase() - const parent: Element | null = node.parentElement - if (!parent) { - parts.unshift(tag) - break + take(16, (el) => /^h[1-6]$/.test(el.tagName.toLowerCase())) + take( + 16, + (el) => + ['button', 'a', 'input', 'textarea', 'select', 'form'].includes(el.tagName.toLowerCase()) || + !!el.getAttribute('role'), + ) + take(14, (el) => ['p', 'img', 'ul', 'ol', 'table'].includes(el.tagName.toLowerCase())) + take(MAX_ELEMENTS - candidates.length, () => true) + + /* with selectors, the elements they find in place of the automatic outline */ + const matchedBy = new Map() + const unmatched: Array<{ selector: string; reason: 'no visible match' | 'invalid selector' }> = [] + if (asked.length) { + candidates.length = 0 + for (const query of asked) { + let found: HTMLElement[] + try { + found = Array.from(document.querySelectorAll(query)).filter(visible).slice(0, 20) + } catch { + unmatched.push({ selector: query, reason: 'invalid selector' }) + continue + } + if (!found.length) unmatched.push({ selector: query, reason: 'no visible match' }) + for (const el of found) { + /* each asked-for selector gets its 20, not a share of the outline's limit */ + if (matchedBy.has(el)) continue + matchedBy.set(el, query) + candidates.push(el) + } } - const sameTag = Array.from(parent.children).filter((child: Element) => child.tagName === node!.tagName) - const suffix = sameTag.length > 1 ? `:nth-of-type(${sameTag.indexOf(node) + 1})` : '' - parts.unshift(tag + suffix) - node = parent } - return `body > ${parts.join(' > ')}` - } - - function cleanText(value: string | null | undefined, max = 180): string | undefined { - const text = (value || '').replace(/\s+/g, ' ').trim() - if (!text) return undefined - return text.length > max ? `${text.slice(0, max - 1)}…` : text - } - - function normalizedColor(value: string): string | undefined { - if (!value || value === 'rgba(0, 0, 0, 0)' || value === 'transparent') return undefined - return value - } - - const counts = { - colors: new Map(), - backgrounds: new Map(), - fonts: new Map(), - fontSizes: new Map(), - radii: new Map(), - shadows: new Map(), - } - const bump = (map: Map, value?: string) => { - if (value) map.set(value, (map.get(value) || 0) + 1) - } - - const all = Array.from(document.body.querySelectorAll('*')).filter(visible) - for (const el of all.slice(0, MAX_STYLE_SAMPLES)) { - const style = getComputedStyle(el) - bump(counts.colors, normalizedColor(style.color)) - bump(counts.backgrounds, normalizedColor(style.backgroundColor)) - bump(counts.fonts, style.fontFamily) - bump(counts.fontSizes, style.fontSize) - if (style.borderRadius !== '0px') bump(counts.radii, style.borderRadius) - if (style.boxShadow !== 'none') bump(counts.shadows, style.boxShadow) - } - - const semantic = all - .filter((el) => semanticTags.has(el.tagName.toLowerCase()) || !!el.getAttribute('role')) - .sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top) - const candidates: HTMLElement[] = [] - const selected = new Set() - const take = (limit: number, predicate: (el: HTMLElement) => boolean) => { - for (const el of semantic) { - if (candidates.length >= MAX_ELEMENTS || limit <= 0) break - if (selected.has(el) || !predicate(el)) continue - selected.add(el) - candidates.push(el) - limit-- + + const boxOf = (rect: DOMRect) => ({ + x: Math.round(rect.left + scrollX), + y: Math.round(rect.top + scrollY), + width: Math.round(rect.width), + height: Math.round(rect.height), + }) + + /* Layout faults. Text and controls are what a reader notices, so overlaps are + checked between them only: an element with text of its own, an image or a + control, never one inside the other. */ + const problems: Array<{ + type: 'off-frame' | 'clipped' | 'overlap' + selector: string + other?: string + text?: string + rect: { x: number; y: number; width: number; height: number } + detail: string + }> = [] + let problemCount = 0 + const report = (problem: (typeof problems)[number]) => { + problemCount++ + if (problems.length < maxProblems) problems.push(problem) + } + const ownText = (el: Element) => + Array.from(el.childNodes).some((node) => node.nodeType === Node.TEXT_NODE && !!node.textContent?.trim()) + + /* what is left of an element's box once every clipping ancestor has cut it */ + const shownRect = (el: Element): DOMRect => { + let { left, top, right, bottom } = el.getBoundingClientRect() + for (let node = el.parentElement; node; node = node.parentElement) { + const style = getComputedStyle(node) + if (style.overflowX === 'visible' && style.overflowY === 'visible') continue + const clip = node.getBoundingClientRect() + left = Math.max(left, clip.left) + top = Math.max(top, clip.top) + right = Math.min(right, clip.right) + bottom = Math.min(bottom, clip.bottom) + } + return new DOMRect(left, top, Math.max(0, right - left), Math.max(0, bottom - top)) + } + const leaves = all.filter( + (el) => + ownText(el) || + ['img', 'svg', 'button', 'input', 'textarea', 'select', 'video'].includes(el.tagName.toLowerCase()), + ) + /* Past the left or right edge: each element, since each is its own fix. Past the + bottom: one line for the lot, since it is one fix (the frame's height or the + page's length), led by the first element it cuts. */ + let below: { el: HTMLElement; box: ReturnType } | undefined + let belowCount = 0 + let lowest = 0 + for (const el of leaves) { + const box = boxOf(shownRect(el)) + if (!box.width || !box.height) continue + const sides = [ + box.x < -1 && `${-box.x}px past the left edge`, + box.x + box.width > frameWidth + 1 && `${box.x + box.width - frameWidth}px past the right edge`, + ].filter(Boolean) + if (sides.length) + report({ + type: 'off-frame', + selector: selectorFor(el), + text: cleanText(el.innerText, 80), + rect: box, + detail: sides.join(', '), + }) + if (box.y + box.height > frameHeight + 1) { + belowCount++ + lowest = Math.max(lowest, box.y + box.height) + if (!below || box.y < below.box.y) below = { el, box } + } + } + if (below) + report({ + type: 'off-frame', + selector: selectorFor(below.el), + text: cleanText(below.el.innerText, 80), + rect: below.box, + detail: `content runs ${lowest - frameHeight}px below the frame's ${frameHeight}px height (${belowCount} element${ + belowCount === 1 ? '' : 's' + }, from this one down): raise the frame's height or shorten the content`, + }) + /* text its own box cuts off; an image a rounded card crops is meant to be */ + const texts = leaves.filter(ownText) + for (const el of all) { + const style = getComputedStyle(el) + if (style.overflowX === 'visible' && style.overflowY === 'visible') continue + if (['auto', 'scroll'].includes(style.overflowX) || ['auto', 'scroll'].includes(style.overflowY)) continue + const bounds = el.getBoundingClientRect() + const cut = texts.find((text) => { + if (text !== el && !el.contains(text)) return false + const rect = text.getBoundingClientRect() + return ( + rect.right > bounds.right + 1 || + rect.bottom > bounds.bottom + 1 || + rect.left < bounds.left - 1 || + (text === el && (text.scrollWidth > text.clientWidth + 1 || text.scrollHeight > text.clientHeight + 1)) + ) + }) + if (!cut) continue + report({ + type: 'clipped', + selector: selectorFor(el), + text: cleanText(cut.innerText, 80), + rect: boxOf(bounds), + detail: + style.textOverflow === 'ellipsis' + ? 'text cut off with an ellipsis' + : 'text cut off by the box (overflow)', + }) + } + /* each line box of wrapped inline text, not the box around all its lines, which + covers whatever sits beside the first and last line */ + const sized = leaves.slice(0, 400).map((el) => { + const shown = shownRect(el) + const lines = Array.from(el.getClientRects()) + .map((r) => { + const left = Math.max(r.left, shown.left) + const top = Math.max(r.top, shown.top) + const right = Math.min(r.right, shown.right) + const bottom = Math.min(r.bottom, shown.bottom) + return new DOMRect(left, top, right - left, bottom - top) + }) + .filter((r) => r.width > 0 && r.height > 0) + return { el, shown, lines } + }) + const overlapOf = (a: DOMRect[], b: DOMRect[]) => { + for (const x of a) + for (const y of b) { + const w = Math.min(x.right, y.right) - Math.max(x.left, y.left) + const h = Math.min(x.bottom, y.bottom) - Math.max(x.top, y.top) + /* a few px is a tight line height or a hairline, not an overlap */ + if (w > 4 && h > 4) return { w, h } + } + return undefined + } + for (let i = 0; i < sized.length; i++) { + for (let j = i + 1; j < sized.length; j++) { + const a = sized[i]! + const b = sized[j]! + if (a.el.contains(b.el) || b.el.contains(a.el)) continue + const hit = overlapOf(a.lines, b.lines) + if (!hit) continue + report({ + type: 'overlap', + selector: selectorFor(a.el), + other: selectorFor(b.el), + text: cleanText(a.el.innerText, 80), + rect: boxOf(a.shown), + detail: `overlaps ${b.el.tagName.toLowerCase()}${ + cleanText(b.el.innerText, 40) ? ` "${cleanText(b.el.innerText, 40)}"` : '' + } by ${Math.round(hit.w)}×${Math.round(hit.h)}px`, + }) + } + } + + const elements = candidates.map((el) => { + const rect = el.getBoundingClientRect() + const style = getComputedStyle(el) + const image = el instanceof HTMLImageElement ? cleanText(el.alt || el.getAttribute('aria-label')) : undefined + return { + selector: selectorFor(el), + ...(matchedBy.has(el) ? { matched: matchedBy.get(el) } : {}), + tag: el.tagName.toLowerCase(), + role: el.getAttribute('role') || undefined, + text: image || cleanText(el.innerText || el.getAttribute('aria-label') || el.getAttribute('placeholder')), + rect: { + x: Math.round(rect.left + scrollX), + y: Math.round(rect.top + scrollY), + width: Math.round(rect.width), + height: Math.round(rect.height), + }, + style: { + color: style.color, + background: style.backgroundColor, + font: style.fontFamily, + fontSize: style.fontSize, + fontWeight: style.fontWeight, + }, + } + }) + + const top = (map: Map, limit: number) => + [...map.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, limit) + .map(([value]) => value) + const rootStyle = getComputedStyle(document.documentElement) + const cssVariables: Record = {} + for (const name of Array.from(rootStyle)) { + if (!name.startsWith('--') || Object.keys(cssVariables).length >= 40) continue + const value = rootStyle.getPropertyValue(name).trim() + if (value && value.length <= 160) cssVariables[name] = value } - } - take(18, (el) => - ['header', 'nav', 'main', 'section', 'article', 'aside', 'footer'].includes(el.tagName.toLowerCase()), - ) - take(16, (el) => /^h[1-6]$/.test(el.tagName.toLowerCase())) - take( - 16, - (el) => - ['button', 'a', 'input', 'textarea', 'select', 'form'].includes(el.tagName.toLowerCase()) || - !!el.getAttribute('role'), - ) - take(14, (el) => ['p', 'img', 'ul', 'ol', 'table'].includes(el.tagName.toLowerCase())) - take(MAX_ELEMENTS - candidates.length, () => true) - const elements = candidates.map((el) => { - const rect = el.getBoundingClientRect() - const style = getComputedStyle(el) - const image = el instanceof HTMLImageElement ? cleanText(el.alt || el.getAttribute('aria-label')) : undefined return { - selector: selectorFor(el), - tag: el.tagName.toLowerCase(), - role: el.getAttribute('role') || undefined, - text: image || cleanText(el.innerText || el.getAttribute('aria-label') || el.getAttribute('placeholder')), - rect: { - x: Math.round(rect.left + scrollX), - y: Math.round(rect.top + scrollY), - width: Math.round(rect.width), - height: Math.round(rect.height), - }, - style: { - color: style.color, - background: style.backgroundColor, - font: style.fontFamily, - fontSize: style.fontSize, - fontWeight: style.fontWeight, + title: document.title, + design: { + colors: top(counts.colors, 10), + backgrounds: top(counts.backgrounds, 10), + fonts: top(counts.fonts, 8), + fontSizes: top(counts.fontSizes, 10), + radii: top(counts.radii, 8), + shadows: top(counts.shadows, 6), + cssVariables, }, + elements, + unmatched, + problems, + problemCount, } - }) - - const top = (map: Map, limit: number) => - [...map.entries()] - .sort((a, b) => b[1] - a[1]) - .slice(0, limit) - .map(([value]) => value) - const rootStyle = getComputedStyle(document.documentElement) - const cssVariables: Record = {} - for (const name of Array.from(rootStyle)) { - if (!name.startsWith('--') || Object.keys(cssVariables).length >= 40) continue - const value = rootStyle.getPropertyValue(name).trim() - if (value && value.length <= 160) cssVariables[name] = value - } - - return { - title: document.title, - design: { - colors: top(counts.colors, 10), - backgrounds: top(counts.backgrounds, 10), - fonts: top(counts.fonts, 8), - fontSizes: top(counts.fontSizes, 10), - radii: top(counts.radii, 8), - shadows: top(counts.shadows, 6), - cssVariables, - }, - elements, - } - }) + }, + { + asked: (options.selectors ?? []).slice(0, 20), + frameWidth: Math.round(frame.width), + frameHeight: Math.round(frame.height), + maxProblems: MAX_PROBLEMS, + }, + ) return { document: { @@ -423,6 +641,9 @@ async function inspectOn(page: Page, frame: Frame): Promise { }, design: inspection.design, elements: inspection.elements, + ...(inspection.unmatched.length ? { unmatched: inspection.unmatched } : {}), + problems: inspection.problems, + problemCount: inspection.problemCount, } } } diff --git a/tests/inspectFrame.test.ts b/tests/inspectFrame.test.ts new file mode 100644 index 000000000..72749fa83 --- /dev/null +++ b/tests/inspectFrame.test.ts @@ -0,0 +1,122 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { describe, expect, it, vi } from 'vitest' +import { findBrowserPath, inspectFrame } from '../server/screenshot.ts' +import type { Frame } from '../shared/types.ts' + +vi.mock('../server/db/persist.ts', () => ({ + saveCanvas: () => {}, + saveFrame: () => {}, + saveFrameNow: async () => {}, + saveActivity: () => {}, + saveFrameVersion: () => {}, + saveComponent: () => {}, +})) + +/** inspect_frame: the rendered frame as data, with the layout faults a reviewer would flag. */ + +const frame = (body: string, size = { width: 400, height: 300 }): Frame => ({ + id: 'inspected', + canvasId: 'inspect-canvas', + name: 'Screen', + html: `${body}`, + x: 0, + y: 0, + ...size, + createdAt: 0, + updatedAt: 0, + updatedBy: 'alice', +}) + +const FAULTY = frame(` +

Runs off the side

+
A label far too long for its pill
+

Arrivals

+ 12:40 +`) + +const CLEAN = frame(` +
+ +
+

One clean line

+`) + +describe.skipIf(!findBrowserPath())('inspectFrame', () => { + it('reports text past the edge, cut off by its box, and overlapping', async () => { + const { problems, problemCount } = await inspectFrame(FAULTY) + const byType = (type: string) => problems.filter((p) => p.type === type) + expect(byType('off-frame')).toEqual([ + expect.objectContaining({ text: 'Runs off the side', detail: expect.stringContaining('past the right edge') }), + ]) + expect(byType('clipped')).toEqual([ + expect.objectContaining({ selector: expect.stringContaining('div'), detail: 'text cut off with an ellipsis' }), + ]) + expect(byType('overlap')).toEqual([ + expect.objectContaining({ text: 'Arrivals', detail: expect.stringContaining('"12:40"') }), + ]) + expect(problemCount).toBe(3) + }, 30_000) + + it('leaves a clean frame alone, an image a rounded card crops included', async () => { + expect((await inspectFrame(CLEAN)).problems).toEqual([]) + }, 30_000) + + it('reports on the asked-for selectors in place of the outline', async () => { + const result = await inspectFrame(FAULTY, { selectors: ['.badge', '.missing', 'p[', 'h2, .pill'] }) + expect(result.elements.map((e) => [e.matched, e.text])).toEqual([ + ['.badge', '12:40'], + ['h2, .pill', 'A label far too long for its pill'], + ['h2, .pill', 'Arrivals'], + ]) + expect(result.unmatched).toEqual([ + { selector: '.missing', reason: 'no visible match' }, + { selector: 'p[', reason: 'invalid selector' }, + ]) + }, 30_000) + + it('reports text its own fixed height cuts off', async () => { + const clamped = frame( + '

Three lines of wrapped text that its twenty pixel box cuts down to one

', + ) + expect((await inspectFrame(clamped)).problems).toEqual([ + expect.objectContaining({ type: 'clipped', detail: 'text cut off by the box (overflow)' }), + ]) + }, 30_000) + + it('returns every match of every asked-for selector, past the outline’s 64', async () => { + const rows = ['a', 'b', 'c', 'd'] + .map((group) => + Array.from( + { length: 20 }, + (_, i) => `${i}`, + ).join(''), + ) + .join('') + const result = await inspectFrame(frame(rows), { selectors: ['.a', '.b', '.c', '.d'] }) + expect(result.elements).toHaveLength(80) + expect(result.unmatched ?? []).toEqual([]) + }, 30_000) + + it('is an MCP tool', async () => { + const { store } = await import('../server/store.ts') + const actions = await import('../server/actions.ts') + const { buildMcpServer } = await import('../server/mcp.ts') + const canvas = store.createCanvas('inspect', 'owner') + const owner = actions.resolveActor({ name: 'Owner', kind: 'user' }) + const made = actions.createFrame(canvas.id, { name: 'Screen', html: FAULTY.html, width: 400, height: 300 }, owner)! + const client = new Client({ name: 'inspect-test', version: '1.0.0' }) + const [a, b] = InMemoryTransport.createLinkedPair() + await buildMcpServer('Owner', 'owner').connect(b) + await client.connect(a) + const result = (await client.callTool({ + name: 'inspect_frame', + arguments: { frame_id: made.id, selectors: ['.badge'] }, + })) as { isError?: boolean; content: { text: string }[] } + await client.close() + expect(result.isError).toBeFalsy() + const body = JSON.parse(result.content[0]!.text) as { problemCount: number; elements: { text: string }[] } + expect(body.problemCount).toBe(3) + expect(body.elements.map((e) => e.text)).toEqual(['12:40']) + }, 30_000) +}) From dd8d0e039068300a2489e84031dde4eb8357f796 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 15 Nov 2026 22:49:52 -0800 Subject: [PATCH 03/13] fix(ios): sharp frames at every zoom, no jitter from scale-change transitions (#576) * fix(ios): sharp frames at every zoom, no jitter from scale-change transitions Frames were soft at most zoom levels: Core Animation stretches each frame bitmap with a linear filter, and while the camera offset rested on whole device pixels, each frame's origin did not (nor did the first fit), so most zooms blurred every glyph by up to half a pixel. Frame layers now snap to the device-pixel grid at the camera's density, and tiles reach screen density at the deepest zoom (cap 8 -> 12 on a 3x screen). Frames with `transition: all` jittered by a pixel or two and repainted forever: base and tile paint one document at different scales, and each scale change recomputed device-pixel-snapped border widths, which started CSS transitions. The Blitz and Stylo forks now restyle a scale change with TraversalFlags::DeviceChangeOnly, which starts no transitions (kgoedecke/blitz 35a984f, kgoedecke/stylo 39c0595); rust/tests/rescale_transitions.rs covers it. Playing frames keep one tile: playback paints at screen density within a one-screen budget, no static tile is painted between its steps, and only a playback step decides that an animation ended. Co-Authored-By: Claude Opus 5.5 * fix(ios): size frame layers to the bitmap's whole pixels, test animations advance Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 81848d46a1e81ac08c3ba43989b5c3d1bbffd818) --- ios/BlitzKit/rust/Cargo.lock | 46 +++++----- ios/BlitzKit/rust/Cargo.toml | 39 ++++----- .../rust/tests/rescale_transitions.rs | 83 +++++++++++++++++++ ios/Doop/Blitz/BlitzCanvasView.swift | 74 +++++++++++++---- ios/README.md | 33 ++++++-- 5 files changed, 208 insertions(+), 67 deletions(-) create mode 100644 ios/BlitzKit/rust/tests/rescale_transitions.rs diff --git a/ios/BlitzKit/rust/Cargo.lock b/ios/BlitzKit/rust/Cargo.lock index 37c81396f..ebdc1ed97 100644 --- a/ios/BlitzKit/rust/Cargo.lock +++ b/ios/BlitzKit/rust/Cargo.lock @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "blitz-dom" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "accesskit", "anyrender", @@ -243,7 +243,7 @@ dependencies = [ "color", "cssparser", "cursor-icon", - "debug_timer 0.1.3 (git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe)", + "debug_timer 0.1.3 (git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9)", "euclid", "html-escape", "image", @@ -277,7 +277,7 @@ dependencies = [ [[package]] name = "blitz-html" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "blitz-dom", "blitz-traits", @@ -288,7 +288,7 @@ dependencies = [ [[package]] name = "blitz-net" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "blitz-traits", "data-url", @@ -304,7 +304,7 @@ dependencies = [ [[package]] name = "blitz-paint" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "anyrender", "anyrender_svg", @@ -327,7 +327,7 @@ dependencies = [ [[package]] name = "blitz-traits" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "atomic_refcell", "bitflags 2.13.2", @@ -756,7 +756,7 @@ checksum = "da220af51a1a335e9a930beaaef53d261e41ea9eecfb3d973a3ddae1a7284b9c" [[package]] name = "debug_timer" version = "0.1.3" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" [[package]] name = "deranged" @@ -928,7 +928,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2804,7 +2804,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2878,7 +2878,7 @@ dependencies = [ [[package]] name = "selectors" version = "0.41.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "bitflags 2.13.2", "cssparser", @@ -2966,7 +2966,7 @@ dependencies = [ [[package]] name = "servo_arc" version = "0.5.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "serde", "stable_deref_trait", @@ -3212,7 +3212,7 @@ dependencies = [ [[package]] name = "stylo" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "arrayvec", @@ -3268,7 +3268,7 @@ dependencies = [ [[package]] name = "stylo_atoms" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "string_cache", "string_cache_codegen", @@ -3277,7 +3277,7 @@ dependencies = [ [[package]] name = "stylo_derive" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "darling", "proc-macro2", @@ -3289,7 +3289,7 @@ dependencies = [ [[package]] name = "stylo_dom" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "bitflags 2.13.2", "stylo_malloc_size_of", @@ -3298,7 +3298,7 @@ dependencies = [ [[package]] name = "stylo_malloc_size_of" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "cssparser", @@ -3316,7 +3316,7 @@ dependencies = [ [[package]] name = "stylo_static_prefs" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "toml", ] @@ -3324,7 +3324,7 @@ dependencies = [ [[package]] name = "stylo_taffy" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "bitflags 2.13.2", "stylo", @@ -3335,7 +3335,7 @@ dependencies = [ [[package]] name = "stylo_traits" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "bitflags 2.13.2", @@ -3447,7 +3447,7 @@ dependencies = [ "getrandom", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3590,7 +3590,7 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "to_shmem" version = "0.6.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "cssparser", "servo_arc", @@ -3603,7 +3603,7 @@ dependencies = [ [[package]] name = "to_shmem_derive" version = "0.2.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "darling", "proc-macro2", @@ -4085,7 +4085,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/ios/BlitzKit/rust/Cargo.toml b/ios/BlitzKit/rust/Cargo.toml index bb5f564c8..9d4c45bec 100644 --- a/ios/BlitzKit/rust/Cargo.toml +++ b/ios/BlitzKit/rust/Cargo.toml @@ -11,14 +11,14 @@ crate-type = ["staticlib", "rlib"] [dependencies] # Blitz from the `doop` branch of kgoedecke/blitz: DioxusLabs/blitz at 0f60502 plus our # rendering fixes (inline SVG, web fonts, placeholders, filters, opt-in prefers-reduced-motion), -# each also sent upstream. +# each also sent upstream, and a scale change that starts no CSS transitions (fork only for now). # Update by rebasing that branch and bumping the rev here. -blitz-dom = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["default"] } +blitz-dom = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["default"] } # Same taffy as the pinned Blitz workspace: the bridge re-rounds layout on the device-pixel grid. taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "49152ca29664f9687c714c7732d88ff07d62110a", default-features = false, features = ["std", "content_size"] } -blitz-html = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } -blitz-paint = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["svg"] } -blitz-traits = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } +blitz-html = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } +blitz-paint = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["svg"] } +blitz-traits = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } # Same parley revision as the pinned Blitz commit, for one shared font context. parley = { git = "https://github.com/linebender/parley", rev = "718dcb721941fd8e72128833122d31f5a4e80504", default-features = false, features = ["std", "system"] } anyrender = "0.14" @@ -39,32 +39,33 @@ url = "2" # panics there; documents still retain downloaded resources in memory. Keep the # existing disk cache on Apple targets, without changing their feature set. [target.'cfg(not(target_os = "android"))'.dependencies] -blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["cache"] } +blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["cache"] } [target.'cfg(target_os = "android")'.dependencies] -blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } +blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } # Local fixes; see the header of each vendored Cargo.toml. # Stylo (the `stylo` crates below) from the `doop` branch of kgoedecke/stylo: 0.22.0 with # `background-clip: text` and `-webkit-text-fill-color` parsed in Servo builds, and the -# `prefers-reduced-motion` media feature. +# `prefers-reduced-motion` media feature, and `TraversalFlags::DeviceChangeOnly` (a restyle for a +# new device pixel ratio starts no transitions). # anyrender from the `doop` branch of kgoedecke/anyrender: the published 0.14 / anyrender_skia # 0.12 commit plus the variable-font fix (DioxusLabs/anyrender#128). Both crates come from the # fork so that blitz-paint and the Skia backend share one `anyrender`. [patch.crates-io] anyrender = { git = "https://github.com/kgoedecke/anyrender", rev = "229216b1c86c13b8ba00eaf8d274d42f4ce91d80" } anyrender_skia = { git = "https://github.com/kgoedecke/anyrender", rev = "229216b1c86c13b8ba00eaf8d274d42f4ce91d80" } -stylo = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_traits = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_atoms = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_dom = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_static_prefs = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_derive = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_malloc_size_of = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -selectors = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -servo_arc = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -to_shmem = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -to_shmem_derive = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } +stylo = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_traits = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_atoms = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_dom = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_static_prefs = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_derive = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_malloc_size_of = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +selectors = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +servo_arc = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +to_shmem = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +to_shmem_derive = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } [features] default = ["skia"] diff --git a/ios/BlitzKit/rust/tests/rescale_transitions.rs b/ios/BlitzKit/rust/tests/rescale_transitions.rs new file mode 100644 index 000000000..ffaeff251 --- /dev/null +++ b/ios/BlitzKit/rust/tests/rescale_transitions.rs @@ -0,0 +1,83 @@ +//! The canvas paints one document at two scales, a base bitmap and a zoomed tile, +//! switching back and forth. A new scale recomputes lengths snapped to device pixels +//! (a 1px border is about 2 CSS px at 0.51 and 1 px at 5.63); that must not start CSS +//! transitions, or every `transition: all` box animates between the two widths and +//! the frame jitters, reporting itself as animating forever. +use std::ffi::CString; + +use doopblitz::*; + +const W: u32 = 400; +const H: u32 = 300; + +fn base(doc: *mut Doc, scale: f32, time: f64) { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + doopblitz_doc_set_viewport(doc, W, H, scale); + let buf = doopblitz_doc_render_at(doc, time, &mut w, &mut h, &mut len); + doopblitz_buffer_free(buf, len); +} + +/// The base bitmap at `scale` and `time`, as RGBA bytes. +fn base_pixels(doc: *mut Doc, scale: f32, time: f64) -> Vec { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + doopblitz_doc_set_viewport(doc, W, H, scale); + let buf = doopblitz_doc_render_at(doc, time, &mut w, &mut h, &mut len); + assert!(!buf.is_null()); + let pixels = unsafe { std::slice::from_raw_parts(buf, len) }.to_vec(); + doopblitz_buffer_free(buf, len); + pixels +} + +fn tile(doc: *mut Doc, scale: f32, time: f64) { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + let buf = doopblitz_doc_render_region_at(doc, time, scale, 0.0, 0.0, 200.0, 100.0, &mut w, &mut h, &mut len); + doopblitz_buffer_free(buf, len); +} + +fn open(body: &str) -> *mut Doc { + let html = CString::new(format!("{body}")).unwrap(); + let url = CString::new("https://doop.design/").unwrap(); + doopblitz_doc_new(html.as_ptr(), url.as_ptr(), W, H, 0.51) +} + +#[test] +fn switching_between_base_and_tile_scales_starts_no_transitions() { + let doc = open(r#"
Card
"#); + let mut time = 1.0; + base(doc, 0.51, time); + assert!(!doopblitz_doc_is_animating(doc), "a static page is not animating"); + for _ in 0..3 { + time += 0.05; + tile(doc, 5.63, time); + assert!(!doopblitz_doc_is_animating(doc), "a tile at a new scale started a transition"); + time += 0.05; + base(doc, 0.51, time); + assert!(!doopblitz_doc_is_animating(doc), "the base at its old scale started a transition"); + } + doopblitz_doc_free(doc); +} + +#[test] +fn keyframe_animations_keep_running_across_scale_changes() { + // Two copies of a spinning page; only `switched` has tiles painted between its + // base frames. Each base frame must show the animation moved on, and match the + // copy that never changed scale, so it neither froze nor restarted. + let page = r#"

spinning

"#; + let (switched, steady) = (open(page), open(page)); + let mut time = 1.0; + let mut previous = base_pixels(switched, 0.51, time); + assert_eq!(previous, base_pixels(steady, 0.51, time)); + assert!(doopblitz_doc_is_animating(switched)); + for _ in 0..3 { + tile(switched, 5.63, time + 0.05); + assert!(doopblitz_doc_is_animating(switched), "a scale change stopped a running animation"); + time += 0.1; + let frame = base_pixels(switched, 0.51, time); + assert!(doopblitz_doc_is_animating(switched), "a scale change stopped a running animation"); + assert_ne!(frame, previous, "the animation froze across a scale change"); + assert!(frame == base_pixels(steady, 0.51, time), "a scale change restarted or shifted the animation"); + previous = frame; + } + doopblitz_doc_free(switched); + doopblitz_doc_free(steady); +} diff --git a/ios/Doop/Blitz/BlitzCanvasView.swift b/ios/Doop/Blitz/BlitzCanvasView.swift index 8f02f54cc..cd8921739 100644 --- a/ios/Doop/Blitz/BlitzCanvasView.swift +++ b/ios/Doop/Blitz/BlitzCanvasView.swift @@ -50,7 +50,7 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { #endif private static let minZoom: CGFloat = 0.03 - private static let maxZoom: CGFloat = 4 + static let maxZoom: CGFloat = 4 init(model: CanvasModel) { self.model = model @@ -381,9 +381,17 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { zoom = max(Self.minZoom, min(1, available.width / CGFloat(maxX - minX), available.height / CGFloat(maxY - minY))) offset = CGPoint(x: viewport.midX - CGFloat(maxX + minX) * zoom / 2, y: viewport.midY - CGFloat(maxY + minY) * zoom / 2) + restOnPixels() applyTransform() } + /// Rest the camera offset on whole device pixels; with each frame layer snapped + /// at the same density, bitmaps are never resampled by a fraction of a pixel. + private func restOnPixels() { + let s = UIScreen.main.scale + offset = CGPoint(x: (offset.x * s).rounded() / s, y: (offset.y * s).rounded() / s) + } + /// Keep fitted designs clear of the right rail and bottom prompt, with room /// at the top for a title and an agent chip row stacked above it. private var unobscuredViewport: CGRect { @@ -397,9 +405,7 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { relayout?.cancel() let work = DispatchWorkItem { [weak self] in guard let self else { return } - // Rest on whole device pixels so bitmaps are never resampled by a fraction. - let s = UIScreen.main.scale - self.offset = CGPoint(x: (self.offset.x * s).rounded() / s, y: (self.offset.y * s).rounded() / s) + self.restOnPixels() self.applyTransform() self.rerenderVisible() } @@ -695,13 +701,22 @@ private final class FrameLayer { private var tilePending: (CGRect, CGFloat)? /// Bumped by `clearTile()`: a tile painted for an older request is dropped. private var tileVersion = 0 - /// Tiles cover about a screen, so density can go well past the base cap. - private static let maxTileDensity: CGFloat = 8 + /// Tiles cover about a screen, so density can go well past the base cap: up to + /// screen density at the canvas's deepest zoom, so a tile is never stretched. + private static let maxTileDensity: CGFloat = CanvasView.maxZoom * UIScreen.main.scale /// Playback repaints only the on-screen part of the frame. Steps are self-paced - /// by the paint; the density is chosen so one step stays near `playbackPixels` - /// (about 16 ms on Skia), which keeps motion smooth at any zoom. + /// by the paint. The budget is one screen of device pixels plus the step's 10% + /// margin, so a frame playing on screen paints at screen density (the static + /// tile's density): a lower playback density rounded the layout to a coarser grid + /// and blurred it, and alternating the two made the frame jump by a pixel or two. private static let animationInterval: Double = 1.0 / 60 - private static let playbackPixels: CGFloat = 550_000 + private static let playbackPixels: CGFloat = { + let screen = UIScreen.main.nativeBounds + return screen.width * screen.height * 1.25 + }() + /// When this frame last painted a playback step; a static tile stays out of its way. + private var lastPlaybackAt: CFTimeInterval = 0 + private var playing: Bool { animating && CACurrentMediaTime() - lastPlaybackAt < 0.5 } /// The last camera handed to `setLOD`, so a tile can be refreshed when playback ends. private var lastView: CGRect? private var lastLOD: CGFloat = 0 @@ -796,9 +811,7 @@ private final class FrameLayer { if newRect != rect { let resized = newRect.size != rect.size rect = newRect - CATransaction.begin(); CATransaction.setDisableActions(true) - layer.frame = rect - CATransaction.commit() + placeLayer() if resized { lastChange = CACurrentMediaTime() let size = rect.size, scale = Float(clamp(targetScale)) @@ -831,8 +844,29 @@ private final class FrameLayer { /// Local drag preview; the model is updated when the drag ends. func move(to origin: CGPoint) { rect.origin = origin + placeLayer() + } + + /// Screen pixels per CSS pixel at the last settled camera; 0 before the first. + private var pixelDensity: CGFloat = 0 + + /// Put the layer at `rect`, its origin snapped to the device-pixel grid at the + /// settled camera's density. The camera offset rests on whole device pixels too, + /// so the bitmap's pixels (and a tile's, painted at that density) land one on one + /// on screen pixels; otherwise the linear filter blurs every glyph by up to half a pixel. + /// The size is snapped too, to the whole pixels the engine rounds the bitmap to + /// (a 401 px frame at density 1.5 is a 602 px bitmap), so it is not squeezed into + /// 601.5 screen pixels; the frame's own geometry stays `rect`. + private func placeLayer() { + var frame = rect + if pixelDensity > 0 { + let snap = { (v: CGFloat) in (v * self.pixelDensity).rounded() / self.pixelDensity } + frame = CGRect(x: snap(rect.minX), y: snap(rect.minY), + width: max(1, (rect.width * pixelDensity).rounded()) / pixelDensity, + height: max(1, (rect.height * pixelDensity).rounded()) / pixelDensity) + } CATransaction.begin(); CATransaction.setDisableActions(true) - layer.frame = rect + layer.frame = frame CATransaction.commit() } @@ -842,6 +876,8 @@ private final class FrameLayer { targetScale = visible ? clamp(lod) : min(currentScale == 0 ? Self.parkedScale : currentScale, Self.parkedScale) lastView = visible ? viewportInFrame : nil lastLOD = lod + pixelDensity = lod + placeLayer() refreshTile() #if DEBUG if StressDriver.enabled, visible { @@ -889,8 +925,9 @@ private final class FrameLayer { func tickAnimation(time: Double, viewportInFrame: CGRect, lod: CGFloat) { guard animating, document != nil, !tileRendering, time - lastAnimationStep >= Self.animationInterval else { return } lastAnimationStep = time - let area = viewportInFrame.width * viewportInFrame.height * 1.21 - let density = max(0.25, min(lod, (Self.playbackPixels / max(1, area)).squareRoot())) + lastPlaybackAt = CACurrentMediaTime() + let area = viewportInFrame.width * viewportInFrame.height * 1.21 * lod * lod + let density = max(0.25, min(lod, Self.maxTileDensity, lod * (Self.playbackPixels / max(1, area)).squareRoot())) requestTile(region: tileRegion(around: viewportInFrame, margin: 0.1, density: density), density: density, time: time, force: true) } @@ -899,6 +936,9 @@ private final class FrameLayer { /// Deep zoom: the base bitmap cannot reach screen density, so paint just the /// part on screen as a tile over it, at (close to) screen density. private func refreshTile() { + // A playing frame's tile belongs to the playback loop: a static tile painted + // between its steps, at another density and an older pose, made it jump. + guard !playing else { return } if let view = lastView, lastLOD > targetScale + 0.05 { let density = min(lastLOD, Self.maxTileDensity) requestTile(region: tileRegion(around: view, margin: 0.3, density: density), density: density, time: animationTime) @@ -950,7 +990,9 @@ private final class FrameLayer { self.tileRegion = region self.tileDensity = density } - if self.animating, !stillAnimating { + // Only a playback step (painted at the current time) can tell that the + // animation ran out; a static tile is painted at an older pose. + if force, self.animating, !stillAnimating { // The animation ran out: paint the base at its final pose; that // render then refreshes or drops the tile, so nothing jumps back. self.animating = false diff --git a/ios/README.md b/ios/README.md index 6b167a168..696485c10 100644 --- a/ios/README.md +++ b/ios/README.md @@ -51,10 +51,22 @@ HTML/CSS engine (Stylo + Taffy + Parley), compiled into the app as a static libr - **Deep zoom tiles**: a base bitmap is capped at 3 bitmap pixels per CSS pixel and about two screens of pixels. When the screen density exceeds what the base bitmap holds, the part of the frame on screen (plus a 30% margin) is painted as a tile at - up to 8 bitmap pixels per CSS pixel and composited over the base, so text stays - sharp at any zoom at roughly one screen of pixels per paint. Tiles refresh when a - gesture settles and when the frame's HTML changes; a tiled frame holds its - animations still. + screen density (up to 12 bitmap pixels per CSS pixel at 400% on a 3x screen) and + composited over the base, so text stays sharp at any zoom at roughly one screen of + pixels per paint. Tiles refresh when a gesture settles and when the frame's HTML + changes; a tiled frame holds its animations still. +- **Pixel alignment**: Core Animation stretches each bitmap with a linear filter, so + a bitmap is only sharp when its pixels land on screen pixels. When the camera + settles its offset rests on whole device pixels (the first fit included) and each + frame layer's origin is snapped to the device-pixel grid at the camera's density; + a frame half a pixel off blurred every glyph (55-80% of full sharpness at most + zooms, only 100% and 200% were crisp). +- **Scale changes start no transitions**: base and tile paint one document at + different scales, and a new scale recomputes lengths snapped to device pixels (a 1px + border is about 2 CSS px at 0.5x). The Blitz and Stylo forks restyle for a scale + change with `TraversalFlags::DeviceChangeOnly`, which starts no CSS transitions; + otherwise every `transition: all` box animated between the two widths, the frame + jittered by a pixel or two and repainted forever. `rust/tests/rescale_transitions.rs`. - **SVG**: `blitz-paint` is pulled in with `default-features = false` so the bridge controls what it links; its `svg` feature must stay on, or neither inline `` elements nor SVG images (``, backgrounds) are painted at all. @@ -94,11 +106,14 @@ HTML/CSS engine (Stylo + Taffy + Parley), compiled into the app as a static libr - **CSS animations**: a frame whose document reports running animations or transitions (`doopblitz_doc_is_animating`) is played by a `CADisplayLink` while it is on screen: each step paints only the on-screen part of the frame as a tile - (`doopblitz_doc_render_region_at`) at a density chosen so one step stays near - 550k pixels, about 10-20 ms on Skia, which gives 30-40 steps a second at any - zoom. Playback pauses during gestures and for frames narrower than 100 pt, at - most two frames play at once, and when an animation ends the tile is repainted - at the density the camera wants. Base bitmaps keep the last animation pose. + (`doopblitz_doc_render_region_at`) at screen density, within a budget of one + screen of device pixels per step (about 15 ms on an iPhone 15 Pro Max). While a + frame plays, its tile is the playback tile alone: a static tile at another density + and an older pose between steps made it jump, and only a playback step decides + that the animation ended. Playback pauses during gestures and for frames narrower + than 100 pt, at most two frames play at once, and when an animation ends the tile + is repainted at the density the camera wants. Base bitmaps keep the last animation + pose. - **Element inspection**: tapping inside any frame selects it and hit tests the Blitz DOM automatically, without a separate mode. A compact, icon-only glass action bar above the prompt offers Copy, Paste, Duplicate, Delete, Comment and Export for From d9bd657dfc5f62f22298d2cf6c70adb21fb760c6 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 15 Nov 2026 22:52:33 -0800 Subject: [PATCH 04/13] fix(comments): keep an open thread above the frame size badge (#577) * fix(comments): keep an open thread above the frame size badge The selected frame's size badge is drawn in a screen-space layer after the world, so it painted over any open comment thread. An open thread is now portalled into its own screen-space layer above the badges and kept on its pin as the camera pans and zooms (as Figma's thread does), and as frames move. The badge also hides while its frame's comment composer is open. Co-Authored-By: Claude Opus 5.5 * test(comments): check an open thread paints above another frame's size badge Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit eccfaa30a4c4c913d3a0ed16b7a2c961a6ab1cec) --- src/components/CanvasComments.tsx | 2 + src/components/CommentPopovers.tsx | 73 ++++++++++++++++++++++++- src/components/FrameLabelLayer.ts | 5 ++ src/components/FrameView.tsx | 4 ++ src/components/Stage.tsx | 42 ++++++++------ tests/commentThreadStackBrowser.test.ts | 64 ++++++++++++++++++++-- 6 files changed, 165 insertions(+), 25 deletions(-) diff --git a/src/components/CanvasComments.tsx b/src/components/CanvasComments.tsx index 3749556ed..1591e52a8 100644 --- a/src/components/CanvasComments.tsx +++ b/src/components/CanvasComments.tsx @@ -101,6 +101,8 @@ export function CanvasComments({ } function onPress(e: PointerEvent) { if (rootRef.current?.contains(e.target as Node)) return + /* an open thread is portalled out of this root (CommentPin) */ + if (e.target instanceof Element && e.target.closest('[data-comment-thread-anchor]')) return close() } window.addEventListener('keydown', onKey) diff --git a/src/components/CommentPopovers.tsx b/src/components/CommentPopovers.tsx index ba5951af4..f140e221d 100644 --- a/src/components/CommentPopovers.tsx +++ b/src/components/CommentPopovers.tsx @@ -1,4 +1,5 @@ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react' +import { createPortal } from 'react-dom' import type { ElementComment } from '../../shared/types' import { colorFor } from '../../shared/types' import { DEFAULT_ROLE_NAME, mentionedRole } from '../../shared/agents' @@ -11,6 +12,7 @@ import { Textarea } from './ui/textarea' import { CheckIcon, CommentIcon, SparkIcon, SyncIcon } from './ui/icons' import { RoleMark } from './RoleMark' import { useT, type Translate } from '../lib/i18n' +import { CommentThreadLayer } from './FrameLabelLayer' /* The comment UI — pins, the composer, an open thread — is shared by the frames (element comments, FrameView) and the canvas itself (canvas @@ -29,7 +31,11 @@ export const PIN_SCALE = '[transform:translate(-50%,-50%)_scale(calc(1/var(--zoo * every frame, since this pin may sit inside a frame that clips it. On * release the thread is re-pinned to whatever is under the pointer * (src/lib/commentMove.ts); Esc puts it back. A press that moves less than - * the threshold is the click that toggles the thread. */ + * the threshold is the click that toggles the thread. + * + * Under a Stage the open thread is portalled into its screen-space layer + * (`CommentThreadLayer`), above the frames' size badges, and kept on its + * pin as the camera pans and zooms, as Figma's thread is. */ export function CommentPin({ thread, open, @@ -58,6 +64,54 @@ export function CommentPin({ const abandonPress = useRef<(() => void) | null>(null) useEffect(() => () => abandonPress.current?.(), []) const t = useT() + const threadLayer = useContext(CommentThreadLayer) + const pinRef = useRef(null) + const anchorRef = useRef(null) + const showThread = open && !dragged + useLayoutEffect(() => { + const pin = pinRef.current + const anchor = anchorRef.current + if (!showThread || !threadLayer || !pin || !anchor) return + /* the anchor is the pin's box in the layer, the thread hangs under it */ + const place = () => { + const p = pin.getBoundingClientRect() + const l = threadLayer.getBoundingClientRect() + anchor.style.left = `${p.left - l.left}px` + anchor.style.top = `${p.top - l.top}px` + anchor.style.width = `${p.width}px` + anchor.style.height = `${p.height}px` + } + place() + /* the pin's pop-in animates its transform, which drops its centring + while it runs: a thread opened mid-pop is placed again once it ends */ + let live = true + for (const a of pin.getAnimations()) void a.finished.then(() => live && place()).catch(() => {}) + let raf = 0 + const unsub = useStore.subscribe((s, prev) => { + /* a frame moved or resized (a drag, a peer's edit): measured once the + pin has been drawn where it now is */ + if (s.canvas !== prev.canvas) { + cancelAnimationFrame(raf) + raf = requestAnimationFrame(place) + } + const v = s.viewport + const u = prev.viewport + if (v === u) return + /* the pin is drawn in the world (screen = world × zoom + offset) at a + constant screen size, so its centre moves with the camera. Worked + out here rather than measured: the Stage may not have moved the + world for this camera yet */ + const cx = parseFloat(anchor.style.left) + anchor.offsetWidth / 2 + const cy = parseFloat(anchor.style.top) + anchor.offsetHeight / 2 + anchor.style.left = `${parseFloat(anchor.style.left) + ((cx - u.x) / u.zoom) * v.zoom + v.x - cx}px` + anchor.style.top = `${parseFloat(anchor.style.top) + ((cy - u.y) / u.zoom) * v.zoom + v.y - cy}px` + }) + return () => { + live = false + unsub() + cancelAnimationFrame(raf) + } + }, [showThread, threadLayer, left, top]) function onPointerDown(e: React.PointerEvent) { e.stopPropagation() @@ -134,6 +188,7 @@ export function CommentPin({ working && "after:absolute after:-inset-1.5 after:rounded-[inherit] after:border-2 after:border-current after:opacity-50 after:content-[''] after:[animation:stream-pulse_1.1s_ease-in-out_infinite]", )} + ref={pinRef} style={{ left, top, background: colorFor(root.from) }} onPointerDown={onPointerDown} onClick={() => { @@ -146,7 +201,19 @@ export function CommentPin({ title={`${root.from}: ${root.text}${thread.length > 1 ? t('stage.pinReplies', { count: thread.length - 1 }) : ''}`} > {agentItem?.failedAt ? '!' : working ? : } - {open && !dragged && children} + {showThread && + (threadLayer + ? createPortal( +
+ {children} +
, + threadLayer, + ) + : children)} ) } diff --git a/src/components/FrameLabelLayer.ts b/src/components/FrameLabelLayer.ts index c2924f9db..c6ca8d4c0 100644 --- a/src/components/FrameLabelLayer.ts +++ b/src/components/FrameLabelLayer.ts @@ -5,3 +5,8 @@ import { createContext } from 'react' * and crisp text at every zoom. Frame names are not here: they sit inside * their frame so they stack with it. Null outside a Stage. */ export const FrameLabelLayer = createContext(null) + +/** The Stage's screen-space layer an open comment thread is portalled into, + * above the size badges, so no badge covers it (CommentPin keeps it on its + * pin). Null outside a Stage, where the thread hangs off its pin. */ +export const CommentThreadLayer = createContext(null) diff --git a/src/components/FrameView.tsx b/src/components/FrameView.tsx index 827bc0277..9908e7590 100644 --- a/src/components/FrameView.tsx +++ b/src/components/FrameView.tsx @@ -1699,6 +1699,10 @@ export const FrameView = memo(function FrameView({ !shapeMoving && !editing && !pathEdit && + /* the badge's layer paints above the whole world, so it would sit + on top of this frame's composer (an open thread is in a layer + above the badges) */ + !composing && (!wantedSel || shellPicked) && createPortal(
(null) const pixelGridRef = useRef(null) const [labelLayer, setLabelLayer] = useState(null) + const [threadLayer, setThreadLayer] = useState(null) const zoomLabelRef = useRef(null) const setViewport = useStore((s) => s.setViewport) const canvas = usePageCanvas() @@ -1197,27 +1198,32 @@ export function Stage({ className="world absolute left-0 top-0 origin-top-left will-change-transform data-rezoom:**:transition-none!" ref={worldRef} > - - - - - - - - - - {showCursors && } - {drawing.preview} - {marquee && ( -
- )} + + + + + + + + + + + {showCursors && } + {drawing.preview} + {marquee && ( +
+ )} +
{/* the selected frame's size badge, in screen px (FrameLabelLayer); after the world so no frame, however it stacks, covers it */}
+ {/* an open comment thread, in screen px above the badges, so no + badge covers it; CommentPin keeps it on its pin */} +
{showRulers && }
diff --git a/tests/commentThreadStackBrowser.test.ts b/tests/commentThreadStackBrowser.test.ts index 1c818f020..31db1f0bc 100644 --- a/tests/commentThreadStackBrowser.test.ts +++ b/tests/commentThreadStackBrowser.test.ts @@ -4,8 +4,10 @@ import { findBrowserPath } from '../server/screenshot' import { fixtureUrl, pagePerTest } from './browser' import type { ElementComment, Frame } from '../shared/types' -/* An open comment thread paints above every frame on the page, also when its - own frame is not selected and a frame in front overlaps where it opens. */ +/* An open comment thread paints above every frame on the page and above any + frame's size badge, also when its own frame is not selected and a frame in + front overlaps where it opens. It stays on its pin while the camera pans and + zooms, as Figma's does. */ const frame = (id: string, x: number, createdAt: number, rotation?: number): Frame => ({ id, @@ -50,7 +52,7 @@ describe.skipIf(!findBrowserPath())('comment thread stacking', { timeout: 30_000 await page.setViewport({ width: 1200, height: 800 }) }) - async function seed(rotation?: number) { + async function seed(rotation?: number, comment: ElementComment = COMMENT) { await page.goto(fixtureUrl('rulers.html')) await page.waitForFunction(() => !!window.rulersHarness) await page.evaluate( @@ -66,7 +68,7 @@ describe.skipIf(!findBrowserPath())('comment thread stacking', { timeout: 30_000 window.rulersHarness.comments([c]) }, frames(rotation), - COMMENT, + comment, ) await page.waitForSelector('[aria-label="Canvas tools"]') await page.evaluate(() => window.rulersHarness.viewport({ x: 40, y: 40, zoom: 1 })) @@ -111,6 +113,60 @@ describe.skipIf(!findBrowserPath())('comment thread stacking', { timeout: 30_000 expect(stack[0]).toBe('popover') } + /* where the open thread sits relative to its pin */ + async function offsetFromPin() { + const pin = (await (await page.$('[title^="Tester:"]'))!.boundingBox())! + const popover = (await (await page.$('[data-comment-popover]'))!.boundingBox())! + return { x: Math.round(popover.x - pin.x), y: Math.round(popover.y - pin.y) } + } + + it('stays on its pin while the camera zooms and pans', async () => { + await seed() + await (await page.waitForSelector('[title^="Tester:"]'))!.click() + await page.waitForSelector('[data-comment-popover]') + await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished))) + const before = await offsetFromPin() + for (const viewport of [ + { x: 40, y: 40, zoom: 2.5 }, + { x: -120, y: 10, zoom: 0.4 }, + { x: 100, y: 10, zoom: 1.3 }, + ]) { + await page.evaluate((viewport) => window.rulersHarness.viewport(viewport), viewport) + expect(await offsetFromPin()).toEqual(before) + } + }) + + it("paints above another frame's size badge", async () => { + /* the pin sits by back's bottom edge, so the thread hangs over the badge + under front, which is selected */ + await seed(undefined, { ...COMMENT, x: 100, y: 285 }) + await page.evaluate(() => window.rulersHarness.select(['front'])) + const badge = (await (await page.waitForSelector('[data-frame-size]'))!.boundingBox())! + await (await page.waitForSelector('[title^="Tester:"]'))!.click() + const popover = (await (await page.waitForSelector('[data-comment-popover]'))!.boundingBox())! + await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished))) + const left = Math.max(badge.x, popover.x) + const right = Math.min(badge.x + badge.width, popover.x + popover.width) + const top = Math.max(badge.y, popover.y) + const bottom = Math.min(badge.y + badge.height, popover.y + popover.height) + expect(right > left && bottom > top).toBe(true) + const stack = await page.evaluate( + (x, y) => { + /* the badge takes no pointer events, which hit testing would skip */ + document.querySelector('[data-frame-size]')!.style.pointerEvents = 'auto' + return document + .elementsFromPoint(x, y) + .map((el) => + el.closest('[data-comment-popover]') ? 'popover' : el.closest('[data-frame-size]') ? 'badge' : null, + ) + .filter(Boolean) + }, + (left + right) / 2, + (top + bottom) / 2, + ) + expect(stack[0]).toBe('popover') + }) + it('opens above a frame in front of its own', async () => { await seed() await expectThreadOnTop() From e48ca749e118c550bb8c00a0967750e91f9bb453 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 15 Nov 2026 23:30:19 -0800 Subject: [PATCH 05/13] feat(canvas): remove the element toolbar over a picked element (#582) * feat(canvas): remove the element toolbar over a picked element Co-Authored-By: Claude Fable 5.2 * fix(canvas): keep an element link for readers in the frame menu Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 (cherry picked from commit a614f88da82f6a3b3f6abfbec7863b4e4d94be1e) --- .context/TECHSTACK.md | 5 +- src/components/ElementContextMenu.tsx | 10 ++ src/components/FrameContextMenu.tsx | 10 ++ src/components/FrameView.tsx | 225 ++++++++++---------------- src/lib/frameRuntime.ts | 2 +- src/lib/i18n/en/stage.ts | 3 - src/lib/i18n/pt-BR/stage.ts | 3 - tests/canvasClipboardBrowser.test.ts | 16 +- tests/drawingShapesBrowser.test.ts | 4 +- tests/pageCanvasBrowser.test.ts | 46 ++++-- 10 files changed, 147 insertions(+), 177 deletions(-) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index b9bbd82e1..bfa6b7d6e 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -29,7 +29,7 @@ internal selection language. - Element links use `/c/?frame=&element=` (no selector form, and no backwards compatibility for the old one). `src/lib/elementLink.ts` owns copying from the - element toolbar and Layers menu, stamping first when the element has no id; `Stage.tsx` + element menu and Layers menu, stamping first when the element has no id; `Stage.tsx` focuses its page and frame; `FrameView.tsx` resolves the id in the ready iframe, including script-created elements, re-picks the positional path so the Layers panel follows, and falls back to frame details if nothing carries the id. Browser regressions in @@ -762,8 +762,7 @@ data-doop-webfonts>` for the roster families the frame names and does not load i bounds and turned with it, so a turned layer keeps its grips and resizes along its own axes (`derotateDelta`; no guide snapping while turned). `sizable` now admits the element's own turn and still refuses a turned, skewed, 3D or nonuniformly scaled ancestor; unsupported transforms - use the axis-aligned rendered bounds for the selection outline. The element toolbar lifts to 30px above a - selection wearing furniture, clear of the top zones. Tests: `elementRotate.test.ts`, + use the axis-aligned rendered bounds for the selection outline. Tests: `elementRotate.test.ts`, `elementRotateBrowser.test.ts`, the turned cases in `elementResizeBrowser.test.ts`. - Rulers and guides (`src/components/Rulers.tsx`, math in `src/lib/rulers.ts`): ⇧R or the zoom menu toggles `` rulers docked on the stage's top and left edges (the top bar and the floating diff --git a/src/components/ElementContextMenu.tsx b/src/components/ElementContextMenu.tsx index debbadb6b..de85ac270 100644 --- a/src/components/ElementContextMenu.tsx +++ b/src/components/ElementContextMenu.tsx @@ -247,6 +247,16 @@ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementI )} + {/* an element a script made is not in the saved HTML, but one wearing + an id in the live document can still be linked */} + {selector && !exists && hit?.elementId && ( + <> + + void copyElementLink(frame, { selector, ...hit })}> + {t('stage.copyLinkToElement')} + + + )} ) } diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index a3e9f6af1..eea928ce0 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -16,6 +16,7 @@ import { MenuHint } from './ui/menu' import { FrameExportModal } from './FrameExportModal' import { FrameHistoryModal } from './FrameHistoryModal' import { trackPngCopy } from '../lib/exportEvents' +import { copyElementLink, type LinkTarget } from '../lib/elementLink' async function copyImageUrl(frame: Frame) { const notify = useStore.getState().pushNotice @@ -33,10 +34,14 @@ export function FrameContextMenu({ frame, at, onRename, + element, }: { frame: Frame at: MutableRefObject<{ x: number; y: number }> onRename?: () => void + /** the element a reader has picked in the frame: readers get this menu + * everywhere, so the element's link is offered here */ + element?: LinkTarget }) { const t = useT() const renameRequested = useRef(false) @@ -169,6 +174,11 @@ export function FrameContextMenu({ > {t('stage.copyLink')} + {element && ( + void copyElementLink(frame, element)}> + {t('stage.copyLinkToElement')} + + )} { trackPngCopy('frame', 'frame_menu') diff --git a/src/components/FrameView.tsx b/src/components/FrameView.tsx index 9908e7590..16fbe45ee 100644 --- a/src/components/FrameView.tsx +++ b/src/components/FrameView.tsx @@ -13,7 +13,6 @@ import { loadPathEdit, type PathEditSource } from '../lib/pathEditing' import { currentPageCanvas } from '../lib/pages' import { noteFrameDocument, registerFrameWindow, requestFrame, unregisterFrameWindow } from '../lib/frameBridge' import { api } from '../lib/api' -import { copyElementLink } from '../lib/elementLink' import { sendWs } from '../lib/ws' import { throttle } from '../lib/throttle' import { getIdentity } from '../lib/identity' @@ -30,7 +29,6 @@ import { ElementContextMenu, type LiveHit } from './ElementContextMenu' import { TextFormatToolbar } from './TextFormatToolbar' import type { TextFormatState } from '../lib/richText' import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from './ui/context-menu' -import { DEFAULT_ROLE_ID } from '../../shared/agents' import { posthog } from '../lib/posthog' import { isResidentLimit } from './TeamAllowance' import { CommentComposer, CommentPin, CommentThread } from './CommentPopovers' @@ -38,9 +36,8 @@ import { PixelGrid } from './PixelGrid' import { FRAME_COMMENT_SELECTOR, isElementComment, isFrameComment, elementCommentPosition } from '../../shared/comments' import { elementIdSelector } from '../../shared/elementId' import { cn } from '@/lib/utils' -import { Button } from './ui/button' import { Tooltip } from './ui/tooltip' -import { CommentIcon, EditIcon, EyeClosedIcon, GithubIcon, LockIcon, SyncIcon, SparkIcon } from './ui/icons' +import { EditIcon, EyeClosedIcon, GithubIcon, LockIcon, SyncIcon } from './ui/icons' import { isSyncedFrame } from '../lib/sync' import { isGithubFrame, isGithubPlaceholder } from '../lib/github' import { AgentIcon } from './AgentIcon' @@ -99,13 +96,10 @@ function designOffset(e: React.PointerEvent, rotation = 0): { x: nu far out, so a pin or label never dwarfs the frame it sits on). Preserve these expressions exactly. */ const COUNTER_SCALE = '[transform:scale(min(calc(1/var(--zoom,1)),2.4))]' -/* The element toolbar and the composer are not capped, like the rest of the +/* The text formatting bar and the composer are not capped, like the rest of the comment UI (CommentPopovers): screen UI the user reads and types in keeps its size at every zoom, the way Figma's comment pins do. */ const POPOVER_SCALE = '[transform:scale(calc(1/var(--zoom,1)))_translateY(calc(-100%_-_8px))]' -/* the same popover over a selection wearing its grips: it sits clear of - the rotate zones outside the top corners, which reach 25px above */ -const POPOVER_SCALE_CLEAR = '[transform:scale(calc(1/var(--zoom,1)))_translateY(calc(-100%_-_30px))]' /* screen px between a frame's name and its top edge, at every zoom */ const LABEL_GAP = 6 @@ -115,7 +109,7 @@ function badgeBottom(frame: Frame): number { const b = rotatedBounds(frame, frame.rotation ?? 0) return b.y + b.height } -/* a selected frame's outline, grips and toolbar paint above every frame on +/* a selected frame's outline, grips and popovers paint above every frame on the page (whose z-indexes are their ranks in the paint order), so a layer in front never covers the selection being worked on */ const SELECTION_CHROME_Z = 1_000_000 @@ -124,8 +118,6 @@ const EDITOR_CHIP = /* a frame narrower on screen than a chip's words keeps only its icon, so neighbouring frames' chips never run into each other */ const EDITOR_CHIP_TEXT = '@max-[180px]/title:hidden' -/* the element toolbar's buttons sit on ink and stay compact */ -const EL_TOOLBAR_BTN = 'rounded-[7px] px-2 py-1 text-xs' /** A hidden frame's place on the stage: nothing, unless it is selected — * then a dashed box with its name, so a pick from the Layers panel still @@ -214,7 +206,7 @@ interface ProbeHit { } /* what a surface click's probe is for; see `probeIntent` */ -type ProbeIntent = 'toolbar' | 'comment' | 'toggle' +type ProbeIntent = 'pick' | 'comment' | 'toggle' /* a key the frame runtime relays from its own document, over its port */ interface KeyRelay { @@ -268,6 +260,9 @@ export const FrameView = memo(function FrameView({ >('frame') const [menuProbe, setMenuProbe] = useState<{ request: number; html: string; x: number; y: number } | null>(null) const menuKind = useRef<'frame' | 'element'>('frame') + /* the element a reader had picked when they opened the frame menu, which + is the only menu they get: its link is offered there */ + const [menuElement, setMenuElement] = useState(null) const menuRequest = useRef(0) const surfaceRef = useRef(null) const elementMove = useElementMove(frame, layoutZoom) @@ -686,8 +681,8 @@ export const FrameView = memo(function FrameView({ if (only && !more.length) recordUpdate(only.frameId, only.before, only.after) else if (more.length) recordUpdates(updates) /* a click (no drag) on the frame surface targets the element under - the cursor: probe it and show the element toolbar */ - if (!moved && probeOnClick) probeAt(off.x, off.y, togglesElement ? 'toggle' : 'toolbar') + the cursor: probe it and pick it */ + if (!moved && probeOnClick) probeAt(off.x, off.y, togglesElement ? 'toggle' : 'pick') /* a moved frame carries its picked element along, so the pick (and the panel showing it) stays; a press on a layer that cannot move lands here too, and must not close the panel it was meant for. A @@ -969,10 +964,10 @@ export const FrameView = memo(function FrameView({ const [pinPos, setPinPos] = useState>({}) const probeReq = useRef(0) const probeTimer = useRef(null) - /* what the pending probe is for: the element toolbar, (Comment tool) a + /* what the pending probe is for: picking the element, (Comment tool) a composer opened straight away on the hit, or (⇧-click) adding the hit to the picked set or dropping it */ - const probeIntent = useRef('toolbar') + const probeIntent = useRef('pick') /* the design-space point the pending probe asks about */ const probePoint = useRef({ x: 0, y: 0 }) const activeSelRef = useRef(null) @@ -1050,9 +1045,6 @@ export const FrameView = memo(function FrameView({ if (!layerHover) setHover(null) } - /* composer prefill for the element toolbar */ - const [composePrefill, setComposePrefill] = useState('') - function cancelProbe() { probeReq.current += 1 if (probeTimer.current) { @@ -1065,7 +1057,6 @@ export const FrameView = memo(function FrameView({ function closeElementPopovers() { cancelProbe() setComposing(false) - setComposePrefill('') setOpenThread(null) } @@ -1083,12 +1074,11 @@ export const FrameView = memo(function FrameView({ Math.min(FRAME_NAME_COMMENT_AT, frame.height / 2), ), ) - setComposePrefill('') setComposing(true) } /* delayed slightly so the second click of a double-click (→ edit mode) - cancels it instead of flashing the toolbar; a comment click has no + cancels it instead of flashing the pick; a comment click has no double-click to wait out, so it probes at once */ /* the layers picked in this frame, which tell the runtime how deep in its groups a click lands */ @@ -1097,7 +1087,7 @@ export const FrameView = memo(function FrameView({ return s.selectedElement?.frameId === frame.id ? pickedSelectors(s) : [] } - function probeAt(x: number, y: number, intent: ProbeIntent = 'toolbar') { + function probeAt(x: number, y: number, intent: ProbeIntent = 'pick') { if (!frame.html || editing) return /* the current pick stays until the probe answers: clearing it here would close the element panel and reopen it a beat later on the next @@ -1115,7 +1105,7 @@ export const FrameView = memo(function FrameView({ '*', ) }, - intent === 'toolbar' ? 250 : 0, + intent === 'pick' ? 250 : 0, ) } @@ -1228,7 +1218,7 @@ export const FrameView = memo(function FrameView({ shell is a resize of the locked shape */ const shellLocked = useMemo(() => !!shellSel && isLayerLocked(frame, shellSel), [frame, shellSel]) /* Returning to a frame-only link (or closing the element panel) also - removes the previous element's toolbar and outline. */ + removes the previous element's outline. */ useLayoutEffect(() => { // eslint-disable-next-line react/set-state-in-effect -- queued on purpose, see above if (!wantedSel) setProbe((p) => (p?.selector === FRAME_COMMENT_SELECTOR ? p : null)) @@ -1318,13 +1308,11 @@ export const FrameView = memo(function FrameView({ return } /* a plain click on one of several picked elements leaves it alone picked */ - if (hit && probeIntent.current === 'toolbar') + if (hit && probeIntent.current === 'pick') useStore.getState().pickElement({ frameId: frame.id, selector: hit.selector }, true) setProbe(hit) - /* the Comment tool skips the element toolbar: the composer opens on - the hit, the same one the toolbar's own Comment button opens */ + /* the Comment tool opens the composer on the hit */ if (hit && probeIntent.current === 'comment') { - setComposePrefill('') setComposing(true) } } @@ -1504,7 +1492,7 @@ export const FrameView = memo(function FrameView({ /* A fast double-click can precede the delayed single-click probe. Resolve its element now so the properties panel opens in that case too. */ if (at) { - probeIntent.current = 'toolbar' + probeIntent.current = 'pick' probeReq.current += 1 iframeRef.current?.contentWindow?.postMessage( { type: 'doop:probe', reqId: probeReq.current, x: at.x, y: at.y, grouped: true, selected: pickedHere() }, @@ -1674,6 +1662,7 @@ export const FrameView = memo(function FrameView({ if (editing) exitEdit() menuKind.current = 'frame' setMenuTarget('frame') + setMenuElement(readOnly && probe && probe.selector !== FRAME_COMMENT_SELECTOR ? probe : null) setMenuProbe(null) return } @@ -1955,7 +1944,7 @@ export const FrameView = memo(function FrameView({ {(!editing || panMode || fileDragging || tool !== 'select') &&
}
{/* everything drawn over the frame rather than in it: selection ring, - element outlines, grips, comments and the element toolbar. While + element outlines, grips, comments and the text formatting bar. While the frame is selected the layer stacks above every frame, so a layer in front of this one never hides what is being worked on */}
)} - {/* element comments: pins + element toolbar + composer, all in frame - coords. The toolbar anchors to the probed element normally, and to - the actively edited element in edit mode. `data-comment-ui`: the + {/* element comments: pins + composer, and the text formatting bar + while editing, all in frame coords. They anchor to the probed + element normally, and to the actively edited element in edit mode. `data-comment-ui`: the Comment tool's cursor is forced over the whole stage except inside the comment UI, which keeps its own cursors. */} {(() => { @@ -2176,117 +2165,67 @@ export const FrameView = memo(function FrameView({ ) })} - {anchor && (editing || !multiPick) && selected && !contextMenuOpen && !elementMove.moving && ( -
e.stopPropagation()} - > - {!composing ? ( - <> - {editing && ( -
- { - posthog.capture('text_formatted', { command }) - iframeRef.current?.contentWindow?.postMessage( - { type: 'doop:text-format', command }, - '*', - ) - }} - /> -
- )} -
- - {anchor.tag} - - - - - {!editing && canEdit && anchor.text !== '' && ( - - )} + />
- - ) : ( - { - /* Keep the clicked point until the element moves. If the + ) : ( + { + /* Keep the clicked point until the element moves. If the element cannot be found in saved HTML, use a frame pin. */ - api - .addComment(frame.id, { - selector: anchor.selector, - ...(anchor.elementId ? { elementId: anchor.elementId } : {}), - snippet: anchor.snippet, - text, - x: anchor.point?.x ?? anchor.rect.x, - y: anchor.point?.y ?? anchor.rect.y, - elementOrigin: { x: anchor.rect.x, y: anchor.rect.y }, - }) - .then(() => posthog.capture('element_comment_created')) - .catch((err) => { - /* an @mention past the free tier raises the wall */ - if (isResidentLimit(err)) useStore.getState().setLimitWall(true) - else console.error(err) - }) - if (editing) setComposing(false) - else closePopovers() - }} - onCancel={() => (editing ? setComposing(false) : closePopovers())} - /> - )} -
- )} + api + .addComment(frame.id, { + selector: anchor.selector, + ...(anchor.elementId ? { elementId: anchor.elementId } : {}), + snippet: anchor.snippet, + text, + x: anchor.point?.x ?? anchor.rect.x, + y: anchor.point?.y ?? anchor.rect.y, + elementOrigin: { x: anchor.rect.x, y: anchor.rect.y }, + }) + .then(() => posthog.capture('element_comment_created')) + .catch((err) => { + /* an @mention past the free tier raises the wall */ + if (isResidentLimit(err)) useStore.getState().setLimitWall(true) + else console.error(err) + }) + if (editing) setComposing(false) + else closePopovers() + }} + onCancel={() => (editing ? setComposing(false) : closePopovers())} + /> + )} +
+ )}
) })()} @@ -2315,7 +2254,7 @@ export const FrameView = memo(function FrameView({
{menuTarget === 'frame' ? ( - + ) : (menuProbe && menuProbe.html !== frame.html) || (typeof menuTarget === 'object' && menuTarget.html !== frame.html) ? ( diff --git a/src/lib/frameRuntime.ts b/src/lib/frameRuntime.ts index 4dc813058..028f48828 100644 --- a/src/lib/frameRuntime.ts +++ b/src/lib/frameRuntime.ts @@ -292,7 +292,7 @@ export const FRAME_BOOTSTRAP = ` } /* tell the parent which element is selected for editing, so it can anchor - the element toolbar (comment etc.) to it */ + the text formatting bar to it */ function activeInfo() { return activeEl ? hitInfo(activeEl) : null } diff --git a/src/lib/i18n/en/stage.ts b/src/lib/i18n/en/stage.ts index 757978fc4..38601c8ff 100644 --- a/src/lib/i18n/en/stage.ts +++ b/src/lib/i18n/en/stage.ts @@ -45,9 +45,6 @@ export const stage = { githubImportedTip: 'Imported from a GitHub repo', isDesigning: '{name} is designing', isOnIt: '{name} is on it', - elementComment: 'Comment', - askAi: 'Ask AI', - editText: 'Edit text', textFormatting: 'Text formatting', textBold: 'Bold', textItalic: 'Italic', diff --git a/src/lib/i18n/pt-BR/stage.ts b/src/lib/i18n/pt-BR/stage.ts index 665448fdc..ef5001c95 100644 --- a/src/lib/i18n/pt-BR/stage.ts +++ b/src/lib/i18n/pt-BR/stage.ts @@ -45,9 +45,6 @@ export const stage: Catalog['stage'] = { githubImportedTip: 'Importado de um repositório do GitHub', isDesigning: '{name} está desenhando', isOnIt: '{name} está cuidando disso', - elementComment: 'Comentar', - askAi: 'Pedir à IA', - editText: 'Editar texto', textFormatting: 'Formatação de texto', textBold: 'Negrito', textItalic: 'Itálico', diff --git a/tests/canvasClipboardBrowser.test.ts b/tests/canvasClipboardBrowser.test.ts index 7f6be430e..3dff6f541 100644 --- a/tests/canvasClipboardBrowser.test.ts +++ b/tests/canvasClipboardBrowser.test.ts @@ -82,9 +82,7 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard }) } - /* the frame's name at its left end: a picked element near the frame's - top wears its toolbar over the middle of the name, clear of the rotate - zones, and a centre click would land on the toolbar */ + /* the frame's name at its left end, clear of a picked element's rotate zones */ async function clickFrameTitle(button: 'left' | 'right' = 'left') { await page.click('[data-frame-title]', { button, offset: { x: 4, y: 9 } }) } @@ -104,15 +102,13 @@ describe.skipIf(!findBrowserPath() || !CLIPBOARD_IS_RELIABLE)('canvas clipboard await page.waitForSelector('[role="menu"]', { hidden: true }) } + /* a double-click on text opens it for editing */ async function editText() { const doc = (await (await page.$('iframe[data-doop-frame]'))!.contentFrame())! - await doc.click('h1') - const edit = await page.waitForFunction(() => - [...document.querySelectorAll('button')].find((el) => el.textContent?.trim() === 'Edit text'), - ) - const button = await edit.asElement()!.toElement('button') - await button.click() - await doc.click('h1') + const inner = await doc.$eval('h1', (el) => el.getBoundingClientRect().toJSON()) + const outer = await page.$eval('iframe[data-doop-frame]', (el) => el.getBoundingClientRect().toJSON()) + const zoom = outer.width / FRAME.width + await page.mouse.click(outer.x + (inner.x + 5) * zoom, outer.y + (inner.y + 5) * zoom, { count: 2 }) await doc.waitForSelector('[contenteditable]') return doc } diff --git a/tests/drawingShapesBrowser.test.ts b/tests/drawingShapesBrowser.test.ts index e3904a6b5..0ac5658bc 100644 --- a/tests/drawingShapesBrowser.test.ts +++ b/tests/drawingShapesBrowser.test.ts @@ -152,7 +152,7 @@ describe.skipIf(!findBrowserPath())('drawing on the canvas', { timeout: 30_000 } expect(inserted[0]!.html).toContain('data-doop-drawing="circle"') expect(inserted[0]!.html).toContain('left: 55px; top: 60px; width: 40px; height: 40px;') await page.waitForFunction(() => window.drawingHarness.state().selectedElement?.frameId === 'drawn-1') - await page.waitForSelector('[data-comment-ui] button') + await page.waitForSelector('[data-rotate-handle]') // Deselect first: a shape can be grabbed directly, not only after a prior pick. await page.mouse.click(1100, 550) await drag([350, 360], [750, 360]) @@ -163,7 +163,7 @@ describe.skipIf(!findBrowserPath())('drawing on the canvas', { timeout: 30_000 } save after it, still on its way when the store already shows the move */ await expect.poll(() => saved[0]!.html).not.toContain('data-doop-drawing') await page.waitForFunction(() => window.drawingHarness.state().selectedElement?.frameId === 'drawn-2') - await page.waitForSelector('[data-comment-ui] button') + await page.waitForSelector('[data-rotate-handle]') await page.mouse.click(1100, 550) await drag([750, 360], [500, 600]) const outside = (await waitForFrames(3))[2]! diff --git a/tests/pageCanvasBrowser.test.ts b/tests/pageCanvasBrowser.test.ts index 03990bcdc..db9f05a40 100644 --- a/tests/pageCanvasBrowser.test.ts +++ b/tests/pageCanvasBrowser.test.ts @@ -79,6 +79,22 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 await page.waitForSelector('iframe[data-doop-frame]') } + /* right-click an element of the target frame and take its menu's link item */ + async function copyLinkTo(selector: string) { + const iframe = (await page.$('iframe[title="target"]'))! + const doc = (await iframe.contentFrame())! + const inner = await doc.$eval(selector, (el) => el.getBoundingClientRect().toJSON()) + const outer = await iframe.evaluate((el) => el.getBoundingClientRect().toJSON()) + const zoom = outer.width / 200 + await page.mouse.click(outer.x + (inner.x + 5) * zoom, outer.y + (inner.y + 5) * zoom, { button: 'right' }) + const item = await page.waitForFunction(() => + [...document.querySelectorAll('[role="menuitem"]')].find( + (el) => el.firstChild?.textContent === 'Copy link to element', + ), + ) + await (await item.asElement()!.toElement('div')).click() + } + it('restores pan and zoom when returning to a page', async () => { await load(canvas([frame('directory', 'first', 0), frame('target', 'second', 3000)])) const initial = await page.evaluate(() => window.pageState().viewport) @@ -155,7 +171,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 canvas([frame('original', 'first', 0), target]), `?${new URLSearchParams({ frame: target.id, element: 'h1h1h1' })}`, ) - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.waitForFunction((sel) => window.pageState().selectedElement?.selector === sel, {}, selector) expect(await page.evaluate(() => window.pageState())).toMatchObject({ activePageId: pageId, @@ -166,8 +181,8 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 viewport: { x: -2500, y: 300, zoom: 1 }, }) - // Copy through the actual element toolbar, then reopen the resulting URL. - await page.locator('button[aria-label="Copy link to element"]').click() + // Copy through the element's own menu, then reopen the resulting URL. + await copyLinkTo('h1') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const copied = await page.evaluate(() => navigator.clipboard.readText()) const url = new URL(copied) @@ -176,7 +191,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 expect(url.searchParams.get('element')).toBe('h1h1h1') expect(url.searchParams.has('selector')).toBe(false) await load(canvas([target]), url.search) - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.waitForFunction((sel) => window.pageState().selectedElement?.selector === sel, {}, selector) // Deselecting still removes the probe and its panel after a deep link. @@ -189,8 +203,8 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 const target = { ...frame('target', 'first', 0), html: '

Design

Body

' } await load(canvas([target]), '?frame=target') await page.evaluate(() => window.pickElement('target', '#hero > p:nth-of-type(1)')) - await page.waitForSelector('button[aria-label="Copy link to element"]') - await page.locator('button[aria-label="Copy link to element"]').click() + await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > p:nth-of-type(1)') + await copyLinkTo('p') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const url = new URL(await page.evaluate(() => navigator.clipboard.readText())) const elementId = url.searchParams.get('element')! @@ -203,6 +217,19 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > p:nth-of-type(1)') }) + it('lets a reader copy the link of the element they picked from the frame menu', async () => { + const target = { + ...frame('target', 'first', 0), + html: '

Design

', + } + await load({ ...canvas([target]), role: 'view' }, '?frame=target&element=h1h1h1') + await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > h1:nth-of-type(1)') + await copyLinkTo('h1') + await page.waitForFunction(() => window.pageState().notice === 'Element link copied') + const url = new URL(await page.evaluate(() => navigator.clipboard.readText())) + expect(url.searchParams.get('element')).toBe('h1h1h1') + }) + it('falls back to the frame when no element carries the linked id', async () => { await load( canvas([frame('target', 'second', 3000)]), @@ -246,7 +273,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 `, } await load(canvas([frame('original', 'first', 0), target]), '?frame=target&element=chart0') - await page.waitForSelector('button[aria-label="Copy link to element"]', { timeout: 5000 }) await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#chart') expect(await page.evaluate(() => window.pageState())).toMatchObject({ activePageId: pageId, @@ -258,12 +284,11 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 expect(await page.evaluate(() => window.pageState().notice)).toBeUndefined() /* the live element wears its id, so the link needs no stamp */ - await page.locator('button[aria-label="Copy link to element"]').click() + await copyLinkTo('#chart') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(new URL(copied).searchParams.get('element')).toBe('chart0') await load(canvas([target]), new URL(copied).search) - await page.waitForSelector('button[aria-label="Copy link to element"]', { timeout: 5000 }) await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#chart') }) @@ -282,7 +307,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 inspectorOpen: true, notice: 'This element no longer exists. Showing its frame instead.', }) - expect(await page.$('button[aria-label="Copy link to element"]')).toBeNull() }) it('follows another element link and browser history within the same mounted canvas', async () => { @@ -297,7 +321,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 window.dispatchEvent(new PopStateEvent('popstate')) }) await waitState('second link', () => window.pageState().selectedElement?.selector === '#two') - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.evaluate(() => history.back()) await waitState('back to the first link', () => window.pageState().selectedElement?.selector === '#one') await page.evaluate(() => { @@ -305,7 +328,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 window.dispatchEvent(new PopStateEvent('popstate')) }) await waitState('frame-only link', () => window.pageState().inspectorOpen && !window.pageState().selectedElement) - await page.waitForSelector('button[aria-label="Copy link to element"]', { hidden: true }) }) it('does not snap a drag to the invisible frame on another page', async () => { From 9ebfb3f9d66bcbc5fc8dcb6b58d442be76d62f39 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Tue, 17 Nov 2026 20:00:47 -0800 Subject: [PATCH 06/13] fix(home): fit the composer row and connect marks on phones (#593) The send button was pushed outside the composer at phone width and the GitHub mark in the connect bar was squeezed to a dot. Below md the model button hides the effort level (still set in its menu) and shrinks to truncate, Files is icon-only, and path-based brand marks no longer shrink. Co-authored-by: Claude Opus 5.5 (cherry picked from commit bb90742e6cd23574e09de4d139e4b5cf017917ad) --- src/components/HomeHero.tsx | 8 +++++--- src/components/ModelPicker.tsx | 5 +++-- src/components/ui/brand-mark.tsx | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/components/HomeHero.tsx b/src/components/HomeHero.tsx index 84b31291e..e8e5279fe 100644 --- a/src/components/HomeHero.tsx +++ b/src/components/HomeHero.tsx @@ -313,8 +313,10 @@ export function HomeHero({ className="gap-[7px] rounded-row text-ink-soft transition-colors hover:text-ink" onClick={actions.onImport} title={t('home.attachTitle')} + aria-label={t('home.files')} > - {t('home.files')} + {/* icon only on a phone, so the row keeps room for the model's name and the send button */} + {t('home.files')} @@ -346,10 +348,10 @@ export function HomeHero({ {/* the marks rest a little faded and desaturated; the bar's hover wakes the row, and the mark under the pointer comes fully to life and lifts */} - + diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsx index 5436a7a1a..251008730 100644 --- a/src/components/ModelPicker.tsx +++ b/src/components/ModelPicker.tsx @@ -116,7 +116,7 @@ export function ModelPicker({ disabled = false }: { disabled?: boolean }) { variant="quiet" disabled={disabled || !runners} aria-label={t('panels.modelAria', { label })} - className={cn('min-w-0 gap-[5px]')} + className={cn('min-w-0 shrink gap-[5px]')} icon={ {mark ? ( @@ -129,7 +129,8 @@ export function ModelPicker({ disabled = false }: { disabled?: boolean }) { } > {label} - {effortLabel && {effortLabel}} + {/* on a phone the composer row has no room for it; the menu still shows and sets it */} + {effortLabel && {effortLabel}} diff --git a/src/components/ui/brand-mark.tsx b/src/components/ui/brand-mark.tsx index 40ae87729..18fb82ec5 100644 --- a/src/components/ui/brand-mark.tsx +++ b/src/components/ui/brand-mark.tsx @@ -136,7 +136,7 @@ function path(d: string, defaultColor = 'currentColor') { height={size} viewBox="0 0 24 24" fill={color ?? defaultColor} - className={className} + className={cn('flex-none', className)} aria-hidden > From 66722db77f658f3ce3e169578d15e292a97c3846 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Tue, 17 Nov 2026 23:03:13 -0800 Subject: [PATCH 07/13] =?UTF-8?q?fix(layers):=20select=20several=20frames?= =?UTF-8?q?=20and=20canvas=20shapes=20with=20=E2=87=A7/=E2=8C=98-click=20(?= =?UTF-8?q?#591)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(layers): select several frames and canvas shapes with ⇧/⌘-click Top-level rows ignored the modifier keys, so two frames or two canvas shapes could not be selected together from the Layers panel. ⇧/⌘-click now adds a root row to the selection or drops it, every selected root row is highlighted, ⌫ in the tree deletes all of them, and the arrow keys find a canvas shape selected as a whole. Co-Authored-By: Claude Opus 5.5 * fix(layers): keep a shape locked on its own layer out of a ⌫ on the selection Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 6a179657449b26720729319890175db2475da399) --- .context/TECHSTACK.md | 4 ++- src/components/LayersPanel.tsx | 40 +++++++++++++++++-------- src/lib/layerEdits.ts | 3 +- tests/layersStack.test.tsx | 55 +++++++++++++++++++++++++++++++++- 4 files changed, 87 insertions(+), 15 deletions(-) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index bfa6b7d6e..3dce41ff6 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -568,7 +568,9 @@ data-doop-webfonts>` for the roster families the frame names and does not load i (`store.pickElements`), and ⌘] / ⌘[ step the picked elements, together, or the selected frame forward or backward, ⌘⌥] / ⌘⌥[ to the front or back (`reorderElements` / `reorderLayers`, `restackFrame`), one undo step each. A picked standalone shape is its page's row: Tab, ⌘A and - the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and + the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). In the Layers panel ⇧/⌘-click on a + top-level row (frame or canvas shape) adds it to the selection or drops it, as ⇧-click does on the canvas, + and ⌫ in the tree deletes every selected one. ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and something is selected, so buttons, menus and the Layers tree keep theirs. The bracket chords are read by `code` too, since ⌥ changes the typed character on macOS. Tests: `selectionKeys.test.ts`. - Canvas commands (`src/lib/actions/`): every editor command is one entry in `registry.ts` (id, diff --git a/src/components/LayersPanel.tsx b/src/components/LayersPanel.tsx index 21a95a3f2..bb2f24a6f 100644 --- a/src/components/LayersPanel.tsx +++ b/src/components/LayersPanel.tsx @@ -16,7 +16,6 @@ import { layerPlacement } from '../lib/frameBridge' import { currentPageCanvas, usePageCanvas } from '../lib/pages' import { PagesPanel, sectionHeading } from './PagesPanel' import { getIdentity } from '../lib/identity' -import { deleteFramesTracked } from '../lib/history' import { renameComponent, rootPartKey } from '../lib/components' import { ancestorsOf, @@ -29,6 +28,7 @@ import { } from '../lib/layers' import { deleteLayers, + deleteSelection, renameFrame, renameLayer, dropLayer, @@ -251,6 +251,7 @@ export function LayersPanel({ const pageCanvas = usePageCanvas() const frames = useMemo(() => pageCanvas?.frames ?? [], [pageCanvas]) const selectedId = useStore((s) => s.selectedId) + const selectedIds = useStore((s) => s.selectedIds) const selectedElement = useStore((s) => s.selectedElement) /* every row of a multi-element pick is highlighted; a string key keeps the selection identity-stable between store updates */ @@ -320,12 +321,21 @@ export function LayersPanel({ useEffect(() => { rowsRef.current = rows }, [rows]) - const currentKey = selectedElement ? rowKey(selectedElement.frameId, selectedElement.selector) : selectedId + /* a canvas shape selected as a whole is listed as its one layer's row */ + const currentKey = selectedElement + ? rowKey(selectedElement.frameId, selectedElement.selector) + : (rows.find((r) => isRoot(r) && r.frame.id === selectedId)?.key ?? selectedId) /* a layer row opens the element properties panel; a frame row closes it and leaves the frame's own inspector to the frame-name click */ function activate(row: VisibleRow, toggle = false) { const s = useStore.getState() + /* ⇧/⌘-click on a frame or a canvas shape adds it to the selection, or + drops it, as ⇧-click does on the canvas */ + if (toggle && isRoot(row)) { + s.toggleSelect(row.frame.id) + return + } /* ⇧/⌘-click adds a layer to the frame's picked set, or drops it */ if (toggle && row.kind === 'node' && s.selectedElement?.frameId === row.frame.id) { s.toggleElement({ frameId: row.frame.id, selector: row.node.selector }) @@ -531,9 +541,10 @@ export function LayersPanel({ if (e.repeat || readOnly) break /* a locked frame stays; deleteLayers refuses a locked element itself and takes a standalone element's shell frame along with its layer */ - if (row?.kind === 'frame') { - if (!row.frame.locked) deleteFramesTracked([row.frame]) - } else if (row) deleteLayers(row.frame, pickedSelectors(useStore.getState())) + /* with no layer picked, every selected frame and canvas shape goes, + as ⌫ on the canvas takes them */ + if (row && !useStore.getState().selectedElement) deleteSelection() + else if (row) deleteLayers(row.frame, pickedSelectors(useStore.getState())) break default: return @@ -659,19 +670,22 @@ export function LayersPanel({ setOpen(row.key, !row.open)} - onActivate={() => activate(row)} + onActivate={(toggle) => activate(row, toggle)} onPointerDown={(e) => onRowPointerDown(e, row)} /> ) : ( setOpen(row.key, !row.open)} @@ -826,7 +840,7 @@ function FrameRow({ dragging: boolean drop?: Drop['place'] onToggle: () => void - onActivate: () => void + onActivate: (toggle: boolean) => void onPointerDown: (e: ReactPointerEvent) => void }) { const { frame } = row @@ -865,11 +879,11 @@ function FrameRow({ onToggleHidden={readOnly ? undefined : () => setFrameHidden(frame, !frame.hidden)} locked={!!frame.locked} onToggleLocked={readOnly ? undefined : () => setFramesLocked([frame], !frame.locked)} - onClick={onActivate} + onClick={(e) => onActivate(e.shiftKey || e.metaKey || e.ctrlKey)} onDoubleClick={startRename} onContextMenu={() => { pasteAt.current = { x: window.innerWidth / 2, y: window.innerHeight / 2 } - if (!useStore.getState().selectedIds.includes(frame.id)) onActivate() + if (!useStore.getState().selectedIds.includes(frame.id)) onActivate(false) }} onPointerDown={onPointerDown} trailing={ @@ -1024,7 +1038,9 @@ function NodeRow({ }} onContextMenu={() => { pasteAt.current = { x: window.innerWidth / 2, y: window.innerHeight / 2 } - onActivate(false) + /* a right-click on a shape in a multi-selection keeps the selection */ + const s = useStore.getState() + if (!(standalone && s.selectedIds.length > 1 && s.selectedIds.includes(frame.id))) onActivate(false) }} onPointerDown={onPointerDown} /* the row under the pointer is outlined on the canvas too, as a diff --git a/src/lib/layerEdits.ts b/src/lib/layerEdits.ts index 325231ae6..9380dc6c5 100644 --- a/src/lib/layerEdits.ts +++ b/src/lib/layerEdits.ts @@ -259,7 +259,8 @@ export function deleteSelection(): boolean { else s.pickElement(null) return true } - const selected = frames.filter((f) => s.selectedIds.includes(f.id) && !f.locked) + /* a shape locked on its own layer is as locked as a locked frame */ + const selected = frames.filter((f) => s.selectedIds.includes(f.id) && !isStackLocked(f)) if (!selected.length) return false deleteFramesTracked(selected) return true diff --git a/tests/layersStack.test.tsx b/tests/layersStack.test.tsx index d5e53e138..2c8897f4b 100644 --- a/tests/layersStack.test.tsx +++ b/tests/layersStack.test.tsx @@ -9,6 +9,7 @@ const restackFrames = vi.fn((_canvasId: string, _frames: StackWrite[]) => Promis const createFrame = vi.fn((canvasId: string, input: Partial & { name: string }) => Promise.resolve({ ...frameWith('new', 9), canvasId, ...input } as Frame), ) +const deleteFrame = vi.fn((_id: string) => Promise.resolve()) vi.mock('../src/lib/api', () => ({ api: { /* the Components tab's dot asks; nothing waits in these tests */ @@ -17,7 +18,7 @@ vi.mock('../src/lib/api', () => ({ restackFrames: (canvasId: string, frames: StackWrite[]) => restackFrames(canvasId, frames), createFrame: (canvasId: string, input: Partial & { name: string }) => createFrame(canvasId, input), updateFrame: () => Promise.resolve(), - deleteFrame: () => Promise.resolve(), + deleteFrame: (id: string) => deleteFrame(id), }, ApiError: class extends Error {}, errorMessage: (_err: unknown, fallback: string) => fallback, @@ -122,6 +123,58 @@ describe('LayersPanel stacking', () => { container.remove() }) + it('adds a frame or a canvas shape to the selection with ⇧- or ⌘-click, and drops it again', () => { + const click = (key: string, init: MouseEventInit = {}) => + act(() => { + row(key).dispatchEvent(new MouseEvent('click', { bubbles: true, ...init })) + }) + const selected = () => [...useStore.getState().selectedIds].sort() + click('s1') + click('f1', { shiftKey: true }) + expect(selected()).toEqual(['f1', 's1']) + expect(row('s1').getAttribute('aria-selected')).toBe('true') + expect(row('f1').getAttribute('aria-selected')).toBe('true') + click('f2', { metaKey: true }) + expect(selected()).toEqual(['f1', 'f2', 's1']) + click('f1', { shiftKey: true }) + expect(selected()).toEqual(['f2', 's1']) + /* a plain click narrows to the one row */ + click('f2') + expect(selected()).toEqual(['f2']) + }) + + it('deletes every selected frame and shape with ⌫ in the tree', () => { + deleteFrame.mockClear() + act(() => useStore.getState().selectMany(['f1', 's1'])) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })) + }) + expect(deleteFrame.mock.calls.map(([id]) => id).sort()).toEqual(['f1', 's1']) + }) + + it('keeps a shape locked on its own layer when ⌫ deletes the selection', () => { + deleteFrame.mockClear() + const lockedShape = shape.replace('data-doop-drawing="rect"', 'data-doop-drawing="rect" data-doop-locked=""') + act(() => useStore.getState().patchFrameLocal('s1', { html: lockedShape })) + act(() => useStore.getState().selectMany(['f1', 's1'])) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })) + }) + expect(deleteFrame.mock.calls.map(([id]) => id)).toEqual(['f1']) + }) + + it('walks the rows from a canvas shape selected as a whole', () => { + act(() => useStore.getState().select('s1')) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) + }) + /* the list runs s1, f2, f1: the row under the shape is f2 */ + expect(useStore.getState().selectedIds).toEqual(['f2']) + }) + it('lists the frame in front at the top', () => { expect(stack()).toEqual(['f1', 'f2', 's1']) expect(listed()).toEqual(['s1', 'f2', 'f1']) From caed9e78c91b8bf213d66efeda7cf6b92f4d71c9 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Tue, 17 Nov 2026 23:09:12 -0800 Subject: [PATCH 08/13] feat(comments): @mention people and copy a link to a comment (#594) * feat(comments): @mention people and copy a link to a comment Typing @ in a comment, a thread reply or the Comments panel lists the canvas's people (owner, members, workspace members) and, for editors, its agents. A mentioned person is emailed at once and left out of that comment's digest. Names are resolved once against everyone eligible, with the ids the picker chose for a name several people share, and the agent matcher reads the text with people blanked out, so a person named like an agent never starts one. Agents tag people the same way through MCP and the resident. Pins and Comments panel rows get a "Copy link to comment" right-click item, and an open thread a link button; a link follows its thread to its current frame. Co-Authored-By: Claude Opus 5.5 * fix(comments): address review of mentions and comment links - send only the latest pick of a shared name, and forget picks once the draft empties, so an earlier Sam is not emailed again - an agent picked over a person named like its handle stays the agent's - every reader of the canvas's people redraws when the list arrives, so a thread's mentions highlight without waiting for another render - a comment link to a thread on another page opens the thread Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit b2fc825b7025b9e6827a827cad23533c15f75fe5) --- .context/TECHSTACK.md | 24 +++ server/actions.ts | 29 +++- server/canvasPeople.ts | 91 ++++++++++ server/commentNotifications.ts | 49 +++++- server/events.ts | 17 +- server/guide.ts | 5 +- server/index.ts | 53 ++++-- server/mcp.ts | 12 +- server/resident.ts | 33 ++-- shared/personMentions.ts | 161 ++++++++++++++++++ src/components/CanvasComments.tsx | 8 +- src/components/CommentPopovers.tsx | 225 +++++++++++++++--------- src/components/CommentsPanel.tsx | 155 ++++++++++------- src/components/FrameView.tsx | 7 +- src/components/MentionPicker.tsx | 263 +++++++++++++++++++++++++++++ src/components/Stage.tsx | 9 +- src/hooks/use-mention-people.ts | 53 ++++++ src/lib/api.ts | 22 ++- src/lib/commentLink.ts | 30 ++++ src/lib/i18n/en/stage.ts | 6 + src/lib/i18n/pt-BR/stage.ts | 6 + tests/canvasCommentsRoute.test.ts | 25 +++ tests/commentLink.test.ts | 22 +++ tests/commentNotifications.test.ts | 82 +++++++++ tests/commentsPanel.test.tsx | 113 +++++++++++++ tests/mcp-comments-write.test.ts | 17 +- tests/personMentions.test.ts | 134 +++++++++++++++ tests/residentComments.test.ts | 10 ++ 28 files changed, 1457 insertions(+), 204 deletions(-) create mode 100644 server/canvasPeople.ts create mode 100644 shared/personMentions.ts create mode 100644 src/components/MentionPicker.tsx create mode 100644 src/hooks/use-mention-people.ts create mode 100644 src/lib/commentLink.ts create mode 100644 tests/commentLink.test.ts create mode 100644 tests/personMentions.test.ts diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 3dce41ff6..eccbafd5a 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -878,6 +878,30 @@ data-doop-webfonts>` for the roster families the frame names and does not load i (`actions.handBackComment`: unclaimed, no longer an agent item in memory and in its row, the thread open), so the person's `@mention` answer queues fresh work carrying the whole conversation. MCP agents have had the same two tools all along. Tests: `residentComments.test.ts`, `agentToolParity.test.ts`. +- People in comments (`shared/personMentions.ts`, `server/canvasPeople.ts`, `src/components/MentionPicker.tsx`): + a mention is `@` plus the person's account name in the text (`@Ana Souza`, longest name first, + no case, a name ends where no letter, combining mark, digit or `_` follows). Typing `@` in the + composer, a thread reply or the Comments panel's reply lists the canvas's people (owner, + members, workspace members, from `GET /api/canvases/:id/people`, comment role, names and faces + only, asked again whenever a field mounts) and, for editors, its agents; the thread draws + mentions in brand. Names are not unique, so the picker sends the ids it picked as `mentions` + beside the text (the latest pick of a name in the draft; an agent picked over a person + named like its handle rides as `agent:`, so the agent gets it). The routes, MCP `reply_to_comment` and the resident's reply resolve the text + once (`resolveCommentMentions` → `resolvePersonMentions`) against everyone eligible (those + people plus the thread's authors) before any filtering: a name several people share reaches + only the picked ones, and nobody when none was picked. The result's `roleText` (people + blanked out) is what the agent matcher, the edit-access check and the meter read, so + `@Doop Fan` is not `@doop`; the resident strips agent mentions only outside people's + (`withoutAgentMentions`). The ids ride the `comment.created` / `comment.replied` event, and + `commentNotifications.ts` emails each at once (`mentionEmail`) and leaves them out of that + comment's digest. The author, someone who switched comment emails off, a banned account or + someone who lost access is not written to. Comment links (`src/lib/commentLink.ts`, the shape + of `server/links.ts`'s `commentLink`): "Copy link to comment" on a pin's right-click menu, an + open Comments panel row's, and the link button on a thread's first message. Opening one, + `Stage` follows the root to its current frame, not the one the link names. Tests: + `personMentions.test.ts`, `commentLink.test.ts`, the `@mentions` cases in + `commentNotifications.test.ts`, the picker cases in `commentsPanel.test.tsx`, the mention and + `/people` cases in `canvasCommentsRoute.test.ts`, the person case in `residentComments.test.ts`. - Chat in the Agents tab (`src/components/AgentChat.tsx`, `src/lib/agentChat.ts`): under Recent tasks, each composer prompt (a board card without a `kind`) and any feedback left on it is a turn, oldest first, with the agent's answer under it: waiting, working, the run's closing words, diff --git a/server/actions.ts b/server/actions.ts index 5723f9095..216989213 100644 --- a/server/actions.ts +++ b/server/actions.ts @@ -1,3 +1,4 @@ +import type { ResolvedMentions } from '../shared/personMentions.ts' import { nanoid } from 'nanoid' import { indexOfAscii, lastIndexOfAscii } from '../shared/asciiSearch.ts' import { env } from './env.ts' @@ -837,7 +838,7 @@ async function frameAnchor(frame: Frame, input: FrameAnchorInput, by: string): P export async function addElementComment( frameId: string, - input: FrameAnchorInput & { text: string }, + input: FrameAnchorInput & { text: string; mentions?: ResolvedMentions }, from: string, fromUserId?: string, ): Promise { @@ -846,7 +847,7 @@ export async function addElementComment( const anchor = await frameAnchor(frame, input, from) /* a frame deleted while its element was being stamped takes no comment */ if (!store.getFrame(frameId)) return undefined - return postComment(frame.canvasId, anchor, input.text, from, fromUserId) + return postComment(frame.canvasId, anchor, input.text, from, fromUserId, 'user', undefined, input.mentions) } /** The anchor as it is written onto a comment; what the anchor does not @@ -1010,14 +1011,23 @@ export const moveComment = atomic(async function moveComment( * between frames, or a spot where something should go. */ export function addCanvasComment( canvasId: string, - input: { pageId: string; x: number; y: number; text: string }, + input: { pageId: string; x: number; y: number; text: string; mentions?: ResolvedMentions }, from: string, fromUserId?: string, ): ElementComment | undefined { const canvas = store.getCanvas(canvasId) if (!canvas || !canvasPages(canvas).some((page) => page.id === input.pageId)) return undefined if (!Number.isFinite(input.x) || !Number.isFinite(input.y)) return undefined - return postComment(canvasId, { pageId: input.pageId, x: input.x, y: input.y }, input.text, from, fromUserId) + return postComment( + canvasId, + { pageId: input.pageId, x: input.x, y: input.y }, + input.text, + from, + fromUserId, + 'user', + undefined, + input.mentions, + ) } /** Reply inside a thread: the reply inherits the root comment's anchor (its @@ -1029,12 +1039,13 @@ export function replyToComment( from: string, fromUserId?: string, kind: ActorKind = 'user', + mentions?: ResolvedMentions, ): ElementComment | undefined { const open = openThread(commentId) if (!open) return undefined const anchor = replyAnchor(open) if (!anchor) return undefined - return postComment(open.root.canvasId, anchor, text, from, fromUserId, kind, open.root.id) + return postComment(open.root.canvasId, anchor, text, from, fromUserId, kind, open.root.id, mentions) } function replyAnchor({ root, frame }: { root: ElementComment; frame?: Frame }): CommentAnchor | undefined { @@ -1074,11 +1085,14 @@ function postComment( fromUserId?: string, kind: ActorKind = 'user', parentId?: string, + /** the people the text @mentions, read by the caller (server/canvasPeople.ts) */ + mentions?: ResolvedMentions, ): ElementComment | undefined { const clean = text.trim() if (!clean) return undefined - /* @Doop, @brand, @a11y… — whichever resident agent is mentioned picks it up */ - const mentioned = mentionedRole(clean, canvasRoster(canvasId)) + /* @Doop, @brand, @a11y… — whichever resident agent is mentioned picks it + up; a person's name (`@Brand Smith`) is not an agent's */ + const mentioned = mentionedRole(mentions?.roleText ?? clean, canvasRoster(canvasId)) const list = commentLog.get(canvasId) ?? [] /* strictly increasing per canvas: thread order is reconstructed from `at` after a restart, so two messages must never share a timestamp */ @@ -1120,6 +1134,7 @@ function postComment( comment, frame, actorKind: kind, + ...(mentions?.ids.length ? { mentions: mentions.ids } : {}), }) return comment } diff --git a/server/canvasPeople.ts b/server/canvasPeople.ts new file mode 100644 index 000000000..450861304 --- /dev/null +++ b/server/canvasPeople.ts @@ -0,0 +1,91 @@ +import { and, eq, inArray, or, isNull } from 'drizzle-orm' +import { db } from './db/index.ts' +import * as authSchema from './db/auth-schema.ts' +import { workspaceMemberIds } from './workspaces.ts' +import { avatarUrl } from '../shared/avatar.ts' +import { resolvePersonMentions, type ResolvedMentions } from '../shared/personMentions.ts' +import type { Canvas, ElementComment } from '../shared/types.ts' +import { commentThread } from './actions.ts' + +/** The people a comment on this canvas may @mention: everyone who has it for + * good (the owner, invited members, the members of its workspace). Share-link + * visitors are not listed: a link is not a membership, and their names would + * reach everyone else holding it. */ +export function mentionableIds(canvas: Canvas): string[] { + const ids = new Set() + if (canvas.ownerId) ids.add(canvas.ownerId) + for (const id of canvas.memberIds ?? []) ids.add(id) + if (canvas.workspaceId) for (const id of workspaceMemberIds(canvas.workspaceId)) ids.add(id) + return [...ids] +} + +export interface CanvasPerson { + id: string + name: string + image?: string +} + +/** Those people with their names and faces, banned accounts left out. */ +export function mentionablePeople(canvas: Canvas): Promise { + return peopleByIds(mentionableIds(canvas)) +} + +async function peopleByIds(ids: string[]): Promise { + if (!ids.length) return [] + const rows = await db + .select({ id: authSchema.user.id, name: authSchema.user.name, image: authSchema.user.image }) + .from(authSchema.user) + .where(and(inArray(authSchema.user.id, ids), or(isNull(authSchema.user.banned), eq(authSchema.user.banned, false)))) + const byId = new Map(rows.map((r) => [r.id, r])) + return ids.flatMap((id) => { + const row = byId.get(id) + if (!row) return [] + const image = avatarUrl(row.image) + return [{ id, name: row.name, ...(image ? { image } : {}) }] + }) +} + +/** Who a comment's text @mentions: the canvas's people and whoever already + * wrote in the thread (`authorIds`), each read by name against all of them + * before anything else is decided, so a name is never handed to a shorter + * one because its owner turned email off. `picked` is what the editor's + * picker chose, for a name several people share (an unknown id is ignored). + * Who is then actually told (the author, opt-outs, access) is the + * notifier's business. */ +export async function resolveCommentMentions( + canvas: Canvas, + text: string, + { authorIds = [], picked }: { authorIds?: readonly string[]; picked?: unknown } = {}, +): Promise { + if (!text.includes('@')) return { ids: [], roleText: text } + try { + const people = await peopleByIds([...new Set([...mentionableIds(canvas), ...authorIds])]) + return resolvePersonMentions(text, people, pickedIds(picked)) + } catch (err) { + /* the comment still posts; nobody is emailed about a mention */ + console.error(`[comments] could not read the people on ${canvas.id}`, err) + return { ids: [], roleText: text } + } +} + +/** Everyone a comment on this canvas may @mention, the thread's authors + * included; none when they cannot be read (nobody is then emailed). */ +export async function commentPeople(canvas: Canvas, authorIds: readonly string[] = []): Promise { + try { + return await peopleByIds([...new Set([...mentionableIds(canvas), ...authorIds])]) + } catch (err) { + console.error(`[comments] could not read the people on ${canvas.id}`, err) + return [] + } +} + +/** The accounts that already wrote in a comment's thread. */ +export function threadAuthorIds(comment: ElementComment): string[] { + return commentThread(comment).flatMap((c) => (c.fromUserId ? [c.fromUserId] : [])) +} + +/** The ids a request sent as its picks, if they are a short list of strings. */ +export function pickedIds(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((v): v is string => typeof v === 'string' && v.length > 0 && v.length <= 64).slice(0, 20) +} diff --git a/server/commentNotifications.ts b/server/commentNotifications.ts index e08081af2..cd270d330 100644 --- a/server/commentNotifications.ts +++ b/server/commentNotifications.ts @@ -24,6 +24,8 @@ import type { ActorKind, Canvas, ElementComment } from '../shared/types.ts' * message. Held mail is in memory only — a restart during the window drops * it, which is acceptable for a courtesy email and keeps this state-free. * + * Someone a comment @mentions is told at once instead (tellMentioned). + * * Requires SMTP (server/mailer.ts). Without it nothing is queued: an email * nobody receives is not worth logging on every comment. */ @@ -69,7 +71,52 @@ export function onCanvasEvent(canvasId: string, event: CanvasEvent): void { ...(event.frame ? { frameName: event.frame.name } : {}), actorKind: event.actorKind, } - for (const userId of recipientsFor(canvas, event.comment, event.actorKind)) queue(userId, canvasId, item) + /* someone the comment @mentions hears about it at once, on its own, and + not again in the digest; the author's own mention tells nobody */ + const author = event.actorKind === 'user' ? event.comment.fromUserId : undefined + const mentioned = (event.mentions ?? []).filter((id) => id !== author) + const told = new Set(mentioned) + for (const userId of recipientsFor(canvas, event.comment, event.actorKind)) + if (!told.has(userId)) queue(userId, canvasId, item) + if (mentioned.length) void tellMentioned(canvasId, item, mentioned) +} + +/** Email the people a comment @mentions (resolved when it was posted, + * server/canvasPeople.ts), each once. Someone who switched comment emails + * off, was banned or can no longer open the canvas is not written to. */ +async function tellMentioned(canvasId: string, item: PendingComment, ids: string[]) { + try { + const people = await mailableForComments(ids) + /* access is read after the lookup: it may have changed meanwhile */ + const canvas = store.getCanvas(canvasId) + if (!canvas) return + await Promise.all( + people + .filter((person) => canAccessCanvas(person.id, canvas)) + .map((person) => + sendMail(mentionEmail(person, canvas, item)).catch((err: unknown) => { + console.error(`[comments] mention email to ${person.id} failed`, err) + }), + ), + ) + } catch (err) { + console.error(`[comments] could not read the people mentioned on ${canvasId}`, err) + } +} + +/** The email for one comment that names the person. */ +export function mentionEmail( + person: Mailable, + canvas: Pick, + { comment, frameName }: PendingComment, +): { to: string; subject: string; text: string } { + const where = frameName ? `in ${quote(frameName)}` : 'on the canvas' + const text = comment.text.length > 600 ? `${comment.text.slice(0, 597)}…` : comment.text + return { + to: person.email, + subject: `${comment.from} mentioned you on ${quote(canvas.name)}`, + text: `Hi ${person.name || 'there'},\n\n${comment.from} mentioned you ${where}:\n\n ${quote(text.replace(/\n/g, '\n '))}\n\nReply in the thread:\n${commentLink(comment)}\n\n—\nYou get this because you collaborate on ${quote(canvas.name)}. Turn comment emails off under Settings → Your account: ${settingsLink('account')}\n`, + } } function queue(userId: string, canvasId: string, item: PendingComment) { diff --git a/server/events.ts b/server/events.ts index 75679a645..e4d628225 100644 --- a/server/events.ts +++ b/server/events.ts @@ -12,8 +12,21 @@ import type { Actor, ActorKind, AgentTask, ElementComment, Frame } from '../shar */ export type CanvasEvent = /* `frame` is an element comment's frame; a canvas comment has none */ - | { type: 'comment.created'; comment: ElementComment; frame: Frame | undefined; actorKind: ActorKind } - | { type: 'comment.replied'; comment: ElementComment; frame: Frame | undefined; actorKind: ActorKind } + /* `mentions`: the people the text @mentions (shared/personMentions.ts) */ + | { + type: 'comment.created' + comment: ElementComment + frame: Frame | undefined + actorKind: ActorKind + mentions?: string[] + } + | { + type: 'comment.replied' + comment: ElementComment + frame: Frame | undefined + actorKind: ActorKind + mentions?: string[] + } /** the root of a thread (or a lone reply) was resolved; `by` is a display name */ | { type: 'comment.resolved'; comment: ElementComment; frame: Frame | undefined; by: string } | { type: 'frame.created'; frame: Frame; actor: Actor } diff --git a/server/guide.ts b/server/guide.ts index b6aa4c63b..e082c4466 100644 --- a/server/guide.ts +++ b/server/guide.ts @@ -783,8 +783,9 @@ reply inherits the root's element anchor, so an @mention reaches the resident ag the same context the conversation is about. Close the thread with resolve_comment once the request is carried out; resolving an @mention thread also records the exchange in the canvas Memory. Writing is metered only when a reply @mentions a resident role, exactly -like a comment left in the browser. Reading does not claim work or resolve it; task -feedback is separate (get_feedback). +like a comment left in the browser. To tag a person, write @ and their name as a comment's +\`from\` spells it ("@Ana Souza"): they are emailed at once. Reading does not claim work or +resolve it; task feedback is separate (get_feedback). `, export: `# Exporting frames (images, PDF) diff --git a/server/index.ts b/server/index.ts index 8fb06263b..2bb90573a 100644 --- a/server/index.ts +++ b/server/index.ts @@ -69,6 +69,7 @@ import { liveActivitiesRouter, logLiveActivityRequests, startLiveActivityDeliver import { onCanvasEvent } from './events.ts' import * as imageDescriptions from './imageDescriptions.ts' import * as commentNotifications from './commentNotifications.ts' +import { mentionablePeople, resolveCommentMentions, threadAuthorIds } from './canvasPeople.ts' import { notificationsRouter } from './notifications.ts' import * as webhooks from './webhooks.ts' import { webhooksRouter } from './webhookRoutes.ts' @@ -1702,6 +1703,19 @@ app.get('/api/canvases/:id/members', async (req, res) => { ) }) +/* the people a comment may @mention (owner, members, workspace members), + names and faces only, for the comment field's picker */ +app.get('/api/canvases/:id/people', async (req, res) => { + const c = requireCanvas(req, res, req.params.id, 'comment') + if (!c) return + mentionablePeople(c) + .then((people) => res.json(people)) + .catch((err: unknown) => { + console.error(`[comments] could not list the people on ${c.id}`, err) + res.status(500).json({ error: 'could not list the people on this canvas' }) + }) +}) + app.post('/api/canvases/:id/members', async (req, res) => { const c = requireCanvas(req, res, req.params.id, 'edit') if (!c) return @@ -2855,11 +2869,16 @@ app.post('/api/frames/:id/versions/:versionId/restore', async (req, res) => { app.post('/api/frames/:id/comments', async (req, res) => { const frame = requireFrame(req, res, req.params.id, 'comment') if (!frame) return - const { selector, elementId, snippet, text, x, y, elementOrigin } = req.body ?? {} - if (refuseAgentMention(req, res, frame.canvasId, String(text ?? ''))) return + const { selector, elementId, snippet, x, y, elementOrigin } = req.body ?? {} + const text = String(req.body?.text ?? '').trim() + const canvas = store.getCanvas(frame.canvasId) + const mentions = canvas + ? await resolveCommentMentions(canvas, text, { picked: req.body?.mentions }) + : { ids: [], roleText: text } + if (refuseAgentMention(req, res, frame.canvasId, mentions.roleText)) return /* a comment that @mentions a resident agent is a new command to the team, so it's metered like a card; plain comments and replies stay free */ - if (mentionedRole(String(text ?? ''), actions.canvasRoster(frame.canvasId))) { + if (mentionedRole(mentions.roleText, actions.canvasRoster(frame.canvasId))) { const gate = await allowance.consumeResidentTask(req.user!.id) if (!gate.ok) { return res.status(403).json({ error: 'resident_limit', used: gate.used, limit: gate.limit }) @@ -2867,7 +2886,7 @@ app.post('/api/frames/:id/comments', async (req, res) => { } const comment = await actions.addElementComment( req.params.id, - { selector, elementId, snippet, text: String(text ?? ''), x, y, elementOrigin }, + { selector, elementId, snippet, text, x, y, elementOrigin, mentions }, req.user!.name, req.user!.id, ) @@ -2902,11 +2921,12 @@ app.post('/api/canvases/:id/comments', async (req, res) => { return res.status(400).json({ error: 'page not found' }) } if (!Number.isFinite(x) || !Number.isFinite(y)) return res.status(400).json({ error: 'x and y must be numbers' }) - const body = String(text ?? '') - if (!body.trim()) return res.status(400).json({ error: 'empty text' }) - if (refuseAgentMention(req, res, canvas.id, body)) return + const body = String(text ?? '').trim() + if (!body) return res.status(400).json({ error: 'empty text' }) + const mentions = await resolveCommentMentions(canvas, body, { picked: req.body?.mentions }) + if (refuseAgentMention(req, res, canvas.id, mentions.roleText)) return let gate: Awaited> | undefined - if (mentionedRole(body, actions.canvasRoster(canvas.id))) { + if (mentionedRole(mentions.roleText, actions.canvasRoster(canvas.id))) { gate = await allowance.consumeResidentTask(req.user!.id) if (!gate.ok) { return res.status(403).json({ error: 'resident_limit', used: gate.used, limit: gate.limit }) @@ -2914,7 +2934,7 @@ app.post('/api/canvases/:id/comments', async (req, res) => { } const comment = actions.addCanvasComment( canvas.id, - { pageId, x: Number(x), y: Number(y), text: body }, + { pageId, x: Number(x), y: Number(y), text: body, mentions }, req.user!.name, req.user!.id, ) @@ -2935,20 +2955,25 @@ app.post('/api/comments/:id/replies', async (req, res) => { const found = actions.findComment(req.params.id) if (!found) return res.status(404).json({ error: 'comment not found' }) if (!requireCanvas(req, res, found.canvasId, 'comment')) return - const text = String(req.body?.text ?? '') - if (!text.trim() || !actions.openThread(req.params.id)) { + const text = String(req.body?.text ?? '').trim() + const canvas = store.getCanvas(found.canvasId) + if (!text || !canvas || !actions.openThread(req.params.id)) { return res.status(404).json({ error: 'thread resolved or empty text' }) } - if (refuseAgentMention(req, res, found.canvasId, text)) return + const mentions = await resolveCommentMentions(canvas, text, { + authorIds: threadAuthorIds(found), + picked: req.body?.mentions, + }) + if (refuseAgentMention(req, res, found.canvasId, mentions.roleText)) return /* same rule as a fresh comment: only an @mention costs a resident task */ let gate: Awaited> | undefined - if (mentionedRole(text, actions.canvasRoster(found.canvasId))) { + if (mentionedRole(mentions.roleText, actions.canvasRoster(found.canvasId))) { gate = await allowance.consumeResidentTask(req.user!.id) if (!gate.ok) { return res.status(403).json({ error: 'resident_limit', used: gate.used, limit: gate.limit }) } } - const reply = actions.replyToComment(req.params.id, text, req.user!.name, req.user!.id) + const reply = actions.replyToComment(req.params.id, text, req.user!.name, req.user!.id, 'user', mentions) if (!reply) { /* the thread closed while the meter was being written: give the task back — a failed refund is logged, never turned into a 500 */ diff --git a/server/mcp.ts b/server/mcp.ts index 98d303bdd..597b91e47 100644 --- a/server/mcp.ts +++ b/server/mcp.ts @@ -85,6 +85,7 @@ import { normalizeImportUrl } from './importer.ts' import { extensions, type McpToolHelpers } from './extensions.ts' import { websiteAccessErrorMessage } from './websiteAccess.ts' import { mentionedRole } from '../shared/agents.ts' +import { resolveCommentMentions, threadAuthorIds } from './canvasPeople.ts' import * as allowance from './allowance.ts' import { embedsPreview, previewOf, previewToolMeta, registerFramePreview, type CanvasPreview } from './chatgptApp.ts' import * as persist from './db/persist.ts' @@ -1142,7 +1143,7 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st { title: 'Reply to a comment', description: - 'Reply inside an element-comment thread on a canvas. The reply inherits the root comment’s element anchor, so an @mention in it gives the resident agent the same anchor the conversation is about. Writing does not resolve the thread — read the request with get_comments, make the change, then close it with resolve_comment. If the text @mentions a resident role (e.g. "@Doop"), it counts as a new resident task against the account’s meter, exactly like a comment left in the browser.', + 'Reply inside an element-comment thread on a canvas. The reply inherits the root comment’s element anchor, so an @mention in it gives the resident agent the same anchor the conversation is about. Writing does not resolve the thread — read the request with get_comments, make the change, then close it with resolve_comment. If the text @mentions a resident role (e.g. "@Doop"), it counts as a new resident task against the account’s meter, exactly like a comment left in the browser. To tag a person, write @ and their name exactly as a comment\'s `from` spells it (e.g. "@Ana Souza"): someone the canvas is shared with, or already in the thread, is emailed at once.', annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, inputSchema: { canvas_id: z.string(), @@ -1155,10 +1156,13 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st if (!canvasFor(canvas_id, 'comment')) return noCanvas(canvas_id) const found = actions.findComment(comment_id) if (!found || found.canvasId !== canvas_id) return noComment(comment_id) - if (!body.trim() || !actions.openThread(comment_id)) return err('thread resolved or empty text') + const canvas = store.getCanvas(canvas_id) + if (!body.trim() || !canvas || !actions.openThread(comment_id)) return err('thread resolved or empty text') + /* people it tags are emailed; a person's name is never an agent's */ + const mentions = await resolveCommentMentions(canvas, body.trim(), { authorIds: threadAuthorIds(found) }) /* an @mention commands the resident agent to change frames — the REST reply route holds comment-only visitors to the same rule */ - const mentioned = mentionedRole(body, actions.canvasRoster(canvas_id)) + const mentioned = mentionedRole(mentions.roleText, actions.canvasRoster(canvas_id)) if (mentioned && !canvasFor(canvas_id, 'edit')) return err('asking an agent to change the canvas needs edit access') const actor = actorFrom(agent_name) @@ -1177,7 +1181,7 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st /* attributed to the agent, billed to the connecting user: the resident picks whose model account pays from the requester id, and without one it falls back to the canvas owner's — wrong on a shared canvas */ - const reply = actions.replyToComment(comment_id, body, actor.name, ownerId, 'agent') + const reply = actions.replyToComment(comment_id, body, actor.name, ownerId, 'agent', mentions) if (!reply) { /* the thread closed while the meter was being written: give the task back */ if (gate && ownerId) { diff --git a/server/resident.ts b/server/resident.ts index eb524d3ec..cfb0b4156 100644 --- a/server/resident.ts +++ b/server/resident.ts @@ -23,7 +23,9 @@ import { RESIDENT_TASK_LIMIT } from './allowance.ts' import * as actions from './actions.ts' import { captureFeature, captureTokenResults } from './featureEvents.ts' import { inspectFrame, renderFrame } from './screenshot.ts' -import { AGENT_ROLES, DEFAULT_ROLE_ID, roleById, roleByAgentName, roleName, withoutMentions } from '../shared/agents.ts' +import { AGENT_ROLES, DEFAULT_ROLE_ID, roleById, roleByAgentName, roleName } from '../shared/agents.ts' +import { resolvePersonMentions, withoutAgentMentions, type Mentionable } from '../shared/personMentions.ts' +import { commentPeople, threadAuthorIds } from './canvasPeople.ts' import type { AgentRole, Roster } from '../shared/agents.ts' import { runnerKey } from '../shared/agentRunner.ts' import * as imageSearch from './imageSearch.ts' @@ -1133,14 +1135,24 @@ export function replyInThread( actor: Actor, runState: Pick, awaiting = false, + /** the people it may tag (server/canvasPeople.ts commentPeople) */ + people: readonly Mentionable[] = [], ): { ok: true; reply: ElementComment } | { ok: false; error: string } { - const clean = withoutMentions(text, actions.canvasRoster(canvasId)).trim() + /* agents' @mentions become plain names; people's stay, and are emailed */ + const clean = withoutAgentMentions(text, actions.canvasRoster(canvasId), people).trim() if (!clean) return { ok: false, error: 'empty reply' } const found = actions.findComment(commentId) if (!found || found.canvasId !== canvasId) return { ok: false, error: 'no such comment on this canvas' } const open = actions.openThread(commentId) if (!open) return { ok: false, error: 'thread resolved, or its frame is gone' } - const reply = actions.replyToComment(commentId, clean, actor.name, undefined, 'agent') + const reply = actions.replyToComment( + commentId, + clean, + actor.name, + undefined, + 'agent', + resolvePersonMentions(clean, people), + ) if (!reply) return { ok: false, error: 'thread resolved meanwhile' } runState.repliedThreads.add(open.root.id) if (awaiting) runState.awaitingThreads.add(open.root.id) @@ -1497,7 +1509,7 @@ const TOOLS: Anthropic.Tool[] = [ { name: 'reply_to_comment', description: - 'Answer inside a comment thread on this canvas — the person who left the comment sees it under their pin. Use it when a request needs a decision only they can make, or deserves a word mid-task; your final message is posted into every thread you worked on automatically, so do not repeat it here. Plain prose, no @mentions. Replying does not resolve the thread.', + 'Answer inside a comment thread on this canvas — the person who left the comment sees it under their pin. Use it when a request needs a decision only they can make, or deserves a word mid-task; your final message is posted into every thread you worked on automatically, so do not repeat it here. Plain prose and no agent @mentions; to bring a person in, write @ and their name as the thread spells it ("@Ana Souza") and they are emailed. Replying does not resolve the thread.', input_schema: { type: 'object', properties: { @@ -2420,14 +2432,11 @@ async function runResidentTool( } case 'reply_to_comment': { const awaiting = (block.input as { awaiting_answer?: unknown }).awaiting_answer === true - const posted = replyInThread( - canvasId, - String(input.comment_id ?? ''), - String(input.text ?? ''), - actor, - runState, - awaiting, - ) + const commentId = String(input.comment_id ?? '') + const thread = actions.findComment(commentId) + const canvas = store.getCanvas(canvasId) + const people = canvas && thread ? await commentPeople(canvas, threadAuthorIds(thread)) : [] + const posted = replyInThread(canvasId, commentId, String(input.text ?? ''), actor, runState, awaiting, people) if (!posted.ok) return fail(posted.error) return ok( awaiting diff --git a/shared/personMentions.ts b/shared/personMentions.ts new file mode 100644 index 000000000..00cd6d6ed --- /dev/null +++ b/shared/personMentions.ts @@ -0,0 +1,161 @@ +/** + * People @mentioned in a comment. A mention is `@` and the person's name as + * their account spells it (`@Ana Souza`), matched without case, at the start + * of the text or after a space or punctuation, and ending where a letter or + * digit does not follow. The editor's picker writes exactly that, and an + * agent tags someone by writing it too, so the text is the whole record: + * nothing beside it is stored, and the server reads the mentions again from + * the text when it decides who to tell. + * + * Longer names win over a prefix of them (`@Ana Souza` over `@Ana`), and two + * mentions never share characters. Names are not unique: where several people + * share the one written, the editor sends the ids it picked alongside the text, + * and a name nobody picked among several reaches nobody rather than a guess + * (resolvePersonMentions). + */ + +import { withoutMentions, type Roster } from './agents.ts' + +export interface Mentionable { + id: string + name: string +} + +export interface MentionMatch

{ + person: P + /** index of the `@` */ + start: number + /** index just past the name */ + end: number +} + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/* what continues a name: a letter (accents written as combining marks too), + a digit or an underscore. A mention starts after anything else but an @ */ +const NAME_CHAR = '[\\p{L}\\p{M}\\p{N}_]' +const startsMention = (before: string | undefined) => !before || !new RegExp(`${NAME_CHAR}|@`, 'u').test(before) + +/** Every mention in the text, in order. */ +export function findMentions

(text: string, people: readonly P[]): MentionMatch

[] { + if (!text.includes('@')) return [] + const found: MentionMatch

[] = [] + const taken = (start: number, end: number) => found.some((m) => start < m.end && m.start < end) + const byLength = [...people].filter((p) => p.name.trim()).sort((a, b) => b.name.length - a.name.length) + for (const person of byLength) { + const pattern = new RegExp(`@${escape(person.name.trim())}(?!${NAME_CHAR})`, 'giu') + for (const m of text.matchAll(pattern)) { + const start = m.index ?? 0 + const end = start + m[0].length + if (startsMention(text[start - 1]) && !taken(start, end)) found.push({ person, start, end }) + } + } + return found.sort((a, b) => a.start - b.start) +} + +/** The people the text mentions, each once, in order of first mention. */ +export function mentionedPeople

(text: string, people: readonly P[]): P[] { + const seen = new Set() + const out: P[] = [] + for (const { person } of findMentions(text, people)) { + if (seen.has(person.id)) continue + seen.add(person.id) + out.push(person) + } + return out +} + +/** How the editor's picker marks an agent it picked among the ids it sends + * (`agent:polish`), so a person named like the agent's handle is not taken + * for it. */ +export const AGENT_PICK = 'agent:' + +export interface ResolvedMentions { + /** the people the text mentions, each once */ + ids: string[] + /** the text with every person's mention blanked out, for the agent + * matcher: `@Brand Smith` must not read as `@brand` */ + roleText: string +} + +/** Who a comment's text mentions among `people`. A name several people share + * goes to those of them in `picked` (the ids the editor's picker chose), and + * to nobody when none of them was picked. Where the picker chose an agent + * (`AGENT_PICK`) whose handle is written there, and none of the people the + * name could be, the mention is the agent's and is left in `roleText`. */ +export function resolvePersonMentions( + text: string, + people: readonly Mentionable[], + picked: readonly string[] = [], +): ResolvedMentions { + const byName = new Map() + for (const p of people) { + const key = p.name.trim().toLowerCase() + if (!key) continue + byName.set(key, [...(byName.get(key) ?? []), p]) + } + const names = [...byName.keys()].map((key) => ({ id: key, name: key })) + const agentPicks = picked.filter((p) => p.startsWith(AGENT_PICK)).map((p) => p.slice(AGENT_PICK.length).toLowerCase()) + const agentAt = (m: MentionMatch, handle: string) => + handle.length >= m.end - m.start - 1 && + text.slice(m.start + 1, m.start + 1 + handle.length).toLowerCase() === handle + const ids = new Set() + let roleText = text + for (const m of findMentions(text, names)) { + const sharing = byName.get(m.person.id) ?? [] + const pickedHere = sharing.filter((p) => picked.includes(p.id)) + if (!pickedHere.length && agentPicks.some((handle) => agentAt(m, handle))) continue + const chosen = sharing.length === 1 ? sharing : pickedHere + for (const p of chosen) ids.add(p.id) + roleText = roleText.slice(0, m.start) + ' '.repeat(m.end - m.start) + roleText.slice(m.end) + } + return { ids: [...ids], roleText } +} + +/** The text cut into plain runs and mentions, for drawing mentions apart. */ +export function mentionSegments

( + text: string, + people: readonly P[], +): ({ text: string; person?: undefined } | { text: string; person: P })[] { + const out: ({ text: string; person?: undefined } | { text: string; person: P })[] = [] + let at = 0 + for (const m of findMentions(text, people)) { + if (m.start > at) out.push({ text: text.slice(at, m.start) }) + out.push({ text: text.slice(m.start, m.end), person: m.person }) + at = m.end + } + if (at < text.length) out.push({ text: text.slice(at) }) + return out +} + +/** The `@query` being typed at the caret, if any: from an `@` where a mention + * may start (findMentions' rule), up to the caret, on one line. Names have + * spaces, so the query may too, up to a length no name reaches. */ +export function activeMentionQuery(text: string, caret: number): { start: number; query: string } | null { + const before = text.slice(0, caret) + const at = before.lastIndexOf('@') + if (at < 0) return null + if (!startsMention(before[at - 1])) return null + const query = before.slice(at + 1) + if (query.length > 40 || /[\n@]/.test(query) || /^\s/.test(query) || /\s{2}/.test(query)) return null + return { start: at, query } +} + +/** Whether a name answers a typed query: the whole name, or any of its words, + * starts with it. A trailing space counts, so `@Ana ` still leads to + * `Ana Souza` but a name just picked (`@Ana Souza `) answers nothing more. */ +export function nameMatches(name: string, query: string): boolean { + const q = query.trimStart().toLowerCase() + if (!q) return true + const n = name.toLowerCase() + return n.startsWith(q) || n.split(/\s+/).some((word) => word.startsWith(q)) +} + +/** The text with every agent @mention turned into a plain name, except inside + * a person's mention: words an agent writes about a request must not become + * a new one, but `@Brand Smith` stays a mention of Brand Smith. */ +export function withoutAgentMentions(text: string, roster: Roster, people: readonly Mentionable[]): string { + return mentionSegments(text, people) + .map((part) => (part.person ? part.text : withoutMentions(part.text, roster))) + .join('') +} diff --git a/src/components/CanvasComments.tsx b/src/components/CanvasComments.tsx index 1591e52a8..3c1f60b38 100644 --- a/src/components/CanvasComments.tsx +++ b/src/components/CanvasComments.tsx @@ -113,10 +113,10 @@ export function CanvasComments({ } }, [anyOpen, close]) - function post(text: string) { + function post(text: string, mentions: string[]) { if (!canvasId || !pageId || !composeAt) return api - .addCanvasComment(canvasId, { pageId, x: composeAt.x, y: composeAt.y, text }) + .addCanvasComment(canvasId, { pageId, x: composeAt.x, y: composeAt.y, text, mentions }) .then(() => posthog.capture('canvas_comment_created')) .catch(reportLimit) onComposeDone() @@ -146,9 +146,9 @@ export function CanvasComments({ > + onReply={(text, mentions) => api - .replyComment(c.id, text) + .replyComment(c.id, text, mentions) .then(() => posthog.capture('element_comment_replied')) .catch((err) => { /* the wall explains a hit limit; anything else surfaces diff --git a/src/components/CommentPopovers.tsx b/src/components/CommentPopovers.tsx index f140e221d..c2487834b 100644 --- a/src/components/CommentPopovers.tsx +++ b/src/components/CommentPopovers.tsx @@ -2,14 +2,18 @@ import { useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNod import { createPortal } from 'react-dom' import type { ElementComment } from '../../shared/types' import { colorFor } from '../../shared/types' -import { DEFAULT_ROLE_NAME, mentionedRole } from '../../shared/agents' +import { DEFAULT_ROLE_NAME } from '../../shared/agents' import { useRoster } from '../hooks/use-roster' import { cn } from '@/lib/utils' import { canCommentOpenCanvas, canEditOpenCanvas, useStore } from '../lib/store' import { clientToWorld, dropComment, DRAG_THRESHOLD_PX } from '../lib/commentMove' import { Button } from './ui/button' import { Textarea } from './ui/textarea' -import { CheckIcon, CommentIcon, SparkIcon, SyncIcon } from './ui/icons' +import { CheckIcon, CommentIcon, LinkIcon, SparkIcon, SyncIcon } from './ui/icons' +import { IconButton } from './ui/icon-button' +import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from './ui/context-menu' +import { MentionText, useAgentMention, useMentionPicker } from './MentionPicker' +import { copyCommentLink } from '../lib/commentLink' import { RoleMark } from './RoleMark' import { useT, type Translate } from '../lib/i18n' import { CommentThreadLayer } from './FrameLabelLayer' @@ -177,44 +181,57 @@ export function CommentPin({ } return ( -

{ - if (suppressClick.current) { - suppressClick.current = false - return - } - onToggle() - }} - title={`${root.from}: ${root.text}${thread.length > 1 ? t('stage.pinReplies', { count: thread.length - 1 }) : ''}`} - > - {agentItem?.failedAt ? '!' : working ? : } - {showThread && - (threadLayer - ? createPortal( -
- {children} -
, - threadLayer, - ) - : children)} -
+ + +
e.stopPropagation()} + onClick={() => { + if (suppressClick.current) { + suppressClick.current = false + return + } + onToggle() + }} + title={`${root.from}: ${root.text}${thread.length > 1 ? t('stage.pinReplies', { count: thread.length - 1 }) : ''}`} + > + {agentItem?.failedAt ? '!' : working ? : } + {showThread && + (threadLayer + ? createPortal( +
+ {children} +
, + threadLayer, + ) + : children)} +
+
+ + void copyCommentLink(root)}> + + {t('stage.copyCommentLink')} + + +
) } @@ -224,7 +241,8 @@ export function CommentComposer({ initialText = '', placeholder, }: { - onSubmit: (text: string) => void + /** `mentions`: the people picked from the @ list (server/canvasPeople.ts) */ + onSubmit: (text: string, mentions: string[]) => void onCancel: () => void initialText?: string placeholder?: string @@ -233,26 +251,38 @@ export function CommentComposer({ const [text, setText] = useState(initialText) const taRef = useRef(null) useEffect(() => taRef.current?.focus(), []) - const send = () => text.trim() && onSubmit(text) + const mentions = useMentionPicker({ value: text, onChange: setText, fieldRef: taRef }) + const send = () => text.trim() && onSubmit(text, mentions.picked(text)) /* @mention a resident agent to route the comment to it; without one the - comment is a note for the humans in the room */ + comment is a note for the humans in the room. Asking one takes edit. */ const roster = useRoster() - const mentioned = mentionedRole(text, roster) + const canAskAgents = useStore(canEditOpenCanvas) + const mentioned = useAgentMention(text, mentions.picked(text)) return (
-