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(md): find all mention chips in document search (#8695)
Wolf Mermelsteinf15017c89522
diff --git a/apps/web/src/features/calendar/utils/calendar-description.test.ts b/apps/web/src/features/calendar/utils/calendar-description.test.tsindex 946b54df62..c3eaf03495 100644--- a/apps/web/src/features/calendar/utils/calendar-description.test.ts+++ b/apps/web/src/features/calendar/utils/calendar-description.test.ts@@ -189,7 +189,7 @@ describe('exportCalendarDescription', () => {` about <span data-document-mention="true" data-document-id="${DOCUMENT_ID}" data-document-name="August Cycle Planning" data-block-name="md">August Cycle Planning</span></p>`);expect(exportCalendarDescription(editor)).toBe(- `<p>ping Teo Nys about <a href="${window.location.origin}/app/md/${DOCUMENT_ID}">August Cycle Planning</a></p>`+ `<p>ping @Teo Nys about <a href="${window.location.origin}/app/md/${DOCUMENT_ID}">August Cycle Planning</a></p>`);});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.test.tsindex e59dd8159c..66cf2cb842 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.test.ts@@ -1,6 +1,8 @@import { $createListItemNode, $createListNode } from '@lexical/list';import {+ $createContactMentionNode,$createDocumentMentionNode,+ $createGroupMentionNode,$createUserMentionNode,} from '@macro-inc/lexical-core';import {@@ -15,9 +17,11 @@ import {$getRoot,createEditor,type LexicalEditor,+ type LexicalNode,} from 'lexical';import { describe, expect, it } from 'vitest';import {+ DO_REPLACE_COMMAND,DO_SEARCH_COMMAND,findAndReplacePlugin,type NodekeyOffset,@@ -49,7 +53,29 @@ function createSearchEditor(): {};}-describe('findAndReplacePlugin document mentions', () => {+function searchMention(createMention: () => LexicalNode, query: string) {+ const { editor, getListOffset } = createSearchEditor();+ let mentionKey = '';++ editor.update(+ () => {+ const mention = createMention();+ mentionKey = mention.getKey();+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('Hello '), mention);+ $getRoot().clear().append(paragraph);+ },+ { discrete: true }+ );++ editor.getEditorState().read(() => {+ editor.dispatchCommand(DO_SEARCH_COMMAND, query);+ });++ return { offsets: getListOffset(), mentionKey };+}++describe('findAndReplacePlugin mention chips', () => {it('finds a substring in an inline task chip title', () => {const { editor, getListOffset } = createSearchEditor();let mentionKey = '';@@ -112,28 +138,87 @@ describe('findAndReplacePlugin document mentions', () => {expect(offsets.every((offset) => offset.key === textKey)).toBe(true);});- it('does not match ignored user-mention display names', () => {+ it('finds a user mention display name', () => {+ const { offsets, mentionKey } = searchMention(+ () =>+ $createUserMentionNode({+ userId: 'user-1',+ email: '[email protected]',+ displayName: 'refs',+ }),+ '@refs'+ );++ expect(offsets.some((offset) => offset.key === mentionKey)).toBe(true);+ expect(offsets[0]?.offset.start).toBe(0);+ expect(offsets[0]?.offset.end).toBe(5);+ });++ it('finds a group mention alias', () => {+ const { offsets, mentionKey } = searchMention(+ () => $createGroupMentionNode({ groupAlias: 'refs' }),+ '@refs'+ );++ expect(offsets.some((offset) => offset.key === mentionKey)).toBe(true);+ expect(offsets[0]?.offset.start).toBe(0);+ expect(offsets[0]?.offset.end).toBe(5);+ });++ it('finds a contact mention name', () => {+ const { offsets, mentionKey } = searchMention(+ () =>+ $createContactMentionNode({+ contactId: 'contact-1',+ name: 'Ada Lovelace',+ emailOrDomain: '[email protected]',+ isCompany: false,+ }),+ 'Lovelace'+ );++ expect(offsets.some((offset) => offset.key === mentionKey)).toBe(true);+ expect(offsets[0]?.offset.start).toBe(4);+ expect(offsets[0]?.offset.end).toBe(12);+ });++ it('does not delete text beside a mention when replace spans both', () => {const { editor, getListOffset } = createSearchEditor();editor.update(() => {- const mention = $createUserMentionNode({- userId: 'user-1',- email: '[email protected]',- displayName: 'Wolf UniqueHandle',- });const paragraph = $createParagraphNode();- paragraph.append($createTextNode('Hello '), mention);+ paragraph.append(+ $createUserMentionNode({+ userId: 'user-1',+ email: '[email protected]',+ displayName: 'refs',+ }),+ $createTextNode(' today')+ );$getRoot().clear().append(paragraph);},{ discrete: true });editor.getEditorState().read(() => {- editor.dispatchCommand(DO_SEARCH_COMMAND, 'UniqueHandle');+ editor.dispatchCommand(DO_SEARCH_COMMAND, '@refs to');});+ expect(getListOffset().length).toBeGreaterThan(1);- expect(getListOffset()).toEqual([]);+ editor.update(+ () => {+ editor.dispatchCommand(DO_REPLACE_COMMAND, {+ replaceString: 'x',+ nodeKeyOffsetList: getListOffset(),+ });+ },+ { discrete: true }+ );++ expect(+ editor.getEditorState().read(() => $getRoot().getTextContent())+ ).toBe('@refs today');});});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.tsindex 05ffe3ab03..72927c5b60 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts@@ -51,10 +51,10 @@ type FindAndReplaceProps = {};function shouldIgnoreNodeType(type: string) {- // Document mentions (task chips, doc/channel refs, …) stay searchable via- // getTextContent() so Ctrl+F matches their visible titles. Replace still- // no-ops on them because they are not TextNodes.- const ignoredTypes = ['user-mention', 'horizontalrule', 'equation'];+ // Mention chips stay searchable via getTextContent() so Ctrl+F matches+ // their visible titles. Replace still no-ops on them because they are+ // not TextNodes.+ const ignoredTypes = ['horizontalrule', 'equation'];return ignoredTypes.includes(type);}@@ -162,6 +162,16 @@ function selectNextKey(key: NodeKey) {$setSelection(nodeSelection);}+function pairKeysWithNonTextNodes(items: NodekeyOffset[]): Set<number> {+ const skip = new Set<number>();+ for (const item of items) {+ if (item.pairKey === undefined) continue;+ const node = $getNodeByKey(item.key);+ if (!node || !$isTextNode(node)) skip.add(item.pairKey);+ }+ return skip;+}+function areListOffsetsEqual(left: NodekeyOffset[], right: NodekeyOffset[]) {if (left.length !== right.length) return false;for (let i = 0; i < left.length; i += 1) {@@ -194,11 +204,17 @@ function registerFindAndReplacePlugin(DO_REPLACE_COMMAND,(payload: ReplacePayload) => {editor.update(() => {+ const skipPairKeys = pairKeysWithNonTextNodes(+ payload.nodeKeyOffsetList+ );let previousNodeKey = '';let lengthDiff = 0;let replaceStart: number,replaceEnd: number = 0;payload.nodeKeyOffsetList.map((item) => {+ if (item.pairKey !== undefined && skipPairKeys.has(item.pairKey)) {+ return;+ }if (previousNodeKey === item.key) {replaceStart = item.offset.start - lengthDiff;replaceEnd = item.offset.end - lengthDiff;@@ -240,6 +256,9 @@ function registerFindAndReplacePlugin(DO_REPLACE_ONCE_COMMAND,(payload: ReplacePayload) => {editor.update(() => {+ const skipPairKeys = pairKeysWithNonTextNodes(+ payload.nodeKeyOffsetList+ );let previousNodeKey = '';let lengthDiff = 0;let replaceStart: number,@@ -247,6 +266,9 @@ function registerFindAndReplacePlugin(let replacedCount = 0;let nextKey = '';payload.nodeKeyOffsetList.map((item) => {+ if (item.pairKey !== undefined && skipPairKeys.has(item.pairKey)) {+ return;+ }if (previousNodeKey === item.key) {replaceStart = item.offset.start - lengthDiff;replaceEnd = item.offset.end - lengthDiff;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.test.tsindex 2544b65578..2791d4b0d4 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.test.ts@@ -2,16 +2,21 @@import { describe, expect, it } from 'vitest';import { resolveSearchHighlightRanges } from './searchHighlightTarget';-function mentionChip(title: string, collapsed = false): HTMLElement {+function mentionChip(+ attr: string,+ title: string,+ options: { collapsed?: boolean; prefix?: string } = {}+): HTMLElement {const root = document.createElement('span');- root.setAttribute('data-document-mention', 'true');+ root.setAttribute(attr, 'true');const icon = document.createElement('span');icon.appendChild(document.createElement('svg'));root.appendChild(icon);- if (!collapsed) {+ if (!options.collapsed) {const name = document.createElement('span');- name.setAttribute('data-document-name', title);- name.appendChild(document.createTextNode(title));+ name.appendChild(+ document.createTextNode(`${options.prefix ?? ''}${title}`)+ );root.appendChild(name);}document.body.appendChild(root);@@ -20,7 +25,7 @@ function mentionChip(title: string, collapsed = false): HTMLElement {describe('resolveSearchHighlightRanges', () => {it('highlights the matching substring inside a task chip title', () => {- const chip = mentionChip('Fix login bug');+ const chip = mentionChip('data-document-mention', 'Fix login bug');const ranges = resolveSearchHighlightRanges(chip, {start: 4,end: 9,@@ -33,8 +38,56 @@ describe('resolveSearchHighlightRanges', () => {expect(ranges[0]?.endOffset).toBe(9);});+ it('highlights a user mention using searchable offsets that include @', () => {+ const chip = mentionChip('data-user-mention', 'Wolf UniqueHandle', {+ prefix: '@',+ });+ const ranges = resolveSearchHighlightRanges(chip, {+ start: 1,+ end: 5,+ isReplace: true,+ });++ expect(ranges).toHaveLength(1);+ expect(ranges[0]?.startContainer.textContent).toBe('@Wolf UniqueHandle');+ expect(ranges[0]?.startOffset).toBe(1);+ expect(ranges[0]?.endOffset).toBe(5);+ });++ it('shifts a skill slash that is not in searchable text', () => {+ const chip = mentionChip('data-document-mention', 'draft-skill', {+ prefix: '/',+ });+ const ranges = resolveSearchHighlightRanges(chip, {+ start: 0,+ end: 5,+ isReplace: true,+ });++ expect(ranges).toHaveLength(1);+ expect(ranges[0]?.startContainer.textContent).toBe('/draft-skill');+ expect(ranges[0]?.startOffset).toBe(1);+ expect(ranges[0]?.endOffset).toBe(6);+ });++ it('does not shift a group mention whose text already includes @', () => {+ const chip = mentionChip('data-group-mention', '@refs');+ const ranges = resolveSearchHighlightRanges(chip, {+ start: 0,+ end: 5,+ isReplace: true,+ });++ expect(ranges).toHaveLength(1);+ expect(ranges[0]?.startContainer.textContent).toBe('@refs');+ expect(ranges[0]?.startOffset).toBe(0);+ expect(ranges[0]?.endOffset).toBe(5);+ });+it('falls back to the whole chip when the title is collapsed', () => {- const chip = mentionChip('Fix login bug', true);+ const chip = mentionChip('data-document-mention', 'Fix login bug', {+ collapsed: true,+ });const ranges = resolveSearchHighlightRanges(chip, {start: 0,end: 13,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.tsindex 9a6371db1d..3fb89b33bf 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlightTarget.ts@@ -9,11 +9,24 @@ function getDeepestFirstChild(return htmlEl;}-export function isDocumentMentionElement(element: HTMLElement): boolean {- return (- element.hasAttribute('data-document-mention') ||- element.querySelector('[data-document-mention]') !== null- );+function isMentionAttr(name: string): boolean {+ return name.endsWith('-mention');+}++function mentionRoot(element: HTMLElement): HTMLElement | null {+ if ([...element.attributes].some((attr) => isMentionAttr(attr.name))) {+ return element;+ }+ for (const child of element.querySelectorAll<HTMLElement>('*')) {+ if ([...child.attributes].some((attr) => isMentionAttr(attr.name))) {+ return child;+ }+ }+ return null;+}++export function isMentionElement(element: HTMLElement): boolean {+ return mentionRoot(element) !== null;}function rangesFromTextOffsets(@@ -44,6 +57,17 @@ function rangesFromTextOffsets(return ranges;}+/**+ * Skill chips render a leading `/` that is not in getTextContent(). User and+ * group mentions already include `@` in searchable text, so do not shift those.+ */+function mentionMatchShift(text: string, offset: SplitOffset): number {+ if (text.startsWith('/') && text.length - 1 >= offset.end) {+ return 1;+ }+ return 0;+}+/*** Map a find-match offset onto DOM ranges. Mention chips are decorator nodes,* so character offsets must be applied to the title text inside the pill@@ -53,17 +77,19 @@ export function resolveSearchHighlightRanges(element: HTMLElement,offset: SplitOffset): Range[] {- if (isDocumentMentionElement(element)) {- const nameEl =- (element.hasAttribute('data-document-name')- ? element- : element.querySelector('[data-document-name]')) ?? element;- const ranges = rangesFromTextOffsets(nameEl, offset.start, offset.end);+ const mention = mentionRoot(element);+ if (mention) {+ const shift = mentionMatchShift(mention.textContent ?? '', offset);+ const ranges = rangesFromTextOffsets(+ mention,+ offset.start + shift,+ offset.end + shift+ );if (ranges.length > 0) {return ranges;}const range = document.createRange();- range.selectNode(element);+ range.selectNode(mention);return [range];}@@ -85,7 +111,7 @@ export function getSearchHighlightClientRects(): DOMRect[] {const ranges = resolveSearchHighlightRanges(element, offset);const rects = ranges.flatMap((range) => [...range.getClientRects()]);- if (rects.length === 0 && isDocumentMentionElement(element)) {+ if (rects.length === 0 && isMentionElement(element)) {const box = element.getBoundingClientRect();if (box.width > 0 || box.height > 0) {return [box];diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.tsindex 3bdb8a007f..cd09d7f4ff 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts@@ -345,7 +345,7 @@ describe('@ trigger position', () => {expect(harness.children()).toEqual(['text:hello ',- 'user-mention:Jo',+ 'user-mention:@Jo','text:world',]);});diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 8944b4672a..2cc889b4e6 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2438,8 +2438,8 @@ filter, and tap a result to insert a single mention. The menu should remainvisible above the keyboard while typing.`Ctrl+F` / `Cmd+F` opens the in-document find bar. Matches include paragraph-text and inline mention chips (tasks, docs, channels, skills, …) by the title-shown on the chip.+text and every inline mention chip (people, groups, tasks, docs, channels,+skills, dates, tags, …) by the title shown on the chip.On touch devices, the text-selection menu (Copy, Cut, Comment, Share, and otheravailable actions) appears above the floating header, comment input, and bottomdiff --git a/packages/lexical-core/nodes/UserMentionNode.ts b/packages/lexical-core/nodes/UserMentionNode.tsindex 85243eb12d..8f6f7bcdf2 100644--- a/packages/lexical-core/nodes/UserMentionNode.ts+++ b/packages/lexical-core/nodes/UserMentionNode.ts@@ -190,12 +190,12 @@ export class UserMentionNode extends DecoratorNode<for (const [k, v] of Object.entries(this.getDataAttrs())) {element.setAttribute(k, v.toString());}- element.textContent = this.__displayName;+ element.textContent = this.getTextContent();return { element };}getTextContent(): string {- return this.__displayName;+ return this.__displayName ? `@${this.__displayName}` : '';}getSearchText(): string {diff --git a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts b/packages/lexical-core/tests/internal-transformer-fallbacks.test.tsindex 1007105767..a07b34ecc1 100644--- a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts+++ b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts@@ -92,7 +92,7 @@ describe('internal transformer fallbacks', () => {? paragraph.getFirstChild(): null;expect($isUserMentionNode(node)).toBe(true);- expect(node?.getTextContent()).toBe('a');+ expect(node?.getTextContent()).toBe('@a');});});