fix: preserve matrix.to mentions when editing

This commit is contained in:
7w1 committed 2026-05-17 20:26:26 -05:00
1 parent a64c28a7aa
commit fdeaf481ef
14 files changed
+389 -14

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ import { mxcUrlToHttp } from '$utils/matrix';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { nicknamesAtom } from '$state/nicknames';
import { BlockType } from './types';
import { getBeginCommand } from './utils';
import { formatMentionElementDisplayName, getBeginCommand } from './utils';
import type { CommandElement, EmoticonElement, LinkElement, MentionElement } from './slate';
// Put this at the start and end of an inline component to work around this Chromium bug:
@@ -32,7 +32,7 @@ function RenderMentionElement({
const nicknames = useAtomValue(nicknamesAtom);
const nickname = nicknames[element.id];
const displayName = nickname ? `@${nickname}` : element.name;
const displayName = nickname ? `@${nickname}` : formatMentionElementDisplayName(element);
return (
<span
@@ -18,7 +18,12 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { useAtomValue } from 'jotai';
import { nicknamesAtom } from '$state/nicknames';
import { createMentionElement, moveCursor, replaceWithElement } from '$components/editor/utils';
import {
createMentionElement,
moveCursor,
replaceWithElement,
resolveUserMentionName,
} from '$components/editor/utils';
import { getMxIdServer } from '$utils/mxIdHelper';
import { AutocompleteMenu } from './AutocompleteMenu';
import type { AutocompleteQuery } from './autocompleteQuery';
@@ -113,7 +118,7 @@ export function UserMentionAutocomplete({
const handleAutocomplete: MentionAutoCompleteHandler = (uId, name) => {
const mentionEl = createMentionElement(
uId,
name.startsWith('@') ? name : `@${name}`,
resolveUserMentionName(uId, { room, nicknames }),
mx.getUserId() === uId || roomAliasOrId === uId
);
replaceWithElement(editor, query.range, mentionEl);
+15 -5
View File
@@ -1,5 +1,6 @@
import type { Descendant } from 'slate';
import type { MentionResolveOptions } from './utils';
import {
MX_EMOTICON_MD_END,
MX_EMOTICON_MD_SEP,
@@ -9,6 +10,7 @@ import {
import { BlockType } from './types';
import type { ParagraphElement } from './slate';
import { createEmoticonElement } from './utils';
import { expandMatrixMentionMarkdownInText } from './matrixMentionMarkdown';
/** Matches placeholders emitted by htmlToMarkdown for &lt;img data-mx-emoticon&gt;. */
const MX_EMOTICON_MD_TOKEN = new RegExp(
@@ -35,14 +37,19 @@ function mergeAdjacentTextNodes(
return out.length > 0 ? out : [{ text: '' }];
}
function lineToParagraphChildren(line: string): ParagraphElement['children'] {
function lineToParagraphChildren(
line: string,
mentionOptions?: MentionResolveOptions
): ParagraphElement['children'] {
MX_EMOTICON_MD_TOKEN.lastIndex = 0;
const parts: ParagraphElement['children'] = [];
let last = 0;
let match: RegExpExecArray | null;
while ((match = MX_EMOTICON_MD_TOKEN.exec(line)) !== null) {
if (match.index > last) {
parts.push({ text: line.slice(last, match.index) });
parts.push(
...expandMatrixMentionMarkdownInText(line.slice(last, match.index), mentionOptions)
);
}
const [, src, shortcode] = match;
if (src && shortcode && validateMxcUrl(src)) {
@@ -53,15 +60,18 @@ function lineToParagraphChildren(line: string): ParagraphElement['children'] {
last = MX_EMOTICON_MD_TOKEN.lastIndex;
}
if (last < line.length) {
parts.push({ text: line.slice(last) });
parts.push(...expandMatrixMentionMarkdownInText(line.slice(last), mentionOptions));
}
return mergeAdjacentTextNodes(parts);
}
export const plainToEditorInput = (text: string): Descendant[] => {
export const plainToEditorInput = (
text: string,
mentionOptions?: MentionResolveOptions
): Descendant[] => {
const lines = text.split('\n');
return lines.map((lineText) => ({
type: BlockType.Paragraph,
children: lineToParagraphChildren(lineText),
children: lineToParagraphChildren(lineText, mentionOptions),
}));
};
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import type { Room } from '$types/matrix-sdk';
import { plainToEditorInput } from './input';
import { BlockType } from './types';
import { htmlToMarkdown } from '$plugins/markdown';
import {
expandMatrixMentionMarkdownInText,
mentionFromMatrixToMarkdownLink,
} from './matrixMentionMarkdown';
const roomWithMember = (userId: string, rawDisplayName: string): Room =>
({
getMember: (id: string) =>
id === userId ? ({ userId: id, rawDisplayName } as never) : undefined,
}) as unknown as Room;
describe('matrixMentionMarkdown', () => {
it('recognizes matrix.to user permalinks as mentions with @ display name', () => {
const room = roomWithMember('@alice:example.org', 'Alice');
const el = mentionFromMatrixToMarkdownLink('Alice', 'https://matrix.to/#/@alice:example.org', {
room,
});
expect(el).toMatchObject({
type: BlockType.Mention,
id: '@alice:example.org',
name: '@Alice',
});
});
it('expands markdown matrix.to user links into Mention elements', () => {
const room = roomWithMember('@alice:example.org', 'Alice');
const parts = expandMatrixMentionMarkdownInText(
'hi [Alice](https://matrix.to/#/@alice:example.org)!',
{ room }
);
expect(parts).toEqual([
{ text: 'hi ' },
expect.objectContaining({
type: BlockType.Mention,
id: '@alice:example.org',
name: '@Alice',
}),
{ text: '!' },
]);
});
it('expands preview-suppressed matrix.to mention links from corrupted edits', () => {
const parts = expandMatrixMentionMarkdownInText(
'hi [Alice](<https://matrix.to/#/@alice:example.org>)!'
);
expect(parts[1]).toMatchObject({
type: BlockType.Mention,
id: '@alice:example.org',
});
});
it('plainToEditorInput round-trips formatted_body user mentions', () => {
const room = roomWithMember('@alice:example.org', 'Alice');
const md = htmlToMarkdown(
'<p>Hello <a href="https://matrix.to/#/@alice:example.org">Alice</a>!</p>'
);
const doc = plainToEditorInput(md, { room });
const paragraph = doc[0] as { children: unknown[] };
expect(paragraph.children).toEqual([
{ text: 'Hello ' },
expect.objectContaining({
type: BlockType.Mention,
id: '@alice:example.org',
name: '@Alice',
}),
{ text: '!' },
]);
});
it('does not treat regular https links as mentions', () => {
const parts = expandMatrixMentionMarkdownInText('[site](https://example.org/)');
expect(parts).toEqual([{ text: '[site](https://example.org/)' }]);
});
});
@@ -0,0 +1,100 @@
import type { InlineElement } from './slate';
import {
parseMatrixToRoom,
parseMatrixToRoomEvent,
parseMatrixToUser,
isMatrixToMentionHref,
} from '$plugins/matrix-to';
import type { MentionResolveOptions } from './utils';
import {
createMentionElement,
getMarkdownCodeSpanRanges,
isInsideMarkdownCodeSpan,
resolveRoomMentionHighlight,
resolveRoomMentionName,
resolveUserMentionHighlight,
resolveUserMentionName,
} from './utils';
/** [label](href) or [label](<href>) */
const MD_INLINE_LINK = /\[((?:[^\]\]\\]|\\.)*)\]\((?:<([^>]+)>|([^)]+))\)/g;
export const mentionFromMatrixToMarkdownLink = (
label: string,
href: string,
options?: MentionResolveOptions
): InlineElement | null => {
const trimmedHref = href.trim();
if (!isMatrixToMentionHref(trimmedHref)) return null;
const userId = parseMatrixToUser(trimmedHref);
if (userId) {
return createMentionElement(
userId,
resolveUserMentionName(userId, options),
resolveUserMentionHighlight(userId, options)
);
}
const roomEvent = parseMatrixToRoomEvent(trimmedHref);
if (roomEvent) {
return createMentionElement(
roomEvent.roomIdOrAlias,
resolveRoomMentionName(roomEvent.roomIdOrAlias, label, options),
resolveRoomMentionHighlight(roomEvent.roomIdOrAlias, options),
roomEvent.eventId,
roomEvent.viaServers
);
}
const room = parseMatrixToRoom(trimmedHref);
if (room) {
return createMentionElement(
room.roomIdOrAlias,
resolveRoomMentionName(room.roomIdOrAlias, label, options),
resolveRoomMentionHighlight(room.roomIdOrAlias, options),
undefined,
room.viaServers
);
}
return null;
};
export const expandMatrixMentionMarkdownInText = (
text: string,
options?: MentionResolveOptions
): InlineElement[] => {
const codeSpanRanges = getMarkdownCodeSpanRanges(text);
const parts: InlineElement[] = [];
let last = 0;
MD_INLINE_LINK.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = MD_INLINE_LINK.exec(text)) !== null) {
const start = match.index;
const end = start + match[0].length;
if (isInsideMarkdownCodeSpan(start, end, codeSpanRanges)) continue;
const label = match[1] ?? '';
const href = (match[2] ?? match[3] ?? '').trim();
if (start > last) {
parts.push({ text: text.slice(last, start) });
}
const mention = mentionFromMatrixToMarkdownLink(label, href, options);
if (mention) {
parts.push(mention);
} else {
parts.push({ text: match[0] });
}
last = end;
}
if (last < text.length) {
parts.push({ text: text.slice(last) });
}
return parts.length > 0 ? parts : [{ text: '' }];
};
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest';
import type { Room } from '$types/matrix-sdk';
import {
formatMentionElementDisplayName,
formatUserMentionDisplayName,
resolveUserMentionName,
} from './utils';
import { BlockType } from './types';
const roomWithMember = (userId: string, rawDisplayName: string): Room =>
({
getMember: (id: string) =>
id === userId ? ({ userId: id, rawDisplayName } as never) : undefined,
}) as unknown as Room;
describe('mention resolve', () => {
it('resolveUserMentionName uses room membership and adds @', () => {
const room = roomWithMember('@alice:example.org', 'Alice');
expect(resolveUserMentionName('@alice:example.org', { room })).toBe('@Alice');
});
it('formatMentionElementDisplayName adds @ to legacy mention nodes without prefix', () => {
expect(
formatMentionElementDisplayName({
type: BlockType.Mention,
id: '@alice:example.org',
name: 'Alice',
highlight: true,
children: [{ text: '' }],
})
).toBe('@Alice');
});
it('formatUserMentionDisplayName is idempotent for names that already include @', () => {
expect(formatUserMentionDisplayName('@Alice')).toBe('@Alice');
});
});
+68
View File
@@ -1,5 +1,9 @@
import type { BasePoint, BaseRange } from 'slate';
import { Editor, Element, Point, Range, Text, Transforms } from 'slate';
import type { Room } from '$types/matrix-sdk';
import type { Nicknames } from '$state/nicknames';
import { getMxIdLocalPart, isUserId } from '$utils/matrix';
import { getMemberDisplayName } from '$utils/room';
import { BlockType } from './types';
import type {
CommandElement,
@@ -9,6 +13,70 @@ import type {
MentionElement,
} from './slate';
export type MentionResolveOptions = {
room?: Room;
nicknames?: Nicknames;
mxUserId?: string;
};
/** Same @-prefix rule as {@link UserMentionAutocomplete} and timeline mention insertion. */
export const formatUserMentionDisplayName = (name: string): string =>
name.startsWith('@') ? name : `@${name}`;
export const resolveUserMentionName = (userId: string, options?: MentionResolveOptions): string => {
const base =
(options?.room && getMemberDisplayName(options.room, userId, options.nicknames)) ??
getMxIdLocalPart(userId) ??
userId;
return formatUserMentionDisplayName(base);
};
/** Same #-prefix rule as {@link RoomMentionAutocomplete}. */
export const formatRoomMentionDisplayName = (name: string): string => {
if (name === '@room') return '@room';
return name.startsWith('#') ? name : `#${name}`;
};
export const resolveRoomMentionName = (
roomIdOrAlias: string,
label: string,
options?: MentionResolveOptions
): string => {
const trimmed = label.trim();
if (trimmed === '@room') return '@room';
if (trimmed) return formatRoomMentionDisplayName(trimmed);
if (
options?.room &&
(options.room.roomId === roomIdOrAlias || options.room.getCanonicalAlias() === roomIdOrAlias)
) {
return formatRoomMentionDisplayName(options.room.name || roomIdOrAlias);
}
return formatRoomMentionDisplayName(roomIdOrAlias);
};
export const resolveUserMentionHighlight = (
userId: string,
options?: MentionResolveOptions
): boolean => options?.mxUserId === userId;
export const resolveRoomMentionHighlight = (
roomIdOrAlias: string,
options?: MentionResolveOptions
): boolean => {
if (!options?.room) return true;
const { roomId } = options.room;
const alias = options.room.getCanonicalAlias();
return roomId === roomIdOrAlias || alias === roomIdOrAlias;
};
export const formatMentionElementDisplayName = (element: MentionElement): string => {
if (isUserId(element.id)) {
return formatUserMentionDisplayName(element.name);
}
if (element.name === '@room') return '@room';
return formatRoomMentionDisplayName(element.name);
};
export const resetEditor = (editor: Editor) => {
Transforms.delete(editor, {
at: {
@@ -1,5 +1,6 @@
import type { KeyboardEventHandler, MouseEventHandler } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
import type { RectCords } from 'folds';
import { Box, Chip, Icon, IconButton, Icons, PopOut, Spinner, Text, as, config } from 'folds';
import { Editor, Transforms } from 'slate';
@@ -46,6 +47,7 @@ import { UseStateProvider } from '$components/UseStateProvider';
import { EmojiBoard } from '$components/emoji-board';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { nicknamesAtom } from '$state/nicknames';
import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '$utils/room';
import { mobileOrTablet } from '$utils/user-agent';
import { useComposingCheck } from '$hooks/useComposingCheck';
@@ -53,6 +55,7 @@ import { floatingEditor } from '$styles/overrides/Composer.css';
import { RenderMessageContent } from '$components/RenderMessageContent';
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser';
import { isMatrixToMentionHref } from '$plugins/matrix-to';
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
import type { HTMLReactParserOptions } from 'html-react-parser';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
@@ -75,6 +78,7 @@ type MessageEditorProps = {
export const MessageEditor = as<'div', MessageEditorProps>(
({ room, roomId, mEvent, imagePackRooms, onCancel, ...props }, ref) => {
const mx = useMatrixClient();
const nicknames = useAtomValue(nicknamesAtom);
const editor = useEditor();
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
const isComposing = useComposingCheck();
@@ -151,7 +155,15 @@ export const MessageEditor = as<'div', MessageEditorProps>(
// it needs to be separated such that it can be reintroduced before the < in case of regular text
// or after it in case that it is matching a <a> tag
const strippedS = s.substring(1);
const matrixToMentionAnchorHref =
isHTML && s.toLowerCase().startsWith('<a')
? s.match(/href\s*=\s*["']([^"']+)["']/i)?.[1]
: undefined;
const isMatrixToMentionAnchor =
matrixToMentionAnchorHref !== undefined &&
isMatrixToMentionHref(matrixToMentionAnchorHref);
const isHidden =
!isMatrixToMentionAnchor &&
(bundleContent?.length === 0 ||
bundleContent.filter((b) => s.includes(b.matched_url)).length === 0) &&
strippedS.match(LINKINPUTREGEX) !== null;
@@ -364,12 +376,18 @@ export const MessageEditor = as<'div', MessageEditorProps>(
useEffect(() => {
const [body, customHtml] = getPrevBodyAndFormattedBody();
const mentionOptions = {
room,
nicknames,
mxUserId: mx.getUserId(),
};
const initialValue = plainToEditorInput(
customHtml
? stripMarkdownEscapesForHiddenPreviews(htmlToMarkdown(customHtml))
: typeof body === 'string'
? body
: ''
: '',
mentionOptions
);
Transforms.select(editor, {
@@ -379,7 +397,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
editor.insertFragment(initialValue);
if (!mobileOrTablet()) ReactEditor.focus(editor);
}, [editor, getPrevBodyAndFormattedBody]);
}, [editor, getPrevBodyAndFormattedBody, room, nicknames, mx]);
useEffect(() => {
if (saveState.status === AsyncStatus.Success) {
@@ -64,6 +64,15 @@ describe('readdAngleBracketsForHiddenPreviews', () => {
);
});
it('does not wrap matrix.to mention destinations in markdown links', () => {
expect(
readdAngleBracketsForHiddenPreviews(
'Hello [Alice](https://matrix.to/#/@alice:example.org)!',
[]
)
).toBe('Hello [Alice](https://matrix.to/#/@alice:example.org)!');
});
it('does not corrupt markdown suppressed links [url](<url>)', () => {
expect(
readdAngleBracketsForHiddenPreviews(
@@ -1,8 +1,19 @@
import type { BundleContent } from '$components/message';
import { isMatrixToMentionHref, testMatrixTo } from '$plugins/matrix-to';
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\()@!$&'*+,;%=]+)`;
const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g');
/** True when `urlStart` lies inside the destination of a markdown link `[…](…)`. */
const isUrlInsideMarkdownLinkDestination = (body: string, urlStart: number): boolean => {
const destOpen = body.lastIndexOf('](', urlStart);
if (destOpen === -1) return false;
const destStart = destOpen + 2;
const destClose = body.indexOf(')', destStart);
if (destClose === -1) return urlStart >= destStart;
return urlStart >= destStart && urlStart < destClose;
};
/**
* `htmlToMarkdown()` escapes `<` and `>` into `\<` and `\>` in text nodes.
*
@@ -49,6 +60,17 @@ export function readdAngleBracketsForHiddenPreviews(
const offset = args[args.length - 2] as number;
if (!url || previewed.has(url)) return full;
// matrix.to user/room/event permalinks inside markdown link destinations are mentions, not previews.
const urlIndex = body.indexOf(url, offset);
if (
urlIndex !== -1 &&
testMatrixTo(url) &&
isMatrixToMentionHref(url) &&
isUrlInsideMarkdownLinkDestination(body, urlIndex)
) {
return full;
}
// URL is the label of a markdown link [url](...) — do not insert "<" into the label.
const after = body.slice(offset + full.length, offset + full.length + 2);
if (after === '](') {
@@ -61,7 +83,6 @@ export function readdAngleBracketsForHiddenPreviews(
}
// If the URL is already wrapped as <url>, leave it alone.
const urlIndex = body.indexOf(url, offset);
if (urlIndex !== -1 && body.slice(urlIndex - 1, urlIndex + url.length + 1) === `<${url}>`) {
return full;
}
@@ -67,6 +67,11 @@ describe('htmlToMarkdown', () => {
expect(htmlToMarkdown(html)).toBe('[https://example.org/](<https://example.org/>)');
});
it('does not use preview-suppressed destinations for matrix.to user mentions', () => {
const html = '<p>&lt;<a href="https://matrix.to/#/@alice:example.org">Alice</a>&gt;</p>';
expect(htmlToMarkdown(html)).toBe('[Alice](https://matrix.to/#/@alice:example.org)');
});
it('converts hidden-preview wrapped links when angle brackets are decimal entities', () => {
const html = '<p>&#60;<a href="https://example.org/">https://example.org/</a>&#62;</p>';
expect(htmlToMarkdown(html)).toBe('[https://example.org/](<https://example.org/>)');
+6 -2
View File
@@ -6,6 +6,7 @@ import {
validateMxcUrl,
} from './extensions/matrix-emoticon';
import { escapeMarkdownInlineSequences } from './utils';
import { isMatrixToMentionHref } from '$plugins/matrix-to';
/**
* Converts Matrix-compatible HTML back to markdown for round-trip editing.
@@ -232,8 +233,11 @@ function processChildren(
) {
const href = next.attribs.href ?? '';
const content = next.children.map((c) => processNode(c, listDepth, insideCode)).join('');
// Suppressed autolink: [label](<href>) so bracket text is not run through escapeMarkdown as "\<".
out.push(`[${content}](<${href}>)`);
if (isMatrixToMentionHref(href)) {
out.push(`[${content}](${href})`);
} else {
out.push(`[${content}](<${href}>)`);
}
i += 2;
continue;
}
+8
View File
@@ -4,6 +4,7 @@ import {
getMatrixToRoomEvent,
getMatrixToUser,
isRedundantMatrixToAnchorText,
isMatrixToMentionHref,
parseMatrixToRoom,
parseMatrixToRoomEvent,
parseMatrixToUser,
@@ -92,6 +93,13 @@ describe('testMatrixTo', () => {
expect(testMatrixTo('http://matrix.to/#/@alice:example.com')).toBe(true);
});
it('isMatrixToMentionHref matches user, room, and event permalinks only', () => {
expect(isMatrixToMentionHref('https://matrix.to/#/@alice:example.com')).toBe(true);
expect(isMatrixToMentionHref('https://matrix.to/#/!room:example.com')).toBe(true);
expect(isMatrixToMentionHref('https://matrix.to/#/!room:example.com/$event123')).toBe(true);
expect(isMatrixToMentionHref('https://example.com')).toBe(false);
});
it('rejects non-matrix.to URLs', () => {
expect(testMatrixTo('https://example.com')).toBe(false);
expect(testMatrixTo('https://notmatrix.to/#/@alice:example.com')).toBe(false);
+11
View File
@@ -81,6 +81,17 @@ const getMatchRegexes = () => {
export const testMatrixTo = (href: string): boolean => getMatchRegexes().any.test(href);
/** True when the URL is a matrix.to user, room, or event permalink (a mention), not an arbitrary link. */
export const isMatrixToMentionHref = (href: string): boolean => {
const trimmed = href.trim();
if (!testMatrixTo(trimmed)) return false;
return !!(
parseMatrixToUser(trimmed) ??
parseMatrixToRoom(trimmed) ??
parseMatrixToRoomEvent(trimmed)
);
};
export const parseMatrixToUser = (href: string): string | undefined => {
const match = href.match(getMatchRegexes().user);
if (!match) return undefined;