Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(editor): let @ open the mentions menu in front of a word (#6790)

Peter Chinmand248a9bb5084
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index e4406a8836..374b95f9ac 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -277,9 +277,10 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {
}
}
-// Validators for the position of the @ trigger.
+// Validator for the position of the @ trigger. Only the text before the caret
+// constrains it, so `@` stays literal mid-word but opens the menu in front of a
+// word — the word itself is left out of the search.
const beforeRegex = /[(['\"\`\s]$/;
-const afterRegex = /^[)\]'\"\`\s]/;
/**
* When mentions nodes are selected by using the arrow keys, we want to be able to delete them.
@@ -644,11 +645,7 @@ function registerMentionsPlugin(
editor.registerCommand(
TYPE_AT_SYMBOL_COMMAND,
() => {
- const shouldTrigger = validTriggerPosition(
- editor,
- beforeRegex,
- afterRegex
- );
+ const shouldTrigger = validTriggerPosition(editor, beforeRegex, null);
if (shouldTrigger) {
editor.update(() => {
$insertNodes([$createInlineSearchNode('@')]);
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.ts
new file mode 100644
index 0000000000..85f732179c
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts
@@ -0,0 +1,265 @@
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+
+vi.hoisted(() => {
+ if (typeof globalThis.Worker === 'undefined') {
+ (globalThis as any).Worker = class FakeWorker {
+ onmessage = null;
+ postMessage() {}
+ terminate() {}
+ addEventListener() {}
+ removeEventListener() {}
+ };
+ }
+});
+
+// Stub any imports before they import the entire app (sad).
+vi.mock('@core/constant/allBlocks', () => ({
+ verifyBlockName: (name: string) => name,
+}));
+vi.mock('@core/signal/mention', () => ({
+ untrackMention: vi.fn(),
+}));
+vi.mock('@service-storage/client', () => ({
+ blockNameToItemType: (name: string) => name,
+}));
+vi.mock('../utils', async () => {
+ const { $getNodeByKey } = await import('lexical');
+ return {
+ $collapseSelection: vi.fn(),
+ $traverseNodes: vi.fn(),
+ nodeByKey: (editorOrState: any, key: string) => {
+ let node: any;
+ editorOrState.read(() => {
+ node = $getNodeByKey(key);
+ });
+ return node;
+ },
+ };
+});
+vi.mock('../plugins/shared', () => ({
+ mapRegisterDelete: () => () => {},
+}));
+
+import { SupportedNodeTypes } from '@macro-inc/lexical-core/node-list';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $isRangeSelection,
+ createEditor,
+ type LexicalEditor,
+ type TextNode,
+} from 'lexical';
+import { createSignal } from 'solid-js';
+import {
+ INSERT_USER_MENTION_COMMAND,
+ mentionsPlugin,
+ REMOVE_INLINE_SEARCH_COMMAND,
+} from '../plugins/mentions/mentionsPlugin';
+import type { MenuOperations } from '../shared/inlineMenu';
+
+type Harness = {
+ editor: LexicalEditor;
+ /** Types `text` the way a keyboard would: keydown first, then the character. */
+ type: (text: string) => void;
+ /** `type:"text"` for every child of the first paragraph. */
+ children: () => string[];
+ searchTerms: string[];
+ opened: () => number;
+};
+
+let cleanups: Array<() => void> = [];
+
+beforeEach(() => {
+ cleanups = [];
+ return () => {
+ for (const cleanup of cleanups) cleanup();
+ document.body.innerHTML = '';
+ };
+});
+
+function setup(withParagraph: (text: typeof $createTextNode) => void): Harness {
+ const editor = createEditor({
+ namespace: 'mention-trigger-test',
+ nodes: [...SupportedNodeTypes],
+ onError: (e) => {
+ throw e;
+ },
+ });
+
+ const rootElement = document.createElement('div');
+ rootElement.contentEditable = 'true';
+ document.body.appendChild(rootElement);
+ editor.setRootElement(rootElement);
+
+ const [isOpen, setIsOpen] = createSignal(false);
+ const [searchTerm, setSearchTerm] = createSignal('');
+ const searchTerms: string[] = [];
+ let openCount = 0;
+ const menu: MenuOperations = {
+ openMenu: () => {
+ openCount += 1;
+ setIsOpen(true);
+ },
+ closeMenu: () => setIsOpen(false),
+ searchTerm,
+ setSearchTerm: (term) => {
+ searchTerms.push(term);
+ setSearchTerm(term);
+ },
+ isOpen,
+ setIsOpen,
+ };
+
+ cleanups.push(mentionsPlugin({ menu })(editor));
+
+ editor.update(() => withParagraph($createTextNode), { discrete: true });
+ editor.read(() => {});
+
+ const type = (text: string) => {
+ for (const character of text) {
+ rootElement.dispatchEvent(
+ new KeyboardEvent('keydown', { key: character, bubbles: true })
+ );
+ editor.read(() => {});
+ editor.update(
+ () => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) selection.insertText(character);
+ },
+ { discrete: true }
+ );
+ editor.read(() => {});
+ }
+ };
+
+ return {
+ editor,
+ type,
+ children: () =>
+ editor.getEditorState().read(() =>
+ $getRoot()
+ .getChildren()
+ .flatMap((block) =>
+ 'getChildren' in block
+ ? (block as any)
+ .getChildren()
+ .map(
+ (node: any) => `${node.getType()}:${node.getTextContent()}`
+ )
+ : []
+ )
+ ),
+ searchTerms,
+ opened: () => openCount,
+ };
+}
+
+/** A paragraph holding `text`, with the caret placed at `offset`. */
+function paragraphWithCaret(text: string, offset: number) {
+ return (createText: (text: string) => TextNode) => {
+ const paragraph = $createParagraphNode();
+ const node = createText(text);
+ paragraph.append(node);
+ $getRoot().clear().append(paragraph);
+ node.select(offset, offset);
+ };
+}
+
+describe('@ trigger position', () => {
+ test('opens a blank menu at the start of a word, leaving the word alone', () => {
+ const harness = setup(paragraphWithCaret('hello world', 6));
+
+ harness.type('@');
+
+ expect(harness.opened()).toBe(1);
+ expect(harness.searchTerms.at(-1)).toBe('');
+ expect(harness.children()).toEqual([
+ 'text:hello ',
+ 'inline-search:@',
+ 'text:world',
+ ]);
+ });
+
+ test('searches only what is typed after the @, not the following word', () => {
+ const harness = setup(paragraphWithCaret('hello world', 6));
+
+ harness.type('@jo');
+
+ expect(harness.searchTerms.at(-1)).toBe('jo');
+ expect(harness.children()).toEqual([
+ 'text:hello ',
+ 'inline-search:@jo',
+ 'text:world',
+ ]);
+ });
+
+ test('inserts the chosen mention before the untouched following word', () => {
+ const harness = setup(paragraphWithCaret('hello world', 6));
+
+ harness.type('@jo');
+ harness.editor.dispatchCommand(REMOVE_INLINE_SEARCH_COMMAND, undefined);
+ harness.editor.read(() => {});
+ harness.editor.dispatchCommand(INSERT_USER_MENTION_COMMAND, {
+ userId: 'user-1',
+ email: '[email protected]',
+ displayName: 'Jo',
+ });
+ harness.editor.read(() => {});
+
+ expect(harness.children()).toEqual([
+ 'text:hello ',
+ 'user-mention:Jo',
+ 'text:world',
+ ]);
+ });
+
+ test('stays a literal @ in the middle of a word', () => {
+ const harness = setup(paragraphWithCaret('hello world', 3));
+
+ harness.type('@');
+
+ expect(harness.opened()).toBe(0);
+ expect(harness.children()).toEqual(['text:hel@lo world']);
+ });
+
+ test('stays a literal @ mid-word across a formatting boundary', () => {
+ const harness = setup((createText) => {
+ const paragraph = $createParagraphNode();
+ const bold = createText('bo');
+ bold.toggleFormat('bold');
+ const rest = createText('ld');
+ paragraph.append(bold, rest);
+ $getRoot().clear().append(paragraph);
+ rest.select(0, 0);
+ });
+
+ harness.type('@');
+
+ expect(harness.opened()).toBe(0);
+ expect(harness.children().join('')).not.toContain('inline-search');
+ });
+
+ test('opens the menu after a trailing space', () => {
+ const harness = setup(paragraphWithCaret('hello ', 6));
+
+ harness.type('@');
+
+ expect(harness.opened()).toBe(1);
+ expect(harness.children()).toEqual(['text:hello ', 'inline-search:@']);
+ });
+
+ test('opens the menu at the start of an empty paragraph', () => {
+ const harness = setup(() => {
+ const paragraph = $createParagraphNode();
+ $getRoot().clear().append(paragraph);
+ paragraph.select();
+ });
+
+ harness.type('@');
+
+ expect(harness.opened()).toBe(1);
+ expect(harness.children()).toEqual(['inline-search:@']);
+ });
+});
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 4a370a4185..3a0578afb8 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -296,6 +296,10 @@ nodes — use the snapshot itself to verify content. For formatting checks, run
Body placeholder advertises: `/` for block commands, `@` to reference files, `;` for snippets.
Markdown auto-format works while typing (`#` heading, `[]` checklist, `>` quote).
+`@` opens the mention menu wherever the caret starts a word, including directly
+in front of existing text — the menu opens empty there instead of searching for
+the word ahead of the caret. Typed inside a word (`he@llo`) it stays literal text.
+
`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.
diff --git a/packages/lexical-core/nodes/InlineSearchNode.ts b/packages/lexical-core/nodes/InlineSearchNode.ts
index e7da30f3d7..feaf464831 100644
--- a/packages/lexical-core/nodes/InlineSearchNode.ts
+++ b/packages/lexical-core/nodes/InlineSearchNode.ts
@@ -5,6 +5,7 @@ import {
$getNodeByKey,
$getSelection,
$isRangeSelection,
+ $isTextNode,
type EditorConfig,
type EditorState,
type LexicalEditor,
@@ -44,10 +45,30 @@ export const SEARCH_NODE_TYPE_VALUES = {
[InlineSearchNodesType.Tags]: '##',
};
+/**
+ * The text the caret sits behind. A caret at offset 0 of a text node is still
+ * mid-word when the previous sibling is another run of the same word, as
+ * happens where formatting splits one word across text nodes.
+ */
+function $textBeforeCaret(anchorNode: LexicalNode, offset: number): string {
+ const text = anchorNode.getTextContent().slice(0, offset);
+ if (text !== '' || !$isTextNode(anchorNode)) return text;
+ const previous = anchorNode.getPreviousSibling();
+ return $isTextNode(previous) ? previous.getTextContent() : '';
+}
+
+/**
+ * Decides whether a trigger character typed at the caret should open an inline
+ * search menu.
+ *
+ * `before` guards against triggering inside a word. `after` guards against
+ * triggering immediately in front of one; pass `null` to allow a trigger at the
+ * start of a word, where the following text is left out of the search term.
+ */
export function validTriggerPosition(
editor: LexicalEditor,
before: RegExp = /\s$/,
- after: RegExp = /^\s/
+ after: RegExp | null = /^\s/
) {
return editor.getEditorState().read(() => {
const selection = $getSelection();
@@ -57,9 +78,7 @@ export function validTriggerPosition(
if ($isInlineSearchNode(anchorNode)) return false;
if ($isChildOfCode(anchorNode)) return false;
- const beforeText = anchorNode
- .getTextContent()
- .slice(0, selection.anchor.offset);
+ const beforeText = $textBeforeCaret(anchorNode, selection.anchor.offset);
if (beforeText.endsWith('`')) {
return false;
@@ -69,6 +88,8 @@ export function validTriggerPosition(
return false;
}
+ if (after === null) return true;
+
const afterText = anchorNode
.getTextContent()
.slice(selection.anchor.offset);