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.

chg(md): resolve display name for user mentions (#5624)

Seamus5c6b24261afb
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/UserMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/UserMention.tsx
index 1870de0165..6ea16748b7 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/UserMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/UserMention.tsx
@@ -1,10 +1,15 @@
import { HoverCard } from '@core/component/HoverCard';
import { UserTooltip } from '@core/component/UserTooltip';
-import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';
+import { getDisplayNameParts, macroIdToEmail, tryMacroId } from '@core/user';
import type { UserMentionDecoratorProps } from '@macro-inc/lexical-core';
import { cn } from '@ui';
-import { createMemo, createSignal, useContext } from 'solid-js';
+import { createEffect, createMemo, createSignal, useContext } from 'solid-js';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
+import { UPDATE_USER_DISPLAY_NAME_COMMAND } from '../../plugins';
+
+function emailLocalPart(email: string): string {
+ return email.split('@')[0] || email;
+}
export function UserMention(props: UserMentionDecoratorProps) {
const lexicalWrapper = useContext(LexicalWrapperContext);
@@ -19,19 +24,52 @@ export function UserMention(props: UserMentionDecoratorProps) {
// Convert String wrapper to primitive string
const userId = () => String(props.userId);
const propEmail = () => String(props.email);
+ const propDisplayName = () => props.displayName?.trim() ?? '';
const macroId = createMemo(() =>
props.userId ? tryMacroId(userId()) : undefined
);
- const displayName = () => getDisplayName(macroId());
-
const email = createMemo(() => {
const id = macroId();
if (id) return macroIdToEmail(id);
return propEmail();
});
+ const displayNameParts = createMemo(() => {
+ const id = macroId();
+ if (!id) return undefined;
+ return getDisplayNameParts(id, { emailFallback: 'local-part' });
+ });
+
+ const mentionDisplayName = createMemo(() => {
+ const parts = displayNameParts();
+ return (
+ parts?.firstName ||
+ propDisplayName() ||
+ parts?.fullName ||
+ emailLocalPart(propEmail())
+ );
+ });
+
+ const tooltipDisplayName = createMemo(
+ () => displayNameParts()?.fullName || mentionDisplayName()
+ );
+
+ createEffect(() => {
+ const nextDisplayName = mentionDisplayName().trim();
+ if (!nextDisplayName || nextDisplayName === propDisplayName()) return;
+
+ setTimeout(() => {
+ lexicalWrapper?.editor?.dispatchCommand(
+ UPDATE_USER_DISPLAY_NAME_COMMAND,
+ {
+ [userId()]: nextDisplayName,
+ }
+ );
+ });
+ });
+
const [open, setOpen] = createSignal(false);
return (
@@ -50,15 +88,16 @@ export function UserMention(props: UserMentionDecoratorProps) {
<span
data-user-id={props.userId}
data-email={props.email}
+ data-display-name={mentionDisplayName()}
data-user-mention="true"
>
- @{propEmail().split('@')[0]}
+ @{mentionDisplayName()}
</span>
</span>
}
content={
<UserTooltip
- displayName={displayName() || email() || propEmail()}
+ displayName={tooltipDisplayName() || email() || propEmail()}
email={email() || propEmail()}
id={userId()}
onClose={() => setOpen(false)}
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 84307b2e91..5f71dc3a5b 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
@@ -107,6 +107,10 @@ export const UPDATE_DOCUMENT_NAME_COMMAND: LexicalCommand<
Record<string, string>
> = createCommand('UPDATE_DOCUMENT_NAME_COMMAND');
+export const UPDATE_USER_DISPLAY_NAME_COMMAND: LexicalCommand<
+ Record<string, string>
+> = createCommand('UPDATE_USER_DISPLAY_NAME_COMMAND');
+
export const INSERT_USER_MENTION_COMMAND: LexicalCommand<UserMentionInfo> =
createCommand('INSERT_USER_MENTION_COMMAND');
@@ -689,6 +693,46 @@ function registerMentionsPlugin(
COMMAND_PRIORITY_NORMAL
),
+ editor.registerCommand(
+ UPDATE_USER_DISPLAY_NAME_COMMAND,
+ (payload) => {
+ editor.update(
+ () => {
+ const nodesToUpdate: UserMentionNode[] = [];
+ $traverseNodes($getRoot(), (node) => {
+ const newName =
+ node instanceof UserMentionNode
+ ? payload[node.getUserId()]
+ : undefined;
+ if (
+ node instanceof UserMentionNode &&
+ newName &&
+ node.getDisplayName() !== newName
+ ) {
+ nodesToUpdate.push(node);
+ }
+ });
+
+ nodesToUpdate.forEach((node) => {
+ const newName = payload[node.getUserId()];
+ if (newName) node.setDisplayName(newName);
+ });
+ },
+ {
+ tag: [
+ HISTORIC_TAG,
+ SKIP_DOM_SELECTION_TAG,
+ SKIP_SCROLL_INTO_VIEW_TAG,
+ ],
+ discrete: true,
+ }
+ );
+
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ ),
+
editor.registerMutationListener(
InlineSearchNode,
(mutatedNodes, { prevEditorState }) =>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
index 71e7af8266..54b0eb217f 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
@@ -74,6 +74,12 @@ type DateItem = ParsedDate & {
id: string;
};
+function getUserMentionDisplayName(user: IUser): string {
+ const name = user.name.trim();
+ if (name && name !== user.email) return name.split(/\s+/)[0] || name;
+ return user.email.split('@')[0] || user.email;
+}
+
export type UserMentionRecord = {
documentId: string;
mentions: string[];
@@ -173,6 +179,7 @@ export async function handleUserMention(
editor.dispatchCommand(INSERT_USER_MENTION_COMMAND, {
userId: user.id,
email: user.email,
+ displayName: getUserMentionDisplayName(user),
mentionUuid: mentionId,
});
}
diff --git a/packages/lexical-core/nodes/UserMentionNode.ts b/packages/lexical-core/nodes/UserMentionNode.ts
index 94a7c53406..85243eb12d 100644
--- a/packages/lexical-core/nodes/UserMentionNode.ts
+++ b/packages/lexical-core/nodes/UserMentionNode.ts
@@ -16,6 +16,7 @@ import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
export type UserMentionInfo = {
userId: string;
email: string;
+ displayName?: string;
mentionUuid?: string;
};
@@ -24,18 +25,26 @@ export type SerializedUserMentionNode = Spread<
SerializedLexicalNode
>;
-export type UserMentionDecoratorProps = {
- userId: String;
- email: String;
+export type UserMentionDecoratorProps = UserMentionInfo & {
key: NodeKey;
theme: EditorThemeClasses;
};
+type UserMentionConstructorOptions = {
+ displayName?: string;
+ mentionUuid?: string;
+};
+
+function getEmailLocalPart(email: string): string {
+ return email.split('@')[0] || email;
+}
+
export class UserMentionNode extends DecoratorNode<
DecoratorComponent<UserMentionDecoratorProps> | undefined
> {
__userId: string;
__email: string;
+ __displayName: string;
__mentionUuid: string | undefined;
static getType() {
@@ -54,7 +63,10 @@ export class UserMentionNode extends DecoratorNode<
return new UserMentionNode(
node.__userId,
node.__email,
- node.__mentionUuid,
+ {
+ displayName: node.__displayName,
+ mentionUuid: node.__mentionUuid,
+ },
node.__key
);
}
@@ -64,10 +76,32 @@ export class UserMentionNode extends DecoratorNode<
email: string,
mentionUuid?: string,
key?: NodeKey
+ );
+ constructor(
+ userId: string,
+ email: string,
+ options?: UserMentionConstructorOptions,
+ key?: NodeKey
+ );
+ constructor(
+ userId: string,
+ email: string,
+ mentionUuidOrOptions?: string | UserMentionConstructorOptions,
+ key?: NodeKey
) {
super(key);
+ const options =
+ typeof mentionUuidOrOptions === 'object'
+ ? mentionUuidOrOptions
+ : undefined;
+ const mentionUuid =
+ typeof mentionUuidOrOptions === 'string'
+ ? mentionUuidOrOptions
+ : options?.mentionUuid;
+
this.__userId = userId;
this.__email = email;
+ this.__displayName = options?.displayName || getEmailLocalPart(email);
this.__mentionUuid = mentionUuid;
}
@@ -75,6 +109,7 @@ export class UserMentionNode extends DecoratorNode<
const node = $createUserMentionNode({
userId: serializedNode.userId,
email: serializedNode.email,
+ displayName: serializedNode.displayName,
mentionUuid: serializedNode.mentionUuid,
});
$applyIdFromSerialized(node, serializedNode);
@@ -86,6 +121,7 @@ export class UserMentionNode extends DecoratorNode<
...super.exportJSON(),
userId: this.__userId,
email: this.__email,
+ displayName: this.__displayName,
mentionUuid: this.__mentionUuid,
type: UserMentionNode.getType(),
version: 1,
@@ -96,6 +132,7 @@ export class UserMentionNode extends DecoratorNode<
return {
userId: this.__userId,
email: this.__email,
+ displayName: this.__displayName,
mentionUuid: this.__mentionUuid,
};
}
@@ -114,6 +151,7 @@ export class UserMentionNode extends DecoratorNode<
'data-user-mention': true,
'data-user-id': this.__userId,
'data-email': this.__email,
+ 'data-display-name': this.__displayName,
'data-mention-uuid': this.__mentionUuid || '',
};
}
@@ -128,11 +166,14 @@ export class UserMentionNode extends DecoratorNode<
conversion: (domNode: HTMLElement) => {
const userId = domNode.getAttribute('data-user-id');
const email = domNode.getAttribute('data-email');
+ const displayName =
+ domNode.getAttribute('data-display-name') ?? undefined;
if (userId && email) {
const node = $createUserMentionNode({
userId,
email,
+ displayName,
});
return { node };
}
@@ -149,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.__email;
+ element.textContent = this.__displayName;
return { element };
}
getTextContent(): string {
- return this.__email;
+ return this.__displayName;
}
getSearchText(): string {
@@ -179,6 +220,15 @@ export class UserMentionNode extends DecoratorNode<
writable.__email = email;
}
+ getDisplayName(): string {
+ return this.__displayName;
+ }
+
+ setDisplayName(displayName: string) {
+ const writable = this.getWritable();
+ writable.__displayName = displayName;
+ }
+
getMentionUuid(): string | undefined {
return this.__mentionUuid;
}
@@ -204,13 +254,13 @@ export class UserMentionNode extends DecoratorNode<
export function $createUserMentionNode(params: {
userId: string;
email: string;
+ displayName?: string;
mentionUuid?: string;
}) {
- const node = new UserMentionNode(
- params.userId,
- params.email,
- params.mentionUuid
- );
+ const node = new UserMentionNode(params.userId, params.email, {
+ displayName: params.displayName,
+ mentionUuid: params.mentionUuid,
+ });
return $applyNodeReplacement(node);
}
diff --git a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
index 29e6a1a256..41fff30119 100644
--- a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
+++ b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
@@ -6,6 +6,7 @@ import {
$isUnknownMentionNode,
type UnknownMentionNode,
} from '../nodes/UnknownMentionNode';
+import { $isUserMentionNode } from '../nodes/UserMentionNode';
import { ALL_TRANSFORMERS } from '../transformers';
async function importMarkdown(markdown: string) {
@@ -80,6 +81,21 @@ describe('internal transformer fallbacks', () => {
});
});
+ it('ignores malformed user mention displayName values', async () => {
+ const editor = await importMarkdown(
+ '<m-user-mention>{"userId":"u1","email":"[email protected]","displayName":{"first":"A"}}</m-user-mention>'
+ );
+
+ editor.getEditorState().read(() => {
+ const paragraph = $getRoot().getFirstChild();
+ const node = $isParagraphNode(paragraph)
+ ? paragraph.getFirstChild()
+ : null;
+ expect($isUserMentionNode(node)).toBe(true);
+ expect(node?.getTextContent()).toBe('a');
+ });
+ });
+
it.each([
['<m-user-mention>{bad}</m-user-mention>', 'Unknown User'],
['<m-user-mention>{"email":"[email protected]"}</m-user-mention>', 'Unknown User'],
@@ -91,14 +107,17 @@ describe('internal transformer fallbacks', () => {
['<m-snapshot>{bad}</m-snapshot>', 'Unknown Snapshot'],
['<m-await>{bad}</m-await>', 'Unknown Await'],
['<m-link>{bad}</m-link>', 'Unknown Link'],
- ])('falls back for malformed text transformer payload %#', async (markdown, name) => {
- const editor = await importMarkdown(markdown);
-
- editor.getEditorState().read(() => {
- const unknown = findUnknownMention();
- expect(unknown?.getName()).toBe(name);
- });
- });
+ ])(
+ 'falls back for malformed text transformer payload %#',
+ async (markdown, name) => {
+ const editor = await importMarkdown(markdown);
+
+ editor.getEditorState().read(() => {
+ const unknown = findUnknownMention();
+ expect(unknown?.getName()).toBe(name);
+ });
+ }
+ );
it.each([
['<m-document-card>{bad}</m-document-card>', 'Unknown Item'],
@@ -115,15 +134,18 @@ describe('internal transformer fallbacks', () => {
'<m-email-thread-embed>{bad}</m-email-thread-embed>',
'Unknown Email Thread',
],
- ])('wraps malformed element transformer fallback in a paragraph %#', async (markdown, name) => {
- const editor = await importMarkdown(markdown);
-
- editor.getEditorState().read(() => {
- const firstChild = $getRoot().getFirstChild();
- expect($isParagraphNode(firstChild)).toBe(true);
-
- const unknown = findUnknownMention();
- expect(unknown?.getName()).toBe(name);
- });
- });
+ ])(
+ 'wraps malformed element transformer fallback in a paragraph %#',
+ async (markdown, name) => {
+ const editor = await importMarkdown(markdown);
+
+ editor.getEditorState().read(() => {
+ const firstChild = $getRoot().getFirstChild();
+ expect($isParagraphNode(firstChild)).toBe(true);
+
+ const unknown = findUnknownMention();
+ expect(unknown?.getName()).toBe(name);
+ });
+ }
+ );
});
diff --git a/packages/lexical-core/tests/mentions.test.ts b/packages/lexical-core/tests/mentions.test.ts
index 6cd77e10bb..834310b07e 100644
--- a/packages/lexical-core/tests/mentions.test.ts
+++ b/packages/lexical-core/tests/mentions.test.ts
@@ -13,10 +13,16 @@ import {
} from '../utils/parsers';
describe('parseUserMentions', () => {
- it('extracts email from user mention', () => {
+ it('extracts email local part from user mention', () => {
const input =
'<m-user-mention>{"email":"[email protected]"}</m-user-mention>';
- expect(parseUserMentions(input)).toBe('[email protected]');
+ expect(parseUserMentions(input)).toBe('john');
+ });
+
+ it('prefers displayName over email', () => {
+ const input =
+ '<m-user-mention>{"displayName":"John","email":"[email protected]"}</m-user-mention>';
+ expect(parseUserMentions(input)).toBe('John');
});
it('returns empty string for missing email', () => {
@@ -32,7 +38,7 @@ describe('parseUserMentions', () => {
it('handles multiple mentions', () => {
const input =
'Hello <m-user-mention>{"email":"[email protected]"}</m-user-mention> and <m-user-mention>{"email":"[email protected]"}</m-user-mention>';
- expect(parseUserMentions(input)).toBe('Hello [email protected] and [email protected]');
+ expect(parseUserMentions(input)).toBe('Hello a and c');
});
it('passes through text without mentions', () => {
@@ -196,7 +202,7 @@ describe('markdownToPlainText', () => {
'please review <m-document-mention>{"documentName":"Report"}</m-document-mention> ' +
'by <m-date-mention>{"displayFormat":"Friday"}</m-date-mention>.';
expect(markdownToPlainText(input)).toBe(
- 'Hello [email protected], please review Report by Friday.'
+ 'Hello john, please review Report by Friday.'
);
});
@@ -291,7 +297,7 @@ describe('markdownToEmbeddingText', () => {
'<m-group-mention>{"groupAlias":"here"}</m-group-mention>, due ' +
'<m-date-mention>{"displayFormat":"Friday"}</m-date-mention>.';
expect(markdownToEmbeddingText(input)).toBe(
- 'Hello [email protected] and @here, due Friday.'
+ 'Hello john and @here, due Friday.'
);
});
@@ -339,9 +345,7 @@ describe('markdownToEmbeddingText', () => {
'<m-table-row><m-table-cell>Owner</m-table-cell><m-table-cell>Task</m-table-cell></m-table-row>' +
'<m-table-row><m-table-cell><m-user-mention>{"email":"[email protected]"}</m-user-mention></m-table-cell><m-table-cell>fix\\nbug</m-table-cell></m-table-row>' +
'</m-table>';
- expect(markdownToEmbeddingText(input)).toBe(
- 'Owner | Task\[email protected] | fix bug'
- );
+ expect(markdownToEmbeddingText(input)).toBe('Owner | Task\na | fix bug');
});
it('unwraps email thread embeds and resolves mentions inside them', () => {
diff --git a/packages/lexical-core/tests/xml-serialize.test.ts b/packages/lexical-core/tests/xml-serialize.test.ts
index e51ff7f2f6..a005e992e0 100644
--- a/packages/lexical-core/tests/xml-serialize.test.ts
+++ b/packages/lexical-core/tests/xml-serialize.test.ts
@@ -278,18 +278,24 @@ describe('xml serialization', () => {
`);
});
- it('user mention keeps userId + email', () => {
+ it('user mention keeps userId, email, and display name', () => {
expect(
serialize(() => {
const p = $createParagraphNode();
- p.append($createUserMentionNode({ userId: 'u_1', email: '[email protected]' }));
+ p.append(
+ $createUserMentionNode({
+ userId: 'u_1',
+ email: '[email protected]',
+ displayName: 'Alice',
+ })
+ );
$getRoot().append(p);
})
).toMatchInlineSnapshot(`
"
<doc>
<p>
- <user-mention userId="u_1" email="[email protected]"/>
+ <user-mention userId="u_1" email="[email protected]" name="Alice"/>
</p>
</doc>"
`);
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index d264bc9ce3..8b50352a25 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -31,6 +31,7 @@ export const I_USER_MENTION: TextMatchTransformer = {
const data = JSON.stringify({
userId: node.getUserId(),
email: node.getEmail(),
+ displayName: node.getDisplayName(),
});
return `<m-user-mention>${data}</m-user-mention>`;
},
@@ -40,7 +41,11 @@ export const I_USER_MENTION: TextMatchTransformer = {
for (const field of ['userId', 'email']) {
if (!(field in data)) throw new Error(`Missing field ${field}`);
}
- const userMentionNode = new UserMentionNode(data.userId, data.email);
+ const displayName =
+ typeof data.displayName === 'string' ? data.displayName : undefined;
+ const userMentionNode = new UserMentionNode(data.userId, data.email, {
+ displayName,
+ });
node.replace(userMentionNode);
} catch (e) {
console.error('Error in I_USER_MENTION replace:', e);
diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.ts
index 839d61e01f..7b0be5cfc6 100644
--- a/packages/lexical-core/transformers/xml/codecs.ts
+++ b/packages/lexical-core/transformers/xml/codecs.ts
@@ -317,6 +317,7 @@ export function serializeNode(node: SerNode): FxpNode {
nodeAttrs(n, {
...(n.userId && { userId: n.userId }),
...(n.email && { email: n.email }),
+ ...(n.displayName && { name: n.displayName }),
})
)
)
diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.ts
index 668c398e36..ad623bfe51 100644
--- a/packages/lexical-core/transformers/xml/nodes.ts
+++ b/packages/lexical-core/transformers/xml/nodes.ts
@@ -165,6 +165,7 @@ export type UserMentionNode = Id & {
version: number;
userId: string;
email: string;
+ displayName?: string;
};
export type DocumentMentionNode = Id & {
diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.ts
index 6f510e5166..72025c3d31 100644
--- a/packages/lexical-core/utils/parsers.ts
+++ b/packages/lexical-core/utils/parsers.ts
@@ -2,13 +2,22 @@ export function parseUserMentions(text: string): string {
return text.replace(/<m-user-mention>(.*?)<\/m-user-mention>/g, (_, json) => {
try {
const data = JSON.parse(json);
- return data.email || '';
+ return userMentionDisplayText(data);
} catch {
return '';
}
});
}
+function userMentionDisplayText(data: {
+ displayName?: string;
+ email?: string;
+}) {
+ if (data.displayName) return data.displayName;
+ if (data.email) return data.email.split('@')[0] || data.email;
+ return '';
+}
+
export function parseContactMentions(text: string): string {
return text.replace(
/<m-contact-mention>(.*?)<\/m-contact-mention>/g,
@@ -315,7 +324,7 @@ export function markdownToEmbeddingText(markdown: string): string {
'm-katex-equation',
(data) => data.equation || ''
);
- text = replaceJsonTag(text, 'm-user-mention', (data) => data.email || '');
+ text = replaceJsonTag(text, 'm-user-mention', userMentionDisplayText);
text = replaceJsonTag(
text,
'm-contact-mention',