Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(fig): use Macro comments for design comments (#7567)
Jacob Beckerman6b1835eeb5f1
diff --git a/apps/web/src/features/block-fig/browser-test/README.md b/apps/web/src/features/block-fig/browser-test/README.mdindex 3f24211a56..96332adce7 100644--- a/apps/web/src/features/block-fig/browser-test/README.md+++ b/apps/web/src/features/block-fig/browser-test/README.md@@ -25,10 +25,11 @@ design; saves stay in memory, and `?reload` reopens each one. Test-onlyfixture stands in for Google Fonts and this computer's fonts(`font-source.ts`): every family is served as the bundled Inter, and"Nowhere Grotesk" is installed locally;-- `comments`: the in-memory comment store (`memory-comments.ts`, the- `FigCommentStore` contract the app fulfils with document discussions):+- `comments`: the in-memory comment store (`memory-comments.tsx`, the+ `FigCommentStore` contract the app fulfils with Macro comments, with+ plain stand-ins for the shared message thread and composer):`threads()`, `arrive(author, text, target)` (someone else comments or- replies), `notified()` (mentions that would notify), and `people`.+ replies), `follow(threadId)` (a followed comment link), and `people`.`?present=<frame id>` opens presenting that frame, as a copied frame linkdoes.@@ -80,9 +81,9 @@ overlay, Back, Close, a link, and a legacy connection, made bythe arrow keys, the selected frame, copying a frame link and opening it),clicking through the prototype (hotspot hints, overlays closing on a clickoutside), editing interactions and flows in the Prototype tab (with the-connection noodles, undo, and saving), and comments (placing one on a-frame, @mentions, replies, unread badges, resolving and reopening, and the-pin following its frame).+connection noodles, undo, and saving), and the comment tool (placing a+comment on a frame, replies, unread badges, resolving and reopening, the+pin following its frame, and following a comment link).`?libraries` keeps two designs in memory, "Design system"(`design-system.fig`, or `&library=<file>`) and a blank "App", with thediff --git a/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.tsindex b960562bce..58382378a3 100644--- a/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts+++ b/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts@@ -241,7 +241,7 @@ test('edits interactions and flows in the Prototype tab and saves them', async (await presented(page, '1:40');});-test('comments: pins, replies, mentions, unread, resolve, and moving with the frame', async ({+test('comments: pins, replies, unread, resolve, and moving with the frame', async ({page,}) => {await open(page, '&edit');@@ -268,31 +268,29 @@ test('comments: pins, replies, mentions, unread, resolve, and moving with the frawait page.mouse.click(box.x + box.width * 0.12, box.y + box.height * 0.3);const input = page.getByTestId('fig-comment-input');await expect(input).toBeFocused();- await input.pressSequentially('Please check @Bl');- await expect(page.getByTestId('fig-mention-option')).toHaveText([- 'Blair Chen',- ]);- await page.keyboard.press('Enter');- await input.pressSequentially('thanks');+ // Typing in the comment box never reaches the canvas's shortcuts.+ await input.pressSequentially('Please check this');+ await expect(page.getByTestId('fig-tool-comment')).toHaveAttribute(+ 'aria-pressed',+ 'true'+ );await page.keyboard.press('Enter');const pin = page.getByTestId('fig-comment-pin');await expect(pin).toHaveCount(1);const popover = page.getByTestId('fig-comment-popover');- await expect(popover.getByTestId('fig-comment-mention')).toHaveText(- '@Blair Chen'- );+ await expect(popover.getByTestId('fig-comment-item')).toHaveText([+ 'Alex Morgan Please check this',+ ]);const thread = await page.evaluate(() =>window.figFixture.comments.threads()[0] as {id: string;- anchor: { nodeId: string };+ anchor: { pageId: string; nodeId: string; x: number; y: number };});expect(thread.anchor.nodeId).toBe('1:10');- expect(- await page.evaluate(() => window.figFixture.comments.notified())- ).toEqual([{ to: 'user-blair', threadId: thread.id }]);+ await expect(popover).toHaveAttribute('data-thread', thread.id);// A reply.await popover.getByTestId('fig-comment-reply').fill('One more thing');@@ -345,4 +343,24 @@ test('comments: pins, replies, mentions, unread, resolve, and moving with the fr.toBeGreaterThan(20);const after = await pin.boundingBox();expect(Math.abs((before?.y ?? 0) - (after?.y ?? 0))).toBeLessThan(2);++ // A comment link turns the tool on at its thread.+ await page.keyboard.press('Escape');+ await expect(page.getByTestId('fig-comments-panel')).toHaveCount(0);+ const linked = await page.evaluate((anchor) => {+ const f = window.figFixture.comments;+ const id = f.arrive(f.people[2], 'Linked', {+ anchor: { ...anchor, x: 40, y: 40 },+ });+ f.follow(id);+ return id;+ }, thread.anchor);+ await expect(page.getByTestId('fig-tool-comment')).toHaveAttribute(+ 'aria-pressed',+ 'true'+ );+ await expect(popover).toHaveAttribute('data-thread', linked);+ await expect(popover.getByTestId('fig-comment-item')).toHaveText([+ 'Casey Diaz Linked',+ ]);});diff --git a/apps/web/src/features/block-fig/browser-test/fixture.tsx b/apps/web/src/features/block-fig/browser-test/fixture.tsxindex 4ac9f562b0..75aa508b4f 100644--- a/apps/web/src/features/block-fig/browser-test/fixture.tsx+++ b/apps/web/src/features/block-fig/browser-test/fixture.tsx@@ -58,8 +58,8 @@ declare global {text: string,target: { threadId: string } | { anchor: FigCommentAnchor }) => string;- /** Mentions that would have notified someone. */- notified: () => { to: string; threadId: string }[];+ /** Opens a thread, as following a comment link does. */+ follow: (threadId: string) => void;people: FigPerson[];};};@@ -95,7 +95,7 @@ function Fixture() {comments: {threads: comments.store.threads,arrive: comments.arrive,- notified: comments.notified,+ follow: comments.follow,people: FIXTURE_PEOPLE,},fontRequests: fixtureFonts.requests,diff --git a/apps/web/src/features/block-fig/browser-test/memory-comments.ts b/apps/web/src/features/block-fig/browser-test/memory-comments.tsdeleted file mode 100644index 949454783d..0000000000--- a/apps/web/src/features/block-fig/browser-test/memory-comments.ts+++ /dev/null@@ -1,125 +0,0 @@-/**- * Comments kept in memory for the browser fixture: the `FigCommentStore`- * contract the app fulfils with document discussions. `arrive` adds a- * comment from someone else, as a live update would.- */--import { createSignal } from 'solid-js';-import type { FigCommentStore } from '../context/fig-comments';-import type {- FigCommentAnchor,- FigCommentThread,- FigPerson,-} from '../core/comments';--export const FIXTURE_PEOPLE: FigPerson[] = [- { id: 'user-alex', name: 'Alex Morgan' },- { id: 'user-blair', name: 'Blair Chen' },- { id: 'user-casey', name: 'Casey Diaz' },-];--export function createMemoryComments(me: FigPerson = FIXTURE_PEOPLE[0]) {- const [threads, setThreads] = createSignal<FigCommentThread[]>([]);- const [seen, setSeen] = createSignal<Record<string, number>>({});- const notified: { to: string; threadId: string }[] = [];- let next = 0;- const id = () => `c${++next}`;- // Strictly increasing, so a comment posted right after reading is newer.- let clock = 0;- const now = () => {- clock = Math.max(clock + 1, Date.now());- return clock;- };-- const store: FigCommentStore = {- threads,- me: () => me,- canComment: () => true,- seenAt: (threadId) => seen()[threadId],- markSeen: (threadId) => setSeen((s) => ({ ...s, [threadId]: now() })),- async create(anchor: FigCommentAnchor, text, mentions) {- const commentId = id();- setThreads((list) => [- ...list,- {- id: commentId,- anchor,- resolved: false,- comments: [- { id: commentId, author: me, text, mentions, createdAt: now() },- ],- },- ]);- store.markSeen(commentId);- for (const m of mentions)- notified.push({ to: m.id, threadId: commentId });- return commentId;- },- async reply(threadId, text, mentions) {- setThreads((list) =>- list.map((t) =>- t.id === threadId- ? {- ...t,- comments: [- ...t.comments,- { id: id(), author: me, text, mentions, createdAt: now() },- ],- }- : t- )- );- store.markSeen(threadId);- for (const m of mentions) notified.push({ to: m.id, threadId });- },- async setResolved(threadId, resolved) {- setThreads((list) =>- list.map((t) => (t.id === threadId ? { ...t, resolved } : t))- );- },- async deleteThread(threadId) {- setThreads((list) => list.filter((t) => t.id !== threadId));- },- people: (query) =>- FIXTURE_PEOPLE.filter(- (p) =>- p.id !== me.id && p.name.toLowerCase().includes(query.toLowerCase())- ),- };-- /** Someone else comments: a reply to `threadId`, or a new thread. */- const arrive = (- author: FigPerson,- text: string,- target: { threadId: string } | { anchor: FigCommentAnchor }- ) => {- const comment = {- id: id(),- author,- text,- mentions: [],- createdAt: now(),- };- if ('threadId' in target)- setThreads((list) =>- list.map((t) =>- t.id === target.threadId- ? { ...t, comments: [...t.comments, comment] }- : t- )- );- else- setThreads((list) => [- ...list,- {- id: comment.id,- anchor: target.anchor,- resolved: false,- comments: [comment],- },- ]);- return comment.id;- };-- return { store, arrive, notified: () => [...notified] };-}diff --git a/apps/web/src/features/block-fig/browser-test/memory-comments.tsx b/apps/web/src/features/block-fig/browser-test/memory-comments.tsxnew file mode 100644index 0000000000..98d305f2c2--- /dev/null+++ b/apps/web/src/features/block-fig/browser-test/memory-comments.tsx@@ -0,0 +1,183 @@+/**+ * Comments kept in memory for the browser fixture: the `FigCommentStore`+ * contract the app fulfils with Macro comments. Its thread and composer are+ * plain stand-ins for the app's shared message thread and composer (which+ * need the message service), enough to drive the viewer's comment tool.+ * `arrive` adds a comment from someone else, as a live update would, and+ * `follow` opens a thread as a comment link does.+ */++import { createSignal, For, onMount } from 'solid-js';+import type {+ FigCommentComposerProps,+ FigCommentStore,+} from '../context/fig-comments';+import type {+ FigComment,+ FigCommentAnchor,+ FigCommentThread,+ FigPerson,+} from '../core/comments';++export const FIXTURE_PEOPLE: FigPerson[] = [+ { id: 'user-alex', name: 'Alex Morgan' },+ { id: 'user-blair', name: 'Blair Chen' },+ { id: 'user-casey', name: 'Casey Diaz' },+];++/** A text box: Enter posts, ⇧Enter starts a new line. */+function TextBox(props: {+ testId: string;+ placeholder: string;+ autofocus?: boolean;+ onPost: (text: string) => void;+}) {+ let input!: HTMLTextAreaElement;+ onMount(() => {+ if (props.autofocus) input.focus({ preventScroll: true });+ });+ const post = () => {+ const text = input.value.trim();+ if (!text) return;+ props.onPost(text);+ input.value = '';+ };+ return (+ <div class="flex flex-col gap-1.5">+ <textarea+ ref={input}+ rows={2}+ class="w-full resize-none rounded-md border border-edge-muted bg-input px-2 py-1.5 text-ink text-xs outline-none placeholder:text-ink-placeholder focus:border-accent"+ placeholder={props.placeholder}+ data-testid={props.testId}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ post();+ }+ }}+ />+ <button+ type="button"+ class="self-end rounded-md bg-accent px-2 py-1 text-accent-contrast text-xs"+ data-testid={`${props.testId}-post`}+ onClick={post}+ >+ Post+ </button>+ </div>+ );+}++export function createMemoryComments(me: FigPerson = FIXTURE_PEOPLE[0]) {+ const [threads, setThreads] = createSignal<FigCommentThread[]>([]);+ const [seen, setSeen] = createSignal<Record<string, number>>({});+ const [linked, setLinked] = createSignal<{ threadId: string | null }>();+ let next = 0;+ const id = () => `c${++next}`;+ // Strictly increasing, so a comment posted right after reading is newer.+ let clock = 0;+ const now = () => {+ clock = Math.max(clock + 1, Date.now());+ return clock;+ };++ const add = (threadId: string, comment: FigComment) =>+ setThreads((list) =>+ list.map((t) =>+ t.id === threadId+ ? {+ ...t,+ comments: [...t.comments, comment],+ replyCount: t.replyCount + 1,+ }+ : t+ )+ );+ const start = (anchor: FigCommentAnchor, comment: FigComment) =>+ setThreads((list) => [+ ...list,+ {+ id: comment.id,+ anchor,+ resolved: false,+ comments: [comment],+ replyCount: 0,+ },+ ]);+ const write = (author: FigPerson, text: string): FigComment => ({+ id: id(),+ author,+ text,+ createdAt: now(),+ });++ const markSeen = (threadId: string) =>+ setSeen((s) => ({ ...s, [threadId]: now() }));++ const store: FigCommentStore = {+ threads,+ me: () => me,+ canComment: () => true,+ seenAt: (threadId) => seen()[threadId],+ markSeen,+ async setResolved(threadId, resolved) {+ setThreads((list) =>+ list.map((t) => (t.id === threadId ? { ...t, resolved } : t))+ );+ },+ Thread: (props) => {+ const thread = () => threads().find((t) => t.id === props.threadId);+ return (+ <div class="flex flex-col gap-3">+ <For each={thread()?.comments}>+ {(c) => (+ <div class="text-xs" data-testid="fig-comment-item">+ <span class="font-medium">{c.author.name}</span> {c.text}+ </div>+ )}+ </For>+ <TextBox+ testId="fig-comment-reply"+ placeholder="Reply"+ onPost={(text) => {+ add(props.threadId, write(me, text));+ markSeen(props.threadId);+ }}+ />+ </div>+ );+ },+ Composer: (props: FigCommentComposerProps) => (+ <TextBox+ testId="fig-comment-input"+ placeholder="Add a comment"+ autofocus+ onPost={(text) => {+ const comment = write(me, text);+ start(props.anchor, comment);+ markSeen(comment.id);+ props.onPosted(comment.id);+ }}+ />+ ),+ linked,+ };++ /** Someone else comments: a reply to `threadId`, or a new thread. */+ const arrive = (+ author: FigPerson,+ text: string,+ target: { threadId: string } | { anchor: FigCommentAnchor }+ ) => {+ const comment = write(author, text);+ if ('threadId' in target) add(target.threadId, comment);+ else start(target.anchor, comment);+ return comment.id;+ };++ /** Follows a link to a thread, as opening a copied comment link does. */+ const follow = (threadId: string) => setLinked({ threadId });++ return { store, arrive, follow };+}diff --git a/apps/web/src/features/block-fig/components/comment-composer.tsx b/apps/web/src/features/block-fig/components/comment-composer.tsxdeleted file mode 100644index e7cc9ee081..0000000000--- a/apps/web/src/features/block-fig/components/comment-composer.tsx+++ /dev/null@@ -1,172 +0,0 @@-/**- * A comment box: Enter posts (⇧Enter for a new line), Escape cancels, and- * `@` offers people to mention. Keeps the text when posting fails.- */--import { Button } from '@ui/components/Button';-import { createSignal, For, onMount, Show } from 'solid-js';-import {- type FigPerson,- insertMention,- mentionQuery,- mentionsIn,-} from '../core/comments';--export function CommentComposer(props: {- placeholder: string;- /** `data-testid` of the box; the button is `<testId>-post`. */- testId: string;- submitLabel?: string;- autofocus?: boolean;- people: (query: string) => FigPerson[];- onSubmit: (text: string, mentions: FigPerson[]) => Promise<unknown>;- onCancel?: () => void;- /** Escape with nothing to cancel (closes what holds the box). */- onEscape?: () => void;-}) {- const [text, setText] = createSignal('');- const [picked, setPicked] = createSignal<FigPerson[]>([]);- const [query, setQuery] = createSignal<{ start: number; query: string }>();- const [highlight, setHighlight] = createSignal(0);- const [busy, setBusy] = createSignal(false);- let input!: HTMLTextAreaElement;-- onMount(() => {- if (props.autofocus) input.focus({ preventScroll: true });- });-- const options = () => {- const q = query();- return q ? props.people(q.query).slice(0, 6) : [];- };-- const sync = () => {- setText(input.value);- setQuery(mentionQuery(input.value, input.selectionStart ?? 0));- setHighlight(0);- };-- const choose = (person: FigPerson) => {- const q = query();- if (!q) return;- const next = insertMention(- input.value,- q.start,- input.selectionStart ?? input.value.length,- person- );- input.value = next.text;- input.setSelectionRange(next.caret, next.caret);- setPicked((p) => [...p, person]);- setText(next.text);- setQuery(undefined);- input.focus();- };-- const submit = async () => {- const value = text().trim();- if (!value || busy()) return;- setBusy(true);- try {- await props.onSubmit(value, mentionsIn(value, picked()));- input.value = '';- setText('');- setPicked([]);- // Keep typing where you were (and keep the keys in the viewer).- if (input.isConnected) input.focus({ preventScroll: true });- } catch {- // The text stays for another try; the store reports the failure.- } finally {- setBusy(false);- }- };-- const onKeyDown = (e: KeyboardEvent) => {- const list = options();- if (list.length > 0) {- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {- e.preventDefault();- const step = e.key === 'ArrowDown' ? 1 : -1;- setHighlight((h) => (h + step + list.length) % list.length);- return;- }- if (e.key === 'Enter' || e.key === 'Tab') {- e.preventDefault();- choose(list[highlight()] ?? list[0]);- return;- }- }- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();- void submit();- } else if (e.key === 'Escape') {- e.preventDefault();- if (query()) setQuery(undefined);- else if (props.onCancel) props.onCancel();- else props.onEscape?.();- }- // Typing here never reaches the viewer's shortcuts.- e.stopPropagation();- };-- return (- <div class="relative flex flex-col gap-1.5">- <textarea- ref={input}- rows={2}- class="w-full resize-none rounded-md border border-edge-muted bg-input px-2 py-1.5 text-ink text-xs outline-none placeholder:text-ink-placeholder focus:border-accent"- placeholder={props.placeholder}- data-testid={props.testId}- onInput={sync}- onClick={sync}- onKeyDown={onKeyDown}- onKeyUp={(e) => e.stopPropagation()}- />- <Show when={options().length > 0}>- <div- class="absolute top-full left-0 z-10 mt-1 w-48 overflow-hidden rounded-md border border-edge-muted bg-panel py-1 shadow-lg"- role="listbox"- data-testid="fig-mention-menu"- >- <For each={options()}>- {(person, k) => (- <button- type="button"- role="option"- aria-selected={highlight() === k()}- class="block w-full truncate px-2 py-1 text-left text-xs"- classList={{ 'bg-hover': highlight() === k() }}- data-testid="fig-mention-option"- onPointerDown={(e) => e.preventDefault()}- onClick={() => choose(person)}- >- {person.name}- </button>- )}- </For>- </div>- </Show>- <div class="flex justify-end gap-1.5">- <Show when={props.onCancel}>- <Button- variant="ghost"- size="sm"- data-testid={`${props.testId}-cancel`}- onClick={() => props.onCancel?.()}- >- Cancel- </Button>- </Show>- <Button- variant="accent"- size="sm"- disabled={!text().trim() || busy()}- data-testid={`${props.testId}-post`}- onClick={() => void submit()}- >- {props.submitLabel ?? 'Post'}- </Button>- </div>- </div>- );-}diff --git a/apps/web/src/features/block-fig/components/comment-pins.tsx b/apps/web/src/features/block-fig/components/comment-pins.tsxindex 79e76582ef..8086bd72f1 100644--- a/apps/web/src/features/block-fig/components/comment-pins.tsx+++ b/apps/web/src/features/block-fig/components/comment-pins.tsx@@ -2,17 +2,19 @@* Comments on the canvas while the comment tool is on: a pin per thread at* a constant size wherever the view is zoomed (filled when unread), the* open thread beside its pin, and a click anywhere placing a new comment.+ * The thread and the composer inside the cards are the comment store's.*/-import { For, Show } from 'solid-js';+import CheckCircle from '@phosphor/check-circle.svg';+import X from '@phosphor/x.svg';+import { For, type JSX, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';import { type Camera, pageToScreen, screenToPage } from '../core/camera';import { initialsOf } from '../core/comments';import type { FigComments } from '../primitives/create-fig-comments';-import { CommentComposer } from './comment-composer';-import { CommentThreadView } from './comment-thread';-/** Width of the thread card beside a pin, CSS px. */-const CARD = 280;+/** Width of the card beside a pin, CSS px. */+const CARD = 320;function Pin(props: {label: string;@@ -47,19 +49,60 @@ function Pin(props: {);}+/**+ * A card beside a pin. Its pointer and wheel stay off the canvas (it+ * scrolls instead of panning); Escape closes it once whatever has focus+ * inside (a mention menu, an edit) has had it.+ */+function PinCard(props: {+ /** The pin, in screen px. */+ at: { x: number; y: number };+ viewport: { w: number; h: number };+ testId: string;+ thread?: string;+ resolved?: boolean;+ onClose: () => void;+ children: JSX.Element;+}) {+ const top = () =>+ Math.max(8, Math.min(props.at.y - 28, props.viewport.h - 160));+ return (+ <div+ class="absolute z-10 flex flex-col overflow-hidden rounded-lg border border-edge-muted bg-panel text-ink text-xs shadow-lg"+ style={{+ left: `${Math.max(8, Math.min(props.at.x + 16, props.viewport.w - CARD - 8))}px`,+ top: `${top()}px`,+ width: `${CARD}px`,+ 'max-height': `${Math.max(120, props.viewport.h - top() - 8)}px`,+ }}+ data-testid={props.testId}+ data-thread={props.thread}+ data-resolved={+ props.resolved === undefined ? undefined : String(props.resolved)+ }+ onPointerDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ onKeyDown={(e) => {+ if (e.key !== 'Escape' || e.defaultPrevented) return;+ e.preventDefault();+ props.onClose();+ }}+ >+ {props.children}+ </div>+ );+}+export function CommentPins(props: {comments: FigComments;camera: Camera;viewport: { w: number; h: number };+ /** A card closed with Escape: keys go back to the canvas. */+ onDismiss: () => void;}) {const c = props.comments;const store = c.store;const screen = (p: { x: number; y: number }) => pageToScreen(props.camera, p);- /** Where a card beside screen point `p` fits in the view. */- const cardAt = (p: { x: number; y: number }) => ({- left: `${Math.max(8, Math.min(p.x + 16, props.viewport.w - CARD - 8))}px`,- top: `${Math.max(8, Math.min(p.y - 28, props.viewport.h - 220))}px`,- });const shownPins = () =>c.pins()@@ -128,6 +171,10 @@ export function CommentPins(props: {<Show when={c.draft()}>{(d) => {const at = () => screen(d().at);+ const close = () => {+ c.cancelDraft();+ props.onDismiss();+ };return (<><div@@ -136,54 +183,83 @@ export function CommentPins(props: {><Pin label="+" open testId="fig-comment-draft-pin" /></div>- <div- class="absolute z-10 rounded-lg border border-edge-muted bg-panel p-2 shadow-lg"- style={{ ...cardAt(at()), width: `${CARD}px` }}- data-testid="fig-comment-draft"- onPointerDown={(e) => e.stopPropagation()}+ <PinCard+ at={at()}+ viewport={props.viewport}+ testId="fig-comment-draft"+ onClose={close}>- <CommentComposer- placeholder="Add a comment"- testId="fig-comment-input"- autofocus- people={store.people}- onSubmit={(text, mentions) => c.post(text, mentions)}- onCancel={() => c.cancelDraft()}- />- </div>+ <div class="min-h-0 overflow-y-auto p-2">+ <Dynamic+ component={store.Composer}+ anchor={d().anchor}+ onPosted={c.posted}+ onCancel={close}+ />+ </div>+ </PinCard></>);}}</Show>- <Show when={open()}>- {(pin) => (- <div- class="absolute z-10 max-h-[60%] overflow-y-auto rounded-lg border border-edge-muted bg-panel p-3 shadow-lg"- style={{ ...cardAt(screen(pin().at)), width: `${CARD}px` }}- data-testid="fig-comment-popover"- data-thread={pin().thread.id}- onPointerDown={(e) => e.stopPropagation()}- >- <CommentThreadView- thread={pin().thread}- canComment={store.canComment()}- canDelete={pin().thread.comments[0]?.author.id === store.me()?.id}- people={store.people}- onReply={(text, mentions) =>- store.reply(pin().thread.id, text, mentions)- }- onResolve={(resolved) =>- void store.setResolved(pin().thread.id, resolved)- }- onClose={() => c.setOpenThread(undefined)}- onDelete={() => {- const id = pin().thread.id;- c.setOpenThread(undefined);- void store.deleteThread(id);- }}- />- </div>- )}+ {/* Keyed by thread, so opening another starts its thread afresh. */}+ <Show when={open()?.thread.id} keyed>+ {(threadId) => {+ const thread = () => open()?.thread;+ const close = () => {+ c.setOpenThread(undefined);+ props.onDismiss();+ };+ return (+ <Show when={open()}>+ {(pin) => (+ <PinCard+ at={screen(pin().at)}+ viewport={props.viewport}+ testId="fig-comment-popover"+ thread={threadId}+ resolved={thread()?.resolved ?? false}+ onClose={close}+ >+ <div class="flex h-9 shrink-0 items-center gap-1 border-edge-muted border-b pr-1 pl-3">+ <span class="flex-1 text-[11px] text-ink-muted">+ {thread()?.resolved ? 'Resolved' : 'Comment'}+ </span>+ <Show when={store.canComment()}>+ <button+ type="button"+ class="flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-ink-muted hover:bg-hover hover:text-ink"+ data-testid={+ thread()?.resolved+ ? 'fig-comment-reopen'+ : 'fig-comment-resolve'+ }+ onClick={() =>+ void store.setResolved(threadId, !thread()?.resolved)+ }+ >+ <CheckCircle class="size-3.5" />+ {thread()?.resolved ? 'Reopen' : 'Resolve'}+ </button>+ </Show>+ <button+ type="button"+ class="flex size-6 items-center justify-center rounded-md text-ink-muted hover:bg-hover hover:text-ink"+ aria-label="Close comment"+ data-testid="fig-comment-close"+ onClick={close}+ >+ <X class="size-3.5" />+ </button>+ </div>+ <div class="min-h-0 flex-1 overflow-y-auto p-3">+ <Dynamic component={store.Thread} threadId={threadId} />+ </div>+ </PinCard>+ )}+ </Show>+ );+ }}</Show></div>);diff --git a/apps/web/src/features/block-fig/components/comment-thread.tsx b/apps/web/src/features/block-fig/components/comment-thread.tsxdeleted file mode 100644index 6ba3f5fce0..0000000000--- a/apps/web/src/features/block-fig/components/comment-thread.tsx+++ /dev/null@@ -1,138 +0,0 @@-/**- * One comment thread: its comments with their authors and times, mentions- * highlighted, Resolve or Reopen, Delete, and a reply box.- */--import CheckCircle from '@phosphor/check-circle.svg';-import Trash from '@phosphor/trash.svg';-import { For, Show } from 'solid-js';-import {- type FigComment,- type FigCommentThread,- type FigPerson,- initialsOf,- mentionParts,- relativeTime,-} from '../core/comments';-import { CommentComposer } from './comment-composer';--export function CommentAvatar(props: { person: FigPerson }) {- return (- <span- class="flex size-6 shrink-0 items-center justify-center rounded-full bg-accent-bg font-medium text-[10px] text-accent"- title={props.person.name}- >- {initialsOf(props.person.name)}- </span>- );-}--export function CommentText(props: { comment: FigComment }) {- return (- <p class="whitespace-pre-wrap break-words text-ink text-xs">- <For each={mentionParts(props.comment.text, props.comment.mentions)}>- {(part) =>- part.mention ? (- <span- class="font-medium text-accent"- data-testid="fig-comment-mention"- >- {part.text}- </span>- ) : (- part.text- )- }- </For>- </p>- );-}--function CommentItem(props: { comment: FigComment; now: number }) {- return (- <div class="flex gap-2" data-testid="fig-comment-item">- <CommentAvatar person={props.comment.author} />- <div class="min-w-0 flex-1">- <div class="flex items-baseline gap-1.5">- <span class="truncate font-medium text-ink text-xs">- {props.comment.author.name}- </span>- <span class="shrink-0 text-[11px] text-ink-muted">- {relativeTime(props.comment.createdAt, props.now)}- </span>- </div>- <CommentText comment={props.comment} />- </div>- </div>- );-}--export function CommentThreadView(props: {- thread: FigCommentThread;- canComment: boolean;- /** Whether this person may delete the thread (its author). */- canDelete: boolean;- people: (query: string) => FigPerson[];- onReply: (text: string, mentions: FigPerson[]) => Promise<unknown>;- onResolve: (resolved: boolean) => void;- onDelete: () => void;- /** Escape in the reply box. */- onClose?: () => void;-}) {- const now = Date.now();- return (- <div- class="flex flex-col gap-3"- data-testid="fig-comment-thread"- data-thread={props.thread.id}- data-resolved={props.thread.resolved ? 'true' : 'false'}- >- <div class="flex items-center gap-1">- <Show when={props.thread.resolved}>- <span class="text-[11px] text-ink-muted">Resolved</span>- </Show>- <div class="ml-auto flex items-center gap-0.5">- <Show when={props.canComment}>- <button- type="button"- class="flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-ink-muted hover:bg-hover hover:text-ink"- data-testid={- props.thread.resolved- ? 'fig-comment-reopen'- : 'fig-comment-resolve'- }- onClick={() => props.onResolve(!props.thread.resolved)}- >- <CheckCircle class="size-3.5" />- {props.thread.resolved ? 'Reopen' : 'Resolve'}- </button>- </Show>- <Show when={props.canDelete}>- <button- type="button"- class="rounded-md p-1 text-ink-muted hover:bg-hover hover:text-ink"- aria-label="Delete thread"- data-testid="fig-comment-delete"- onClick={() => props.onDelete()}- >- <Trash class="size-3.5" />- </button>- </Show>- </div>- </div>- <For each={props.thread.comments}>- {(c) => <CommentItem comment={c} now={now} />}- </For>- <Show when={props.canComment}>- <CommentComposer- placeholder="Reply"- testId="fig-comment-reply"- submitLabel="Reply"- people={props.people}- onSubmit={props.onReply}- onEscape={props.onClose}- />- </Show>- </div>- );-}diff --git a/apps/web/src/features/block-fig/context/fig-comments.ts b/apps/web/src/features/block-fig/context/fig-comments.tsindex db8183dba5..7c58172652 100644--- a/apps/web/src/features/block-fig/context/fig-comments.ts+++ b/apps/web/src/features/block-fig/context/fig-comments.ts@@ -1,18 +1,29 @@/**- * Where a design's comments live, injected by the block (document- * discussions in the app, an in-memory store in the browser fixture), so- * the viewer's comment UI has no app dependencies.+ * Where a design's comments live and how they are written and shown,+ * injected by the block (Macro comments in the app, an in-memory store in+ * the browser fixture), so the viewer's comment tool has no app+ * dependencies. The viewer owns the pins, the thread list, and where a+ * thread opens; the store supplies the thread and composer inside them.*/-import type { Accessor } from 'solid-js';+import type { Accessor, Component } from 'solid-js';import type {FigCommentAnchor,FigCommentThread,FigPerson,} from '../core/comments';+export interface FigCommentComposerProps {+ /** Where the new thread pins. */+ anchor: FigCommentAnchor;+ /** The thread was posted; it opens beside its pin. */+ onPosted: (threadId: string) => void;+ /** The composer was closed without posting. */+ onCancel: () => void;+}+export interface FigCommentStore {- /** Every thread on the design, as it is now. */+ /** Every thread pinned on the design, as it is now. */threads: Accessor<FigCommentThread[]>;/** The person commenting; `undefined` when not signed in. */me: Accessor<FigPerson | undefined>;@@ -21,21 +32,16 @@ export interface FigCommentStore {/** When this person last read a thread (ms), for unread badges. */seenAt: (threadId: string) => number | undefined;markSeen: (threadId: string) => void;- /** Starts a thread; resolves to its id. */- create: (- anchor: FigCommentAnchor,- text: string,- mentions: FigPerson[]- ) => Promise<string>;- reply: (- threadId: string,- text: string,- mentions: FigPerson[]- ) => Promise<void>;setResolved: (threadId: string, resolved: boolean) => Promise<void>;- deleteThread: (threadId: string) => Promise<void>;- /** Loads every reply of a thread (lists may hold only the first few). */- load?: (threadId: string) => void;- /** People who can be mentioned, matching `query`. */- people: (query: string) => FigPerson[];+ /** A thread's comments with their replies and the reply box. */+ Thread: Component<{ threadId: string }>;+ /** The box that starts a thread. */+ Composer: Component<FigCommentComposerProps>;+ /** Comments on the whole design (pinned nowhere), below the list. */+ Discussion?: Component;+ /**+ * The comment a link opened: its pinned thread, or `null` for one in the+ * discussion. A new value each time a link is followed.+ */+ linked?: Accessor<{ threadId: string | null } | undefined>;}diff --git a/apps/web/src/features/block-fig/core/comments.test.ts b/apps/web/src/features/block-fig/core/comments.test.tsindex 040b89d3a0..cac4f364da 100644--- a/apps/web/src/features/block-fig/core/comments.test.ts+++ b/apps/web/src/features/block-fig/core/comments.test.ts@@ -5,11 +5,7 @@ import {byActivity,type FigCommentThread,filterThreads,- insertMention,isUnread,- mentionParts,- mentionQuery,- mentionsIn,} from './comments';const alex = { id: 'u1', name: 'Alex Morgan' };@@ -21,15 +17,15 @@ const thread = (times: [string, number][]): FigCommentThread => ({id,- anchor: null,+ anchor: { pageId: '0:1', nodeId: null, x: 0, y: 0 },resolved,comments: times.map(([author, createdAt], k) => ({id: `${id}-${k}`,author: author === 'u1' ? alex : blair,text: 'hi',- mentions: [],createdAt,})),+ replyCount: times.length - 1,});describe('anchoring', () => {@@ -75,30 +71,3 @@ describe('threads', () => {expect(isUnread(c, 'u2', undefined)).toBe(true);});});--describe('mentions', () => {- it('finds the @query being typed', () => {- expect(mentionQuery('Hey @Bl', 7)).toEqual({ start: 4, query: 'Bl' });- expect(mentionQuery('@', 1)).toEqual({ start: 0, query: '' });- expect(mentionQuery('mail@example', 12)).toBeUndefined();- expect(mentionQuery('Hey @Blair done', 15)).toBeUndefined();- });-- it('inserts a mention and keeps those still in the text', () => {- const r = insertMention('Hey @Bl!', 4, 7, blair);- expect(r).toEqual({ text: 'Hey @Blair !', caret: 11 });- expect(mentionsIn(r.text, [blair, alex, blair])).toEqual([blair]);- expect(mentionsIn('Hey', [blair])).toEqual([]);- });-- it('splits text into mentions for display, longest names first', () => {- const parts = mentionParts('cc @Alex Morgan and @Blair.', [alex, blair]);- expect(parts).toEqual([- { text: 'cc ' },- { text: '@Alex Morgan', mention: alex },- { text: ' and ' },- { text: '@Blair', mention: blair },- { text: '.' },- ]);- });-});diff --git a/apps/web/src/features/block-fig/core/comments.ts b/apps/web/src/features/block-fig/core/comments.tsindex f84ada82e4..00b877a92e 100644--- a/apps/web/src/features/block-fig/core/comments.ts+++ b/apps/web/src/features/block-fig/core/comments.ts@@ -1,8 +1,8 @@/*** Comments on a design, as Figma pins them: a thread sits at a point on a- * page, or on a layer (it moves with the layer), and holds replies,- * mentions, and a resolved state. Pure helpers for anchoring, unread- * state, filtering, and @mentions.+ * page, or on a layer (it moves with the layer), and holds replies and a+ * resolved state. Pure helpers for anchoring, unread state, and filtering;+ * the comments themselves are written and shown by the comment store.*/import type { Rect } from '@core/fig-engine/types';@@ -27,21 +27,22 @@ export interface FigPerson {export interface FigComment {id: string;author: FigPerson;- /** Plain text; mentions read `@Name`. */+ /** Plain text, for previews and search. */text: string;- mentions: FigPerson[];/** Milliseconds since the epoch. */createdAt: number;}+/** A thread pinned on the design. */export interface FigCommentThread {/** The first comment's id. */id: string;- /** `null` for a comment on the whole design. */- anchor: FigCommentAnchor | null;+ anchor: FigCommentAnchor;resolved: boolean;- /** The first comment, then replies, oldest first. */+ /** The first comment, then the latest replies, oldest first. */comments: FigComment[];+ /** Every reply, including those `comments` leaves out. */+ replyCount: number;}/** The anchor for a comment placed at page point `at` on `node` (or none). */@@ -108,68 +109,6 @@ export function isUnread();}-/** The `@query` being typed before `caret`, if any. */-export function mentionQuery(- text: string,- caret: number-): { start: number; query: string } | undefined {- const before = text.slice(0, caret);- const m = /(^|\s)@([^\s@]{0,40})$/.exec(before);- if (!m) return undefined;- return { start: before.length - m[2].length - 1, query: m[2] };-}--/** `text` with the `@query` at `start` replaced by `@Name `. */-export function insertMention(- text: string,- start: number,- caret: number,- person: FigPerson-): { text: string; caret: number } {- const inserted = `@${person.name} `;- return {- text: text.slice(0, start) + inserted + text.slice(caret),- caret: start + inserted.length,- };-}--/** The people of `picked` whose `@Name` is still in `text`. */-export function mentionsIn(text: string, picked: readonly FigPerson[]) {- const seen = new Set<string>();- return picked.filter((p) => {- if (seen.has(p.id) || !text.includes(`@${p.name}`)) return false;- seen.add(p.id);- return true;- });-}--/** Splits text into plain runs and mentions of `people`, for display. */-export function mentionParts(- text: string,- people: readonly FigPerson[]-): { text: string; mention?: FigPerson }[] {- const names = [...people].sort((a, b) => b.name.length - a.name.length);- const parts: { text: string; mention?: FigPerson }[] = [];- let plain = '';- for (let i = 0; i < text.length; ) {- const person =- text[i] === '@'- ? names.find((p) => text.startsWith(`@${p.name}`, i))- : undefined;- if (person) {- if (plain) parts.push({ text: plain });- plain = '';- parts.push({ text: `@${person.name}`, mention: person });- i += person.name.length + 1;- } else {- plain += text[i];- i++;- }- }- if (plain) parts.push({ text: plain });- return parts;-}-/** "Just now", "5m", "3h", "2d", or a date. */export function relativeTime(at: number, now: number): string {const s = Math.max(0, Math.round((now - at) / 1000));diff --git a/apps/web/src/features/block-fig/fig-block.tsx b/apps/web/src/features/block-fig/fig-block.tsxindex aff8613006..7a5d20e901 100644--- a/apps/web/src/features/block-fig/fig-block.tsx+++ b/apps/web/src/features/block-fig/fig-block.tsx@@ -33,9 +33,9 @@ import {useCanComment,useCanEdit,useGetPermissions,+ useIsDocumentOwner,} from '@core/signal/permissions';import { getDisplayName, tryMacroId } from '@core/user';-import { idToEmail } from '@core/user/util';import {useBlockDocumentDownloadName,useBlockDocumentName,@@ -65,7 +65,6 @@ import {} from './context/fig-viewer-context';import type { FigData } from './definition';import { createDesignCollabSession } from './queries/fig-collab';-import { useFigComments } from './queries/fig-comments';import { saveFigFile } from './queries/fig-file';import { useFigLibrarySource } from './queries/fig-libraries';import { shareFigEngine } from './queries/fig-sharing';@@ -77,6 +76,7 @@ import {import { createFontSource } from './queries/font-source';import { openFigEngine, prepareFigEngine } from './queries/prepare-engine';import { FigViewer } from './views/fig-viewer';+import { useMacroComments } from './views/macro-comments';/*** ⌘K on a design opens the command menu, which then offers the design@@ -342,13 +342,14 @@ export default function FigBlock(props: { share?: string; present?: string }) {const permissions = useGetPermissions();const canEdit = useCanEdit();const canComment = useCanComment();+ const isOwner = useIsDocumentOwner();const userId = useUserId();- const comments = useFigComments({+ const comments = useMacroComments({documentId,userId,canComment,+ canModerate: isOwner,displayName,- email: idToEmail,});const openShare = useShareModal(() => ({id: documentId,diff --git a/apps/web/src/features/block-fig/primitives/create-fig-comments.ts b/apps/web/src/features/block-fig/primitives/create-fig-comments.tsindex 19cd7d9b4d..9edda79c4c 100644--- a/apps/web/src/features/block-fig/primitives/create-fig-comments.ts+++ b/apps/web/src/features/block-fig/primitives/create-fig-comments.ts@@ -2,7 +2,8 @@* The comment tool's state: whether it is on, the thread open beside its* pin, a comment being placed, the sidebar filter, and where the open* page's threads pin now (layers move, so their bounds are read again- * after every edit).+ * after every edit). A followed comment link turns the tool on at its+ * thread.*/import type { FigEngine } from '@core/fig-engine/client';@@ -56,7 +57,6 @@ export function createFigComments(options: {setOpenThreadSignal(id);if (id) {store.markSeen(id);- store.load?.(id);setDraft(undefined);}};@@ -71,7 +71,7 @@ export function createFigComments(options: {};const pageThreads = createMemo(() =>- store.threads().filter((t) => t.anchor?.pageId === pageId())+ store.threads().filter((t) => t.anchor.pageId === pageId()));// Layer bounds come from the engine (an external system), after edits.@@ -80,7 +80,7 @@ export function createFigComments(options: {on([pageThreads, viewer.page, viewer.editVersion], ([threads, page]) => {const ids = [...new Set(- threads.flatMap((t) => (t.anchor?.nodeId ? [t.anchor.nodeId] : []))+ threads.flatMap((t) => (t.anchor.nodeId ? [t.anchor.nodeId] : []))),];const r = ++request;@@ -103,7 +103,6 @@ export function createFigComments(options: {const pins = createMemo((): CommentPin[] => {const me = store.me()?.id;return pageThreads().flatMap((thread) => {- if (!thread.anchor) return [];const at = anchorPoint(thread.anchor, bounds());if (!at) return [];return [@@ -150,48 +149,67 @@ export function createFigComments(options: {setDraft({ anchor: anchorAt(page, at, node), at });};- /** Posts the placed comment; resolves to the new thread's id. */- const post = async (- text: string,- mentions: Parameters<FigCommentStore['create']>[2]- ) => {- const d = draft();- if (!d) return undefined;- const id = await store.create(d.anchor, text, mentions);+ /** The placed comment was posted: its thread opens beside the pin. */+ const posted = (threadId: string) => {setDraft(undefined);- setOpenThread(id);- return id;+ setOpenThread(threadId);+ };++ /** Where an anchor on the open page pins now (its layer may have moved). */+ const pinPoint = async (anchor: FigCommentAnchor) => {+ if (!anchor.nodeId) return anchorPoint(anchor, new Map());+ try {+ const [g] = await engine.geometry(viewer.page(), [anchor.nodeId]);+ return g ? anchorPoint(anchor, new Map([[g.id, g.bounds]])) : undefined;+ } catch {+ return undefined;+ }};/** Shows a thread: its page, its pin in view, and the thread open. */const reveal = async (thread: FigCommentThread) => {const anchor = thread.anchor;- if (anchor && anchor.pageId !== pageId()) {+ if (anchor.pageId !== pageId()) {const index = viewer.pages.findIndex((p) => p.id === anchor.pageId);if (index >= 0) await viewer.openPage(index);}setOpenThread(thread.id);- const pin = pins().find((p) => p.thread.id === thread.id);- if (pin) {- const v = viewer.viewport();- const z = viewer.camera().zoom;- const view = { w: v.w / z, h: v.h / z };- const c = viewer.camera();- const inView =- pin.at.x >= c.x &&- pin.at.y >= c.y &&- pin.at.x <= c.x + view.w &&- pin.at.y <= c.y + view.h;- if (!inView)- viewer.zoomToRect({- x: pin.at.x - view.w / 2,- y: pin.at.y - view.h / 2,- w: view.w,- h: view.h,- });- }+ if (anchor.pageId !== pageId()) return;+ const at = await pinPoint(anchor);+ if (!at) return;+ const v = viewer.viewport();+ const c = viewer.camera();+ const view = { w: v.w / c.zoom, h: v.h / c.zoom };+ const inView =+ at.x >= c.x &&+ at.y >= c.y &&+ at.x <= c.x + view.w &&+ at.y <= c.y + view.h;+ if (!inView)+ viewer.zoomToRect({+ x: at.x - view.w / 2,+ y: at.y - view.h / 2,+ w: view.w,+ h: view.h,+ });};+ // Following a comment link (navigation, an external event) shows its+ // comment: the thread at its pin, or the list with the discussion.+ createEffect(+ on(+ () => store.linked?.(),+ (link) => {+ if (!link) return;+ setActive(true);+ viewer.setTool('move');+ const thread = store.threads().find((t) => t.id === link.threadId);+ if (thread) void reveal(thread);+ else viewer.setDesignOpen(true);+ }+ )+ );+return {store,active,@@ -206,7 +224,7 @@ export function createFigComments(options: {listed,unreadCount,placeAt,- post,+ posted,reveal,isUnread: (t: FigCommentThread) =>isUnread(t, store.me()?.id, store.seenAt(t.id)),diff --git a/apps/web/src/features/block-fig/queries/fig-comments.test.ts b/apps/web/src/features/block-fig/queries/fig-comments.test.tsnew file mode 100644index 0000000000..0bd945b294--- /dev/null+++ b/apps/web/src/features/block-fig/queries/fig-comments.test.ts@@ -0,0 +1,93 @@+import type { Message, MessageListItem } from '@service-storage/messages';+import { describe, expect, it } from 'vitest';+import { figAnchor, figThread } from './fig-comments';++const parent = { type: 'document' as const, id: 'design' };+const anchor = { type: 'fig', pageId: '0:1', nodeId: '1:10', x: 4, y: 8 };++const message = (id: string, sender: string, content: string): Message => ({+ id,+ parent,+ sender_id: sender,+ content,+ mentions: [],+ attachments: [],+ reactions: [],+ created_at: '2026-10-05T12:00:00.000Z',+ updated_at: '2026-10-05T12:00:00.000Z',+});++const root = (+ overrides: Partial<MessageListItem> = {},+ state: Partial<MessageListItem['state']> = {}+): MessageListItem => ({+ ...message('root', 'u1', 'Check **this**'),+ state: {+ root_id: 'root',+ user_id: 'u1',+ resolved: false,+ anchor: anchor as MessageListItem['state']['anchor'],+ created_at: '',+ updated_at: '',+ ...state,+ },+ thread: { reply_count: 0, preview: [], latest_reply_at: null },+ ...overrides,+});++const name = (id: string) => (id === 'u1' ? 'Alex' : 'Blair');++describe('fig comment threads', () => {+ it('reads only fig pins', () => {+ expect(figAnchor(anchor as MessageListItem['state']['anchor'])).toEqual({+ pageId: '0:1',+ nodeId: '1:10',+ x: 4,+ y: 8,+ });+ expect(figAnchor(null)).toBeNull();+ expect(figThread(root({}, { anchor: null }), name)).toBeUndefined();+ });++ it('summarizes the root and latest replies as plain text', () => {+ const reply = message('r1', 'u2', 'Done');+ const thread = figThread(+ root({+ thread: {+ reply_count: 4,+ preview: [reply, { ...message('r2', 'u2', 'x'), deleted_at: 'now' }],+ latest_reply_at: null,+ },+ }),+ name+ );+ expect(thread?.anchor).toEqual({+ pageId: '0:1',+ nodeId: '1:10',+ x: 4,+ y: 8,+ });+ expect(thread?.replyCount).toBe(4);+ expect(thread?.comments.map((c) => [c.id, c.author.name, c.text])).toEqual([+ ['root', 'Alex', 'Check **this**'],+ ['r1', 'Blair', 'Done'],+ ]);+ });++ it('drops deleted threads, and deleted roots with nothing left', () => {+ expect(figThread(root({}, { deleted_at: 'now' }), name)).toBeUndefined();+ expect(figThread(root({ deleted_at: 'now' }), name)).toBeUndefined();+ const kept = figThread(+ root({+ deleted_at: 'now',+ thread: {+ reply_count: 1,+ preview: [message('r1', 'u2', 'Still here')],+ latest_reply_at: null,+ },+ }),+ name+ );+ expect(kept?.comments.map((c) => c.text)).toEqual(['', 'Still here']);+ });+});diff --git a/apps/web/src/features/block-fig/queries/fig-comments.ts b/apps/web/src/features/block-fig/queries/fig-comments.tsindex 7b0590a180..0b41454c14 100644--- a/apps/web/src/features/block-fig/queries/fig-comments.ts+++ b/apps/web/src/features/block-fig/queries/fig-comments.ts@@ -1,39 +1,32 @@/**- * A design's comments as document discussions (`/dss/messages/document/<id>`),- * the store markdown, PDF, and spreadsheet comments share: a thread is a- * root message with replies, resolved on the thread, and mentions notify- * through the inbox. A pinned thread's anchor is- * `{ type: 'fig', pageId, nodeId, x, y }`, the `fig` variant of the- * storage service's thread anchors; it accepts one only on a design.- * Whole-document discussions show unpinned.+ * A design's comments as Macro comments: document discussions+ * (`/dss/messages/document/<id>`), the store markdown, PDF, and spreadsheet+ * comments share, written with the shared composer's payload. A pinned+ * thread's root carries `{ type: 'fig', pageId, nodeId, x, y }`, the `fig`+ * variant of the storage service's thread anchors (accepted only on a+ * design); the design's other roots are its discussion.*/-import { queryClient } from '@queries/client';-import { useContacts } from '@queries/contacts/contacts';+import type { InputSnapshot } from '@channel/Input';+import { buildPostMessageSendPayload } from '@channel/Input/message-payload';+import { markdownToPlainText } from '@macro-inc/lexical-core';+import { useMessageRootsQuery } from '@queries/messages/document-messages';import {- useMessageActions,- useMessageRootsQuery,-} from '@queries/messages/document-messages';-import { threadRepliesQueryOptions } from '@queries/messages/thread-replies';+ newMessageId,+ usePatchThreadMutation,+ useSendMessageMutation,+} from '@queries/messages/mutations';import type { ThreadAnchor } from '@service-storage/generated/schemas/threadAnchor';-import type {- Message,- MessageListItem,- PostMessage,-} from '@service-storage/messages';-import { createMemo, createSignal } from 'solid-js';-import type { FigCommentStore } from '../context/fig-comments';+import type { Message, MessageListItem } from '@service-storage/messages';+import { type Accessor, createMemo, createSignal } from 'solid-js';import type {FigComment,FigCommentAnchor,FigCommentThread,- FigPerson,} from '../core/comments';-const MENTION = /<m-user-mention>(.*?)<\/m-user-mention>/g;-/** The pin a thread carries, or none for any other kind of anchor. */-function figAnchor(+export function figAnchor(anchor: ThreadAnchor | null | undefined): FigCommentAnchor | null {if (anchor?.type !== 'fig') return null;@@ -45,42 +38,38 @@ function figAnchor(};}-/** Macro Markdown with user mentions → `@Name` text and the people. */-export function fromContent(- content: string,+/**+ * The viewer's summary of a pinned root: its first comment and latest+ * replies as plain text. `undefined` for a root pinned elsewhere or+ * nowhere, or deleted with nothing left to read.+ */+export function figThread(+ item: MessageListItem,name: (userId: string) => string-): { text: string; mentions: FigPerson[] } {- const mentions: FigPerson[] = [];- const text = content.replace(MENTION, (_, json: string) => {- try {- const { userId } = JSON.parse(json) as { userId?: string };- if (!userId) return '';- const person = { id: userId, name: name(userId) };- mentions.push(person);- return `@${person.name}`;- } catch {- return '';- }+): FigCommentThread | undefined {+ const anchor = figAnchor(item.state.anchor);+ if (+ !anchor ||+ item.state.deleted_at ||+ (item.deleted_at && item.thread.reply_count === 0)+ )+ return undefined;+ const comment = (m: Message): FigComment => ({+ id: m.id,+ author: { id: m.sender_id, name: name(m.sender_id) },+ text: m.deleted_at+ ? ''+ : markdownToPlainText(m.content).trim().replace(/\s+/g, ' '),+ createdAt: Date.parse(m.created_at),});- return { text, mentions };-}--/** `@Name` text → Macro Markdown with user mentions, and their references. */-export function toContent(- text: string,- mentions: readonly FigPerson[],- email: (userId: string) => string-): Pick<PostMessage, 'content' | 'mentions'> {- let content = text;- for (const m of mentions)- content = content- .split(`@${m.name}`)- .join(- `<m-user-mention>${JSON.stringify({ userId: m.id, email: email(m.id) })}</m-user-mention>`- );return {- content,- mentions: mentions.map((m) => ({ entity_type: 'user', entity_id: m.id })),+ id: item.id,+ anchor,+ resolved: item.state.resolved,+ comments: [item, ...item.thread.preview.filter((m) => !m.deleted_at)].map(+ comment+ ),+ replyCount: item.thread.reply_count,};}@@ -94,72 +83,34 @@ function readSeen(documentId: string): Record<string, number> {}}-export function useFigComments(options: {+export function useFigCommentSource(options: {documentId: string;- userId: () => string | undefined;- canComment: () => boolean;+ userId: Accessor<string | undefined>;displayName: (userId: string) => string;- email: (userId: string) => string;-}): FigCommentStore {+}) {const parent = () => ({type: 'document' as const,id: options.documentId,});- const roots = useMessageRootsQuery(parent);- const actions = useMessageActions(parent);- const contacts = useContacts();- const [replies, setReplies] = createSignal<Record<string, Message[]>>({});+ const query = useMessageRootsQuery(parent);+ const send = useSendMessageMutation();+ const patchThread = usePatchThreadMutation();const [seen, setSeen] = createSignal(readSeen(options.documentId));- const comment = (m: Message): FigComment => {- const { text, mentions } = fromContent(m.content, options.displayName);- return {- id: m.id,- author: { id: m.sender_id, name: options.displayName(m.sender_id) },- text,- mentions,- createdAt: Date.parse(m.created_at),- };- };-- const thread = (item: MessageListItem): FigCommentThread => {- const full = replies()[item.id] ?? item.thread.preview;- return {- id: item.id,- anchor: figAnchor(item.state.anchor),- resolved: item.state.resolved,- comments: [item, ...full].filter((m) => !m.deleted_at).map(comment),- };- };-- const threads = createMemo(() => {- const items = roots.isSuccess ? roots.data : [];- return items- .filter(- (i) =>- !i.state.deleted_at && (!i.state.anchor || figAnchor(i.state.anchor))- )- .map(thread);- });-- const post = (message: PostMessage) => actions.post(message);- /** A thread's every reply (the list holds only the first few). */- const load = (threadId: string) => {- void queryClient- .fetchQuery(threadRepliesQueryOptions(parent(), threadId))- .then((t) => setReplies((r) => ({ ...r, [threadId]: t.replies })))- .catch(() => undefined);- };+ const roots = () => (query.isSuccess ? query.data : []);+ const threads = createMemo(() =>+ roots().flatMap((item) => figThread(item, options.displayName) ?? [])+ );return {+ parent,+ /** Whether the roots have loaded (a link resolves against them). */+ loaded: () => query.isSuccess,+ roots,+ root: (id: string) => roots().find((item) => item.id === id),threads,- me: () => {- const id = options.userId();- return id ? { id, name: options.displayName(id) } : undefined;- },- canComment: options.canComment,- seenAt: (id) => seen()[id],- markSeen: (id) => {+ seenAt: (id: string): number | undefined => seen()[id],+ markSeen: (id: string) => {const next = { ...seen(), [id]: Date.now() };setSeen(next);try {@@ -168,38 +119,26 @@ export function useFigComments(options: {// Unread state is a convenience; it resets without storage.}},- async create(anchor, text, mentions) {- const created = await post({- ...toContent(text, mentions, options.email),- anchor: { type: 'fig', ...anchor },+ setResolved: async (rootId: string, resolved: boolean) => {+ await patchThread.mutateAsync({+ parent: parent(),+ rootId,+ patch: { resolved },});- return created.id;},- async reply(threadId, text, mentions) {- await post({- ...toContent(text, mentions, options.email),- thread_id: threadId,+ /** Starts a thread pinned at `anchor`; resolves to its id. */+ post: async (anchor: FigCommentAnchor, snapshot: InputSnapshot) => {+ const senderId = options.userId();+ if (!senderId) throw new Error('Sign in to comment');+ const payload = buildPostMessageSendPayload({ snapshot });+ const message = await send.mutateAsync({+ parent: parent(),+ senderId,+ optimisticId: newMessageId(),+ ...payload,+ message: { ...payload.message, anchor: { type: 'fig', ...anchor } },});- load(threadId);- },- async setResolved(threadId, resolved) {- await actions.resolve(threadId, resolved);- },- async deleteThread(threadId) {- await actions.deleteThread(threadId);- },- load,- people: (query) => {- const q = query.toLowerCase();- const me = options.userId();- return contacts()- .filter(- (u) =>- u.id !== me &&- (u.name.toLowerCase().includes(q) ||- u.email.toLowerCase().includes(q))- )- .map((u) => ({ id: u.id, name: u.name || u.email }));+ return message.id;},};}diff --git a/apps/web/src/features/block-fig/views/comments-panel.tsx b/apps/web/src/features/block-fig/views/comments-panel.tsxindex 516cc21a08..aaa9cd1ab8 100644--- a/apps/web/src/features/block-fig/views/comments-panel.tsx+++ b/apps/web/src/features/block-fig/views/comments-panel.tsx@@ -1,13 +1,32 @@-/** The comment tool's searchable thread list, alongside the canvas. */+/**+ * The comment tool's searchable list of pinned threads, alongside the+ * canvas, with the design's discussion (comments pinned nowhere) below.+ */import FunnelSimple from '@phosphor/funnel-simple.svg';import MagnifyingGlass from '@phosphor/magnifying-glass.svg';import X from '@phosphor/x.svg';import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';-import { CommentAvatar, CommentText } from '../components/comment-thread';+import { Dynamic } from 'solid-js/web';import { EditorMenu } from '../components/editor-menu';-import { type CommentFilter, relativeTime } from '../core/comments';+import {+ type CommentFilter,+ type FigPerson,+ initialsOf,+ relativeTime,+} from '../core/comments';import type { FigComments } from '../primitives/create-fig-comments';+function Avatar(props: { person: FigPerson }) {+ return (+ <span+ class="flex size-6 shrink-0 items-center justify-center rounded-full bg-accent-bg font-medium text-[10px] text-accent"+ title={props.person.name}+ >+ {initialsOf(props.person.name)}+ </span>+ );+}+const FILTERS: { value: CommentFilter; label: string }[] = [{ value: 'open', label: 'Open comments' },{ value: 'resolved', label: 'Resolved comments' },@@ -99,15 +118,15 @@ export function CommentsPanel(props: {: c.filter() === 'resolved'? 'No resolved comments.': c.store.canComment()- ? 'No comments yet. Click the canvas to add one.'- : 'No comments yet.'}+ ? 'No comments on the canvas yet. Click it to add one.'+ : 'No comments on the canvas yet.'}</p>}><For each={threads()}>{(thread) => {const first = () => thread.comments[0];- const replies = () => thread.comments.length - 1;+ const replies = () => thread.replyCount;const people = () =>[...new Map(@@ -117,10 +136,7 @@ export function CommentsPanel(props: {])).values(),].slice(0, 4);- const page = () =>- thread.anchor- ? props.pageName(thread.anchor.pageId)- : undefined;+ const page = () => props.pageName(thread.anchor.pageId);return (<buttontype="button"@@ -133,7 +149,7 @@ export function CommentsPanel(props: {><div class="mb-0.5 flex w-full items-center gap-1"><For each={people()}>- {(person) => <CommentAvatar person={person} />}+ {(person) => <Avatar person={person} />}</For><Show when={c.isUnread(thread)}><span@@ -156,11 +172,11 @@ export function CommentsPanel(props: {)}</span></div>- <Show when={first()}>- {(comment) => (- <div class="line-clamp-3">- <CommentText comment={comment()} />- </div>+ <Show when={first()?.text}>+ {(text) => (+ <p class="line-clamp-3 whitespace-pre-wrap break-words text-ink">+ {text()}+ </p>)}</Show><div class="flex gap-2 text-[11px]">@@ -178,6 +194,16 @@ export function CommentsPanel(props: {}}</For></Show>+ <Show when={c.store.Discussion}>+ {(discussion) => (+ <div+ class="border-edge-frame border-t px-3 py-2"+ data-testid="fig-comments-discussion"+ >+ <Dynamic component={discussion()} />+ </div>+ )}+ </Show></div></div>);diff --git a/apps/web/src/features/block-fig/views/fig-viewer.tsx b/apps/web/src/features/block-fig/views/fig-viewer.tsxindex 5984ad0314..a4b2ecf4cb 100644--- a/apps/web/src/features/block-fig/views/fig-viewer.tsx+++ b/apps/web/src/features/block-fig/views/fig-viewer.tsx@@ -1060,6 +1060,7 @@ export function FigViewer() {comments={c()}camera={viewer.camera()}viewport={viewer.viewport()}+ onDismiss={() => root.focus({ preventScroll: true })}/>)}</Show>diff --git a/apps/web/src/features/block-fig/views/macro-comments.tsx b/apps/web/src/features/block-fig/views/macro-comments.tsxnew file mode 100644index 0000000000..c339f87ad8--- /dev/null+++ b/apps/web/src/features/block-fig/views/macro-comments.tsx@@ -0,0 +1,130 @@+/**+ * The design's comment store in the app: Macro comments, shown and written+ * with the shared message thread, composer, and discussion that markdown,+ * PDF, and spreadsheet comments use (replies, reactions, edits, mentions,+ * attachments, and copied links). A `comment_id` link opens its comment.+ */++import { ChannelInput } from '@channel/Input';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import {+ useParamNavigationCount,+ useUrlParams,+} from '@core/component/ParamsProvider';+import { toast } from '@core/component/Toast/Toast';+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';+import { EntityDiscussion } from '@core/messages/EntityDiscussion';+import { MessageThread } from '@core/messages/MessageThread';+import { buildSimpleEntityUrl } from '@core/util/url';+import { useMessageLink } from '@queries/messages/document-messages';+import { type Accessor, createMemo, createSignal, Show } from 'solid-js';+import type {+ FigCommentComposerProps,+ FigCommentStore,+} from '../context/fig-comments';+import { figAnchor, useFigCommentSource } from '../queries/fig-comments';++export function useMacroComments(options: {+ documentId: string;+ userId: Accessor<string | undefined>;+ canComment: Accessor<boolean>;+ /** Delete other people's comments (the document's owner). */+ canModerate: Accessor<boolean>;+ displayName: (userId: string) => string;+}): FigCommentStore {+ const source = useFigCommentSource(options);+ const entity = { type: 'fig', id: options.documentId };+ const buildLink = (message: { id: string }) =>+ buildSimpleEntityUrl(entity, { [COMMENT_LINK_PARAM]: message.id });++ const params = useUrlParams({ commentId: COMMENT_LINK_PARAM });+ const navigation = useParamNavigationCount(COMMENT_LINK_PARAM);+ const target = useMessageLink(source.parent, params.commentId);+ /** Once per followed link, when its thread is known. */+ const linked = createMemo(+ () => {+ const rootId = target.rootId();+ if (!params.commentId() || !rootId || !source.loaded()) return undefined;+ const root = source.root(rootId);+ return {+ key: navigation(),+ threadId: root && figAnchor(root.state.anchor) ? rootId : null,+ };+ },+ undefined,+ { equals: (a, b) => a?.key === b?.key && a?.threadId === b?.threadId }+ );+ // Clicking the linked comment releases its highlight until the next link.+ const [cleared, setCleared] = createSignal<number>();+ const targetIn = (threadId: string | null) => {+ const link = linked();+ return link && link.threadId === threadId && cleared() !== link.key+ ? target.messageId()+ : null;+ };+ const clearTarget = () => setCleared(linked()?.key);++ const Thread = (props: { threadId: string }) => (+ <StaticMarkdownContext>+ <Show when={source.root(props.threadId)}>+ {(root) => (+ <MessageThread+ data={root()}+ canWrite={options.canComment()}+ canModerate={options.canModerate()}+ targetId={targetIn(props.threadId)}+ onClearTarget={clearTarget}+ buildLink={buildLink}+ expanded+ monorail+ />+ )}+ </Show>+ </StaticMarkdownContext>+ );++ const Composer = (props: FigCommentComposerProps) => (+ <StaticMarkdownContext>+ <ChannelInput+ parent={source.parent()}+ flat+ input={{ mode: 'reply', placeholder: 'Add a comment...' }}+ onClose={() => props.onCancel()}+ onEscape={() => props.onCancel()}+ onSendError={() => toast.failure('Could not post the comment')}+ onSend={async (snapshot) => {+ props.onPosted(await source.post(props.anchor, snapshot));+ }}+ />+ </StaticMarkdownContext>+ );++ const Discussion = () => (+ <StaticMarkdownContext>+ <EntityDiscussion+ parent={source.parent()}+ canWrite={options.canComment()}+ canModerate={options.canModerate()}+ link={entity}+ targetId={targetIn(null)}+ label="Discussion"+ />+ </StaticMarkdownContext>+ );++ return {+ threads: source.threads,+ me: () => {+ const id = options.userId();+ return id ? { id, name: options.displayName(id) } : undefined;+ },+ canComment: options.canComment,+ seenAt: source.seenAt,+ markSeen: source.markSeen,+ setResolved: source.setResolved,+ Thread,+ Composer,+ Discussion,+ linked,+ };+}diff --git a/apps/web/src/features/notifications/document-comment-location.ts b/apps/web/src/features/notifications/document-comment-location.tsindex aa9c773013..5f602e50de 100644--- a/apps/web/src/features/notifications/document-comment-location.ts+++ b/apps/web/src/features/notifications/document-comment-location.ts@@ -33,7 +33,7 @@ function safeDocumentContentToBlockName(function resolveBlockCommentParamName(type: BlockName | BlockAlias) {const resolved = resolveBlockAlias(type);- if (resolved === 'md' || resolved === 'spreadsheet')+ if (resolved === 'md' || resolved === 'spreadsheet' || resolved === 'fig')return MD_URL_PARAMS.commentId;if (resolved === 'pdf') return PDF_URL_PARAMS.annotationId;}diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 79a76e335d..777dac15f9 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -1365,23 +1365,29 @@ Layout and test hooks:(`fig-present-button`, ⌥⌘↵ / Ctrl+Alt+Enter) are in the inspector header,or float at the canvas's top right while that panel is hidden. Theshortcuts dialog (`fig-shortcuts`, Ctrl+⇧+?) is also in the main menu.-- **Comments** (the comment tool, C): pins (`fig-comment-pin`,- `data-thread`, `data-unread`) at a constant size over the canvas; a click- places a comment on the top-level frame there (it moves with the frame)- or on the canvas, composed in `fig-comment-input` (Enter posts, ⇧Enter a- new line, `@` offers people: `fig-mention-menu`, `fig-mention-option`).- A pin opens its thread (`fig-comment-popover`: comments- `fig-comment-item`, mentions `fig-comment-mention`, `fig-comment-reply`- with `fig-comment-reply-post`, `fig-comment-resolve` /- `fig-comment-reopen`, and the author's `fig-comment-delete`). The right- panel becomes the comments list (`fig-comments-panel`), with Present and- Zoom in its header. Search (`fig-comments-search`) matches comment text,- replies, and author names. Open `fig-comments-filter` for+- **Comments** (the comment tool, C): Macro comments, the same threads as+ markdown, PDF, and spreadsheet comments. Pins (`fig-comment-pin`,+ `data-thread`, `data-unread`) sit at a constant size over the canvas; a+ click places a comment on the top-level frame there (it moves with the+ frame) or on the canvas, written in `fig-comment-draft` with the app's+ message composer (Enter posts; `@` mentions people and documents;+ attachments; Escape cancels). A pin opens its thread beside it+ (`fig-comment-popover`, `data-thread`, `data-resolved`): the shared+ message thread (replies, reactions, edit, delete, copy link) under a+ header with `fig-comment-resolve` / `fig-comment-reopen` and+ `fig-comment-close`. The right panel becomes the comments list+ (`fig-comments-panel`), with Present and Zoom in its header. Search+ (`fig-comments-search`) matches the first comment, the latest replies,+ and author names. Open `fig-comments-filter` for`fig-comments-filter-<open|resolved|all>`. Rows `fig-comment-row` have- `data-unread`; a row opens the thread on its page. Escape closes the- thread, then the tool. In the app, comments are document discussions- with a `fig` thread anchor, on wherever the viewer is; the fixture keeps- them in memory.+ `data-unread`; a row opens the thread on its page. Below the rows,+ `fig-comments-discussion` holds comments on the whole design. A copied+ comment link (`?comment_id=`) or a comment notification opens the tool+ at its thread (or at the discussion). Escape closes the thread, then the+ tool. In the app, a pinned thread's root carries a `fig` thread anchor;+ the browser fixture keeps comments in memory, with plain stand-ins for+ the thread (`fig-comment-item`, `fig-comment-reply`) and composer+ (`fig-comment-input`).- **Present** (`fig-present`): the selection's top-level frame (or thefirst flow's start, or the first frame) scaled to fit(`fig-present-screen`, `data-frame`), with the prototype playing: clicks