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
fix(comments): deselect a markdown comment on a click outside (#8561)
gbirmanc276c9a7030b
diff --git a/apps/web/src/features/block-md/comments/CommentMargin.test.tsx b/apps/web/src/features/block-md/comments/CommentMargin.test.tsxnew file mode 100644index 0000000000..c43a30519a--- /dev/null+++ b/apps/web/src/features/block-md/comments/CommentMargin.test.tsx@@ -0,0 +1,175 @@+import {+ DRAFT_THREAD_ID,+ type Root,+ type ThreadId,+} from '@core/comments/commentType';+import type { CommentsContextType } from '@core/comments/Thread';+import { MARK_SELECTED_COMMENT_COMMAND } from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';+import { Dialog } from '@kobalte/core/dialog';+import { CommentNode } from '@macro-inc/lexical-core';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { COMMAND_PRIORITY_EDITOR, createEditor } from 'lexical';+import { createContext, createSignal, useContext } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createMarkdownDocumentState } from '../context/markdown-document-state';+import { CommentMargin } from './CommentMargin';++const mocks = vi.hoisted(() => ({+ state: undefined as+ | ReturnType<typeof createMarkdownDocumentState>+ | undefined,+}));++vi.mock('../context/markdown-document-context', () => ({+ useMarkdownDocument: () => ({+ documentId: () => 'document',+ kind: () => 'document',+ state: mocks.state,+ permissions: { canComment: () => true, isOwner: () => false },+ }),+}));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('./commentLayout', () => ({+ createCommentLayout: () => ({+ setThreadHeights: () => {},+ threadPositions: { mark: { layout: { calculatedYPos: 0 } } },+ }),+}));+vi.mock('./messageCommentOperations', () => ({+ useCreateMessageComment: () => async () => null,+}));+vi.mock('./CommentThreadDrawer', () => ({ CommentThreadDrawer: () => null }));+vi.mock('@core/comments/MinimizedThreads', () => ({+ MinimizedThread: () => null,+}));+vi.mock('@core/comments/Thread', () => {+ const CommentsContext = createContext<CommentsContextType>();+ return {+ CommentsContext,+ // Stands in for the margin card: clicking it opens its thread, and its+ // delete confirmation renders into a portal outside the app.+ Thread: (props: { comment: Root; isActive: boolean }) => {+ const context = useContext(CommentsContext);+ const [confirming, setConfirming] = createSignal(false);+ return (+ <article+ aria-current={props.isActive}+ onClick={() => context?.setActiveThread(props.comment.threadId)}+ >+ Comment card+ <button onClick={() => setConfirming(true)}>Delete</button>+ <Dialog open={confirming()} onOpenChange={setConfirming}>+ <Dialog.Portal>+ <Dialog.Content>+ <button>Cancel delete</button>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog>+ </article>+ );+ },+ };+});++const comment: Root = {+ id: 'root',+ rootId: 'root',+ threadId: 'root',+ anchorId: 'mark',+ owner: 'user',+ author: 'user',+ text: 'Comment',+ createdAt: '2026-10-22T00:00:00Z',+ isNew: false,+ children: [],+ replyCount: 0,+};++afterEach(() => {+ cleanup();+});++function setup(open?: { active?: ThreadId; highlighted?: ThreadId[] }) {+ const state = createMarkdownDocumentState();+ mocks.state = state;+ state.setCommentState('threads', { root: comment });+ const editor = createEditor({+ namespace: 'comment-margin',+ nodes: [CommentNode],+ onError: (error) => {+ throw error;+ },+ });+ const releasedMarks = vi.fn();+ editor.registerCommand(+ MARK_SELECTED_COMMENT_COMMAND,+ (ids) => {+ if (ids.length === 0) releasedMarks();+ return true;+ },+ COMMAND_PRIORITY_EDITOR+ );+ state.editor.setMd('editor', editor);+ render(() => (+ <div>+ <button>Sidebar</button>+ <div data-testid="editor" />+ <CommentMargin wideEnough />+ </div>+ ));+ editor.setRootElement(screen.getByTestId('editor'));+ if (open?.active !== undefined) {+ state.setCommentState('activeCommentThread', open.active);+ }+ if (open?.highlighted) {+ state.setCommentState('highlightedCommentThreads', open.highlighted);+ }+ // The modal delete confirmation hides the card from the accessibility tree.+ const card = () => screen.getByRole('article', { hidden: true });+ return { state, card, releasedMarks };+}++describe('CommentMargin', () => {+ it('closes a thread opened from its card when a press lands outside the comments', () => {+ const { state, card, releasedMarks } = setup();+ fireEvent.click(card());+ expect(card().getAttribute('aria-current')).toBe('true');++ fireEvent.pointerDown(screen.getByRole('button', { name: 'Sidebar' }));++ expect(card().getAttribute('aria-current')).toBe('false');+ expect(state.comments.activeCommentThread).toBeNull();+ expect(releasedMarks).toHaveBeenCalledOnce();+ });++ it('keeps the thread open for presses on the editor, the card, and the layers it opened', async () => {+ const { card, releasedMarks } = setup({ active: 'root' });++ fireEvent.pointerDown(screen.getByTestId('editor'));+ fireEvent.pointerDown(card());+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ fireEvent.pointerDown(+ await screen.findByRole('button', { name: 'Cancel delete' })+ );++ expect(card().getAttribute('aria-current')).toBe('true');+ expect(releasedMarks).not.toHaveBeenCalled();+ });++ it('releases a thread highlighted by the caret when a press lands outside', () => {+ const { releasedMarks } = setup({ highlighted: ['root'] });++ fireEvent.pointerDown(screen.getByRole('button', { name: 'Sidebar' }));++ expect(releasedMarks).toHaveBeenCalledOnce();+ });++ it('leaves a draft comment open', () => {+ const { state, releasedMarks } = setup({ active: DRAFT_THREAD_ID });++ fireEvent.pointerDown(screen.getByRole('button', { name: 'Sidebar' }));++ expect(state.comments.activeCommentThread).toBe(DRAFT_THREAD_ID);+ expect(releasedMarks).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/block-md/comments/CommentMargin.tsx b/apps/web/src/features/block-md/comments/CommentMargin.tsxindex 9a8bbd633d..582607985e 100644--- a/apps/web/src/features/block-md/comments/CommentMargin.tsx+++ b/apps/web/src/features/block-md/comments/CommentMargin.tsx@@ -9,6 +9,7 @@ import {type CommentsContextType,Thread,} from '@core/comments/Thread';+import { MARK_SELECTED_COMMENT_COMMAND } from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { autoUpdate, computePosition } from '@floating-ui/dom';import {@@ -33,8 +34,17 @@ const useCommentsContext = (const createComment = useCreateMessageComment();const commentsContext: CommentsContextType = {- setActiveThread: (threadId) =>- setCommentState('activeCommentThread', threadId),+ setActiveThread: (threadId) => {+ setCommentState('activeCommentThread', threadId);+ // Activating a thread selects its mark, and a selected mark keeps its+ // thread active, so releasing the thread releases the mark too.+ if (threadId === null) {+ state.editor.md.editor?.dispatchCommand(+ MARK_SELECTED_COMMENT_COMMAND,+ []+ );+ }+ },setThreadHeight,canComment: permissions.canComment,isDocumentOwner: permissions.isOwner,@@ -86,13 +96,37 @@ export const CommentMargin = (props: { wideEnough: boolean }) => {const commentsContext = useCommentsContext(setThreadHeights);+ let marginRef!: HTMLDivElement;+ const hasOpenThread = createMemo(() =>+ [...activeThreads()].some((id) => !isDraftThreadId(id))+ );+ // An open thread closes when a press lands outside the comments. The+ // editor is left to its selection sync, and layers portaled beside the app+ // (a card's menus and delete confirmation) belong to the card that opened+ // them. A draft keeps its composer, and touch uses the drawer's dismissal.+ createEffect(() => {+ if (!hasOpenThread() || isTouchDevice()) return;+ const app = appRootOf(marginRef);+ const onPointerDown = (e: PointerEvent) => {+ const target = e.target;+ if (!(target instanceof Node) || !app.contains(target)) return;+ if (marginRef.contains(target)) return;+ if (state.editor.md.editor?.getRootElement()?.contains(target)) return;+ commentsContext.setActiveThread(null);+ };+ document.addEventListener('pointerdown', onPointerDown, true);+ onCleanup(() =>+ document.removeEventListener('pointerdown', onPointerDown, true)+ );+ });+// Touch devices never expand floating thread cards; the active thread is// presented in the CommentThreadDrawer instead.const isMinimized = createMemo(() => isTouchDevice() || !props.wideEnough);return (<CommentsContext.Provider value={commentsContext}>- <div class="relative h-full">+ <div ref={marginRef} class="relative h-full"><For each={Object.values(commentState.threads)}>{(thread) => (<Show when={thread}>@@ -135,6 +169,15 @@ export const CommentMargin = (props: { wideEnough: boolean }) => {);};+/** The element under `<body>` that holds `el`: the app, or the portal it renders in. */+function appRootOf(el: HTMLElement): HTMLElement {+ let root = el;+ while (root.parentElement && root.parentElement !== el.ownerDocument.body) {+ root = root.parentElement;+ }+ return root;+}+/**** TODO: this could be useful to provide default positioningdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.test.tsnew file mode 100644index 0000000000..5727978c91--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.test.ts@@ -0,0 +1,72 @@+import { $createCommentNode, CommentNode } from '@macro-inc/lexical-core';+import {+ $createParagraphNode,+ $createRangeSelection,+ $createTextNode,+ $getRoot,+ $setSelection,+ createEditor,+} from 'lexical';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { commentPlugin, MARK_SELECTED_COMMENT_COMMAND } from './commentPlugin';++const disposers: (() => void)[] = [];+afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+});++function setup() {+ const editor = createEditor({+ namespace: 'comment-plugin',+ nodes: [CommentNode],+ onError: (error) => {+ throw error;+ },+ });+ const root = document.createElement('div');+ root.contentEditable = 'true';+ document.body.append(root);+ editor.setRootElement(root);+ const setActiveIds = vi.fn<(ids: string[]) => void>();+ disposers.push(+ commentPlugin({+ peerId: () => '1',+ ops: { add: () => {}, init: () => {}, remove: () => {}, setActiveIds },+ })(editor)+ );+ disposers.push(() => {+ editor.setRootElement(null);+ root.remove();+ });+ return { editor, root, setActiveIds };+}++describe('commentPlugin', () => {+ it('selects the comment under an unmoved caret again when the editor is clicked', () => {+ const { editor, root, setActiveIds } = setup();+ editor.update(+ () => {+ const commented = $createTextNode('world');+ $getRoot().append(+ $createParagraphNode().append(+ $createTextNode('hello '),+ $createCommentNode({ ids: ['mark'] }).append(commented)+ )+ );+ const selection = $createRangeSelection();+ selection.anchor.set(commented.getKey(), 2, 'text');+ selection.focus.set(commented.getKey(), 2, 'text');+ $setSelection(selection);+ },+ { discrete: true }+ );+ expect(setActiveIds).toHaveBeenLastCalledWith(['mark']);++ // The thread is closed from outside the editor; the caret stays put.+ editor.dispatchCommand(MARK_SELECTED_COMMENT_COMMAND, []);+ expect(setActiveIds).toHaveBeenLastCalledWith([]);++ root.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(setActiveIds).toHaveBeenLastCalledWith(['mark']);+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.tsindex 706c6a8272..942adbf7aa 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts@@ -19,7 +19,9 @@ import {$isRangeSelection,$isTextNode,$nodesOfType,+ CLICK_COMMAND,COMMAND_PRIORITY_EDITOR,+ COMMAND_PRIORITY_LOW,createCommand,type LexicalEditor,type LexicalNode,@@ -160,6 +162,29 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {}};+ const $selectMarksAtCaret = () => {+ const selection = $getSelection();+ if (selection === null) return;+ let hasActiveIds = false;+ let newActiveIds: string[] | undefined;++ if ($isRangeSelection(selection)) {+ const markIds = $getMarkIdsAtCaret(+ selection.anchor.getNode(),+ selection.anchor.offset+ );+ if (markIds != null) {+ newActiveIds = markIds;+ hasActiveIds = true;+ }+ }++ if (!hasActiveIds) {+ ops.setActiveIds([]);+ }+ markSelected(newActiveIds);+ };+return mergeRegister(registerNestedElementResolver<CommentNode>(editor,@@ -201,30 +226,20 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {}),editor.registerUpdateListener(({ editorState }) => {- editorState.read(() => {- const selection = $getSelection();- if (selection === null) return;- let hasActiveIds = false;- let newActiveIds: string[] | undefined;-- if ($isRangeSelection(selection)) {- const markIds = $getMarkIdsAtCaret(- selection.anchor.getNode(),- selection.anchor.offset- );- if (markIds != null) {- newActiveIds = markIds;- hasActiveIds = true;- }- }-- if (!hasActiveIds) {- ops.setActiveIds([]);- }- markSelected(newActiveIds);- });+ editorState.read($selectMarksAtCaret);}),+ // A click selects the comments at the caret even when the caret did not+ // move, such as returning to text whose thread was closed from outside.+ editor.registerCommand(+ CLICK_COMMAND,+ () => {+ $selectMarksAtCaret();+ return false;+ },+ COMMAND_PRIORITY_LOW+ ),+editor.registerCommand(CREATE_DRAFT_COMMENT_COMMAND,() => {diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex f008f23ade..da20076741 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2599,6 +2599,11 @@ without changing the card size or header text wrapping. New comments, replies,and edits use plain inputs on the card or drawer's background. On desktop, withthe margin card focused: Enter opens a reply (same as the Reply action; Enter inthe composer then sends), and Escape closes the reply composer, then the card.+A press anywhere outside the comments and the document text (another split, the+sidebar, the document header or empty page) returns a selected card and its+highlighted text to their resting state; menus and dialogs opened from the card+do not, and an unsent new comment keeps its composer. Clicking the commented+text again selects the card again.The pinned reply keeps at least 16px ofbottom clearance above the drawer's curve, including while the keyboard is open,and accounts for the home-indicator safe area when the keyboard is closed.