AI-native design editor. Open-source Figma alternative.
feat(comments): add canvas comments with a comment tool and list (#981)
T3rM1nAt0-R86bd484fea46
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c1fe6d59..7119b4cf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- The editor `Tool` type from `@open-pencil/core` and `@open-pencil/vue` includes `'COMMENT'`, and `EDITOR_TOOLS` and `TOOL_SHORTCUTS` list the Comment tool on <kbd>C</kbd>, so a `Record<Tool, …>` needs a `COMMENT` entry and toolbars built on `ToolbarRoot` show it. The canvas places nothing while it is active; the app's comments layer does.- A paint's `gradientTransform` follows Figma's convention everywhere: it maps the layer's unit square onto gradient space, where a linear gradient runs from (0, 0.5) to (1, 0.5). Gradients made in OpenPencil before this release, which used the inverse, draw differently; code that builds gradients by hand should use `linearGradientTransform` and `ellipticalGradientTransform` from the new `@open-pencil/scene-graph/gradient`, which also has Figma's default transform and stops. `isGradientFill` and `GradientFillType` moved there from `@open-pencil/core/geometry`, and `linearGradientEndpoints` is removed from the canvas module.- `useStrokeControls` from `@open-pencil/vue` acts on the whole selection: `updateAlign`, `selectSide`, and `updateBorderWeight` no longer take a node, and `currentAlign()` and `borderWeight(side)` read the selection and return `MIXED` when it differs. `useEffectsControls().scrubEffect` and `commitEffect` no longer take a node. `useTypography` edits every selected text layer and adds `nodes`, `merged`, and `fontFeature`. The `panels.layersCount` message is now `panels.selectedCount`.- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.@@ -47,6 +48,7 @@### Added+- Comment on designs, as in Figma. Pick the **Comment** tool or press <kbd>C</kbd>, click the canvas, and type; the pin shows your avatar and stays on the top-level layer under it when that layer moves. Open a pin to reply, resolve, copy, or delete it. Comments take bold, italic, strikethrough, links, and numbered and bulleted lists, with Figma's shortcuts or Markdown, and Shift+Enter continues a list. While the Comment tool is active the right sidebar lists the document's threads with search, newest- or oldest-first order, and filters for resolved comments, your threads, and the current page; **View → Comments** (<kbd>⇧</kbd><kbd>C</kbd>), also in the zoom menu and a pin's right-click menu, hides pins outside the tool. Comments are saved in the document as OpenPencil plugin data, so they travel with the `.fig` file, its storage copy, and a collaboration room, comments two people add at the same time are both kept, and Figma and older versions of OpenPencil still open the file. Adding or resolving a comment marks the document as changed, but undo leaves comments alone. Scripts, the AI chat, and MCP clients can act on review feedback too: `openpencil.getComments()`, `addComment()`, and each comment's `reply()` and `resolve()` in `openpencil eval`, and the `get_comments`, `add_comment`, `reply_to_comment`, and `resolve_comment` tools.- Edit a polygon's or star's corner radius, point count, and a star's inner ratio in the properties panel, as in Figma: **Count** from 3 to 60 and **Ratio** as a percentage.- Round a rectangle's, polygon's, or star's corners on the canvas, as in Figma: while the pointer is over a selected shape at least 108 screen pixels across, a handle sits inside each corner of a rectangle and below the top point of a polygon or star, and handles on a polygon's or star's next point and a star's first inner point set its point count and inner ratio. Dragging a rectangle's handle sets every corner while they are equal and only that corner while they differ, <kbd>⌥</kbd> swaps the two, and <kbd>⇧</kbd> rounds to tens; a label beside the pointer shows the radius.- Edit several layers at once as in Figma: the properties panel gives a multi-selection a Layout section with sizes, text resizing, flow, clip content, and a Spacing field that spaces a row or column evenly; Typography for the text among it; corner radius for the layers that have one; the stroke of the layers that have strokes; and Selection colors, which lists every fill and stroke colour in the selection and its children and recolours one everywhere it is used. The panel's header reads "N selected".diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex f93c9cd82..5aae1acb4 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -216,6 +216,12 @@"label": "Design Issues","checkbox": true},+ {+ "id": "view-comments",+ "label": "Comments",+ "accelerator": "Shift+C",+ "checkbox": true+ },{"type": "separator"},diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.tsindex 43f5aef8f..f12d05168 100644--- a/packages/core/src/editor/tool-registry.ts+++ b/packages/core/src/editor/tool-registry.ts@@ -18,7 +18,8 @@ export const EDITOR_TOOLS: EditorToolDef[] = [},{ key: 'PEN', label: 'Pen', shortcut: 'P' },{ key: 'TEXT', label: 'Text', shortcut: 'T' },- { key: 'HAND', label: 'Hand', shortcut: 'H' }+ { key: 'HAND', label: 'Hand', shortcut: 'H' },+ { key: 'COMMENT', label: 'Comment', shortcut: 'C' }]export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {@@ -30,5 +31,6 @@ export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {KeyL: 'LINE',KeyT: 'TEXT',KeyP: 'PEN',- KeyH: 'HAND'+ KeyH: 'HAND',+ KeyC: 'COMMENT'}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex b92017193..9c898730c 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -42,6 +42,7 @@ export type Tool =| 'TEXT'| 'PEN'| 'HAND'+ | 'COMMENT'/** The gradient whose handles the canvas shows while its paint picker is open. */export interface GradientEdit {diff --git a/packages/core/src/openpencil-api/comments.ts b/packages/core/src/openpencil-api/comments.tsnew file mode 100644index 000000000..2ad82ed6b--- /dev/null+++ b/packages/core/src/openpencil-api/comments.ts@@ -0,0 +1,212 @@+import {+ byCreatedAt,+ commentPosition,+ commentTimestamp as now,+ createCommentReply,+ createCommentThread,+ deleteCommentThread,+ editCommentThread,+ findLiveCommentThread,+ liveReplies,+ readComments,+ replyToCommentThread,+ resolveCommentThread,+ takesPartInThread,+ writeComments,+ type CommentAuthor,+ type CommentThread,+ type SceneGraph+} from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { nodeOf, type NodeRef } from './behaviours'++/** Who scripts and agents comment as when they give no name. */+export const DEFAULT_COMMENT_AUTHOR = 'Agent'++export interface CommentFilter {+ /** true for resolved threads only, false for open ones; both when left out. */+ resolved?: boolean+ /** Only threads on this page. */+ page?: NodeRef+ /** Only threads this person started or replied to. */+ author?: string+}++export interface NewComment {+ /** Pin the comment on this layer; it follows the top-level layer it lands on. */+ node?: NodeRef+ /** The page to comment on without a layer; the current page by default. */+ page?: NodeRef+ /** Canvas position on the page, or offset from the layer's top-left corner. */+ x?: number+ y?: number+ author?: string+}++function author(name: string | undefined): CommentAuthor {+ return { name: name?.trim() || DEFAULT_COMMENT_AUTHOR }+}++function pageOf(graph: SceneGraph, nodeId: string): string {+ const page = graph.closest(nodeId, (node) => node.type === 'CANVAS')+ if (!page) throw new Error(`${graph.getNode(nodeId)?.name ?? nodeId} is not on a page`)+ return page.id+}++/**+ * A comment thread as scripts read and answer it, in the style of the Figma API: properties+ * read the thread as the document holds it now, and every change is written at once, where+ * the editor and collaborators see it.+ */+export class CommentHandle {+ constructor(+ private readonly graph: SceneGraph,+ readonly id: string+ ) {}++ private get thread(): CommentThread {+ const thread = findLiveCommentThread(readComments(this.graph), this.id)+ if (!thread) throw new Error(`Comment ${this.id} was deleted`)+ return thread+ }++ private edit(change: (thread: CommentThread) => CommentThread): this {+ const threads = readComments(this.graph)+ if (!findLiveCommentThread(threads, this.id)) throw new Error(`Comment ${this.id} was deleted`)+ writeComments(this.graph, editCommentThread(threads, this.id, now(), change))+ return this+ }++ get text(): string {+ return this.thread.text+ }++ get author(): string {+ return this.thread.author+ }++ get createdAt(): string {+ return this.thread.createdAt+ }++ get resolved(): boolean {+ return this.thread.resolved+ }++ /** The page the comment is on. */+ get page(): { id: string; name: string } {+ const { pageId, pageName } = this.thread+ return { id: pageId, name: this.graph.getNode(pageId)?.name ?? pageName ?? '' }+ }++ /** The top-level layer the comment is pinned to, while it exists. */+ get node(): { id: string; name: string } | null {+ const { nodeId } = this.thread+ const node = nodeId ? this.graph.getNode(nodeId) : undefined+ return node ? { id: node.id, name: node.name } : null+ }++ /** Where the pin is on the page's canvas. */+ get position(): Vector {+ return commentPosition(this.graph, this.thread)+ }++ get replies(): { id: string; author: string; text: string; createdAt: string }[] {+ return liveReplies(this.thread).map(({ id, author, text, createdAt }) => ({+ id,+ author,+ text,+ createdAt+ }))+ }++ /** Answer the thread, which reopens it if it was resolved. */+ reply(text: string, options: { author?: string } = {}): this {+ const body = text.trim()+ if (!body) throw new Error('A reply needs text')+ const entry = createCommentReply(author(options.author), body, now())+ return this.edit((thread) => replyToCommentThread(thread, entry))+ }++ resolve(): this {+ return this.edit((thread) => resolveCommentThread(thread, true, now()))+ }++ reopen(): this {+ return this.edit((thread) => resolveCommentThread(thread, false, now()))+ }++ /** Delete the thread and its replies for everyone. */+ remove(): void {+ this.edit(deleteCommentThread)+ }++ toJSON() {+ return {+ id: this.id,+ text: this.text,+ author: this.author,+ createdAt: this.createdAt,+ resolved: this.resolved,+ page: this.page,+ node: this.node,+ position: this.position,+ replies: this.replies+ }+ }+}++/** The document's live threads, oldest first, narrowed by `filter`. */+export function getComments(graph: SceneGraph, filter: CommentFilter = {}): CommentHandle[] {+ const pageId = filter.page === undefined ? undefined : nodeOf(graph, filter.page).id+ return readComments(graph)+ .filter(+ (thread) =>+ !thread.deleted &&+ (filter.resolved === undefined || thread.resolved === filter.resolved) &&+ (pageId === undefined || thread.pageId === pageId) &&+ (filter.author === undefined || takesPartInThread(thread, filter.author))+ )+ .sort(byCreatedAt)+ .map((thread) => new CommentHandle(graph, thread.id))+}++export function getComment(graph: SceneGraph, id: string): CommentHandle | null {+ return findLiveCommentThread(readComments(graph), id) ? new CommentHandle(graph, id) : null+}++/** Leave a comment on a layer, or at a point of a page. */+export function addComment(+ graph: SceneGraph,+ currentPageId: string,+ text: string,+ options: NewComment = {}+): CommentHandle {+ const body = text.trim()+ if (!body) throw new Error('A comment needs text')+ const dx = options.x ?? 0+ const dy = options.y ?? 0+ let pageId: string+ let at: Vector+ const node = options.node === undefined ? undefined : nodeOf(graph, options.node)+ if (node) {+ pageId = pageOf(graph, node.id)+ const abs = graph.getAbsolutePosition(node.id)+ at = { x: abs.x + dx, y: abs.y + dy }+ } else {+ pageId = options.page === undefined ? currentPageId : nodeOf(graph, options.page).id+ if (graph.getNode(pageId)?.type !== 'CANVAS') throw new Error(`${pageId} is not a page`)+ at = { x: dx, y: dy }+ }+ const thread = createCommentThread(graph, {+ pageId,+ at,+ node,+ author: author(options.author),+ text: body,+ now: now()+ })+ writeComments(graph, [...readComments(graph), thread])+ return new CommentHandle(graph, thread.id)+}diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.tsindex e2adf2a26..58bf54071 100644--- a/packages/core/src/openpencil-api/index.ts+++ b/packages/core/src/openpencil-api/index.ts@@ -14,8 +14,22 @@ import {type BehaviourHandle,type NodeRef} from './behaviours'+import {+ addComment,+ getComment,+ getComments,+ type CommentFilter,+ type CommentHandle,+ type NewComment+} from './comments'export { BehaviourHandle, type NodeRef } from './behaviours'+export {+ CommentHandle,+ DEFAULT_COMMENT_AUTHOR,+ type CommentFilter,+ type NewComment+} from './comments'/*** What OpenPencil adds to the Figma Plugin API for scripts, as the `openpencil` global next to@@ -48,4 +62,24 @@ export class OpenPencilAPI {createSlot(frame: NodeRef): string {return makeSlot(this.figma.graph, frame)}++ /**+ * The document's comment threads, oldest first: all of them, or only resolved or open ones,+ * one page's, or those a person started or replied to, such as `{ resolved: false }`.+ */+ getComments(filter?: CommentFilter): CommentHandle[] {+ return getComments(this.figma.graph, filter)+ }++ getComment(id: string): CommentHandle | null {+ return getComment(this.figma.graph, id)+ }++ /**+ * Leave a comment pinned on a layer, `{ node }`, which it then follows, or at a point of a+ * page, `{ page, x, y }`; the current page by default. `author` names who wrote it.+ */+ addComment(text: string, options?: NewComment): CommentHandle {+ return addComment(this.figma.graph, this.figma.currentPageId, text, options)+ }}diff --git a/packages/core/src/tools/comments.ts b/packages/core/src/tools/comments.tsnew file mode 100644index 000000000..8a925bd98--- /dev/null+++ b/packages/core/src/tools/comments.ts@@ -0,0 +1,117 @@+import * as v from 'valibot'++import { DEFAULT_COMMENT_AUTHOR, OpenPencilAPI } from '#core/openpencil-api'+import { defineTool, toolFailure } from '#core/tools/schema'++const author = v.optional(+ v.pipe(+ v.string(),+ v.description(+ `Name shown as the author, such as your agent's name; "${DEFAULT_COMMENT_AUTHOR}" if omitted`+ )+ )+)++export const getComments = defineTool({+ name: 'get_comments',+ description:+ 'Read the comments people left on the canvas, oldest first: each thread with its text, ' ++ 'author, page, the layer it is pinned to, its position, replies, and whether it is ' ++ 'resolved. Open threads only unless includeResolved is set. Use it to find review ' ++ 'feedback to act on, then reply_to_comment and resolve_comment.',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.strictObject({+ includeResolved: v.optional(v.pipe(v.boolean(), v.description('Also list resolved threads'))),+ page: v.optional(v.pipe(v.string(), v.description('Only threads on this page ID'))),+ author: v.optional(+ v.pipe(v.string(), v.description('Only threads this person started or replied to'))+ )+ }),+ execute: (figma, { includeResolved, page, author }) => {+ try {+ const comments = new OpenPencilAPI(figma).getComments({+ resolved: includeResolved ? undefined : false,+ page,+ author+ })+ return { comments: comments.map((comment) => comment.toJSON()) }+ } catch (error) {+ return toolFailure(error)+ }+ }+})++export const addComment = defineTool({+ name: 'add_comment',+ description:+ 'Leave a comment on the canvas, as a person does with the Comment tool: pinned on a layer ' ++ 'by ID, which it then follows, or at x, y on a page. Text may use Markdown: **bold**, ' ++ '*italic*, ~~strikethrough~~, [links](https://…), and - or 1. lists.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.strictObject({+ text: v.pipe(v.string(), v.minLength(1), v.description('The comment, in Markdown')),+ node: v.optional(v.pipe(v.string(), v.description('Layer ID to pin the comment on'))),+ page: v.optional(+ v.pipe(v.string(), v.description('Page ID without a layer; the current page if omitted'))+ ),+ x: v.optional(+ v.pipe(v.number(), v.description('Canvas X, or offset from the layer’s left edge'))+ ),+ y: v.optional(+ v.pipe(v.number(), v.description('Canvas Y, or offset from the layer’s top edge'))+ ),+ author+ }),+ execute: (figma, { text, ...options }) => {+ try {+ return new OpenPencilAPI(figma).addComment(text, options).toJSON()+ } catch (error) {+ return toolFailure(error)+ }+ }+})++export const replyToComment = defineTool({+ name: 'reply_to_comment',+ description:+ 'Answer a comment thread by ID from get_comments, for example to say what you changed. A ' ++ 'reply reopens a resolved thread. Text may use Markdown, as in add_comment.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.strictObject({+ id: v.pipe(v.string(), v.description('Comment thread ID')),+ text: v.pipe(v.string(), v.minLength(1), v.description('The reply, in Markdown')),+ author+ }),+ execute: (figma, { id, text, author }) => {+ try {+ const comment = new OpenPencilAPI(figma).getComment(id)+ if (!comment) return { error: `No comment ${id}` }+ return comment.reply(text, { author }).toJSON()+ } catch (error) {+ return toolFailure(error)+ }+ }+})++export const resolveComment = defineTool({+ name: 'resolve_comment',+ description:+ 'Mark a comment thread by ID as resolved once its feedback is addressed, which hides it ' ++ 'from the canvas and the open list; pass resolved: false to reopen it.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.strictObject({+ id: v.pipe(v.string(), v.description('Comment thread ID')),+ resolved: v.optional(+ v.pipe(v.boolean(), v.description('false reopens the thread; true by default'))+ )+ }),+ execute: (figma, { id, resolved = true }) => {+ try {+ const comment = new OpenPencilAPI(figma).getComment(id)+ if (!comment) return { error: `No comment ${id}` }+ return (resolved ? comment.resolve() : comment.reopen()).toJSON()+ } catch (error) {+ return toolFailure(error)+ }+ }+})diff --git a/packages/core/src/tools/create/behaviours.ts b/packages/core/src/tools/create/behaviours.tsindex 536c2b201..7986fca51 100644--- a/packages/core/src/tools/create/behaviours.ts+++ b/packages/core/src/tools/create/behaviours.ts@@ -3,11 +3,7 @@ import * as v from 'valibot'import { behaviourSpecSchema } from '@open-pencil/scene-graph'import { OpenPencilAPI } from '#core/openpencil-api'-import { defineTool } from '#core/tools/schema'--const failure = (error: unknown) => ({- error: error instanceof Error ? error.message : String(error)-})+import { defineTool, toolFailure } from '#core/tools/schema'export const setBehaviour = defineTool({name: 'set_behaviour',@@ -36,7 +32,7 @@ export const setBehaviour = defineTool({openpencil.getBehaviour(id)?.remove()return { ok: true }} catch (error) {- return failure(error)+ return toolFailure(error)}}})@@ -54,7 +50,7 @@ export const createSlot = defineTool({try {return { slot: new OpenPencilAPI(figma).createSlot(id) }} catch (error) {- return failure(error)+ return toolFailure(error)}}})@@ -75,7 +71,7 @@ export const getBehaviour = defineTool({try {return openpencil.getBehaviour(id)?.toJSON() ?? { behaviour: null }} catch (error) {- return failure(error)+ return toolFailure(error)}}})diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex a55e62d56..094ee686f 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -10,6 +10,7 @@ import {lintFix} from './analyze'import { designToComponentMap, designToTokens, importDesignTokens } from './codegen'+import { addComment, getComments, replyToComment, resolveComment } from './comments'import {createComponent,createInstance,@@ -121,6 +122,10 @@ export const EXTENDED_TOOLS: ToolDef[] = [insertLibraryComponent,switchPage,pageBounds,+ getComments,+ addComment,+ replyToComment,+ resolveComment,getFontStatus,listFonts,listAvailableFonts,diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.tsindex 6c8cbfc90..1d0c5ef03 100644--- a/packages/core/src/tools/schema.ts+++ b/packages/core/src/tools/schema.ts@@ -120,6 +120,11 @@ export function requireNodes(figma: FigmaAPI, ids: ReadonlyArray<string>): Figmareturn nodes}+/** A tool's answer when the operation it wraps throws: the error's message for the caller. */+export function toolFailure(error: unknown): { error: string } {+ return { error: error instanceof Error ? error.message : String(error) }+}+export function nodeNotFound(id: string): { error: string } {return { error: `Node "${id}" not found` }}diff --git a/packages/core/tests/openpencil-api/comments.test.ts b/packages/core/tests/openpencil-api/comments.test.tsnew file mode 100644index 000000000..165dc69ff--- /dev/null+++ b/packages/core/tests/openpencil-api/comments.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compileScript } from '@open-pencil/core/tools'+import { readComments, SceneGraph } from '@open-pencil/scene-graph'++/** A document with a Card frame holding a Title, as a script would build it. */+async function document() {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ await compileScript(`+ const card = figma.createFrame()+ card.name = 'Card'+ card.x = 100+ card.y = 50+ card.resize(200, 120)+ const title = figma.createText()+ title.name = 'Title'+ card.appendChild(title)+ `)(figma)+ const named = (name: string) => {+ const node = [...graph.getAllNodes()].find((entry) => entry.name === name)+ if (!node) throw new Error(`No ${name}`)+ return node+ }+ return { graph, figma, card: named('Card'), title: named('Title') }+}++describe('openpencil comments', () => {+ test('a script comments on a layer, which pins it to the top-level frame', async () => {+ const { graph, figma, card, title } = await document()+ const comment = await compileScript(`+ return openpencil.addComment('Make the **title** bigger', {+ node: ${JSON.stringify(title.id)},+ x: 4,+ author: 'Reviewer'+ }).toJSON()+ `)(figma)++ expect(comment).toMatchObject({+ text: 'Make the **title** bigger',+ author: 'Reviewer',+ resolved: false,+ node: { id: card.id, name: 'Card' },+ replies: []+ })+ expect(readComments(graph)).toHaveLength(1)+ })++ test('an agent finds open feedback, answers it and resolves it', async () => {+ const { figma, title } = await document()+ await compileScript(`+ openpencil.addComment('Too small', { node: ${JSON.stringify(title.id)}, author: 'Dana' })+ openpencil.addComment('Already fixed', { x: 10, y: 10, author: 'Dana' }).resolve()+ `)(figma)++ const result = await compileScript(`+ const open = openpencil.getComments({ resolved: false })+ for (const comment of open) comment.reply('Bumped it to 24px', { author: 'Claude' }).resolve()+ return {+ open: open.length,+ stillOpen: openpencil.getComments({ resolved: false }).length,+ claude: openpencil.getComments({ author: 'Claude' }).map((comment) => comment.replies)+ }+ `)(figma)++ expect(result).toEqual({+ open: 1,+ stillOpen: 0,+ claude: [[expect.objectContaining({ author: 'Claude', text: 'Bumped it to 24px' })]]+ })+ })++ test('comments survive saving the .fig file and opening it again', async () => {+ await initCodec()+ const { graph, figma } = await document()+ await compileScript(`+ const comment = openpencil.addComment('Check spacing', { x: 5, y: 6 })+ comment.reply('Done').resolve()+ openpencil.addComment('Gone').remove()+ `)(figma)++ const reopened = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ expect(readComments(reopened)).toEqual(readComments(graph))+ expect(readComments(reopened).filter((thread) => !thread.deleted)).toHaveLength(1)+ })++ test('changing a deleted comment names it instead of writing it back', async () => {+ const { figma } = await document()+ const run = compileScript(`+ const comment = openpencil.addComment('Gone')+ comment.remove()+ comment.resolve()+ `)+ await expect(run(figma)).rejects.toThrow('was deleted')+ })+})diff --git a/packages/core/tests/tools/comments.test.ts b/packages/core/tests/tools/comments.test.tsnew file mode 100644index 000000000..1a6a56508--- /dev/null+++ b/packages/core/tests/tools/comments.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++import { addComment, getComments, replyToComment, resolveComment } from '#core/tools/comments'++interface Listed {+ comments: { id: string; resolved: boolean; replies: { author: string }[] }[]+}++function isListed(value: unknown): value is Listed {+ return typeof value === 'object' && value !== null && 'comments' in value+}++async function list(figma: FigmaAPI, includeResolved?: boolean): Promise<Listed['comments']> {+ const result = await getComments.execute(figma, { includeResolved })+ if (!isListed(result)) throw new Error(`Unexpected result: ${JSON.stringify(result)}`)+ return result.comments+}++describe('comment tools', () => {+ test('agents read open comments, reply, and resolve them', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ await addComment.execute(figma, { text: 'Align the button', x: 20, y: 30, author: 'Dana' })+ const [comment] = await list(figma)+ if (!comment) throw new Error('No comment listed')++ await replyToComment.execute(figma, { id: comment.id, text: 'Aligned to the card edge' })+ await resolveComment.execute(figma, { id: comment.id })++ expect(await list(figma)).toEqual([])+ const [resolved] = await list(figma, true)+ expect(resolved).toMatchObject({ id: comment.id, resolved: true, replies: [{ author: 'Agent' }] })+ })++ test('an unknown comment is reported, not created', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ expect(await resolveComment.execute(figma, { id: 'c_missing' })).toEqual({+ error: 'No comment c_missing'+ })+ expect(await list(figma, true)).toEqual([])+ })+})diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex d5ffcf76a..516382dca 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -110,6 +110,21 @@ openpencil eval design.fig -w -c 'Names the component does not have fail with an error that lists the ones it has.+Comments people leave with the Comment tool are part of the document, so scripts and agents can read the feedback on a file, act on it, and answer:++```sh+openpencil eval design.fig -w -c '+ for (const comment of openpencil.getComments({ resolved: false })) {+ console.log(comment.author, comment.node?.name, comment.text)+ comment.reply("Bumped the title to 24px", { author: "Claude" }).resolve()+ }+'+```++- `openpencil.getComments(filter)` lists threads oldest first: all of them, or `{ resolved: false }` for open ones, `{ page }` for one page's, `{ author }` for those a person started or replied to.+- `openpencil.addComment(text, { node, page, x, y, author })` pins a comment on a layer, which it follows, or at a point of a page; the current page by default. `author` is `"Agent"` when left out.+- A comment has `id`, `text` (Markdown), `author`, `createdAt`, `resolved`, `page`, `node` (the top-level layer it is pinned to), `position`, and `replies`, and `reply(text, { author })`, `resolve()`, `reopen()`, and `remove()`. `openpencil.getComment(id)` finds one.+## Supported API surfaceThe API is intentionally close to Figma's Plugin API, but it maps to OpenPencil's scene graph and file format.diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 1c8e9fa83..ec88ae7bc 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -351,6 +351,15 @@ Settings tools never expose credentials, AI models, MCP connections, storage, or| `diff_apply` | Apply a patch after checking the nodes still match its old values || `diff_visual` | Pixel diff between two rendered nodes, returned as an image |+### Comments++| Tool | Description |+|------|-------------|+| `get_comments` | Read the comments left on the canvas, open ones unless asked for resolved too, with their layer, page, and replies |+| `add_comment` | Pin a comment on a layer or at a point of a page, in Markdown |+| `reply_to_comment` | Answer a thread, which reopens it if it was resolved |+| `resolve_comment` | Resolve a thread once its feedback is addressed, or reopen it |+### Navigation| Tool | Description |diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.mdindex 16ad09752..fc6c7eb7a 100644--- a/packages/docs/reference/keyboard-shortcuts.md+++ b/packages/docs/reference/keyboard-shortcuts.md@@ -29,7 +29,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.| <kbd>P</kbd> | Pen | ✅ || <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 || <kbd>T</kbd> | Text | ✅ |-| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>C</kbd> | Comment | ✅ || <kbd>I</kbd> | Eyedropper | 🔲 |## File@@ -69,6 +69,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 || <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 || <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⇧</kbd><kbd>C</kbd> | Show/Hide Comments | ✅ || <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | ✅ || <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> | Preview controls | ✅ || <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |diff --git a/packages/scene-graph/src/comments/document.ts b/packages/scene-graph/src/comments/document.tsnew file mode 100644index 000000000..df1ef91ef--- /dev/null+++ b/packages/scene-graph/src/comments/document.ts@@ -0,0 +1,32 @@+import type { SceneGraph } from '../index'+import { readPluginData, withPluginData } from '../plugin-data/field'+import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'+import type { CommentThread } from '../types'++const { comments } = OPEN_PENCIL_PLUGIN_DATA++/**+ * A document's comment threads, deleted ones included. Comments are part of the document: they+ * live in OpenPencil's plugin data on the document node, so they travel with the `.fig` file,+ * its storage copy and a collaboration room, and Figma or an older OpenPencil open the file as+ * before.+ */+export function readComments(graph: SceneGraph): CommentThread[] {+ return readPluginData(graph.getNode(graph.rootId)?.pluginData, comments) ?? []+}++/**+ * Stores the threads on the document node. This is a document change, so the document asks to+ * be saved, but not an undo step: undoing a layer edit never takes back a comment.+ */+export function writeComments(graph: SceneGraph, threads: readonly CommentThread[]): void {+ const root = graph.getNode(graph.rootId)+ if (!root) return+ graph.updateNode(root.id, {+ pluginData: withPluginData(+ root.pluginData,+ comments,+ threads.length > 0 ? [...threads] : undefined+ )+ })+}diff --git a/packages/scene-graph/src/comments/list.ts b/packages/scene-graph/src/comments/list.tsnew file mode 100644index 000000000..169927106--- /dev/null+++ b/packages/scene-graph/src/comments/list.ts@@ -0,0 +1,52 @@+import type { CommentThread } from '../types'+import { byCreatedAt, liveReplies, takesPartInThread } from './threads'++export const COMMENT_SORTS = ['newest', 'oldest'] as const+export type CommentSort = (typeof COMMENT_SORTS)[number]++export interface CommentListOptions {+ query: string+ showResolved: boolean+ /** Only threads on `pageId`. */+ onlyPage: boolean+ pageId: string+ /** Only threads `author` started or replied to. */+ onlyMine: boolean+ author: string+ sort: CommentSort+}++function matches(thread: CommentThread, query: string): boolean {+ const words = [thread.text, thread.author, thread.nodeName ?? '', thread.pageName ?? '']+ for (const entry of liveReplies(thread)) words.push(entry.text, entry.author)+ return words.some((word) => word.toLocaleLowerCase().includes(query))+}++/**+ * Each thread's number, counted in the order threads were started, as Figma numbers them in its+ * list. Deleted threads keep their place so the numbers people refer to do not shift.+ */+export function commentThreadNumbers(threads: readonly CommentThread[]): Map<string, number> {+ const started = threads.toSorted(byCreatedAt)+ return new Map(started.map((thread, index) => [thread.id, index + 1]))+}++/** The threads the comments list shows for its search, filters and order. */+export function listCommentThreads(+ threads: readonly CommentThread[],+ options: CommentListOptions+): CommentThread[] {+ const query = options.query.trim().toLocaleLowerCase()+ const author = options.author.trim()+ const listed = threads.filter(+ (thread) =>+ !thread.deleted &&+ (options.showResolved || !thread.resolved) &&+ (!options.onlyPage || thread.pageId === options.pageId) &&+ (!options.onlyMine || (author !== '' && takesPartInThread(thread, author))) &&+ (query === '' || matches(thread, query))+ )+ // Ordered by when each thread was started, as Figma's "Sort by date" is.+ const direction = options.sort === 'newest' ? -1 : 1+ return listed.sort((a, b) => direction * byCreatedAt(a, b))+}diff --git a/packages/scene-graph/src/comments/merge.ts b/packages/scene-graph/src/comments/merge.tsnew file mode 100644index 000000000..12aba373f--- /dev/null+++ b/packages/scene-graph/src/comments/merge.ts@@ -0,0 +1,63 @@+import type { CommentReply, CommentThread } from '../types'+import { byCreatedAt } from './threads'++function mergeReplies(first: CommentReply[], second: CommentReply[]): CommentReply[] {+ const byId = new Map<string, CommentReply>()+ for (const reply of [...first, ...second]) {+ const existing = byId.get(reply.id)+ // A deletion is never undone by an older copy of the same reply.+ byId.set(+ reply.id,+ existing ? { ...existing, ...reply, deleted: existing.deleted || reply.deleted } : reply+ )+ }+ return [...byId.values()].sort(byCreatedAt)+}++/**+ * Two copies of a document's comments become one. Nothing is lost: threads and replies are+ * joined by id, and for a thread both copies changed, the newer edit wins while replies from+ * both are kept. Deleted threads and replies stay deleted.+ */+export function mergeCommentThreads(+ local: readonly CommentThread[],+ remote: readonly CommentThread[]+): CommentThread[] {+ const byId = new Map<string, CommentThread>()+ for (const thread of remote) byId.set(thread.id, thread)+ for (const thread of local) {+ const other = byId.get(thread.id)+ if (!other) {+ byId.set(thread.id, thread)+ continue+ }+ const newer = thread.updatedAt >= other.updatedAt ? thread : other+ byId.set(thread.id, {+ ...newer,+ deleted: thread.deleted || other.deleted,+ replies: mergeReplies(other.replies, thread.replies)+ })+ }+ return [...byId.values()].sort(byCreatedAt)+}++/**+ * Whether `local` holds anything `remote` lacks: a thread or reply it does not have, a newer edit,+ * or a deletion. Merging is then needed; otherwise `remote` already says everything.+ */+export function hasNewerComments(+ local: readonly CommentThread[],+ remote: readonly CommentThread[]+): boolean {+ const remoteById = new Map(remote.map((thread) => [thread.id, thread]))+ return local.some((thread) => {+ const other = remoteById.get(thread.id)+ if (!other) return true+ if (thread.updatedAt > other.updatedAt || (thread.deleted && !other.deleted)) return true+ const replies = new Map(other.replies.map((entry) => [entry.id, entry]))+ return thread.replies.some((entry) => {+ const known = replies.get(entry.id)+ return !known || (!!entry.deleted && !known.deleted)+ })+ })+}diff --git a/packages/scene-graph/src/comments/threads.ts b/packages/scene-graph/src/comments/threads.tsnew file mode 100644index 000000000..d1e0bdba2--- /dev/null+++ b/packages/scene-graph/src/comments/threads.ts@@ -0,0 +1,156 @@+import type { SceneGraph } from '../index'+import type { Color, Vector } from '../primitives'+import { randomHex } from '../random'+import type { CommentReply, CommentThread, SceneNode } from '../types'++/** Who writes a comment: their name and, in a collaboration room, their color. */+export interface CommentAuthor {+ name: string+ color?: Color+}++function newCommentId(prefix: 'c' | 'r'): string {+ return `${prefix}_${randomHex(8)}`+}++/** When a comment is written or changed, as stored: an ISO timestamp. */+export function commentTimestamp(): string {+ return new Date().toISOString()+}++/** Oldest first, the order threads and replies are shown and numbered in. */+export function byCreatedAt(a: { createdAt: string }, b: { createdAt: string }): number {+ return a.createdAt.localeCompare(b.createdAt)+}++/** A thread's replies, without the deleted ones kept as tombstones. */+export function liveReplies(thread: CommentThread): CommentReply[] {+ return thread.replies.filter((entry) => !entry.deleted)+}++/** Whether `author` started the thread or replied to it, as Figma's "Only your threads" counts. */+export function takesPartInThread(thread: CommentThread, author: string): boolean {+ return thread.author === author || liveReplies(thread).some((entry) => entry.author === author)+}++/** The thread with `id`, unless it is missing or deleted. */+export function findLiveCommentThread(+ threads: readonly CommentThread[],+ id: string+): CommentThread | undefined {+ return threads.find((thread) => thread.id === id && !thread.deleted)+}++/**+ * The layer a comment on `node` is kept on: its top-level layer, as Figma attaches comments, or+ * within a section the section's own child, as frames move about inside it.+ */+function commentLayer(graph: SceneGraph, node: SceneNode, pageId: string): SceneNode {+ const isSection = (id: string | null) => !!id && graph.getNode(id)?.type === 'SECTION'+ return (+ graph.closest(node.id, (layer) => layer.parentId === pageId || isSection(layer.parentId)) ??+ node+ )+}++/**+ * Where a pin at a canvas point is kept: on the top-level layer under it, or on `node`'s when+ * given, so it follows that layer; on the canvas when nothing is there.+ */+export function commentAnchor(graph: SceneGraph, pageId: string, at: Vector, node?: SceneNode) {+ const target = node ?? graph.hitTest(at.x, at.y, pageId)+ const layer = target ? commentLayer(graph, target, pageId) : null+ const abs = layer ? graph.getAbsolutePosition(layer.id) : null+ return {+ nodeId: layer?.id ?? null,+ nodeName: layer?.name ?? null,+ offsetX: abs ? at.x - abs.x : 0,+ offsetY: abs ? at.y - abs.y : 0,+ x: at.x,+ y: at.y+ }+}++/** Where a thread's pin is now: on its layer while that layer exists, else where it was left. */+export function commentPosition(graph: SceneGraph, thread: CommentThread): Vector {+ const node = thread.nodeId ? graph.getNode(thread.nodeId) : undefined+ if (!node) return { x: thread.x, y: thread.y }+ const abs = graph.getAbsolutePosition(node.id)+ return { x: abs.x + (thread.offsetX ?? 0), y: abs.y + (thread.offsetY ?? 0) }+}++/** A new thread pinned at a canvas point of a page. */+export function createCommentThread(+ graph: SceneGraph,+ options: {+ pageId: string+ at: Vector+ /** Pin it on this layer's top-level layer rather than on whatever is at `at`. */+ node?: SceneNode+ author: CommentAuthor+ text: string+ now: string+ }+): CommentThread {+ const { pageId, at, node, author, text, now } = options+ return {+ id: newCommentId('c'),+ pageId,+ pageName: graph.getNode(pageId)?.name,+ ...commentAnchor(graph, pageId, at, node),+ author: author.name,+ authorColor: author.color,+ text,+ createdAt: now,+ updatedAt: now,+ resolved: false,+ replies: []+ }+}++export function createCommentReply(author: CommentAuthor, text: string, now: string): CommentReply {+ return {+ id: newCommentId('r'),+ author: author.name,+ authorColor: author.color,+ text,+ createdAt: now+ }+}++/** The threads with one changed and marked as edited at `now`, for merging with other copies. */+export function editCommentThread(+ threads: readonly CommentThread[],+ id: string,+ now: string,+ edit: (thread: CommentThread) => CommentThread+): CommentThread[] {+ return threads.map((thread) => (thread.id === id ? { ...edit(thread), updatedAt: now } : thread))+}++/** A reply ends up in the thread and reopens it, as answering a resolved comment does. */+export function replyToCommentThread(thread: CommentThread, reply: CommentReply): CommentThread {+ return { ...thread, resolved: false, resolvedAt: null, replies: [...thread.replies, reply] }+}++export function resolveCommentThread(+ thread: CommentThread,+ resolved: boolean,+ now: string+): CommentThread {+ return { ...thread, resolved, resolvedAt: resolved ? now : null }+}++/** Deleted threads and replies stay as tombstones, so a stale copy cannot bring them back. */+export function deleteCommentThread(thread: CommentThread): CommentThread {+ return { ...thread, deleted: true }+}++export function deleteCommentReply(thread: CommentThread, replyId: string): CommentThread {+ return {+ ...thread,+ replies: thread.replies.map((entry) =>+ entry.id === replyId ? { ...entry, deleted: true } : entry+ )+ }+}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 9fcdb247d..d0c672e0f 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -33,6 +33,10 @@ export * from './icons/glyph'export * from './behaviours/layers'export * from './behaviours/model'export * from './behaviours/spec'+export * from './comments/document'+export * from './comments/list'+export * from './comments/merge'+export * from './comments/threads'export * from './copy'export {createDefaultNode,diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.tsindex d78fcea9a..8d22124e9 100644--- a/packages/scene-graph/src/plugin-data/fields.ts+++ b/packages/scene-graph/src/plugin-data/fields.ts@@ -9,6 +9,7 @@ import type { Rect } from '../primitives'import {MODE_ATTRIBUTE_PATTERN,TOKEN_UNITS,+ type CommentThread,type EnabledLibraryBinding,type ExportSetting,type LayoutDirection,@@ -130,6 +131,55 @@ const sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublicatiocatalogSource: v.optional(v.string())})+// Lenient on purpose: other tools may write comments, so missing fields get defaults and one+// malformed thread is skipped instead of hiding every comment.+const commentAuthorColor = v.fallback(+ v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),+ undefined+)++const commentReply = v.object({+ id: v.string(),+ author: v.fallback(v.string(), ''),+ authorColor: commentAuthorColor,+ text: v.fallback(v.string(), ''),+ createdAt: v.fallback(v.string(), ''),+ deleted: v.optional(v.boolean())+})++const commentThread = v.object({+ id: v.string(),+ pageId: v.string(),+ pageName: v.optional(v.string()),+ nodeId: v.optional(v.nullable(v.string())),+ nodeName: v.optional(v.nullable(v.string())),+ offsetX: v.optional(v.number()),+ offsetY: v.optional(v.number()),+ x: v.fallback(v.number(), 0),+ y: v.fallback(v.number(), 0),+ author: v.fallback(v.string(), ''),+ authorColor: commentAuthorColor,+ text: v.fallback(v.string(), ''),+ createdAt: v.fallback(v.string(), ''),+ updatedAt: v.fallback(v.string(), ''),+ resolved: v.fallback(v.boolean(), false),+ resolvedAt: v.optional(v.nullable(v.string())),+ deleted: v.optional(v.boolean()),+ replies: v.fallback(v.array(commentReply), [])+})++const comments: v.GenericSchema<unknown, CommentThread[]> = v.pipe(+ v.array(v.unknown()),+ v.transform((items) =>+ items.flatMap((item) => {+ const parsed = v.safeParse(commentThread, item)+ if (!parsed.success) return []+ const thread = parsed.output+ return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]+ })+ )+)+/*** Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's* format has no field for. Add a key here, never as a string elsewhere, so reading and writing@@ -157,6 +207,8 @@ export const OPEN_PENCIL_PLUGIN_DATA = {'bookkeeping',sourceLibraryPublication),+ /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */+ comments: jsonPluginDataField('comments', 'bookkeeping', comments),/** Unit and CSS expressions, on each VARIABLE. */token: jsonPluginDataField('token', 'format', token),/** Mode conditions by mode id, on each VARIABLE_SET. */diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex 350128d65..e331a0361 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -420,6 +420,48 @@ export interface SourceLibraryPublication {catalogSource?: string}+/** A reply in a canvas comment thread. */+export interface CommentReply {+ id: string+ author: string+ /** The author's collaboration color when they wrote it, for their avatar. */+ authorColor?: Color+ /** Markdown: bold, italic, strikethrough, links and lists. */+ text: string+ createdAt: string+ deleted?: boolean+}++/** A canvas comment thread, kept in the document's root plugin data. */+export interface CommentThread {+ id: string+ pageId: string+ /** Page name when the pin was placed, for readers of the raw data. */+ pageName?: string+ /** Top-level layer under the pin; the pin follows it when it moves. */+ nodeId?: string | null+ nodeName?: string | null+ /** Offset from the layer's top-left corner, in canvas units. */+ offsetX?: number+ offsetY?: number+ /** Canvas position when the pin was last saved; used when the layer is gone. */+ x: number+ y: number+ author: string+ /** The author's collaboration color when they wrote it, for their avatar. */+ authorColor?: Color+ /** Markdown: bold, italic, strikethrough, links and lists. */+ text: string+ createdAt: string+ /** Bumped on every change. */+ updatedAt: string+ resolved: boolean+ resolvedAt?: string | null+ /** Deleted threads stay as tombstones so a stale copy cannot bring them back. */+ deleted?: boolean+ replies: CommentReply[]+}+export interface SceneNode {id: stringtype: NodeTypediff --git a/packages/scene-graph/tests/comments/document.test.ts b/packages/scene-graph/tests/comments/document.test.tsnew file mode 100644index 000000000..71e6ea571--- /dev/null+++ b/packages/scene-graph/tests/comments/document.test.ts@@ -0,0 +1,78 @@+import { describe, expect, test } from 'bun:test'++import {+ commentAnchor,+ commentPosition,+ readComments,+ SceneGraph,+ writeComments,+ type CommentThread+} from '@open-pencil/scene-graph'++function thread(id: string, patch: Partial<CommentThread> = {}): CommentThread {+ return {+ id,+ pageId: '0:1',+ x: 10,+ y: 20,+ author: 'Ada',+ text: id,+ createdAt: '2026-10-08T10:00:00.000Z',+ updatedAt: '2026-10-08T10:00:00.000Z',+ resolved: false,+ replies: [],+ ...patch+ }+}++describe('document comments', () => {+ test('skip malformed threads and read damaged data as no comments', () => {+ const graph = new SceneGraph()+ const root = graph.getNode(graph.rootId)+ if (!root) throw new Error('Root missing')+ const store = (value: string) =>+ graph.updateNode(root.id, {+ pluginData: [{ pluginId: 'open-pencil', key: 'comments', value }]+ })++ store('not json')+ expect(readComments(graph)).toEqual([])+ store(JSON.stringify([thread('a'), { id: 3 }, 'b']))+ expect(readComments(graph).map((entry) => entry.id)).toEqual(['a'])+ })++ test('removing every thread leaves no entry behind', () => {+ const graph = new SceneGraph()+ writeComments(graph, [thread('a')])+ writeComments(graph, [])+ expect(graph.getNode(graph.rootId)?.pluginData).toEqual([])+ })++ test('a pin follows the top-level layer under it and stays put without one', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Page missing')+ const frame = graph.createNode('FRAME', page.id, { x: 100, y: 50, width: 200, height: 100 })+ graph.createNode('RECTANGLE', frame.id, { x: 10, y: 10, width: 20, height: 20 })++ const anchor = commentAnchor(graph, page.id, { x: 115, y: 65 })+ expect(anchor).toMatchObject({ nodeId: frame.id, offsetX: 15, offsetY: 15 })+ const pinned = { ...thread('a', { pageId: page.id }), ...anchor }+ graph.updateNode(frame.id, { x: 400 })+ expect(commentPosition(graph, pinned)).toEqual({ x: 415, y: 65 })++ expect(commentAnchor(graph, page.id, { x: 900, y: 900 }).nodeId).toBeNull()+ })++ test('inside a section a pin follows the frame it is on, not the whole section', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Page missing')+ const section = graph.createNode('SECTION', page.id, { x: 0, y: 0, width: 800, height: 600 })+ const frame = graph.createNode('FRAME', section.id, { x: 100, y: 100, width: 200, height: 100 })+ graph.createNode('RECTANGLE', frame.id, { x: 10, y: 10, width: 20, height: 20 })++ expect(commentAnchor(graph, page.id, { x: 115, y: 115 }).nodeId).toBe(frame.id)+ })+})+diff --git a/packages/scene-graph/tests/comments/list.test.ts b/packages/scene-graph/tests/comments/list.test.tsnew file mode 100644index 000000000..6ef029134--- /dev/null+++ b/packages/scene-graph/tests/comments/list.test.ts@@ -0,0 +1,94 @@+import { describe, expect, test } from 'bun:test'++import {+ commentThreadNumbers,+ listCommentThreads,+ type CommentListOptions,+ type CommentThread+} from '@open-pencil/scene-graph'+++function thread(id: string, patch: Partial<CommentThread> = {}): CommentThread {+ return {+ id,+ pageId: '0:1',+ x: 0,+ y: 0,+ author: 'Ada',+ text: id,+ createdAt: '2026-10-08T10:00:00.000Z',+ updatedAt: '2026-10-08T10:00:00.000Z',+ resolved: false,+ replies: [],+ ...patch+ }+}++const base: CommentListOptions = {+ query: '',+ showResolved: false,+ onlyPage: false,+ pageId: '0:1',+ onlyMine: false,+ author: 'Ada',+ sort: 'newest'+}++const ids = (threads: CommentThread[]) => threads.map((entry) => entry.id)++describe('comments list', () => {+ test('hides resolved threads until asked and never lists deleted ones', () => {+ const threads = [thread('a'), thread('b', { resolved: true }), thread('c', { deleted: true })]+ expect(ids(listCommentThreads(threads, base))).toEqual(['a'])+ expect(ids(listCommentThreads(threads, { ...base, showResolved: true }))).toEqual(['a', 'b'])+ })++ test('searches text, authors and replies', () => {+ const threads = [+ thread('a', { text: 'Bigger button' }),+ thread('b', {+ replies: [{ id: 'r', author: 'Claude', text: 'Moved the logo', createdAt: '' }]+ })+ ]+ expect(ids(listCommentThreads(threads, { ...base, query: 'button' }))).toEqual(['a'])+ expect(ids(listCommentThreads(threads, { ...base, query: 'LOGO' }))).toEqual(['b'])+ })++ test('filters to this page and to threads I started or replied to', () => {+ const threads = [+ thread('mine'),+ thread('replied', {+ author: 'Claude',+ replies: [{ id: 'r', author: 'Ada', text: 'Done', createdAt: '' }]+ }),+ thread('theirs', { pageId: '0:2', author: 'Claude' })+ ]+ expect(ids(listCommentThreads(threads, { ...base, onlyPage: true }))).toEqual(['mine', 'replied'])+ expect(ids(listCommentThreads(threads, { ...base, onlyMine: true }))).toEqual(['mine', 'replied'])+ })++ test('sorts by when each thread was started', () => {+ const threads = [+ thread('old', {+ createdAt: '2026-10-07T10:00:00.000Z',+ updatedAt: '2026-10-09T10:00:00.000Z'+ }),+ thread('new', { createdAt: '2026-10-08T12:00:00.000Z' })+ ]+ expect(ids(listCommentThreads(threads, base))).toEqual(['new', 'old'])+ expect(ids(listCommentThreads(threads, { ...base, sort: 'oldest' }))).toEqual(['old', 'new'])+ })++ test('numbers threads in the order they were started, deleted ones included', () => {+ const threads = [+ thread('second', { createdAt: '2026-10-08T11:00:00.000Z' }),+ thread('first', { createdAt: '2026-10-08T10:00:00.000Z', deleted: true }),+ thread('third', { createdAt: '2026-10-08T12:00:00.000Z' })+ ]+ expect([...commentThreadNumbers(threads)]).toEqual([+ ['first', 1],+ ['second', 2],+ ['third', 3]+ ])+ })+})diff --git a/packages/scene-graph/tests/comments/merge.test.ts b/packages/scene-graph/tests/comments/merge.test.tsnew file mode 100644index 000000000..f7ef4d61c--- /dev/null+++ b/packages/scene-graph/tests/comments/merge.test.ts@@ -0,0 +1,61 @@+import { expect, test } from 'bun:test'++import {+ hasNewerComments,+ mergeCommentThreads,+ type CommentThread+} from '@open-pencil/scene-graph'+++function thread(id: string, patch: Partial<CommentThread> = {}): CommentThread {+ return {+ id,+ pageId: '0:1',+ x: 0,+ y: 0,+ author: 'Ada',+ text: id,+ createdAt: '2026-10-08T10:00:00.000Z',+ updatedAt: '2026-10-08T10:00:00.000Z',+ resolved: false,+ replies: [],+ ...patch+ }+}++const reply = (id: string, deleted?: boolean) => ({+ id,+ author: 'Ada',+ text: id,+ createdAt: `2026-10-08T10:0${id.length}:00.000Z`,+ deleted+})++test('keeps threads from both copies and the newer edit of a shared one', () => {+ const later = '2026-10-08T11:00:00.000Z'+ const merged = mergeCommentThreads(+ [thread('a', { resolved: true, updatedAt: later }), thread('mine')],+ [thread('a'), thread('theirs')]+ )+ expect(merged.map((entry) => entry.id).toSorted()).toEqual(['a', 'mine', 'theirs'])+ expect(merged.find((entry) => entry.id === 'a')?.resolved).toBe(true)+})++test('joins replies and never brings a deleted thread or reply back', () => {+ const [merged] = mergeCommentThreads(+ [thread('a', { deleted: true, replies: [reply('r'), reply('mine')] })],+ [thread('a', { updatedAt: '2026-10-09T00:00:00.000Z', replies: [reply('r', true)] })]+ )+ expect(merged?.deleted).toBe(true)+ expect(merged?.replies.map((entry) => [entry.id, !!entry.deleted])).toEqual([+ ['r', true],+ ['mine', false]+ ])+})++test('knows when a copy already holds everything another has', () => {+ const local = [thread('a', { replies: [reply('r')] })]+ expect(hasNewerComments(local, mergeCommentThreads(local, [thread('b')]))).toBe(false)+ expect(hasNewerComments(local, [thread('a')])).toBe(true)+ expect(hasNewerComments([thread('a', { deleted: true })], [thread('a')])).toBe(true)+})diff --git a/packages/vue/src/canvas/tools/input.ts b/packages/vue/src/canvas/tools/input.tsindex 2d87b1df4..e7351d01a 100644--- a/packages/vue/src/canvas/tools/input.ts+++ b/packages/vue/src/canvas/tools/input.ts@@ -45,6 +45,9 @@ export function handleToolMouseDown({return}+ // Comments are placed by the app's comments layer above the canvas.+ if (tool === 'COMMENT') return+if (tool === 'SELECT') {handleSelectDown(event,diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.tsindex 14a64b39f..915efff53 100644--- a/packages/vue/src/editor/tool-cursor/index.ts+++ b/packages/vue/src/editor/tool-cursor/index.ts@@ -11,7 +11,8 @@ const TOOL_CURSORS: Record<Tool, string> = {STAR: 'crosshair',TEXT: 'text',PEN: 'crosshair',- HAND: 'grab'+ HAND: 'grab',+ COMMENT: 'crosshair'}export function toolCursor(tool: Tool, override?: string | null): string {diff --git a/packages/vue/src/i18n/index.ts b/packages/vue/src/i18n/index.tsindex 688c48cd3..1a627d197 100644--- a/packages/vue/src/i18n/index.ts+++ b/packages/vue/src/i18n/index.ts@@ -6,6 +6,7 @@ export {useCodeMessages,useCollaborationMessages,useCommandMessages,+ useCommentMessages,useCommonMessages,useCredentialMessages,useDesignCheckMessages,diff --git a/packages/vue/src/i18n/locales/de/comments.json b/packages/vue/src/i18n/locales/de/comments.jsonnew file mode 100644index 000000000..8a45bc1e9--- /dev/null+++ b/packages/vue/src/i18n/locales/de/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Kommentar",+ "comments": "Kommentare",+ "addComment": "Kommentar hinzufügen",+ "reply": "Antworten",+ "send": "Senden",+ "someone": "Jemand",+ "resolve": "Erledigen",+ "reopen": "Wieder öffnen",+ "delete": "Löschen",+ "deleteComment": "Kommentar löschen?",+ "deleteCommentDescription": "Damit werden der Kommentar und alle Antworten für alle entfernt.",+ "deleteReply": "Antwort löschen",+ "copyText": "Text kopieren",+ "goToComment": "Zum Kommentar",+ "moreActions": "Weitere Aktionen",+ "searchComments": "Kommentare durchsuchen",+ "filterAndSort": "Filtern und sortieren",+ "showResolved": "Erledigte Kommentare anzeigen",+ "onlyPage": "Nur aktuelle Seite",+ "onlyMine": "Nur meine Unterhaltungen",+ "newestFirst": "Neueste zuerst",+ "oldestFirst": "Älteste zuerst",+ "empty": "Noch keine Kommentare. Klicke auf die Arbeitsfläche, um einen zu hinterlassen.",+ "noMatches": "Keine passenden Kommentare.",+ "replyCount": "Antworten: {count}",+ "commentDeleted": "Kommentar gelöscht",+ "hideComments": "Kommentare ausblenden"+}diff --git a/packages/vue/src/i18n/locales/de/index.ts b/packages/vue/src/i18n/locales/de/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/de/index.ts+++ b/packages/vue/src/i18n/locales/de/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex d2e68e588..f8e06a823 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Unten ausrichten","multiplayerCursors": "Multiplayer-Cursor","designIssues": "Designprobleme",+ "comments": "Kommentare","preferences": "Einstellungen","snapToGeometry": "An Geometrie ausrichten","snapToObjects": "An Objekten ausrichten",diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.jsonindex c883b9824..cf9769adc 100644--- a/packages/vue/src/i18n/locales/de/tools.json+++ b/packages/vue/src/i18n/locales/de/tools.json@@ -9,5 +9,6 @@"star": "Stern","pen": "Stift","text": "Text",- "hand": "Hand"+ "hand": "Hand",+ "comment": "Kommentar"}diff --git a/packages/vue/src/i18n/locales/es/comments.json b/packages/vue/src/i18n/locales/es/comments.jsonnew file mode 100644index 000000000..01d4ca426--- /dev/null+++ b/packages/vue/src/i18n/locales/es/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Comentario",+ "comments": "Comentarios",+ "addComment": "Añadir un comentario",+ "reply": "Responder",+ "send": "Enviar",+ "someone": "Alguien",+ "resolve": "Resolver",+ "reopen": "Reabrir",+ "delete": "Eliminar",+ "deleteComment": "¿Eliminar comentario?",+ "deleteCommentDescription": "Se eliminarán el comentario y todas sus respuestas para todos.",+ "deleteReply": "Eliminar respuesta",+ "copyText": "Copiar texto",+ "goToComment": "Ir al comentario",+ "moreActions": "Más acciones",+ "searchComments": "Buscar comentarios",+ "filterAndSort": "Filtrar y ordenar",+ "showResolved": "Mostrar comentarios resueltos",+ "onlyPage": "Solo la página actual",+ "onlyMine": "Solo mis conversaciones",+ "newestFirst": "Más recientes primero",+ "oldestFirst": "Más antiguos primero",+ "empty": "Aún no hay comentarios. Haz clic en el lienzo para dejar uno.",+ "noMatches": "Ningún comentario coincide.",+ "replyCount": "Respuestas: {count}",+ "commentDeleted": "Comentario eliminado",+ "hideComments": "Ocultar comentarios"+}diff --git a/packages/vue/src/i18n/locales/es/index.ts b/packages/vue/src/i18n/locales/es/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/es/index.ts+++ b/packages/vue/src/i18n/locales/es/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex f3f20d8db..2759910a9 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Alinear abajo","multiplayerCursors": "Cursores multijugador","designIssues": "Problemas de diseño",+ "comments": "Comentarios","preferences": "Preferencias","snapToGeometry": "Ajustar a la geometría","snapToObjects": "Ajustar a objetos",diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.jsonindex cfa0a60b2..042ba1337 100644--- a/packages/vue/src/i18n/locales/es/tools.json+++ b/packages/vue/src/i18n/locales/es/tools.json@@ -9,5 +9,6 @@"star": "Estrella","pen": "Pluma","text": "Texto",- "hand": "Mano"+ "hand": "Mano",+ "comment": "Comentario"}diff --git a/packages/vue/src/i18n/locales/fr/comments.json b/packages/vue/src/i18n/locales/fr/comments.jsonnew file mode 100644index 000000000..1145bbc74--- /dev/null+++ b/packages/vue/src/i18n/locales/fr/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Commentaire",+ "comments": "Commentaires",+ "addComment": "Ajouter un commentaire",+ "reply": "Répondre",+ "send": "Envoyer",+ "someone": "Quelqu’un",+ "resolve": "Résoudre",+ "reopen": "Rouvrir",+ "delete": "Supprimer",+ "deleteComment": "Supprimer le commentaire ?",+ "deleteCommentDescription": "Le commentaire et toutes ses réponses seront supprimés pour tout le monde.",+ "deleteReply": "Supprimer la réponse",+ "copyText": "Copier le texte",+ "goToComment": "Aller au commentaire",+ "moreActions": "Plus d’actions",+ "searchComments": "Rechercher dans les commentaires",+ "filterAndSort": "Filtrer et trier",+ "showResolved": "Afficher les commentaires résolus",+ "onlyPage": "Page actuelle uniquement",+ "onlyMine": "Mes fils uniquement",+ "newestFirst": "Plus récents d’abord",+ "oldestFirst": "Plus anciens d’abord",+ "empty": "Aucun commentaire pour l’instant. Cliquez sur le canevas pour en laisser un.",+ "noMatches": "Aucun commentaire ne correspond.",+ "replyCount": "Réponses : {count}",+ "commentDeleted": "Commentaire supprimé",+ "hideComments": "Masquer les commentaires"+}diff --git a/packages/vue/src/i18n/locales/fr/index.ts b/packages/vue/src/i18n/locales/fr/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/fr/index.ts+++ b/packages/vue/src/i18n/locales/fr/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex 10176c7da..dbc43e514 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Aligner en bas","multiplayerCursors": "Curseurs multijoueurs","designIssues": "Problèmes de design",+ "comments": "Commentaires","preferences": "Préférences","snapToGeometry": "Aligner sur la géométrie","snapToObjects": "Aligner sur les objets",diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.jsonindex ea3489245..8e8777c3c 100644--- a/packages/vue/src/i18n/locales/fr/tools.json+++ b/packages/vue/src/i18n/locales/fr/tools.json@@ -9,5 +9,6 @@"star": "Étoile","pen": "Plume","text": "Texte",- "hand": "Main"+ "hand": "Main",+ "comment": "Commentaire"}diff --git a/packages/vue/src/i18n/locales/it/comments.json b/packages/vue/src/i18n/locales/it/comments.jsonnew file mode 100644index 000000000..8af88aa7d--- /dev/null+++ b/packages/vue/src/i18n/locales/it/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Commento",+ "comments": "Commenti",+ "addComment": "Aggiungi un commento",+ "reply": "Rispondi",+ "send": "Invia",+ "someone": "Qualcuno",+ "resolve": "Risolvi",+ "reopen": "Riapri",+ "delete": "Elimina",+ "deleteComment": "Eliminare il commento?",+ "deleteCommentDescription": "Il commento e tutte le sue risposte verranno rimossi per tutti.",+ "deleteReply": "Elimina risposta",+ "copyText": "Copia testo",+ "goToComment": "Vai al commento",+ "moreActions": "Altre azioni",+ "searchComments": "Cerca nei commenti",+ "filterAndSort": "Filtra e ordina",+ "showResolved": "Mostra commenti risolti",+ "onlyPage": "Solo pagina corrente",+ "onlyMine": "Solo le mie discussioni",+ "newestFirst": "Prima i più recenti",+ "oldestFirst": "Prima i meno recenti",+ "empty": "Ancora nessun commento. Fai clic sulla tela per lasciarne uno.",+ "noMatches": "Nessun commento corrisponde.",+ "replyCount": "Risposte: {count}",+ "commentDeleted": "Commento eliminato",+ "hideComments": "Nascondi commenti"+}diff --git a/packages/vue/src/i18n/locales/it/index.ts b/packages/vue/src/i18n/locales/it/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/it/index.ts+++ b/packages/vue/src/i18n/locales/it/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 8cc35ec50..6a34d07ac 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Allinea in basso","multiplayerCursors": "Cursori multigiocatore","designIssues": "Problemi di design",+ "comments": "Commenti","preferences": "Preferenze","snapToGeometry": "Aggancia alla geometria","snapToObjects": "Aggancia agli oggetti",diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.jsonindex d77543c43..b00d02ec9 100644--- a/packages/vue/src/i18n/locales/it/tools.json+++ b/packages/vue/src/i18n/locales/it/tools.json@@ -9,5 +9,6 @@"star": "Stella","pen": "Penna","text": "Testo",- "hand": "Mano"+ "hand": "Mano",+ "comment": "Commento"}diff --git a/packages/vue/src/i18n/locales/ja/comments.json b/packages/vue/src/i18n/locales/ja/comments.jsonnew file mode 100644index 000000000..570755b46--- /dev/null+++ b/packages/vue/src/i18n/locales/ja/comments.json@@ -0,0 +1,29 @@+{+ "comment": "コメント",+ "comments": "コメント一覧",+ "addComment": "コメントを追加",+ "reply": "返信",+ "send": "送信",+ "someone": "だれか",+ "resolve": "解決",+ "reopen": "再開",+ "delete": "削除",+ "deleteComment": "コメントを削除しますか?",+ "deleteCommentDescription": "コメントとすべての返信が全員から削除されます。",+ "deleteReply": "返信を削除",+ "copyText": "テキストをコピー",+ "goToComment": "コメントへ移動",+ "moreActions": "その他の操作",+ "searchComments": "コメントを検索",+ "filterAndSort": "絞り込みと並べ替え",+ "showResolved": "解決済みのコメントを表示",+ "onlyPage": "現在のページのみ",+ "onlyMine": "自分のスレッドのみ",+ "newestFirst": "新しい順",+ "oldestFirst": "古い順",+ "empty": "まだコメントはありません。キャンバスをクリックしてコメントを残せます。",+ "noMatches": "一致するコメントはありません。",+ "replyCount": "返信: {count}",+ "commentDeleted": "コメントを削除しました",+ "hideComments": "コメントを非表示"+}diff --git a/packages/vue/src/i18n/locales/ja/index.ts b/packages/vue/src/i18n/locales/ja/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/ja/index.ts+++ b/packages/vue/src/i18n/locales/ja/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex 19eb45057..94252e3ca 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "下揃え","multiplayerCursors": "マルチプレイヤーカーソル","designIssues": "デザインの問題",+ "comments": "コメント一覧","preferences": "環境設定","snapToGeometry": "ジオメトリにスナップ","snapToObjects": "オブジェクトにスナップ",diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.jsonindex 99fbd7cbf..73d4e1bb5 100644--- a/packages/vue/src/i18n/locales/ja/tools.json+++ b/packages/vue/src/i18n/locales/ja/tools.json@@ -9,5 +9,6 @@"star": "スター","pen": "ペンツール","text": "テキスト",- "hand": "手のひらツール"+ "hand": "手のひらツール",+ "comment": "コメント"}diff --git a/packages/vue/src/i18n/locales/pl/comments.json b/packages/vue/src/i18n/locales/pl/comments.jsonnew file mode 100644index 000000000..4fce42799--- /dev/null+++ b/packages/vue/src/i18n/locales/pl/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Komentarz",+ "comments": "Komentarze",+ "addComment": "Dodaj komentarz",+ "reply": "Odpowiedz",+ "send": "Wyślij",+ "someone": "Ktoś",+ "resolve": "Rozwiąż",+ "reopen": "Otwórz ponownie",+ "delete": "Usuń",+ "deleteComment": "Usunąć komentarz?",+ "deleteCommentDescription": "Komentarz i wszystkie odpowiedzi zostaną usunięte dla wszystkich.",+ "deleteReply": "Usuń odpowiedź",+ "copyText": "Kopiuj tekst",+ "goToComment": "Przejdź do komentarza",+ "moreActions": "Więcej działań",+ "searchComments": "Szukaj w komentarzach",+ "filterAndSort": "Filtruj i sortuj",+ "showResolved": "Pokaż rozwiązane komentarze",+ "onlyPage": "Tylko bieżąca strona",+ "onlyMine": "Tylko moje wątki",+ "newestFirst": "Najnowsze najpierw",+ "oldestFirst": "Najstarsze najpierw",+ "empty": "Brak komentarzy. Kliknij obszar roboczy, aby dodać komentarz.",+ "noMatches": "Brak pasujących komentarzy.",+ "replyCount": "Odpowiedzi: {count}",+ "commentDeleted": "Usunięto komentarz",+ "hideComments": "Ukryj komentarze"+}diff --git a/packages/vue/src/i18n/locales/pl/index.ts b/packages/vue/src/i18n/locales/pl/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/pl/index.ts+++ b/packages/vue/src/i18n/locales/pl/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex 81cf2ba58..9be4d2d2f 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Wyrównaj do dołu","multiplayerCursors": "Kursory wielu użytkowników","designIssues": "Problemy projektu",+ "comments": "Komentarze","preferences": "Preferencje","snapToGeometry": "Przyciągaj do geometrii","snapToObjects": "Przyciągaj do obiektów",diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.jsonindex 1043d2657..20151c6cb 100644--- a/packages/vue/src/i18n/locales/pl/tools.json+++ b/packages/vue/src/i18n/locales/pl/tools.json@@ -9,5 +9,6 @@"star": "Gwiazda","pen": "Pióro","text": "Tekst",- "hand": "Dłoń"+ "hand": "Dłoń",+ "comment": "Komentarz"}diff --git a/packages/vue/src/i18n/locales/ru/comments.json b/packages/vue/src/i18n/locales/ru/comments.jsonnew file mode 100644index 000000000..c80e91dc4--- /dev/null+++ b/packages/vue/src/i18n/locales/ru/comments.json@@ -0,0 +1,29 @@+{+ "comment": "Комментарий",+ "comments": "Комментарии",+ "addComment": "Добавить комментарий",+ "reply": "Ответить",+ "send": "Отправить",+ "someone": "Кто-то",+ "resolve": "Решить",+ "reopen": "Открыть снова",+ "delete": "Удалить",+ "deleteComment": "Удалить комментарий?",+ "deleteCommentDescription": "Комментарий и все ответы будут удалены для всех.",+ "deleteReply": "Удалить ответ",+ "copyText": "Копировать текст",+ "goToComment": "Перейти к комментарию",+ "moreActions": "Другие действия",+ "searchComments": "Поиск по комментариям",+ "filterAndSort": "Фильтр и сортировка",+ "showResolved": "Показывать решённые комментарии",+ "onlyPage": "Только текущая страница",+ "onlyMine": "Только мои обсуждения",+ "newestFirst": "Сначала новые",+ "oldestFirst": "Сначала старые",+ "empty": "Комментариев пока нет. Щёлкните по холсту, чтобы оставить комментарий.",+ "noMatches": "Нет подходящих комментариев.",+ "replyCount": "Ответы: {count}",+ "commentDeleted": "Комментарий удалён",+ "hideComments": "Скрыть комментарии"+}diff --git a/packages/vue/src/i18n/locales/ru/index.ts b/packages/vue/src/i18n/locales/ru/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/ru/index.ts+++ b/packages/vue/src/i18n/locales/ru/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex 9dff3ca42..00f92292b 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "Выровнять по нижнему краю","multiplayerCursors": "Курсоры участников","designIssues": "Проблемы дизайна",+ "comments": "Комментарии","preferences": "Настройки","snapToGeometry": "Привязка к геометрии","snapToObjects": "Привязка к объектам",diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.jsonindex 37bbd2b09..d639bcfeb 100644--- a/packages/vue/src/i18n/locales/ru/tools.json+++ b/packages/vue/src/i18n/locales/ru/tools.json@@ -9,5 +9,6 @@"star": "Звезда","pen": "Перо","text": "Текст",- "hand": "Рука"+ "hand": "Рука",+ "comment": "Комментарий"}diff --git a/packages/vue/src/i18n/locales/zh-cn/comments.json b/packages/vue/src/i18n/locales/zh-cn/comments.jsonnew file mode 100644index 000000000..50005c441--- /dev/null+++ b/packages/vue/src/i18n/locales/zh-cn/comments.json@@ -0,0 +1,29 @@+{+ "comment": "评论",+ "comments": "评论列表",+ "addComment": "添加评论",+ "reply": "回复",+ "send": "发送",+ "someone": "某人",+ "resolve": "解决",+ "reopen": "重新打开",+ "delete": "删除",+ "deleteComment": "删除评论?",+ "deleteCommentDescription": "这会为所有人删除该评论及其全部回复。",+ "deleteReply": "删除回复",+ "copyText": "复制文本",+ "goToComment": "转到评论",+ "moreActions": "更多操作",+ "searchComments": "搜索评论",+ "filterAndSort": "筛选和排序",+ "showResolved": "显示已解决的评论",+ "onlyPage": "仅当前页面",+ "onlyMine": "仅我的讨论",+ "newestFirst": "最新优先",+ "oldestFirst": "最早优先",+ "empty": "还没有评论。点击画布即可留下评论。",+ "noMatches": "没有匹配的评论。",+ "replyCount": "回复:{count}",+ "commentDeleted": "评论已删除",+ "hideComments": "隐藏评论"+}diff --git a/packages/vue/src/i18n/locales/zh-cn/index.ts b/packages/vue/src/i18n/locales/zh-cn/index.tsindex f877b7541..0beaf3fd8 100644--- a/packages/vue/src/i18n/locales/zh-cn/index.ts+++ b/packages/vue/src/i18n/locales/zh-cn/index.ts@@ -5,6 +5,7 @@ import automation from './automation.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'+import comments from './comments.json'import common from './common.json'import credentials from './credentials.json'import designCheck from './design-check.json'@@ -32,6 +33,7 @@ export default {code,collaboration,commands,+ comments,common,credentials,designCheck,diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex 34fe6b599..eff6dfb1a 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -58,6 +58,7 @@"arrangeAlignBottom": "底部对齐","multiplayerCursors": "多人光标","designIssues": "设计问题",+ "comments": "评论列表","preferences": "偏好设置","snapToGeometry": "吸附到几何图形","snapToObjects": "吸附到对象",diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.jsonindex 87598e459..549696aaa 100644--- a/packages/vue/src/i18n/locales/zh-cn/tools.json+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json@@ -9,5 +9,6 @@"star": "星形","pen": "钢笔","text": "文本",- "hand": "抓手"+ "hand": "抓手",+ "comment": "评论"}diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.tsindex 311be2443..4aa628a2a 100644--- a/packages/vue/src/i18n/messages.ts+++ b/packages/vue/src/i18n/messages.ts@@ -6,6 +6,7 @@ import {collaborationMessages} from '#vue/i18n/messages/collaboration'import { commandMessageDefaults, commandMessages } from '#vue/i18n/messages/commands'+import { commentMessageDefaults, commentMessages } from '#vue/i18n/messages/comments'import { commonMessageDefaults, commonMessages } from '#vue/i18n/messages/common'import { credentialsMessageDefaults, credentialsMessages } from '#vue/i18n/messages/credentials'import { designCheckMessageDefaults, designCheckMessages } from '#vue/i18n/messages/design-check'@@ -36,6 +37,7 @@ export {codeMessages,collaborationMessages,commandMessages,+ commentMessages,commonMessages,credentialsMessages,designCheckMessages,@@ -64,6 +66,7 @@ export const messageDefaults = {code: codeMessageDefaults,collaboration: collaborationMessageDefaults,commands: commandMessageDefaults,+ comments: commentMessageDefaults,common: commonMessageDefaults,credentials: credentialsMessageDefaults,designCheck: designCheckMessageDefaults,diff --git a/packages/vue/src/i18n/messages/comments.ts b/packages/vue/src/i18n/messages/comments.tsnew file mode 100644index 000000000..8e9042116--- /dev/null+++ b/packages/vue/src/i18n/messages/comments.ts@@ -0,0 +1,35 @@+import { params } from '@nanostores/i18n'++import { i18n } from '#vue/i18n/create'++export const commentMessageDefaults = {+ comment: 'Comment',+ comments: 'Comments',+ addComment: 'Add a comment',+ reply: 'Reply',+ send: 'Send',+ someone: 'Someone',+ resolve: 'Resolve',+ reopen: 'Reopen',+ delete: 'Delete',+ deleteComment: 'Delete comment?',+ deleteCommentDescription: 'This removes the comment and all of its replies for everyone.',+ deleteReply: 'Delete reply',+ copyText: 'Copy text',+ goToComment: 'Go to comment',+ moreActions: 'More actions',+ searchComments: 'Search comments',+ filterAndSort: 'Filter and sort',+ showResolved: 'Show resolved comments',+ onlyPage: 'Only current page',+ onlyMine: 'Only my threads',+ newestFirst: 'Newest first',+ oldestFirst: 'Oldest first',+ empty: 'No comments yet. Click the canvas to leave one.',+ noMatches: 'No comments match.',+ replyCount: params('Replies: {count}'),+ commentDeleted: 'Comment deleted',+ hideComments: 'Hide comments'+} as const++export const commentMessages = i18n('comments', commentMessageDefaults)diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex 4808ea35e..d0495645f 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -38,6 +38,7 @@ export const menuMessageDefaults = {pixelGrid: 'Pixel grid',multiplayerCursors: 'Multiplayer cursors',designIssues: 'Design issues',+ comments: 'Comments',preferences: 'Preferences',snapToGeometry: 'Snap to geometry',snapToObjects: 'Snap to objects',diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.tsindex cf5a011cd..6471d9848 100644--- a/packages/vue/src/i18n/messages/tools.ts+++ b/packages/vue/src/i18n/messages/tools.ts@@ -11,7 +11,8 @@ export const toolMessageDefaults = {star: 'Star',pen: 'Pen',text: 'Text',- hand: 'Hand'+ hand: 'Hand',+ comment: 'Comment'} as constexport const toolMessages = i18n('tools', toolMessageDefaults)diff --git a/packages/vue/src/i18n/useI18n.ts b/packages/vue/src/i18n/useI18n.tsindex 44714d1b2..f64063735 100644--- a/packages/vue/src/i18n/useI18n.ts+++ b/packages/vue/src/i18n/useI18n.ts@@ -10,6 +10,7 @@ import {codeMessages,collaborationMessages,commandMessages,+ commentMessages,commonMessages,credentialsMessages,designCheckMessages,@@ -41,6 +42,7 @@ export const useAutomationMessages = () => useI18nNamespace(automationMessages)export const useCodeMessages = () => useI18nNamespace(codeMessages)export const useCollaborationMessages = () => useI18nNamespace(collaborationMessages)export const useCommandMessages = () => useI18nNamespace(commandMessages)+export const useCommentMessages = () => useI18nNamespace(commentMessages)export const useCommonMessages = () => useI18nNamespace(commonMessages)export const useCredentialMessages = () => useI18nNamespace(credentialsMessages)export const useDesignCheckMessages = () => useI18nNamespace(designCheckMessages)diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 7e2f71385..65dc3752a 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -179,6 +179,18 @@ openpencil eval design.fig -w -c '`openpencil.behaviourKinds` lists every kind with its values and parts; `openpencil.getBehaviour(node)` reads one (a variant reads its set's); `openpencil.createSlot(frame)` makes a frame a slot. The `set_behaviour`, `get_behaviour`, and `create_slot` tools do the same over MCP, and design JSX writes controls with Reka's element names (`Switch.Root`, `Switch.Thumb`).+Comments people leave on the canvas are review feedback you can act on. Read the open ones, change the design, then answer and resolve each, naming yourself as the author:++```bash+openpencil eval design.fig -w -c '+ openpencil.getComments({ resolved: false }).map(c => ({ id: c.id, text: c.text, layer: c.node?.name }))+'+# after the change:+openpencil eval design.fig -w -c 'openpencil.getComment("c_…").reply("Title is 24px now", { author: "Claude" }).resolve()'+```++`openpencil.addComment(text, { node, page, x, y, author })` leaves a new one. Over MCP the same is `get_comments`, `add_comment`, `reply_to_comment`, and `resolve_comment`. Comment text is Markdown.+### DiffCompare nodes and documents, and apply patches:diff --git a/src/app/comments/document.ts b/src/app/comments/document.tsnew file mode 100644index 000000000..1f21423cb--- /dev/null+++ b/src/app/comments/document.ts@@ -0,0 +1,141 @@+import { ref, watch, type Ref } from 'vue'++import {+ commentPosition,+ commentTimestamp as now,+ editCommentThread,+ hasNewerComments,+ mergeCommentThreads,+ readComments,+ writeComments,+ type CommentThread+} from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import type { EditorStore } from '@/app/editor/active-store'++/**+ * The comments of whichever document `storeRef` holds: read from it, written to it, and kept in+ * step with collaborators and with the layers pins sit on. `onDocumentChange` runs when another+ * document's comments take their place.+ */+export function followDocumentComments(+ storeRef: Ref<EditorStore | undefined>,+ onDocumentChange: () => void+) {+ const threads = ref<CommentThread[]>([])+ // Where each pinned thread's layer last put it, kept as layers change rather than as pins are+ // drawn, so a pin whose layer is deleted, even unseen, stays where the layer was.+ const lastSeen = new Map<string, Vector>()+ let bound: EditorStore | null = null+ let unsubscribe: (() => void) | null = null+ let reconcileQueued = false++ function rememberPositions() {+ if (!bound) return+ for (const thread of threads.value) {+ if (thread.deleted || !thread.nodeId || !bound.graph.getNode(thread.nodeId)) continue+ lastSeen.set(thread.id, commentPosition(bound.graph, thread))+ }+ }++ function show(next: CommentThread[]) {+ threads.value = next+ rememberPositions()+ }++ /**+ * The document's comments changed under this session. A collaborator's save replaces them+ * whole, so when two people comment at once one copy wins; whatever this session had that the+ * winning copy lacks is merged back in and written again.+ */+ function reconcile() {+ if (!bound) return+ const incoming = readComments(bound.graph)+ if (!hasNewerComments(threads.value, incoming)) {+ show(incoming)+ return+ }+ const merged = mergeCommentThreads(threads.value, incoming)+ writeComments(bound.graph, merged)+ show(merged)+ }++ function queueReconcile() {+ if (reconcileQueued) return+ reconcileQueued = true+ queueMicrotask(() => {+ reconcileQueued = false+ reconcile()+ })+ }++ /** Change the open document's comments, starting from what it holds now. */+ function mutate(change: (current: CommentThread[]) => CommentThread[]) {+ if (!bound) return+ const next = change(readComments(bound.graph))+ writeComments(bound.graph, next)+ show(next)+ }++ function update(id: string, edit: (thread: CommentThread) => CommentThread) {+ mutate((current) => editCommentThread(current, id, now(), edit))+ }++ /** The layer a pin followed is gone: the pin stays where it was last seen, on the canvas. */+ function detachFromLayer(nodeId: string) {+ if (!threads.value.some((thread) => thread.nodeId === nodeId)) return+ mutate((current) =>+ current.map((thread) => {+ if (thread.nodeId !== nodeId) return thread+ const at = lastSeen.get(thread.id) ?? { x: thread.x, y: thread.y }+ return { ...thread, nodeId: null, x: at.x, y: at.y, updatedAt: now() }+ })+ )+ }++ function replaceDocument() {+ lastSeen.clear()+ onDocumentChange()+ show(bound ? readComments(bound.graph) : [])+ }++ function bind(store: EditorStore | undefined) {+ if ((store ?? null) === bound) return+ unsubscribe?.()+ unsubscribe = null+ bound = store ?? null+ replaceDocument()+ if (!store) return+ const stops = [+ // Comments change on the document node: here, from a collaborator, or by a tool.+ store.onEditorEvent('node:updated', (id) => {+ if (id === store.graph.rootId) queueReconcile()+ else rememberPositions()+ }),+ store.onEditorEvent('node:reparented', rememberPositions),+ // A collaboration room can bring its own document node, with its own comments.+ store.onEditorEvent('node:created', (node) => {+ if (node.parentId === null) queueMicrotask(() => show(readComments(store.graph)))+ }),+ store.onEditorEvent('node:deleted', (id) => queueMicrotask(() => detachFromLayer(id))),+ store.onEditorEvent('graph:replaced', replaceDocument)+ ]+ unsubscribe = () => {+ for (const stop of stops) stop()+ }+ }++ // Setting the active store retriggers it even when it is the same one, as panes take turns.+ watch(storeRef, bind, { immediate: true, flush: 'sync' })++ return {+ threads,+ /** The document comments are read from and written to now. */+ store: () => bound,+ mutate,+ update,+ pinPosition: (thread: CommentThread): Vector =>+ bound ? commentPosition(bound.graph, thread) : { x: thread.x, y: thread.y }+ }+}diff --git a/src/app/comments/format.ts b/src/app/comments/format.tsnew file mode 100644index 000000000..b198c09ee--- /dev/null+++ b/src/app/comments/format.ts@@ -0,0 +1,152 @@+/**+ * Figma's comment formatting, written as Markdown into the plain text a comment stores: bold,+ * italic and strikethrough wrap the selection, a link wraps it as the link text, and the list+ * commands start or continue a numbered or bulleted list.+ */+export type CommentFormat = 'bold' | 'italic' | 'strikethrough' | 'link' | 'numbered' | 'bulleted'++export interface CommentEdit {+ value: string+ start: number+ end: number+}++const WRAPS = {+ bold: '**',+ italic: '*',+ strikethrough: '~~'+} as const satisfies Partial<Record<CommentFormat, string>>++const LIST_ITEM = /^(\s*)(?:(\d+)\.|[-*])\s/u++/** The format a key press asks for, with Figma's shortcuts; `mod` is Cmd on a Mac, Ctrl elsewhere. */+export function commentFormatForKey(event: {+ code: string+ shiftKey: boolean+ altKey: boolean+ mod: boolean+}): CommentFormat | null {+ if (!event.mod || event.altKey) return null+ if (event.shiftKey) {+ if (event.code === 'KeyX') return 'strikethrough'+ if (event.code === 'Digit7') return 'numbered'+ if (event.code === 'Digit8') return 'bulleted'+ return null+ }+ if (event.code === 'KeyB') return 'bold'+ if (event.code === 'KeyI') return 'italic'+ if (event.code === 'KeyK') return 'link'+ return null+}++function lineStart(value: string, at: number) {+ return value.lastIndexOf('\n', at - 1) + 1+}++function lineEnd(value: string, at: number) {+ const end = value.indexOf('\n', at)+ return end === -1 ? value.length : end+}++function wrap({ value, start, end }: CommentEdit, mark: string): CommentEdit {+ const selected = value.slice(start, end)+ const before = value.slice(start - mark.length, start)+ const after = value.slice(end, end + mark.length)+ // Pressing the shortcut again on wrapped text unwraps it.+ if (before === mark && after === mark) {+ return {+ value: value.slice(0, start - mark.length) + selected + value.slice(end + mark.length),+ start: start - mark.length,+ end: end - mark.length+ }+ }+ return {+ value: `${value.slice(0, start)}${mark}${selected}${mark}${value.slice(end)}`,+ start: start + mark.length,+ end: end + mark.length+ }+}++function link({ value, start, end }: CommentEdit): CommentEdit {+ const text = value.slice(start, end)+ // The placeholder URL is selected so typing replaces it; without link text the address is+ // shown as it is.+ if (text === '') {+ return {+ value: `${value.slice(0, start)}<url>${value.slice(end)}`,+ start: start + 1,+ end: start + 4+ }+ }+ const inserted = `[${text}](url)`+ const url = start + text.length + 3+ return {+ value: value.slice(0, start) + inserted + value.slice(end),+ start: url,+ end: url + 3+ }+}++function list({ value, start, end }: CommentEdit, numbered: boolean): CommentEdit {+ const from = lineStart(value, start)+ const to = lineEnd(value, end)+ const lines = value.slice(from, to).split('\n')+ const listed = lines.every((line) => LIST_ITEM.test(line))+ // Turning the same kind of list on again takes the markers off.+ const sameKind = listed && lines.every((line) => /^\s*\d+\.\s/u.test(line) === numbered)+ const next = lines.map((line, index) => {+ const bare = line.replace(LIST_ITEM, '$1')+ if (sameKind) return bare+ return `${numbered ? `${index + 1}.` : '-'} ${bare}`+ })+ const text = next.join('\n')+ const result = value.slice(0, from) + text + value.slice(to)+ // A caret on one line keeps its place in the text; a selection covers the changed lines.+ if (start === end && lines.length === 1) {+ const caret = Math.max(from, start + text.length - (to - from))+ return { value: result, start: caret, end: caret }+ }+ return { value: result, start: from, end: from + text.length }+}++/** Applies a format to the text and selection of a comment being written. */+export function formatComment(edit: CommentEdit, format: CommentFormat): CommentEdit {+ if (format === 'link') return link(edit)+ if (format === 'numbered') return list(edit, true)+ if (format === 'bulleted') return list(edit, false)+ return wrap(edit, WRAPS[format])+}++/**+ * Shift+Enter inside a list item starts the next item, as in Figma; on an empty item it ends the+ * list instead. Returns null outside a list, where Shift+Enter is a plain line break.+ */+export function continueList({ value, start, end }: CommentEdit): CommentEdit | null {+ const from = lineStart(value, start)+ const match = LIST_ITEM.exec(value.slice(from, lineEnd(value, start)))+ if (!match) return null+ const marker = match[0]+ const indent = /^\s*/u.exec(marker)?.[0] ?? ''+ if (value.slice(from, lineEnd(value, start)).length === marker.length) {+ return {+ value: value.slice(0, from) + value.slice(from + marker.length),+ start: from,+ end: from+ }+ }+ const number = Number.parseInt(marker, 10)+ const nextMarker = Number.isNaN(number) ? `${indent}- ` : `${indent}${number + 1}. `+ const inserted = `\n${nextMarker}`+ const at = start + inserted.length+ return { value: value.slice(0, start) + inserted + value.slice(end), start: at, end: at }+}++/** A comment's text without its Markdown, for the one-paragraph preview in the comments list. */+export function commentPreview(text: string): string {+ return text+ .replace(/\[([^\]]*)\]\([^)]*\)/gu, '$1')+ .replace(/(\*\*|~~|\*|~)(\S(?:.*?\S)?)\1/gu, '$2')+ .replace(/^\s*(?:\d+\.|[-*])\s+/gmu, '')+ .replace(/\s*\n\s*/gu, ' ')+ .trim()+}diff --git a/src/app/comments/time.ts b/src/app/comments/time.tsnew file mode 100644index 000000000..5d0fafd55--- /dev/null+++ b/src/app/comments/time.ts@@ -0,0 +1,22 @@+import { createSharedComposable, useNow } from '@vueuse/core'++const MINUTE = 60_000+const HOUR = 60 * MINUTE+const DAY = 24 * HOUR+const WEEK = 7 * DAY++/** One clock for every comment timestamp, so "now" turns into "1 min. ago" on its own. */+export const useCommentClock = createSharedComposable(() => useNow({ interval: 30_000 }))++/** "now", "5 min. ago", "3 hr. ago", "yesterday", then a short date, in the app's locale. */+export function formatCommentTime(iso: string, now: number, locale: string): string {+ const then = Date.parse(iso)+ if (!Number.isFinite(then)) return ''+ const elapsed = Math.max(0, now - then)+ const relative = new Intl.RelativeTimeFormat(locale, { numeric: 'auto', style: 'short' })+ if (elapsed < MINUTE) return relative.format(0, 'second')+ if (elapsed < HOUR) return relative.format(-Math.floor(elapsed / MINUTE), 'minute')+ if (elapsed < DAY) return relative.format(-Math.floor(elapsed / HOUR), 'hour')+ if (elapsed < WEEK) return relative.format(-Math.floor(elapsed / DAY), 'day')+ return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(then)+}diff --git a/src/app/comments/use.ts b/src/app/comments/use.tsnew file mode 100644index 000000000..30fa04ea8--- /dev/null+++ b/src/app/comments/use.ts@@ -0,0 +1,187 @@+import { createEventHook, createGlobalState } from '@vueuse/core'+import { computed, ref, type WritableComputedRef } from 'vue'++import {+ commentAnchor,+ commentTimestamp as now,+ createCommentReply,+ createCommentThread,+ deleteCommentReply,+ deleteCommentThread,+ replyToCommentThread,+ resolveCommentThread+} from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { useCollabIdentity } from '@/app/collab/identity'+import { useActiveEditorStoreRef } from '@/app/editor/active-store'+import type { PagePoint } from '@/app/editor/pages/point'+import { setCommentsOnCanvas } from '@/app/settings/preferences/apply'+import {+ appPreferences,+ updateCommentPreferences,+ type CommentPreferences+} from '@/app/settings/preferences/store'++import { followDocumentComments } from './document'++/** A comment preference the list and menus read and change in place. */+function preference<K extends keyof CommentPreferences>(+ key: K+): WritableComputedRef<CommentPreferences[K]> {+ return computed({+ get: () => appPreferences.value.comments[key],+ set: (value) => updateCommentPreferences({ [key]: value })+ })+}++/**+ * The active document's comments and the comment UI's state, one for the whole app: the canvas+ * layer, the sidebar list, menus and shortcuts share it, and it follows whichever tab is active.+ * Changes are document changes but never undo steps, as in Figma.+ *+ * Escape closes things in order: the composer and the card's popover close themselves, and the+ * editor's Escape asks `closeCard` before it leaves the Comment tool.+ */+export const useComments = createGlobalState(() => {+ const identity = useCollabIdentity()+ const storeRef = useActiveEditorStoreRef()++ const activeThreadId = ref<string | null>(null)+ const draft = ref<PagePoint | null>(null)+ /** Deleting asks first; the confirmation dialog listens for which thread. */+ const deleteRequested = createEventHook<string>()+ const listQuery = ref('')+ const showOnCanvas = computed(() => appPreferences.value.comments.showOnCanvas)+ const listShowResolved = preference('showResolved')+ const listOnlyPage = preference('onlyPage')+ const listOnlyMine = preference('onlyMine')+ const listSort = preference('sort')++ // Another document is open: nothing from the last one stays open or half-written.+ const documentComments = followDocumentComments(storeRef, () => {+ activeThreadId.value = null+ draft.value = null+ })+ const { threads, mutate, update, pinPosition } = documentComments++ function me() {+ return { name: identity.name.value, color: identity.color }+ }++ function startDraft(at: PagePoint) {+ activeThreadId.value = null+ draft.value = at+ }++ function toggleThread(threadId: string) {+ draft.value = null+ activeThreadId.value = activeThreadId.value === threadId ? null : threadId+ }++ /** Close an unsent comment or an open thread; false when neither was open. */+ function closeCard(): boolean {+ const open = draft.value !== null || activeThreadId.value !== null+ draft.value = null+ activeThreadId.value = null+ return open+ }++ function addThread(text: string) {+ const place = draft.value+ const body = text.trim()+ const store = documentComments.store()+ if (!store || !place || !body) return+ const thread = createCommentThread(store.graph, {+ pageId: place.pageId,+ at: place,+ author: me(),+ text: body,+ now: now()+ })+ draft.value = null+ activeThreadId.value = thread.id+ mutate((current) => [...current, thread])+ }++ /** A dragged pin lands on whatever is under it now, as in Figma. */+ function movePin(threadId: string, at: Vector) {+ const store = documentComments.store()+ if (!store) return+ update(threadId, (thread) => ({ ...thread, ...commentAnchor(store.graph, thread.pageId, at) }))+ }++ function reply(threadId: string, text: string) {+ const body = text.trim()+ if (!body) return+ const entry = createCommentReply(me(), body, now())+ update(threadId, (thread) => replyToCommentThread(thread, entry))+ }++ function setResolved(threadId: string, resolved: boolean) {+ update(threadId, (thread) => resolveCommentThread(thread, resolved, now()))+ // A resolved thread leaves the canvas unless resolved comments are shown.+ if (resolved && !listShowResolved.value && activeThreadId.value === threadId) {+ activeThreadId.value = null+ }+ }++ /** Ask before deleting; the confirmation dialog answers with `confirmDelete`. */+ function requestDelete(threadId: string) {+ void deleteRequested.trigger(threadId)+ }++ function confirmDelete(threadId: string) {+ update(threadId, deleteCommentThread)+ if (activeThreadId.value === threadId) activeThreadId.value = null+ }++ function deleteReply(threadId: string, replyId: string) {+ update(threadId, (thread) => deleteCommentReply(thread, replyId))+ }++ /** Show a thread: its page, centered on its pin, with its card open. */+ async function focusThread(threadId: string) {+ const store = documentComments.store()+ const thread = threads.value.find((entry) => entry.id === threadId)+ if (!store || !thread) return+ if (store.state.currentPageId !== thread.pageId && store.graph.getNode(thread.pageId)) {+ await store.switchPage(thread.pageId)+ }+ const { x, y } = pinPosition(thread)+ store.centerOn(x, y)+ draft.value = null+ activeThreadId.value = threadId+ }++ function toggleOnCanvas() {+ setCommentsOnCanvas(!showOnCanvas.value)+ }++ return {+ threads,+ activeThreadId,+ draft,+ onDeleteRequested: deleteRequested.on,+ author: identity.name,+ showOnCanvas,+ listQuery,+ listShowResolved,+ listOnlyPage,+ listOnlyMine,+ listSort,+ pinPosition,+ startDraft,+ toggleThread,+ closeCard,+ addThread,+ movePin,+ reply,+ setResolved,+ requestDelete,+ confirmDelete,+ deleteReply,+ focusThread,+ toggleOnCanvas+ }+})diff --git a/src/app/editor/canvas/context-selection.ts b/src/app/editor/canvas/context-selection.tsindex 53ac4577d..967d2ac23 100644--- a/src/app/editor/canvas/context-selection.ts+++ b/src/app/editor/canvas/context-selection.ts@@ -11,6 +11,9 @@ export function createCanvasContextSelection(function selectAtContextPoint(event: MouseEvent) {const canvas = canvasRef.valueif (!canvas) return+ // Overlays such as comment pins handle their own right-click.+ const target = event.target instanceof Element ? event.target : null+ if (target?.closest('[data-canvas-overlay]')) returnconst rect = canvas.getBoundingClientRect()const sx = event.clientX - rect.leftconst sy = event.clientY - rect.topdiff --git a/src/app/editor/icons.ts b/src/app/editor/icons.tsindex a9c69544b..44d61291e 100644--- a/src/app/editor/icons.ts+++ b/src/app/editor/icons.ts@@ -8,6 +8,7 @@ import IconGrid from '~icons/lucide/grid-3x3'import IconGroup from '~icons/lucide/group'import IconHand from '~icons/lucide/hand'import IconSection from '~icons/lucide/layout-grid'+import IconMessageCircle from '~icons/lucide/message-circle'import IconMinus from '~icons/lucide/minus'import IconMousePointer from '~icons/lucide/mouse-pointer'import IconPenTool from '~icons/lucide/pen-tool'@@ -34,7 +35,8 @@ export const toolIcons: Record<Tool, Component> = {STAR: IconStar,PEN: IconPenTool,TEXT: IconType,- HAND: IconHand+ HAND: IconHand,+ COMMENT: IconMessageCircle}export const NODE_ICONS: Partial<Record<string, typeof IconSquare>> = {diff --git a/src/app/editor/pages/point.ts b/src/app/editor/pages/point.tsnew file mode 100644index 000000000..625084115--- /dev/null+++ b/src/app/editor/pages/point.ts@@ -0,0 +1,6 @@+/** A canvas point on a page. */+export interface PagePoint {+ x: number+ y: number+ pageId: string+}diff --git a/src/app/presence/types.ts b/src/app/presence/types.tsindex 04559557e..c108320ea 100644--- a/src/app/presence/types.ts+++ b/src/app/presence/types.ts@@ -1,19 +1,15 @@import type { Rect } from '@open-pencil/scene-graph/primitives'+import type { PagePoint } from '@/app/editor/pages/point'+export const AGENT_KINDS = ['chat', 'acp', 'harness', 'mcp'] as constexport type AgentKind = (typeof AGENT_KINDS)[number]export const AGENT_STATUSES = ['thinking', 'editing', 'idle'] as constexport type AgentStatus = (typeof AGENT_STATUSES)[number]-export interface PresencePoint {- x: number- y: number- pageId: string-}-/** A person's pointer, with the zoom they view it at so followers can match it. */-export interface PersonPoint extends PresencePoint {+export interface PersonPoint extends PagePoint {zoom?: number}@@ -34,7 +30,7 @@ export interface AgentPresence {/** The page the agent works on, known before its first edit. */pageId?: string/** Where the agent last worked, derived from the nodes it touched. */- cursor?: PresencePoint+ cursor?: PagePointselection?: string[]/** Outlines, in world coordinates on the cursor's page, of what is not a layer yet. */outline?: Rect[]diff --git a/src/app/settings/preferences/apply.ts b/src/app/settings/preferences/apply.tsindex 71027fcd8..699fe733f 100644--- a/src/app/settings/preferences/apply.ts+++ b/src/app/settings/preferences/apply.ts@@ -2,9 +2,14 @@ import type { SnappingPreferences } from '@open-pencil/core/editor'import { getTabsSnapshot } from '@/app/tabs'-import { syncNativeDesignIssuesMenu, syncNativeSnappingMenu } from './native-menu'+import {+ syncNativeCommentsMenu,+ syncNativeDesignIssuesMenu,+ syncNativeSnappingMenu+} from './native-menu'import {appPreferences,+ updateCommentPreferences,updateDesignCheckPreferences,updateSnappingPreferences,type DesignCheckPreset@@ -49,3 +54,11 @@ export function turnOffDesignCheckRule(ruleId: string): void {export function turnOnDesignCheckRules(): void {updateDesignCheckPreferences({ disabledRules: [] })}++/** View → Comments: pins outside the Comment tool, here and in the native menu. */+export function setCommentsOnCanvas(showOnCanvas: boolean): void {+ updateCommentPreferences({ showOnCanvas })+ void syncNativeCommentsMenu(showOnCanvas).catch((error: unknown) => {+ console.error('[Settings] Failed to synchronize the native comments menu:', error)+ })+}diff --git a/src/app/settings/preferences/native-menu.ts b/src/app/settings/preferences/native-menu.tsindex ee91d53fe..05b77e670 100644--- a/src/app/settings/preferences/native-menu.ts+++ b/src/app/settings/preferences/native-menu.ts@@ -3,6 +3,7 @@ import type { SnappingPreferences } from '@open-pencil/core/editor'import { isTauri } from '@/app/tauri/env'export const DESIGN_ISSUES_MENU_ID = 'view-design-issues'+export const COMMENTS_MENU_ID = 'view-comments'const SNAPPING_MENU_IDS = {geometry: 'snap-geometry',@@ -28,3 +29,10 @@ export async function syncNativeDesignIssuesMenu(showOnCanvas: boolean): Promiseconst { invoke } = await import('@tauri-apps/api/core')await invoke('set_native_menu_checked', { id: DESIGN_ISSUES_MENU_ID, checked: showOnCanvas })}++/** View → Comments, which Shift+C and the comment menus also toggle. */+export async function syncNativeCommentsMenu(shown: boolean): Promise<void> {+ if (!isTauri()) return+ const { invoke } = await import('@tauri-apps/api/core')+ await invoke('set_native_menu_checked', { id: COMMENTS_MENU_ID, checked: shown })+}diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex 2b03b40ce..e5ddf1c3c 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -3,6 +3,7 @@ import { uniq } from 'es-toolkit'import * as v from 'valibot'import { DEFAULT_SNAPPING_PREFERENCES, type SnappingPreferences } from '@open-pencil/core/editor'+import { COMMENT_SORTS, type CommentSort } from '@open-pencil/scene-graph'import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'import {@@ -35,6 +36,18 @@ export interface DesignCheckPreferences {disabledRules: string[]}+export interface CommentPreferences {+ /** Pins on the canvas outside the Comment tool; View → Comments, Shift+C. */+ showOnCanvas: boolean+ /** The comments list and the canvas also show resolved threads. */+ showResolved: boolean+ /** The comments list shows only the current page's threads. */+ onlyPage: boolean+ /** The comments list shows only threads you started or replied to. */+ onlyMine: boolean+ sort: CommentSort+}+/** Whether guided AI setup was offered and finished or skipped. */export const AI_SETUP_STATES = ['pending', 'done'] as constexport type AISetupState = (typeof AI_SETUP_STATES)[number]@@ -59,6 +72,7 @@ export interface AppPreferences {canvasMode: CanvasRenderingMode}designCheck: DesignCheckPreferences+ comments: CommentPreferencesonboarding: {aiSetup: AISetupState}@@ -79,6 +93,13 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {},rendering: { canvasMode: 'retained' },designCheck: { showOnCanvas: true, preset: 'recommended', disabledRules: [] },+ comments: {+ showOnCanvas: true,+ showResolved: false,+ onlyPage: false,+ onlyMine: false,+ sort: 'newest'+ },onboarding: { aiSetup: 'pending' }}@@ -134,6 +155,13 @@ const appPreferencesSchema = section({() => [])}),+ comments: section({+ showOnCanvas: v.fallback(v.boolean(), defaults.comments.showOnCanvas),+ showResolved: v.fallback(v.boolean(), defaults.comments.showResolved),+ onlyPage: v.fallback(v.boolean(), defaults.comments.onlyPage),+ onlyMine: v.fallback(v.boolean(), defaults.comments.onlyMine),+ sort: v.fallback(v.picklist(COMMENT_SORTS), defaults.comments.sort)+ }),onboarding: section({aiSetup: v.fallback(v.picklist(AI_SETUP_STATES), defaults.onboarding.aiSetup)})@@ -200,3 +228,10 @@ export function updateDesignCheckPreferences(changes: Partial<DesignCheckPreferedesignCheck: { ...appPreferences.value.designCheck, ...changes }}}++export function updateCommentPreferences(changes: Partial<CommentPreferences>): void {+ appPreferences.value = {+ ...appPreferences.value,+ comments: { ...appPreferences.value.comments, ...changes }+ }+}diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsindex b91433128..cdb40340e 100644--- a/src/app/shell/keyboard/actions.ts+++ b/src/app/shell/keyboard/actions.ts@@ -4,6 +4,7 @@ import { opacityFromBuffer } from '@open-pencil/core/editor'import type { useEditorCommands, useViewportKind } from '@open-pencil/vue'import type { PropertiesTab } from '@/app/ai/chat/use'+import { useComments } from '@/app/comments/use'import type { EditorStore } from '@/app/editor/active-store'type KeyboardActionsOptions = {@@ -78,6 +79,7 @@ export function createKeyboardActions({store.exitContainer()return}+ if (useComments().closeCard()) returnstore.clearSelection()store.setTool('SELECT')}diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsindex fc78ce870..34680dc3f 100644--- a/src/app/shell/keyboard/registry.ts+++ b/src/app/shell/keyboard/registry.ts@@ -5,6 +5,7 @@ import { onScopeDispose } from 'vue'import { editorCommandMetadata } from '@open-pencil/vue'import type { EditorCommandId } from '@open-pencil/vue'+import { useComments } from '@/app/comments/use'import { requestRenameSelection } from '@/app/editor/selection/rename-dialog'import { TOOL_SHORTCUTS } from '@/app/editor/session'import { openSettingsDialog } from '@/app/settings/dialog'@@ -198,6 +199,11 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {run: ({ actions }) => actions.toggleUI()},{ id: 'toggle-ai', keys: '$mod+KeyJ', run: ({ actions }) => actions.toggleAI() },+ {+ id: 'toggle-comments',+ keys: appMenuTinykeysShortcut('view-comments') ?? 'Shift+KeyC',+ run: () => useComments().toggleOnCanvas()+ },{id: 'open-settings',keys: appMenuTinykeysShortcut('settings') ?? '$mod+Comma',diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex c46390c75..962e9216e 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -23,7 +23,11 @@ import { shortcutPlatform, useEditorCommands, useI18n } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'import { openVariablesDialog } from '@/app/editor/tokens/dialog'import { openSettingsDialog } from '@/app/settings/dialog'-import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'+import {+ setCommentsOnCanvas,+ setDesignIssuesOnCanvas,+ setSnappingPreference+} from '@/app/settings/preferences/apply'import { appPreferences } from '@/app/settings/preferences/store'import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'import { openStorageWorkspace } from '@/app/shell/menu/navigation'@@ -120,6 +124,7 @@ export function useAppMenu() {'view-pixel-grid': 'pixelGrid','view-multiplayer-cursors': 'multiplayerCursors','view-design-issues': 'designIssues',+ 'view-comments': 'comments','snap-geometry': 'snapToGeometry','snap-objects': 'snapToObjects','snap-pixel-grid': 'snapToPixelGrid',@@ -203,6 +208,8 @@ export function useAppMenu() {return store.state.showRemoteCursorscase 'view-design-issues':return appPreferences.value.designCheck.showOnCanvas+ case 'view-comments':+ return appPreferences.value.comments.showOnCanvascase 'snap-geometry':return store.state.snappingPreferences.geometrycase 'snap-objects':@@ -242,6 +249,8 @@ export function useAppMenu() {}case 'view-design-issues':return (value: boolean) => setDesignIssuesOnCanvas(value)+ case 'view-comments':+ return (value: boolean) => setCommentsOnCanvas(value)case 'snap-geometry':return (value: boolean) => setSnappingPreference('geometry', value)case 'snap-objects':diff --git a/src/app/shell/menu/editor-actions.ts b/src/app/shell/menu/editor-actions.tsindex c9750f0d0..498275d75 100644--- a/src/app/shell/menu/editor-actions.ts+++ b/src/app/shell/menu/editor-actions.ts@@ -1,7 +1,11 @@import type { SceneNode } from '@open-pencil/scene-graph'import { useEditorStore } from '@/app/editor/active-store'-import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'+import {+ setCommentsOnCanvas,+ setDesignIssuesOnCanvas,+ setSnappingPreference+} from '@/app/settings/preferences/apply'import { appPreferences } from '@/app/settings/preferences/store'type TextFormatUpdates = {@@ -70,6 +74,7 @@ export function createSharedEditorMenuActions(},'view-design-issues': () =>setDesignIssuesOnCanvas(!appPreferences.value.designCheck.showOnCanvas),+ 'view-comments': () => setCommentsOnCanvas(!appPreferences.value.comments.showOnCanvas),'snap-geometry': () =>setSnappingPreference('geometry', !store.state.snappingPreferences.geometry),'snap-objects': () =>diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex 38f367448..ec1fbe7ff 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -195,6 +195,7 @@ export const APP_MENU_SCHEMA = [shortcut: 'ALT+MOD+\\'},{ id: 'view-design-issues', label: 'Design Issues', checkbox: true, handler: 'shell' },+ { id: 'view-comments', label: 'Comments', checkbox: true, shortcut: 'SHIFT+C' },{ type: 'separator' },{id: 'theme',diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.tsindex f9dbd2d74..049590fcd 100644--- a/src/app/shell/menu/shell.ts+++ b/src/app/shell/menu/shell.ts@@ -4,6 +4,7 @@ import { requestAppExit } from '@/app/document/close/exit'import { openSettingsDialog } from '@/app/settings/dialog'import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'import {+ syncNativeCommentsMenu,syncNativeDesignIssuesMenu,syncNativeSnappingMenu} from '@/app/settings/preferences/native-menu'@@ -42,6 +43,12 @@ export function useShellMenu() {})+ void syncNativeCommentsMenu(appPreferences.value.comments.showOnCanvas).catch(+ (error: unknown) => {+ console.error('[Menu] Failed to synchronize the native comments menu:', error)+ }+ )+const { setTheme } = useAppTheme()const { updates } = useI18n()const actions: Partial<Record<string, () => void>> = {diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 6f7531cf3..1775be55c 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -40,6 +40,7 @@ import { createCanvasContextSelection } from '@/app/editor/canvas/context-selectimport { canvasOverlayObstacles } from '@/app/editor/canvas/obstacles'import { useFollowView } from '@/app/presence/follow-view'import { appRuntimeConfig } from '@/app/runtime/config'+import CommentsLayer from '@/components/comments/CommentsLayer.vue'import IssueMarkerTooltip from '@/components/design-check/IssueMarkerTooltip.vue'import PreparationOverlay from '@/components/preparation/canvas/Overlay.vue'import FollowFrame from '@/components/presence/FollowFrame.vue'@@ -312,6 +313,7 @@ const cursor = computed(() =>:followed="followView.label.value"@stop="followView.stop"/>+ <CommentsLayer v-if="isActivePane" :canvas-el="canvasRef" :drawn="drawnView" /><PreparationOverlayv-if="store.state.preparation && store.state.preparation.kind !== 'font-retry'":preparation="store.state.preparation"diff --git a/src/components/MobileDrawer.vue b/src/components/MobileDrawer.vueindex 680994e67..00cafa4a4 100644--- a/src/components/MobileDrawer.vue+++ b/src/components/MobileDrawer.vue@@ -20,6 +20,7 @@ import {import ChatPanel from './ChatPanel.vue'import CodePanel from './CodePanel.vue'+import CommentsPanel from './comments/CommentsPanel.vue'import DesignPanel from './DesignPanel.vue'import LayerTree from './LayerTree/LayerTree.vue'import PagesPanel from './PagesPanel.vue'@@ -187,7 +188,9 @@ const drawerTransition = useMotionTransition({<TabsContent value="design" class="mt-0 h-full data-[state=inactive]:hidden"><div data-test-id="mobile-drawer-design" class="flex h-full flex-col">- <DesignPanel />+ <!-- The Comment tool turns the properties into the comments list, as on desktop. -->+ <CommentsPanel v-if="store.state.activeTool === 'COMMENT'" />+ <DesignPanel v-else /></div></TabsContent>diff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vueindex 7fbe1270b..5ada7442a 100644--- a/src/components/PropertiesPanel.vue+++ b/src/components/PropertiesPanel.vue@@ -11,6 +11,7 @@ import { propertiesTabs } from '@/theme/panel/properties-tabs'import ChatPanel from './ChatPanel.vue'import CodePanel from './CodePanel.vue'+import CommentsPanel from './comments/CommentsPanel.vue'import DesignCheckPanel from './design-check/DesignCheckPanel.vue'import DesignPanel from './DesignPanel.vue'import ZoomDropdown from './editor/ZoomDropdown.vue'@@ -21,6 +22,8 @@ const checkMessages = useDesignCheckMessages()const store = useEditorStore()const tabStyles = propertiesTabs()+/** The Comment tool turns the sidebar into the comments list, as in Figma; the tabs keep their state. */+const commenting = computed(() => store.state.activeTool === 'COMMENT')/** Errors and warnings on the current page; suggestions do not earn an indicator. */const problemCount = computed(() => {@@ -37,7 +40,8 @@ const problemCount = computed(() => {class="flex min-w-0 flex-1 flex-col overflow-hidden border-l border-border bg-panel"style="contain: paint layout style">- <TabsRoot v-model="activeTab" class="flex min-h-0 flex-1 flex-col">+ <CommentsPanel v-if="commenting" />+ <TabsRoot v-show="!commenting" v-model="activeTab" class="flex min-h-0 flex-1 flex-col"><TabsList :class="tabStyles.list()"><TabsTriggervalue="design"diff --git a/src/components/Toolbar/Toolbar.vue b/src/components/Toolbar/Toolbar.vueindex 589803e6c..0b8a31951 100644--- a/src/components/Toolbar/Toolbar.vue+++ b/src/components/Toolbar/Toolbar.vue@@ -37,7 +37,8 @@ const toolLabels = computed<Record<Tool, string>>(() => ({STAR: toolTexts.value.star,PEN: toolTexts.value.pen,TEXT: toolTexts.value.text,- HAND: toolTexts.value.hand+ HAND: toolTexts.value.hand,+ COMMENT: toolTexts.value.comment}))const toolShortcuts: Record<Tool, string> = {@@ -51,7 +52,8 @@ const toolShortcuts: Record<Tool, string> = {STAR: '',PEN: 'P',TEXT: 'T',- HAND: 'H'+ HAND: 'H',+ COMMENT: 'C'}const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })diff --git a/src/components/comments/CommentActionsMenu.vue b/src/components/comments/CommentActionsMenu.vuenew file mode 100644index 000000000..d2b070505--- /dev/null+++ b/src/components/comments/CommentActionsMenu.vue@@ -0,0 +1,100 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import {+ ContextMenuItem,+ ContextMenuSeparator,+ DropdownMenuItem,+ DropdownMenuSeparator+} from 'reka-ui'+import { computed } from 'vue'++import type { CommentThread } from '@open-pencil/scene-graph'+import { useCommentMessages, useCommonMessages } from '@open-pencil/vue'++import { useComments } from '@/app/comments/use'+import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'+import { useActionToast } from '@/app/shell/toast/action'+import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'+import { useMenuUI } from '@/components/ui/menu/menu'++// One list of comment actions for both the right-click menu and the "More actions" button.+const {+ thread,+ kind,+ showGoTo = false,+ showHide = false+} = defineProps<{+ thread: CommentThread+ kind: 'context' | 'dropdown'+ showGoTo?: boolean+ /** Offer Hide comments, as a pin's menu does in Figma. */+ showHide?: boolean+}>()++const comments = useComments()+const messages = useCommentMessages()+const common = useCommonMessages()+const { copy } = useClipboard({ legacy: true })+const { showActionToast } = useActionToast()+const menuCls = useMenuUI({ item: 'justify-start gap-2' })++const Item = computed(() => (kind === 'context' ? ContextMenuItem : DropdownMenuItem))+const Separator = computed(() =>+ kind === 'context' ? ContextMenuSeparator : DropdownMenuSeparator+)++async function copyText() {+ await copy(thread.text)+ showActionToast(common.value.copied)+}+</script>++<template>+ <component+ :is="Item"+ v-if="showGoTo"+ :class="menuCls.item"+ data-command="comment-go-to"+ @select="comments.focusThread(thread.id)"+ >+ <icon-lucide-locate-fixed :class="menuCls.icon" />+ <span>{{ messages.goToComment }}</span>+ </component>+ <component+ :is="Item"+ :class="menuCls.item"+ data-command="comment-resolve"+ @select="comments.setResolved(thread.id, !thread.resolved)"+ >+ <icon-lucide-rotate-ccw v-if="thread.resolved" :class="menuCls.icon" />+ <icon-lucide-circle-check v-else :class="menuCls.icon" />+ <span>{{ thread.resolved ? messages.reopen : messages.resolve }}</span>+ </component>+ <component :is="Item" :class="menuCls.item" data-command="comment-copy" @select="copyText">+ <icon-lucide-copy :class="menuCls.icon" />+ <span>{{ messages.copyText }}</span>+ </component>+ <component :is="Separator" :class="menuCls.separator" />+ <component+ :is="Item"+ :class="menuCls.item"+ data-command="comment-delete"+ @select="comments.requestDelete(thread.id)"+ >+ <icon-lucide-trash-2 :class="menuCls.icon" />+ <span>{{ messages.delete }}</span>+ </component>+ <template v-if="showHide">+ <component :is="Separator" :class="menuCls.separator" />+ <component+ :is="Item"+ :class="menuCls.item"+ data-command="comments-hide"+ @select="comments.toggleOnCanvas"+ >+ <icon-lucide-eye-off :class="menuCls.icon" />+ <span class="flex-1">{{ messages.hideComments }}</span>+ <AppShortcutText>{{ appMenuShortcutLabel('view-comments') }}</AppShortcutText>+ </component>+ </template>+</template>diff --git a/src/components/comments/CommentComposer.vue b/src/components/comments/CommentComposer.vuenew file mode 100644index 000000000..06a8c9587--- /dev/null+++ b/src/components/comments/CommentComposer.vue@@ -0,0 +1,114 @@+<script setup lang="ts">+import { useTextareaAutosize } from '@vueuse/core'+import { computed, nextTick, useTemplateRef } from 'vue'++import { shortcutPlatform, useCommentMessages } from '@open-pencil/vue'++import {+ commentFormatForKey,+ continueList,+ formatComment,+ type CommentEdit+} from '@/app/comments/format'+import AppButton from '@/components/ui/button/AppButton.vue'+import { comments } from '@/theme/comments'++/**+ * Where a comment or reply is written. Enter sends and Shift+Enter starts a new line or list+ * item; Figma's shortcuts format the selection as Markdown (`format.ts`).+ */+const { label, bare = false } = defineProps<{+ label: string+ /** The composer is its card's whole content, as a new comment's is. */+ bare?: boolean+}>()++const emit = defineEmits<{ submit: [text: string]; cancel: [] }>()++const text = defineModel<string>({ default: '' })+const input = useTemplateRef<HTMLTextAreaElement>('input')+useTextareaAutosize({ element: input, input: text })++const messages = useCommentMessages()+const ui = computed(() => comments({ bare }))+const empty = computed(() => text.value.trim() === '')+const mac = shortcutPlatform() === 'mac'++function submit() {+ if (empty.value) return+ emit('submit', text.value.trim())+}++function apply(next: CommentEdit) {+ text.value = next.value+ void nextTick(() => input.value?.setSelectionRange(next.start, next.end))+}++function onKeydown(event: KeyboardEvent) {+ const element = input.value+ // Enter also confirms a word in an input method; that is not sending.+ if (!element || event.isComposing) return+ const current = {+ value: text.value,+ start: element.selectionStart,+ end: element.selectionEnd+ }+ if (event.code === 'Enter' || event.code === 'NumpadEnter') {+ if (event.altKey || event.metaKey || event.ctrlKey) return+ if (!event.shiftKey) {+ event.preventDefault()+ submit()+ return+ }+ const next = continueList(current)+ if (!next) return+ event.preventDefault()+ apply(next)+ return+ }+ const format = commentFormatForKey({+ code: event.code,+ shiftKey: event.shiftKey,+ altKey: event.altKey,+ mod: mac ? event.metaKey : event.ctrlKey+ })+ if (!format) return+ // The editor binds some of these keys too, such as Cmd+K for the command palette.+ event.preventDefault()+ event.stopPropagation()+ apply(formatComment(current, format))+}++function focus() {+ input.value?.focus()+}++defineExpose({ focus })+</script>++<template>+ <form data-slot="comment-composer" :class="ui.composer()" @submit.prevent="submit">+ <textarea+ ref="input"+ v-model="text"+ rows="1"+ :aria-label="label"+ :placeholder="label"+ :class="ui.composerInput()"+ @keydown="onKeydown"+ @keydown.escape.stop.prevent="emit('cancel')"+ />+ <AppButton+ type="submit"+ color="primary"+ variant="solid"+ shape="pill"+ size="xs"+ :disabled="empty"+ :aria-label="messages.send"+ :ui="{ base: 'size-6 shrink-0 px-0' }"+ >+ <icon-lucide-arrow-up class="size-3.5" />+ </AppButton>+ </form>+</template>diff --git a/src/components/comments/CommentDeleteDialog.vue b/src/components/comments/CommentDeleteDialog.vuenew file mode 100644index 000000000..c90c069f8--- /dev/null+++ b/src/components/comments/CommentDeleteDialog.vue@@ -0,0 +1,43 @@+<script setup lang="ts">+import { ref } from 'vue'++import { useCommentMessages, useCommonMessages } from '@open-pencil/vue'++import { useComments } from '@/app/comments/use'+import { useActionToast } from '@/app/shell/toast/action'+import { AppConfirmationDialog } from '@/components/ui/dialog'++/** Asks before a comment is deleted for everyone, wherever the deletion was asked for. */+const comments = useComments()+const messages = useCommentMessages()+const common = useCommonMessages()+const { showActionToast } = useActionToast()++// The dialog closes itself before it confirms, so it keeps which comment it was asked about.+const open = ref(false)+const target = ref<string | null>(null)++comments.onDeleteRequested((id) => {+ target.value = id+ open.value = true+})++function confirm() {+ if (!target.value) return+ comments.confirmDelete(target.value)+ target.value = null+ showActionToast(messages.value.commentDeleted)+}+</script>++<template>+ <AppConfirmationDialog+ v-model:open="open"+ :heading="messages.deleteComment"+ :description="messages.deleteCommentDescription"+ :cancel-label="common.cancel"+ :confirm-label="messages.delete"+ tone="danger"+ @confirm="confirm"+ />+</template>diff --git a/src/components/comments/CommentListItem.stories.ts b/src/components/comments/CommentListItem.stories.tsnew file mode 100644index 000000000..8668ea3c0--- /dev/null+++ b/src/components/comments/CommentListItem.stories.ts@@ -0,0 +1,49 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'++import type { CommentThread } from '@open-pencil/scene-graph'++import CommentListItem from './CommentListItem.vue'+import CommentPin from './CommentPin.vue'+import { discussed, long, resolved } from './examples/threads'++type Args = { thread: CommentThread; number: number; pageName: string; active: boolean }++const meta = {+ title: 'App/Editor/Comments/List Item',+ component: CommentListItem,+ tags: ['autodocs'],+ args: { thread: discussed, number: 4, pageName: 'Checkout', active: false },+ render: (args) => ({+ components: { CommentListItem },+ setup: () => ({ args }),+ template: '<ul class="w-64 bg-panel"><CommentListItem v-bind="args" /></ul>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++/** Who took part, where, and a plain preview of the Markdown. */+export const Discussed: Story = {}++export const Active: Story = { args: { active: true } }++export const Resolved: Story = { args: { thread: resolved, number: 2 } }++export const LongText: Story = { args: { thread: long, number: 7 } }++/** Pins as they sit on the canvas: an author's avatar, open, resolved, and one being written. */+export const Pins: StoryObj = {+ render: () => ({+ components: { CommentPin },+ setup: () => ({ discussed }),+ template: `+ <div class="relative h-24 w-72 rounded-lg bg-canvas">+ <CommentPin :author="discussed.author" :color="discussed.authorColor" aria-label="Dana Scully" class="top-16 left-6" />+ <CommentPin :author="discussed.author" :color="discussed.authorColor" active aria-label="Dana Scully, open" class="top-16 left-24" />+ <CommentPin :author="discussed.author" :color="discussed.authorColor" resolved aria-label="Dana Scully, resolved" class="top-16 left-42" />+ <CommentPin draft aria-hidden="true" tabindex="-1" class="top-16 left-60" />+ </div>+ `+ })+}diff --git a/src/components/comments/CommentListItem.vue b/src/components/comments/CommentListItem.vuenew file mode 100644index 000000000..a218edfa1--- /dev/null+++ b/src/components/comments/CommentListItem.vue@@ -0,0 +1,77 @@+<script setup lang="ts">+import { uniqBy } from 'es-toolkit'+import { computed } from 'vue'++import { liveReplies, type CommentThread } from '@open-pencil/scene-graph'+import { useCommentMessages } from '@open-pencil/vue'++import { commentPreview } from '@/app/comments/format'+import AvatarStack from '@/components/presence/AvatarStack.vue'+import type { PresencePersonRow } from '@/components/presence/rows'+import { comments } from '@/theme/comments'++import { useCommentAuthor } from './author'+import CommentTime from './CommentTime.vue'++/** A thread in the comments list: who took part, where it is, and how it starts. */+const {+ thread,+ number,+ pageName = '',+ active = false+} = defineProps<{+ thread: CommentThread+ /** Its place among the document's threads, as Figma numbers them. */+ number: number+ pageName?: string+ active?: boolean+}>()++const emit = defineEmits<{ select: [] }>()++defineSlots<{ actions?(): unknown }>()++const messages = useCommentMessages()+const author = useCommentAuthor()+const ui = comments()++const replies = computed(() => liveReplies(thread))+// Everyone in the thread, first to speak first; the stack keys them by position.+const people = computed<PresencePersonRow[]>(() =>+ uniqBy([thread, ...replies.value], (entry) => entry.author).map((entry, index) => ({+ clientId: index,+ name: author.name(entry.author),+ color: author.color(entry.authorColor),+ agents: []+ }))+)+</script>++<template>+ <li+ data-slot="comment-list-item"+ :data-active="active || undefined"+ :data-resolved="thread.resolved || undefined"+ :class="ui.item()"+ >+ <button type="button" :class="ui.itemButton()" @click="emit('select')">+ <span :class="ui.itemTop()">+ <AvatarStack+ :people="people"+ :max="3"+ :label="people.map((person) => person.name).join(', ')"+ />+ <span :class="ui.itemPlace()">#{{ number }} · {{ pageName }}</span>+ </span>+ <span :class="ui.itemMeta()">+ <span :class="ui.messageAuthor()">{{ author.name(thread.author) }}</span>+ <CommentTime :at="thread.createdAt" :class="ui.messageTime()" />+ </span>+ <span :class="ui.itemText()">{{ commentPreview(thread.text) }}</span>+ <span v-if="replies.length" :class="ui.itemReplies()">+ {{ messages.replyCount({ count: replies.length }) }}+ </span>+ </button>+ <span v-if="$slots.actions" :class="ui.itemActions()"><slot name="actions" /></span>+ </li>+</template>diff --git a/src/components/comments/CommentMessage.vue b/src/components/comments/CommentMessage.vuenew file mode 100644index 000000000..34ab94611--- /dev/null+++ b/src/components/comments/CommentMessage.vue@@ -0,0 +1,35 @@+<script setup lang="ts">+import type { Color } from '@open-pencil/scene-graph/primitives'++import MarkdownContent from '@/components/markdown/MarkdownContent.vue'+import PersonAvatar from '@/components/presence/PersonAvatar.vue'+import { comments } from '@/theme/comments'++import { useCommentAuthor } from './author'+import CommentTime from './CommentTime.vue'++/** One message of a thread: who wrote it, when, and what. */+const { author, color, at, text } = defineProps<{+ author: string+ color?: Color+ at: string+ text: string+}>()++defineSlots<{ actions?(): unknown }>()++const who = useCommentAuthor()+const ui = comments()+</script>++<template>+ <article data-slot="comment-message" :class="ui.message()">+ <PersonAvatar :name="who.name(author)" :color="who.color(color)" />+ <div :class="ui.messageMeta()">+ <span :class="ui.messageAuthor()">{{ who.name(author) }}</span>+ <CommentTime :at="at" :class="ui.messageTime()" />+ <span v-if="$slots.actions" :class="ui.messageActions()"><slot name="actions" /></span>+ </div>+ <MarkdownContent :content="text" :class="ui.messageText()" />+ </article>+</template>diff --git a/src/components/comments/CommentPin.vue b/src/components/comments/CommentPin.vuenew file mode 100644index 000000000..10ff932ec--- /dev/null+++ b/src/components/comments/CommentPin.vue@@ -0,0 +1,66 @@+<script setup lang="ts">+import type { Color } from '@open-pencil/scene-graph/primitives'++import { commentPreview } from '@/app/comments/format'+import PersonAvatar from '@/components/presence/PersonAvatar.vue'+import { comments } from '@/theme/comments'++import { useCommentAuthor } from './author'+import CommentTime from './CommentTime.vue'++/**+ * A comment on the canvas: its author's avatar in a bubble pointing at the spot. Hovering opens+ * the bubble in place into the start of the comment, as in Figma.+ */+const {+ author = '',+ color,+ text = '',+ at = '',+ active = false,+ resolved = false,+ dragging = false,+ draft = false+} = defineProps<{+ author?: string+ color?: Color+ text?: string+ at?: string+ active?: boolean+ resolved?: boolean+ dragging?: boolean+ /** A comment still being written: an empty bubble, as Figma draws it. */+ draft?: boolean+}>()++const who = useCommentAuthor()+const ui = comments()+</script>++<template>+ <button+ type="button"+ data-slot="comment-pin"+ :data-active="active || undefined"+ :data-resolved="resolved || undefined"+ :data-dragging="dragging || undefined"+ :data-draft="draft || undefined"+ :class="ui.pin()"+ >+ <template v-if="!draft">+ <PersonAvatar :name="author" :color="who.color(color)" />+ <!-- An open or moving pin stays a bubble; its thread or its new place is what matters. -->+ <span v-if="text && !active && !dragging" :class="ui.pinPreview()" aria-hidden="true">+ <span :class="ui.pinPreviewClip()">+ <span :class="ui.pinPreviewBody()">+ <span :class="ui.messageMeta()">+ <span :class="ui.messageAuthor()">{{ author }}</span>+ <CommentTime v-if="at" :at="at" :class="ui.messageTime()" />+ </span>+ <span :class="ui.pinText()">{{ commentPreview(text) }}</span>+ </span>+ </span>+ </span>+ </template>+ </button>+</template>diff --git a/src/components/comments/CommentThreadCard.stories.ts b/src/components/comments/CommentThreadCard.stories.tsnew file mode 100644index 000000000..8618c4e73--- /dev/null+++ b/src/components/comments/CommentThreadCard.stories.ts@@ -0,0 +1,73 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { TooltipProvider } from 'reka-ui'+import { expect, fn, userEvent, within } from 'storybook/test'++import type { CommentThread } from '@open-pencil/scene-graph'++import CommentComposer from './CommentComposer.vue'+import CommentThreadCard from './CommentThreadCard.vue'+import { discussed, long, resolved } from './examples/threads'++type Args = { thread: CommentThread; onReply: (threadId: string, text: string) => void }++const meta = {+ title: 'App/Editor/Comments/Thread Card',+ component: CommentThreadCard,+ tags: ['autodocs'],+ args: { thread: discussed, onReply: fn() },+ render: (args) => ({+ components: { CommentThreadCard, TooltipProvider },+ setup: () => ({ args }),+ template: `+ <TooltipProvider>+ <div class="flex max-h-[28rem] w-80 flex-col overflow-hidden rounded-xl bg-panel shadow-[0_0_0_1px_var(--color-border)]">+ <CommentThreadCard :thread="args.thread" @reply="args.onReply" />+ </div>+ </TooltipProvider>+ `+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++/** Markdown from Figma's formatting: bold, italic, strikethrough, a list and a link. */+export const Formatted: Story = {}++export const Resolved: Story = { args: { thread: resolved } }++export const LongThread: Story = { args: { thread: long } }++export const Replying: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement)+ const reply = canvas.getByRole('textbox', { name: 'Reply' })+ await userEvent.type(reply, 'Looks right')+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}')+ await userEvent.type(reply, 'Shipping it')+ await userEvent.keyboard('{Enter}')+ await expect(args.onReply).toHaveBeenCalledWith(discussed.id, 'Looks right\nShipping it')+ await expect(reply).toHaveValue('')+ }+}++/** The composer on its own, as it opens on a new pin: Shift+Enter continues a list, then ends it. */+export const NewComment: StoryObj<{ onSubmit: (text: string) => void }> = {+ args: { onSubmit: fn() },+ render: (args) => ({+ components: { CommentComposer },+ setup: () => ({ args }),+ template:+ '<div class="w-72 rounded-xl bg-panel p-2 shadow-[0_0_0_1px_var(--color-border)]"><CommentComposer label="Add a comment" @submit="args.onSubmit" /></div>'+ }),+ play: async ({ canvasElement, args }) => {+ const input = within(canvasElement).getByRole('textbox', { name: 'Add a comment' })+ await userEvent.type(input, '- first')+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}')+ await expect(input).toHaveValue('- first\n- ')+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}')+ await expect(input).toHaveValue('- first\n')+ await userEvent.keyboard('{Enter}')+ await expect(args.onSubmit).toHaveBeenCalledWith('- first')+ }+}diff --git a/src/components/comments/CommentThreadCard.vue b/src/components/comments/CommentThreadCard.vuenew file mode 100644index 000000000..0d35961ec--- /dev/null+++ b/src/components/comments/CommentThreadCard.vue@@ -0,0 +1,123 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed, ref, useTemplateRef } from 'vue'++import { liveReplies, type CommentThread } from '@open-pencil/scene-graph'+import { useCommentMessages, useCommonMessages } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import { useMenuUI } from '@/components/ui/menu/menu'+import PanelHeader from '@/components/ui/panel/PanelHeader.vue'+import { comments } from '@/theme/comments'++import CommentComposer from './CommentComposer.vue'+import CommentMessage from './CommentMessage.vue'++/** An open thread: the comment, its replies, and a reply box, as in Figma's comment card. */+const { thread } = defineProps<{ thread: CommentThread }>()++const emit = defineEmits<{+ close: []+ resolve: [threadId: string, resolved: boolean]+ reply: [threadId: string, text: string]+ deleteReply: [threadId: string, replyId: string]+}>()++defineSlots<{ menu?(): unknown }>()++const messages = useCommentMessages()+const common = useCommonMessages()+const menuCls = useMenuUI({ content: 'min-w-40' })+const ui = comments()+const replyText = ref('')+const composer = useTemplateRef<{ focus: () => void }>('composer')+const replies = computed(() => liveReplies(thread))++function sendReply(text: string) {+ emit('reply', thread.id, text)+ replyText.value = ''+}++defineExpose({ focus: () => composer.value?.focus() })+</script>++<template>+ <section+ data-slot="comment-thread"+ :data-resolved="thread.resolved || undefined"+ :aria-label="messages.comment"+ :class="ui.threadCard()"+ >+ <PanelHeader>+ <template #icon><icon-lucide-message-circle class="size-3.5" /></template>+ {{ messages.comment }}+ <template #actions>+ <DropdownMenuRoot v-if="$slots.menu" :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="messages.moreActions">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4">+ <slot name="menu" />+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ <IconButton+ :label="thread.resolved ? messages.reopen : messages.resolve"+ :active="thread.resolved"+ data-command="comment-resolve"+ @click="emit('resolve', thread.id, !thread.resolved)"+ >+ <icon-lucide-circle-check-big v-if="thread.resolved" class="size-3.5" />+ <icon-lucide-circle-check v-else class="size-3.5" />+ </IconButton>+ <IconButton :label="common.close" @click="emit('close')">+ <icon-lucide-x class="size-3.5" />+ </IconButton>+ </template>+ </PanelHeader>++ <div :class="ui.thread()">+ <CommentMessage+ :author="thread.author"+ :color="thread.authorColor"+ :at="thread.createdAt"+ :text="thread.text"+ />+ <CommentMessage+ v-for="entry in replies"+ :key="entry.id"+ :author="entry.author"+ :color="entry.authorColor"+ :at="entry.createdAt"+ :text="entry.text"+ >+ <template #actions>+ <IconButton+ :label="messages.deleteReply"+ @click="emit('deleteReply', thread.id, entry.id)"+ >+ <icon-lucide-trash-2 class="size-3" />+ </IconButton>+ </template>+ </CommentMessage>+ </div>++ <div :class="ui.composerSlot()">+ <CommentComposer+ ref="composer"+ v-model="replyText"+ :label="messages.reply"+ @submit="sendReply"+ @cancel="emit('close')"+ />+ </div>+ </section>+</template>diff --git a/src/components/comments/CommentTime.vue b/src/components/comments/CommentTime.vuenew file mode 100644index 000000000..9d934a280--- /dev/null+++ b/src/components/comments/CommentTime.vue@@ -0,0 +1,17 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { formatCommentTime, useCommentClock } from '@/app/comments/time'++const { at } = defineProps<{ at: string }>()++const now = useCommentClock()+const { locale } = useI18n()+const label = computed(() => formatCommentTime(at, now.value.getTime(), locale.value))+</script>++<template>+ <time :datetime="at">{{ label }}</time>+</template>diff --git a/src/components/comments/CommentsLayer.vue b/src/components/comments/CommentsLayer.vuenew file mode 100644index 000000000..c44cf2820--- /dev/null+++ b/src/components/comments/CommentsLayer.vue@@ -0,0 +1,265 @@+<script setup lang="ts">+import {+ ContextMenuContent,+ ContextMenuPortal,+ ContextMenuRoot,+ ContextMenuTrigger,+ PopoverContent,+ PopoverPortal,+ PopoverRoot+} from 'reka-ui'+import { computed, ref, useTemplateRef, watch } from 'vue'++import type { ViewportTransform } from '@open-pencil/core/geometry'+import type { Vector } from '@open-pencil/scene-graph/primitives'+import { useCommentMessages } from '@open-pencil/vue'++import { useComments } from '@/app/comments/use'+import { useEditorStore } from '@/app/editor/active-store'+import { useMenuUI } from '@/components/ui/menu/menu'+import { usePopoverUI } from '@/components/ui/overlay/popover'+import { COMMENT_PIN_SIZE, comments as commentsTheme } from '@/theme/comments'++import { useCommentAuthor } from './author'+import CommentActionsMenu from './CommentActionsMenu.vue'+import CommentComposer from './CommentComposer.vue'+import CommentPin from './CommentPin.vue'+import CommentThreadCard from './CommentThreadCard.vue'+import { usePinDrag } from './usePinDrag'++const { canvasEl, drawn = null } = defineProps<{+ canvasEl: HTMLCanvasElement | null+ /**+ * The pan and zoom of the canvas's last drawn frame. Pins follow it rather than the live view,+ * which runs ahead of the drawing while panning fast, as preview islands do.+ */+ drawn?: ViewportTransform | null+}>()++/** Room between a card and its pin's bubble. */+const CARD_GAP = 8++const store = useEditorStore()+const comments = useComments()+const messages = useCommentMessages()+const author = useCommentAuthor()+const menuCls = useMenuUI({ content: 'min-w-40' })+const ui = commentsTheme()+const threadCls = usePopoverUI({ content: ui.card() })+const draftCls = usePopoverUI({ content: ui.draftCard() })+const { activeThreadId, draft, showOnCanvas, listShowResolved } = comments+const commenting = computed(() => store.state.activeTool === 'COMMENT')++const draftText = ref('')+const draftComposer = useTemplateRef<{ focus: () => void }>('draftComposer')+const threadCard = useTemplateRef<{ focus: () => void }>('threadCard')++// Picking another tool drops a comment that was never sent, as in Figma.+watch(commenting, (on) => {+ if (!on) draft.value = null+})++const placement = computed<ViewportTransform>(() => drawn ?? store.state)++/** A canvas point in the pins' layer, which panning moves as a whole. */+function toLayer(at: Vector) {+ return { left: at.x * placement.value.zoom, top: at.y * placement.value.zoom }+}++function toScreen(at: Vector) {+ const { left, top } = toLayer(at)+ return { left: left + placement.value.panX, top: top + placement.value.panY }+}++const pinDrag = usePinDrag({+ zoom: () => store.state.zoom,+ onDrop: comments.movePin,+ onClick: comments.toggleThread+})++// Pins show unless View → Comments hid them; the Comment tool always shows them, as in Figma.+const pins = computed(() => {+ // Layers move without the comment changing; re-place pins on every scene change.+ void store.state.sceneVersion+ if (!showOnCanvas.value && !commenting.value) return []+ const pageId = store.state.currentPageId+ return comments.threads.value+ .filter(+ (thread) =>+ !thread.deleted && thread.pageId === pageId && (!thread.resolved || listShowResolved.value)+ )+ .map((thread) => {+ const dragged = pinDrag.draggedTo(thread.id)+ const at = dragged ?? comments.pinPosition(thread)+ return { thread, at, dragging: dragged !== null, ...toLayer(at) }+ })+})++const activePin = computed(() => pins.value.find((pin) => pin.thread.id === activeThreadId.value))+const draftAt = computed(() =>+ draft.value && draft.value.pageId === store.state.currentPageId ? draft.value : null+)+const draftPlace = computed(() => draftAt.value && toLayer(draftAt.value))++// The card sits beside the pin's bubble, which rises above and right of the commented spot,+// on whichever side has room; the bubble's box is what it keeps clear of.+const cardAnchor = computed(() => activePin.value?.at ?? draftAt.value ?? null)+const cardReference = computed(() => {+ const at = cardAnchor.value+ const canvas = canvasEl+ if (!at || !canvas) return null+ const { left, top } = toScreen(at)+ return {+ getBoundingClientRect() {+ const rect = canvas.getBoundingClientRect()+ return new DOMRect(+ rect.left + left,+ rect.top + top - COMMENT_PIN_SIZE,+ COMMENT_PIN_SIZE,+ COMMENT_PIN_SIZE+ )+ }+ }+})++function placeDraft(event: PointerEvent) {+ if (event.button !== 0 || !(event.currentTarget instanceof HTMLElement)) return+ // With a card open, a click on the canvas only closes it, as in Figma.+ if (comments.closeCard()) return+ const rect = event.currentTarget.getBoundingClientRect()+ const at = store.screenToCanvas(event.clientX - rect.left, event.clientY - rect.top)+ comments.startDraft({ pageId: store.state.currentPageId, ...at })+ draftText.value = ''+}++// Scrolling and zooming keep working over pins and while placing comments, as in Figma.+function forwardWheel(event: WheelEvent) {+ if (!canvasEl) return+ event.preventDefault()+ canvasEl.dispatchEvent(new WheelEvent('wheel', event))+}++function postDraft(text: string) {+ comments.addThread(text)+ draftText.value = ''+}++function focusCard() {+ const card = draftAt.value ? draftComposer.value : threadCard.value+ card?.focus()+}++function onCardOpen(event: Event) {+ event.preventDefault()+ focusCard()+}++// The card stays open when a sent comment becomes its thread or another pin is picked.+const cardKey = computed(() => (draftAt.value ? 'draft' : (activePin.value?.thread.id ?? null)))+watch(cardKey, (key) => key && focusCard(), { flush: 'post' })++// Escape closes the card only; the editor's Escape would leave the Comment tool as well.+function onCardEscape(event: KeyboardEvent) {+ event.stopPropagation()+}++function closeCard() {+ comments.closeCard()+}+</script>++<template>+ <!-- Right-clicks here belong to comments, not to the canvas layer menu underneath; scrolling+ and zooming over pins or while placing comments still reach the canvas. -->+ <div :class="ui.layer()" data-canvas-overlay="comments" @contextmenu.stop @wheel="forwardWheel">+ <div+ v-if="commenting"+ :class="ui.capture()"+ data-slot="comments-capture"+ @pointerdown.prevent="placeDraft"+ @contextmenu.prevent+ />++ <div+ :class="ui.pins()"+ :style="{ transform: `translate(${placement.panX}px, ${placement.panY}px)` }"+ >+ <ContextMenuRoot v-for="pin in pins" :key="pin.thread.id" :modal="false">+ <ContextMenuTrigger as-child>+ <CommentPin+ :author="author.name(pin.thread.author)"+ :color="pin.thread.authorColor"+ :text="pin.thread.text"+ :at="pin.thread.createdAt"+ :active="activeThreadId === pin.thread.id"+ :resolved="pin.thread.resolved"+ :dragging="pin.dragging"+ :style="{ left: `${pin.left}px`, top: `${pin.top}px` }"+ :aria-label="`${author.name(pin.thread.author)}: ${pin.thread.text}`"+ @pointerdown.stop="pinDrag.start($event, pin.thread.id, pin.at)"+ @pointermove="pinDrag.move"+ @pointerup="pinDrag.end"+ @pointercancel="pinDrag.end"+ @click.stop="pinDrag.click(pin.thread.id)"+ />+ </ContextMenuTrigger>+ <ContextMenuPortal>+ <ContextMenuContent :class="menuCls.content">+ <CommentActionsMenu :thread="pin.thread" kind="context" show-hide />+ </ContextMenuContent>+ </ContextMenuPortal>+ </ContextMenuRoot>++ <CommentPin+ v-if="draftPlace"+ draft+ :style="{ left: `${draftPlace.left}px`, top: `${draftPlace.top}px` }"+ aria-hidden="true"+ tabindex="-1"+ />+ </div>++ <PopoverRoot+ :open="!!cardReference && (!!activePin || !!draftAt)"+ @update:open="(open: boolean) => !open && closeCard()"+ >+ <PopoverPortal>+ <PopoverContent+ v-if="cardReference"+ :reference="cardReference"+ side="right"+ :align="draftAt ? 'center' : 'start'"+ :side-offset="CARD_GAP"+ :collision-padding="8"+ :class="draftAt ? draftCls.content : threadCls.content"+ data-canvas-obstacle+ @open-auto-focus="onCardOpen"+ @escape-key-down="onCardEscape"+ >+ <CommentComposer+ v-if="draftAt"+ ref="draftComposer"+ v-model="draftText"+ bare+ :label="messages.addComment"+ @submit="postDraft"+ @cancel="closeCard"+ />+ <CommentThreadCard+ v-else-if="activePin"+ ref="threadCard"+ :thread="activePin.thread"+ @close="closeCard"+ @resolve="comments.setResolved"+ @reply="comments.reply"+ @delete-reply="comments.deleteReply"+ >+ <template #menu>+ <CommentActionsMenu :thread="activePin.thread" kind="dropdown" />+ </template>+ </CommentThreadCard>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+ </div>+</template>diff --git a/src/components/comments/CommentsPanel.vue b/src/components/comments/CommentsPanel.vuenew file mode 100644index 000000000..4e6861cb8--- /dev/null+++ b/src/components/comments/CommentsPanel.vue@@ -0,0 +1,184 @@+<script setup lang="ts">+import {+ ContextMenuContent,+ ContextMenuPortal,+ ContextMenuRoot,+ ContextMenuTrigger,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItemIndicator,+ DropdownMenuPortal,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed } from 'vue'++import { commentThreadNumbers, listCommentThreads } from '@open-pencil/scene-graph'+import { useCommentMessages } from '@open-pencil/vue'++import { useComments } from '@/app/comments/use'+import { useEditorStore } from '@/app/editor/active-store'+import ZoomDropdown from '@/components/editor/ZoomDropdown.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'+import PanelHeader from '@/components/ui/panel/PanelHeader.vue'+import { comments as commentsTheme } from '@/theme/comments'++import CommentActionsMenu from './CommentActionsMenu.vue'+import CommentListItem from './CommentListItem.vue'++/** The comments list that takes over the right sidebar while the Comment tool is active. */+const store = useEditorStore()+const comments = useComments()+const messages = useCommentMessages()+const menuCls = useMenuUI({ content: 'min-w-52' })+const itemCls = menuItem({ justify: 'start', class: 'relative pl-7' })+const ui = commentsTheme()+const { listQuery, listShowResolved, listOnlyPage, listSort, listOnlyMine } = comments++const numbers = computed(() => commentThreadNumbers(comments.threads.value))+const listed = computed(() =>+ listCommentThreads(comments.threads.value, {+ query: listQuery.value,+ showResolved: listShowResolved.value,+ onlyPage: listOnlyPage.value,+ pageId: store.state.currentPageId,+ onlyMine: listOnlyMine.value,+ author: comments.author.value,+ sort: listSort.value+ })+)++const filtered = computed(+ () => listQuery.value.trim() !== '' || listOnlyMine.value || listOnlyPage.value+)++function pageName(pageId: string, fallback?: string) {+ return store.graph.getNode(pageId)?.name ?? fallback ?? ''+}++function setSort(value: unknown) {+ if (value === 'newest' || value === 'oldest') listSort.value = value+}+</script>++<template>+ <section :class="ui.panel()" :aria-label="messages.comments" data-slot="comments-panel">+ <PanelHeader>+ <template #icon><icon-lucide-messages-square class="size-3.5" /></template>+ {{ messages.comments }}+ <template #actions>+ <ZoomDropdown />+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="messages.filterAndSort" :active="filtered">+ <icon-lucide-list-filter class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4">+ <DropdownMenuRadioGroup :model-value="listSort" @update:model-value="setSort">+ <DropdownMenuRadioItem value="newest" :class="itemCls">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ messages.newestFirst }}+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="oldest" :class="itemCls">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ messages.oldestFirst }}+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator :class="menuCls.separator" />+ <DropdownMenuCheckboxItem v-model="listShowResolved" :class="itemCls">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ messages.showResolved }}+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem v-model="listOnlyMine" :class="itemCls">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ messages.onlyMine }}+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem v-model="listOnlyPage" :class="itemCls">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ messages.onlyPage }}+ </DropdownMenuCheckboxItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </template>+ </PanelHeader>++ <div :class="ui.panelSearch()">+ <AppInput+ v-model="listQuery"+ type="search"+ size="sm"+ :aria-label="messages.searchComments"+ :placeholder="messages.searchComments"+ >+ <template #leading><icon-lucide-search class="size-3.5" /></template>+ </AppInput>+ </div>++ <AppPlaceholder+ v-if="listed.length === 0"+ size="compact"+ :label="filtered ? messages.noMatches : messages.empty"+ />+ <ul v-else :class="ui.list()" :aria-label="messages.comments">+ <ContextMenuRoot v-for="thread in listed" :key="thread.id" :modal="false">+ <ContextMenuTrigger as-child>+ <CommentListItem+ :thread="thread"+ :number="numbers.get(thread.id) ?? 0"+ :page-name="pageName(thread.pageId, thread.pageName)"+ :active="comments.activeThreadId.value === thread.id"+ @select="comments.focusThread(thread.id)"+ >+ <template #actions>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="messages.moreActions">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4">+ <CommentActionsMenu :thread="thread" kind="dropdown" show-go-to />+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ <IconButton+ :label="thread.resolved ? messages.reopen : messages.resolve"+ :active="thread.resolved"+ data-command="comment-resolve"+ @click="comments.setResolved(thread.id, !thread.resolved)"+ >+ <icon-lucide-circle-check-big v-if="thread.resolved" class="size-3.5" />+ <icon-lucide-circle-check v-else class="size-3.5" />+ </IconButton>+ </template>+ </CommentListItem>+ </ContextMenuTrigger>+ <ContextMenuPortal>+ <ContextMenuContent :class="menuCls.content">+ <CommentActionsMenu :thread="thread" kind="context" show-go-to />+ </ContextMenuContent>+ </ContextMenuPortal>+ </ContextMenuRoot>+ </ul>+ </section>+</template>diff --git a/src/components/comments/author.ts b/src/components/comments/author.tsnew file mode 100644index 000000000..00f2d2b62--- /dev/null+++ b/src/components/comments/author.ts@@ -0,0 +1,16 @@+import type { Color } from '@open-pencil/scene-graph/primitives'+import { useCommentMessages } from '@open-pencil/vue'++import { PEER_COLORS } from '@/constants'++/**+ * How a comment's author is shown: their name, or "Someone" for comments other tools wrote+ * without one, on the color they had in the room, or the first collaborator color.+ */+export function useCommentAuthor() {+ const messages = useCommentMessages()+ return {+ name: (author: string) => author || messages.value.someone,+ color: (color: Color | undefined): Color => color ?? PEER_COLORS[0]+ }+}diff --git a/src/components/comments/examples/threads.ts b/src/components/comments/examples/threads.tsnew file mode 100644index 000000000..0f92994e7--- /dev/null+++ b/src/components/comments/examples/threads.ts@@ -0,0 +1,56 @@+import type { CommentThread } from '@open-pencil/scene-graph'++// Dark enough for white initials to read, as in the presence stories' sample room.+const red = { r: 0.75, g: 0.16, b: 0.16, a: 1 }+const blue = { r: 0.13, g: 0.4, b: 0.75, a: 1 }++const HOUR = 3_600_000+const ago = (hours: number) => new Date(Date.now() - hours * HOUR).toISOString()++/** A thread with a formatted comment and a reply, as two people leave them. */+export const discussed: CommentThread = {+ id: 'c_1',+ pageId: '0:1',+ pageName: 'Checkout',+ nodeId: '1:2',+ nodeName: 'Order summary',+ x: 120,+ y: 80,+ author: 'Dana Scully',+ authorColor: red,+ text: 'The **total** gets lost here. Could we:\n- make it *bigger*\n- drop the ~~divider~~\n\nSee [the brief](https://openpencil.dev).',+ createdAt: ago(5),+ updatedAt: ago(1),+ resolved: false,+ replies: [+ {+ id: 'r_1',+ author: 'Ben Ortiz',+ authorColor: blue,+ text: 'Done, the total is 20px now.',+ createdAt: ago(1)+ }+ ]+}++export const resolved: CommentThread = {+ ...discussed,+ id: 'c_2',+ text: 'Align the button with the card edge.',+ resolved: true,+ resolvedAt: ago(2),+ replies: []+}++export const long: CommentThread = {+ ...discussed,+ id: 'c_3',+ text: 'A longer note that runs on: the hero image crops the product on small screens, the headline wraps onto three lines at 375px, and the secondary button disappears below the fold, so people never see the free shipping offer that the whole page is built around.',+ replies: Array.from({ length: 6 }, (_, index) => ({+ id: `r_long_${index}`,+ author: index % 2 ? 'Dana Scully' : 'Ben Ortiz',+ authorColor: index % 2 ? red : blue,+ text: index % 2 ? 'Agreed.' : 'Trying a shorter headline now.',+ createdAt: ago(4 - index * 0.5)+ }))+}diff --git a/src/components/comments/usePinDrag.ts b/src/components/comments/usePinDrag.tsnew file mode 100644index 000000000..cb32cb4bd--- /dev/null+++ b/src/components/comments/usePinDrag.ts@@ -0,0 +1,78 @@+import { ref } from 'vue'++import type { Vector } from '@open-pencil/scene-graph/primitives'++/** How far, in screen pixels, a press moves before it drags the pin instead of clicking it. */+const PIN_DRAG_THRESHOLD = 3++interface PinDrag {+ id: string+ startX: number+ startY: number+ origin: Vector+ at: Vector+ moved: boolean+}++/**+ * Dragging comment pins, as in Figma: a press that moves a few pixels drags the pin in canvas+ * units, and dropping it calls `onDrop`; a shorter press is a click, which calls `onClick`.+ */+export function usePinDrag(options: {+ zoom: () => number+ onDrop: (threadId: string, at: Vector) => void+ onClick: (threadId: string) => void+}) {+ const drag = ref<PinDrag | null>(null)+ // The click that ends a drag only drops the pin; browsers differ on whether it comes at all.+ let dropped = false++ function start(event: PointerEvent, threadId: string, origin: Vector) {+ if (event.button !== 0 || !(event.currentTarget instanceof HTMLElement)) return+ event.currentTarget.setPointerCapture(event.pointerId)+ dropped = false+ drag.value = {+ id: threadId,+ startX: event.clientX,+ startY: event.clientY,+ origin,+ at: origin,+ moved: false+ }+ }++ function move(event: PointerEvent) {+ const current = drag.value+ if (!current) return+ const dx = event.clientX - current.startX+ const dy = event.clientY - current.startY+ if (!current.moved && Math.hypot(dx, dy) < PIN_DRAG_THRESHOLD) return+ const zoom = options.zoom()+ current.moved = true+ current.at = { x: current.origin.x + dx / zoom, y: current.origin.y + dy / zoom }+ }++ function end() {+ const current = drag.value+ drag.value = null+ if (!current?.moved) return+ dropped = true+ options.onDrop(current.id, current.at)+ }++ function click(threadId: string) {+ if (dropped) {+ dropped = false+ return+ }+ options.onClick(threadId)+ }++ /** Where a pin being dragged is now, or null when it is not the one moving. */+ function draggedTo(threadId: string): Vector | null {+ const current = drag.value+ return current?.id === threadId && current.moved ? current.at : null+ }++ return { start, move, end, click, draggedTo }+}diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vueindex 96da8741f..99227b1b2 100644--- a/src/components/editor/EditorWorkspace.vue+++ b/src/components/editor/EditorWorkspace.vue@@ -14,6 +14,7 @@ import CanvasSplitRoot from '@/components/canvas/CanvasSplitRoot.vue'import CollabPanel from '@/components/collab-panel/CollabPanel.vue'import ActiveRoomOverlay from '@/components/collab-room/ActiveRoomOverlay.vue'import { useRoomActions } from '@/components/collab-room/useRoomActions'+import CommentDeleteDialog from '@/components/comments/CommentDeleteDialog.vue'import EditorCanvas from '@/components/EditorCanvas.vue'import LayersPanel from '@/components/LayersPanel.vue'import MobileDrawer from '@/components/MobileDrawer.vue'@@ -151,4 +152,5 @@ const { pending: roomPending } = useRoomActions()</div><VariablesDialog />+ <CommentDeleteDialog /></template>diff --git a/src/components/editor/ZoomDropdown.vue b/src/components/editor/ZoomDropdown.vueindex 0cffcb6d9..8b30d5b43 100644--- a/src/components/editor/ZoomDropdown.vue+++ b/src/components/editor/ZoomDropdown.vue@@ -12,7 +12,11 @@ import { nextTick, ref, watch } from 'vue'import { useEditorCommands, useI18n } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'-import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'+import {+ setCommentsOnCanvas,+ setDesignIssuesOnCanvas,+ setSnappingPreference+} from '@/app/settings/preferences/apply'import { appPreferences } from '@/app/settings/preferences/store'import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'@@ -207,6 +211,17 @@ watch(open, (v) => {/><span class="flex-1">{{ menuText.designIssues }}</span></DropdownMenuItem>+ <DropdownMenuItem+ :class="itemCls"+ @select.prevent="setCommentsOnCanvas(!appPreferences.comments.showOnCanvas)"+ >+ <icon-lucide-check+ v-if="appPreferences.comments.showOnCanvas"+ class="absolute left-2 size-3.5"+ />+ <span class="flex-1">{{ menuText.comments }}</span>+ <AppShortcutText>{{ appMenuShortcutLabel('view-comments') }}</AppShortcutText>+ </DropdownMenuItem></DropdownMenuContent></DropdownMenuPortal></DropdownMenuRoot>diff --git a/src/theme/comments.ts b/src/theme/comments.tsnew file mode 100644index 000000000..d5aa73ab1--- /dev/null+++ b/src/theme/comments.ts@@ -0,0 +1,66 @@+import { tv } from 'tailwind-variants'++/** A pin's bubble is this many pixels square: `p-1` around a 24px avatar, or `size-8`. */+export const COMMENT_PIN_SIZE = 32++/** Canvas comments: pins, the thread card beside a pin, and the list in the right sidebar. */+export const comments = tv({+ slots: {+ // Below the toolbar and other floating UI, above the canvas.+ layer: 'pointer-events-none absolute inset-0 z-0',+ capture: 'pointer-events-auto absolute inset-0 cursor-crosshair',+ // Pins sit at their zoomed canvas positions in here; panning only moves this layer.+ pins: 'absolute top-0 left-0',+ // A 32px speech bubble whose square corner points at the commented spot, as Figma draws it;+ // hovering opens it in place into a preview of the comment.+ pin: 'group/pin pointer-events-auto absolute flex -translate-y-full cursor-pointer touch-none items-start rounded-2xl rounded-bl-none bg-panel p-1 text-left shadow-md ring-1 ring-black/10 outline-none select-none hover:shadow-lg focus-visible:ring-2 focus-visible:ring-accent data-[active]:ring-2 data-[active]:ring-accent data-[draft]:pointer-events-none data-[draft]:size-8 data-[draft]:bg-accent data-[dragging]:cursor-grabbing data-[dragging]:shadow-lg data-[resolved]:grayscale',+ // Grows from nothing to its content's size, so the bubble opens smoothly in both directions.+ pinPreview:+ 'grid grid-cols-[0fr] grid-rows-[0fr] opacity-0 transition-[grid-template-columns,grid-template-rows,opacity] duration-150 ease-out group-hover/pin:grid-cols-[1fr] group-hover/pin:grid-rows-[1fr] group-hover/pin:opacity-100 group-focus-visible/pin:grid-cols-[1fr] group-focus-visible/pin:grid-rows-[1fr] group-focus-visible/pin:opacity-100 motion-reduce:transition-none',+ pinPreviewClip: 'min-h-0 min-w-0 overflow-hidden',+ pinPreviewBody: 'flex w-max max-w-56 flex-col py-0.5 pr-2 pl-2 text-xs',+ pinText: 'line-clamp-2 break-words text-surface',+ card: 'flex max-h-[min(28rem,70vh)] w-80 flex-col overflow-hidden p-0',+ // A new comment is the composer alone, floating beside its pin, as in Figma.+ draftCard:+ 'w-72 rounded-[20px] p-0 focus-within:shadow-[0_0_0_1px_var(--color-accent),0_8px_30px_rgb(0_0_0/0.4)]',+ threadCard: 'flex min-h-0 flex-col',+ thread: 'scrollbar-thin flex min-h-0 flex-col gap-3 overflow-y-auto px-3 py-2.5',+ message: 'group/message grid grid-cols-[24px_minmax(0,1fr)] gap-x-2 gap-y-0.5',+ messageMeta: 'flex h-6 min-w-0 items-center gap-1.5 text-xs',+ messageAuthor: 'min-w-0 truncate font-semibold text-surface',+ messageTime: 'shrink-0 text-[11px] text-muted',+ messageActions:+ 'ml-auto flex shrink-0 opacity-0 group-focus-within/message:opacity-100 group-hover/message:opacity-100',+ messageText: 'col-start-2 min-w-0 text-xs break-words text-surface',+ composerSlot: 'border-t border-border p-2',+ // One line with the send button beside it, growing as the comment does, as in Figma.+ composer:+ 'flex items-end gap-1 rounded-lg border border-border bg-input py-1 pr-1 pl-3 focus-within:border-panel-focus focus-within:ring-1 focus-within:ring-accent/25',+ composerInput:+ 'scrollbar-thin max-h-40 min-w-0 flex-1 resize-none bg-transparent py-0.5 text-xs leading-5 text-surface outline-none placeholder:text-muted',+ panel: 'flex min-h-0 flex-1 flex-col',+ panelSearch: 'shrink-0 border-b border-border px-3 py-2',+ list: 'scrollbar-thin min-h-0 flex-1 overflow-y-auto',+ item: 'group/item relative border-b border-border/60 hover:bg-hover data-[active]:bg-panel-selected-muted',+ itemButton:+ 'flex w-full cursor-pointer flex-col gap-1 px-3 py-2.5 text-left text-xs outline-none focus-visible:bg-hover',+ itemTop: 'flex h-6 items-center gap-1.5 pr-14',+ itemPlace: 'min-w-0 truncate text-[11px] text-muted',+ itemMeta: 'flex min-w-0 items-baseline gap-1.5',+ itemText: 'line-clamp-3 min-w-0 break-words text-surface/80',+ itemReplies: 'text-[11px] text-muted',+ itemActions:+ 'invisible absolute top-2 right-2 flex gap-0.5 group-focus-within/item:visible group-hover/item:visible group-data-[menu-open]/item:visible',+ menuIndicator: 'absolute left-2'+ },+ variants: {+ /** A composer that is its card's whole content and takes the card's edge. */+ bare: {+ true: {+ composer:+ 'rounded-[20px] border-0 bg-transparent py-1.5 pr-1.5 focus-within:border-0 focus-within:ring-0'+ }+ }+ }+})diff --git a/tests/app/comments/format.test.ts b/tests/app/comments/format.test.tsnew file mode 100644index 000000000..a5bc3415b--- /dev/null+++ b/tests/app/comments/format.test.ts@@ -0,0 +1,79 @@+import { describe, expect, test } from 'bun:test'++import {+ commentFormatForKey,+ commentPreview,+ continueList,+ formatComment,+ type CommentEdit+} from '@/app/comments/format'++/** `[` and `]` mark the selection, `|` a caret. */+function edit(marked: string): CommentEdit {+ const caret = marked.indexOf('|')+ if (caret !== -1) return { value: marked.replace('|', ''), start: caret, end: caret }+ const start = marked.indexOf('[')+ const end = marked.indexOf(']') - 1+ return { value: marked.replace('[', '').replace(']', ''), start, end }+}++function show({ value, start, end }: CommentEdit): string {+ if (start === end) return `${value.slice(0, start)}|${value.slice(start)}`+ return `${value.slice(0, start)}[${value.slice(start, end)}]${value.slice(end)}`+}++function continued(marked: string): string {+ const next = continueList(edit(marked))+ if (!next) throw new Error(`Not a list item: ${marked}`)+ return show(next)+}++describe('comment formatting', () => {+ test('maps Figma’s shortcuts', () => {+ const key = (code: string, shiftKey = false) =>+ commentFormatForKey({ code, shiftKey, altKey: false, mod: true })+ expect([key('KeyB'), key('KeyI'), key('KeyK')]).toEqual(['bold', 'italic', 'link'])+ expect([key('KeyX', true), key('Digit7', true), key('Digit8', true)]).toEqual([+ 'strikethrough',+ 'numbered',+ 'bulleted'+ ])+ expect(commentFormatForKey({ code: 'KeyB', shiftKey: false, altKey: false, mod: false })).toBe(+ null+ )+ })++ test('wraps the selection and unwraps it again', () => {+ const bold = formatComment(edit('make [this] bold'), 'bold')+ expect(show(bold)).toBe('make **[this]** bold')+ expect(show(formatComment(bold, 'bold'))).toBe('make [this] bold')+ expect(show(formatComment(edit('a |b'), 'italic'))).toBe('a *|*b')+ expect(show(formatComment(edit('[gone]'), 'strikethrough'))).toBe('~~[gone]~~')+ })++ test('turns the selection into a link with its address selected', () => {+ expect(show(formatComment(edit('see [docs] here'), 'link'))).toBe('see [docs]([url]) here')+ expect(show(formatComment(edit('see |'), 'link'))).toBe('see <[url]>')+ })++ test('starts, switches and ends lists over the selected lines', () => {+ const bulleted = formatComment(edit('[one\ntwo]'), 'bulleted')+ expect(show(bulleted)).toBe('[- one\n- two]')+ expect(show(formatComment(bulleted, 'numbered'))).toBe('[1. one\n2. two]')+ expect(show(formatComment(bulleted, 'bulleted'))).toBe('[one\ntwo]')+ expect(show(formatComment(edit('intro\nite|m'), 'bulleted'))).toBe('intro\n- ite|m')+ })++ test('Shift+Enter continues a list and ends it on an empty item', () => {+ expect(continued('- one|')).toBe('- one\n- |')+ expect(continued('1. one|')).toBe('1. one\n2. |')+ expect(continued('- one\n- |')).toBe('- one\n|')+ expect(continueList(edit('plain|'))).toBeNull()+ })++ test('previews a comment as one line of plain text', () => {+ expect(+ commentPreview('Make **this** *bigger*, see [docs](https://x.dev)\n- one\n- ~~two~~')+ ).toBe('Make this bigger, see docs one two')+ })+})diff --git a/tests/app/comments/session.test.ts b/tests/app/comments/session.test.tsnew file mode 100644index 000000000..8535386f3--- /dev/null+++ b/tests/app/comments/session.test.ts@@ -0,0 +1,150 @@+import 'fake-indexeddb/auto'+import { afterEach, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { readComments, writeComments, type CommentThread } from '@open-pencil/scene-graph'++import { executeWithPageUndo } from '@/app/automation/execution/editor'+import { useComments } from '@/app/comments/use'+import { setActiveEditorStore } from '@/app/editor/active-store'+import { createEditorStore } from '@/app/editor/session/create'++function thread(id: string, pageId = '0:1'): CommentThread {+ return {+ id,+ pageId,+ x: 0,+ y: 0,+ author: 'Ada',+ text: id,+ createdAt: '2026-10-08T10:00:00.000Z',+ updatedAt: '2026-10-08T10:00:00.000Z',+ resolved: false,+ replies: []+ }+}++const ids = (list: CommentThread[]) => list.map((entry) => entry.id)++const stores: ReturnType<typeof createEditorStore>[] = []+afterEach(() => {+ for (const store of stores.splice(0)) store.dispose()+})++/** A fresh document made the active one, as opening a tab does. */+function openDocument() {+ const store = createEditorStore()+ stores.push(store)+ setActiveEditorStore(store)+ return store+}++/** Leave a comment the way the canvas does: a draft at a point, then its text. */+function comment(store: ReturnType<typeof openDocument>, x: number, y: number, text: string) {+ const comments = useComments()+ comments.startDraft({ pageId: store.state.currentPageId, x, y })+ comments.addThread(text)+ const added = comments.threads.value.at(-1)+ if (!added) throw new Error('No comment added')+ return added+}++test('a comment lands in the document it was written in, not the next one opened', () => {+ const first = openDocument()+ comment(first, 10, 10, 'mine')+ const second = openDocument()+ expect(useComments().threads.value).toEqual([])+ comment(second, 10, 10, 'other')++ expect(readComments(first.graph).map((entry) => entry.text)).toEqual(['mine'])+ expect(readComments(second.graph).map((entry) => entry.text)).toEqual(['other'])+})++test('making the same document active again keeps the open thread', () => {+ const store = openDocument()+ const added = comment(store, 10, 10, 'open me')+ expect(useComments().activeThreadId.value).toBe(added.id)++ // Panes of one tab take turns as the active one without switching documents.+ setActiveEditorStore(store)+ expect(useComments().activeThreadId.value).toBe(added.id)+})++test('commenting marks the document changed without adding an undo step', () => {+ const store = openDocument()+ store.markDocumentSaved()+ const canUndo = store.undo.canUndo++ comment(store, 10, 10, 'a')++ expect(store.hasUnsavedChanges()).toBe(true)+ expect(store.undo.canUndo).toBe(canUndo)+})++test('comments written to the document from elsewhere show up', async () => {+ const store = openDocument()+ writeComments(store.graph, [thread('x', store.state.currentPageId)])+ await Promise.resolve()++ expect(ids(useComments().threads.value)).toEqual(['x'])+})++test('a pin stays where its layer was when the layer is deleted, even if it was never drawn', async () => {+ const store = openDocument()+ const pageId = store.state.currentPageId+ const rect = store.graph.createNode('RECTANGLE', pageId, { x: 100, y: 50, width: 80, height: 40 })+ const pinned = comment(store, 110, 55, 'on the rectangle')+ expect(pinned.nodeId).toBe(rect.id)++ store.graph.updateNode(rect.id, { x: 300 })+ store.graph.deleteNode(rect.id)+ await Promise.resolve()++ const [detached] = readComments(store.graph)+ expect(detached?.nodeId).toBeNull()+ expect(detached && useComments().pinPosition(detached)).toEqual({ x: 310, y: 55 })+})++test('going to a comment opens its page and its thread', async () => {+ const store = openDocument()+ const first = store.state.currentPageId+ const added = comment(store, 40, 40, 'on page one')+ store.preparationController.acknowledgePresentation(Number.MAX_SAFE_INTEGER)+ await store.switchPage(store.graph.addPage('Second').id)+ expect(store.state.currentPageId).not.toBe(first)++ await useComments().focusThread(added.id)++ expect(store.state.currentPageId).toBe(first)+ expect(useComments().activeThreadId.value).toBe(added.id)+})++test('a collaborator’s save that lacks this session’s comment does not lose it', async () => {+ const store = openDocument()+ comment(store, 10, 10, 'mine')++ // Their copy was written before ours arrived, so it replaces the list whole.+ writeComments(store.graph, [thread('theirs', store.state.currentPageId)])+ await Promise.resolve()++ const texts = readComments(store.graph).map((entry) => entry.text)+ expect(texts.toSorted()).toEqual(['mine', 'theirs'])+ expect(useComments().threads.value).toHaveLength(2)+})++test('an agent’s comment is not an undo step either, as comments stay out of undo', async () => {+ const store = openDocument()+ const canUndo = store.undo.canUndo+ const figma = new FigmaAPI(store.graph)+ const addComment = ALL_TOOLS.find((tool) => tool.name === 'add_comment')+ if (!addComment) throw new Error('add_comment missing')++ await executeWithPageUndo(store, store.state.currentPageId, 'Agent: add_comment', () =>+ Promise.resolve(addComment.execute(figma, { text: 'Tighten the spacing', x: 4, y: 4 }))+ )+ await Promise.resolve()++ expect(useComments().threads.value).toHaveLength(1)+ expect(store.undo.canUndo).toBe(canUndo)+})diff --git a/tests/app/comments/time.test.ts b/tests/app/comments/time.test.tsnew file mode 100644index 000000000..295aa16ac--- /dev/null+++ b/tests/app/comments/time.test.ts@@ -0,0 +1,19 @@+import { expect, test } from 'bun:test'++import { formatCommentTime } from '@/app/comments/time'++const NOW = Date.parse('2026-10-09T12:00:00.000Z')+const ago = (ms: number) => new Date(NOW - ms).toISOString()++test('recent comments read as relative times in the given locale', () => {+ expect(formatCommentTime(ago(10_000), NOW, 'en')).toBe('now')+ expect(formatCommentTime(ago(5 * 60_000), NOW, 'en')).toBe('5 min. ago')+ expect(formatCommentTime(ago(3 * 3_600_000), NOW, 'en')).toBe('3 hr. ago')+ expect(formatCommentTime(ago(24 * 3_600_000), NOW, 'en')).toBe('yesterday')+ expect(formatCommentTime(ago(5 * 60_000), NOW, 'de')).toBe('vor 5 Min.')+})++test('older comments show a short date and bad input shows nothing', () => {+ expect(formatCommentTime('2026-09-01T12:00:00.000Z', NOW, 'en')).toBe('Sep 1')+ expect(formatCommentTime('not a date', NOW, 'en')).toBe('')+})diff --git a/tests/app/settings/preferences/store.test.ts b/tests/app/settings/preferences/store.test.tsindex 093b85224..5b04df946 100644--- a/tests/app/settings/preferences/store.test.ts+++ b/tests/app/settings/preferences/store.test.ts@@ -65,4 +65,15 @@ describe('parseAppPreferences', () => {'pending')})++ test('keeps comment view choices and drops an unknown sort order', () => {+ const { comments } = parseAppPreferences({+ comments: { showOnCanvas: false, showResolved: true, sort: 'loudest' }+ })+ expect(comments).toEqual({+ ...DEFAULT_APP_PREFERENCES.comments,+ showOnCanvas: false,+ showResolved: true+ })+ })})diff --git a/tests/e2e/comments/comments.spec.ts b/tests/e2e/comments/comments.spec.tsnew file mode 100644index 000000000..12efbcbca--- /dev/null+++ b/tests/e2e/comments/comments.spec.ts@@ -0,0 +1,120 @@+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'+import { expectDefined } from '#tests/helpers/assert'+import { toolbarToolTestId } from '#tests/helpers/test-ids'++const editor = useEditorSetup()++const commentTool = () => editor.page.getByTestId(toolbarToolTestId('COMMENT'))+const moveTool = () => editor.page.getByTestId(toolbarToolTestId('SELECT'))+const list = () => editor.page.locator('[data-slot="comments-panel"]')+const items = () => list().locator('[data-slot="comment-list-item"]')+const pins = () => editor.page.locator('[data-slot="comment-pin"]:not([data-draft])')+const thread = () => editor.page.locator('[data-slot="comment-thread"]')++async function placeComment(x: number, y: number, text: string) {+ const box = expectDefined(await editor.canvas.canvas.boundingBox(), 'canvas bounds')+ await editor.page.mouse.click(box.x + x, box.y + y)+ const composer = editor.page.getByRole('textbox', { name: 'Add a comment' })+ await expect(composer).toBeFocused()+ await composer.fill(text)+ await composer.press('Enter')+}++test('C picks the Comment tool, which turns the sidebar into the comments list', async () => {+ await editor.canvas.drawRect(100, 100, 200, 150)+ await editor.page.keyboard.press('KeyC')+ await expect(commentTool()).toHaveAttribute('aria-pressed', 'true')+ await expect(moveTool()).toHaveAttribute('aria-pressed', 'false')+ await expect(list()).toBeVisible()++ await placeComment(150, 150, 'first note')+ await expect(pins()).toHaveCount(1)+ await expect(items()).toHaveCount(1)+ // The new thread opens with its reply box ready.+ await expect(thread().getByRole('textbox', { name: 'Reply' })).toBeFocused()+})++test('replies keep line breaks and Escape closes the thread before leaving the tool', async () => {+ const reply = thread().getByRole('textbox', { name: 'Reply' })+ await reply.fill('one')+ await reply.press('Shift+Enter')+ await reply.pressSequentially('two')+ await reply.press('Enter')+ await expect(thread().locator('[data-slot="comment-message"]')).toHaveCount(2)++ await editor.page.keyboard.press('Escape')+ await expect(thread()).toHaveCount(0)+ await expect(commentTool()).toHaveAttribute('aria-pressed', 'true')+ await editor.page.keyboard.press('Escape')+ await expect(moveTool()).toHaveAttribute('aria-pressed', 'true')+ await expect(list()).toHaveCount(0)+ await expect(pins()).toHaveCount(1)+})++test('Shift+C hides pins outside the Comment tool', async () => {+ await editor.page.keyboard.press('Shift+KeyC')+ await expect(pins()).toHaveCount(0)+ await commentTool().click()+ await expect(pins()).toHaveCount(1)+ await editor.page.keyboard.press('Escape')+ await editor.page.keyboard.press('Shift+KeyC')+ await expect(pins()).toHaveCount(1)+})++test('a pin can be dragged, and the toolbar still picks tools in the Comment tool', async () => {+ await commentTool().click()+ const pin = expectDefined(await pins().first().boundingBox(), 'pin bounds')+ await editor.page.mouse.move(pin.x + 8, pin.y + pin.height - 8)+ await editor.page.mouse.down()+ await editor.page.mouse.move(pin.x + 48, pin.y + pin.height + 32, { steps: 4 })+ await editor.page.mouse.up()+ const moved = expectDefined(await pins().first().boundingBox(), 'moved pin bounds')+ expect(Math.round(moved.x - pin.x)).toBe(40)+ expect(Math.round(moved.y + moved.height - (pin.y + pin.height))).toBe(40)+ await expect(thread()).toHaveCount(0)++ // Scrolling over a pin pans the canvas under it; the pin's tip is its bottom edge.+ const tip = moved.y + moved.height+ await editor.page.mouse.move(moved.x + 8, tip - 8)+ await editor.page.mouse.wheel(0, 100)+ await expect+ .poll(async () => {+ const box = await pins().first().boundingBox()+ return box ? tip - (box.y + box.height) : 0+ })+ .toBeGreaterThan(20)++ await editor.page.getByTestId(toolbarToolTestId('RECTANGLE')).click()+ await expect(commentTool()).toHaveAttribute('aria-pressed', 'false')+ await editor.page.keyboard.press('Escape')+})++test('the list searches and resolves threads', async () => {+ await commentTool().click()+ await placeComment(260, 210, 'second note')+ await editor.page.keyboard.press('Escape')+ await expect(items()).toHaveCount(2)++ const search = list().getByRole('searchbox')+ await search.fill('second')+ await expect(items()).toHaveCount(1)+ await search.fill('')+ await expect(items()).toHaveCount(2)++ await items().first().hover()+ await items().first().locator('[data-command="comment-resolve"]').click()+ await expect(items()).toHaveCount(1)+ await expect(pins()).toHaveCount(1)+})++test('right-clicking a pin opens comment actions, not the layer menu', async () => {+ await pins().first().click({ button: 'right' })+ const menu = editor.page.getByRole('menu')+ await expect(menu.locator('[data-command="comment-resolve"]')).toHaveCount(1)+ await expect(menu.getByTestId('context-duplicate')).toHaveCount(0)+ await expect(menu.locator('[data-command="comments-hide"]')).toHaveCount(1)+ await menu.locator('[data-command="comment-delete"]').click()+ await editor.page.getByRole('alertdialog').getByRole('button', { name: 'Delete' }).click()+ await expect(pins()).toHaveCount(0)+ await expect(items()).toHaveCount(0)+})