diff --git a/src/app/components/editor/Elements.tsx b/src/app/components/editor/Elements.tsx index 410d9aa98..6d8cbb297 100644 --- a/src/app/components/editor/Elements.tsx +++ b/src/app/components/editor/Elements.tsx @@ -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 ( { const mentionEl = createMentionElement( uId, - name.startsWith('@') ? name : `@${name}`, + resolveUserMentionName(uId, { room, nicknames }), mx.getUserId() === uId || roomAliasOrId === uId ); replaceWithElement(editor, query.range, mentionEl); diff --git a/src/app/components/editor/input.ts b/src/app/components/editor/input.ts index 471a0e5f5..f2553b1af 100644 --- a/src/app/components/editor/input.ts +++ b/src/app/components/editor/input.ts @@ -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 <img data-mx-emoticon>. */ 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), })); }; diff --git a/src/app/components/editor/matrixMentionMarkdown.test.ts b/src/app/components/editor/matrixMentionMarkdown.test.ts new file mode 100644 index 000000000..45472282f --- /dev/null +++ b/src/app/components/editor/matrixMentionMarkdown.test.ts @@ -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]()!' + ); + 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( + '

Hello Alice!

' + ); + 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/)' }]); + }); +}); diff --git a/src/app/components/editor/matrixMentionMarkdown.ts b/src/app/components/editor/matrixMentionMarkdown.ts new file mode 100644 index 000000000..619da1880 --- /dev/null +++ b/src/app/components/editor/matrixMentionMarkdown.ts @@ -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]() */ +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: '' }]; +}; diff --git a/src/app/components/editor/mentionResolve.test.ts b/src/app/components/editor/mentionResolve.test.ts new file mode 100644 index 000000000..925e835f7 --- /dev/null +++ b/src/app/components/editor/mentionResolve.test.ts @@ -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'); + }); +}); diff --git a/src/app/components/editor/utils.ts b/src/app/components/editor/utils.ts index 03adabd90..bc228dc2d 100644 --- a/src/app/components/editor/utils.ts +++ b/src/app/components/editor/utils.ts @@ -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: { diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 341a227a0..1eea4b41e 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -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 tag const strippedS = s.substring(1); + const matrixToMentionAnchorHref = + isHTML && s.toLowerCase().startsWith(' 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) { diff --git a/src/app/features/room/message/hiddenLinkPreviews.test.ts b/src/app/features/room/message/hiddenLinkPreviews.test.ts index 86b959eb7..dac690966 100644 --- a/src/app/features/room/message/hiddenLinkPreviews.test.ts +++ b/src/app/features/room/message/hiddenLinkPreviews.test.ts @@ -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]()', () => { expect( readdAngleBracketsForHiddenPreviews( diff --git a/src/app/features/room/message/hiddenLinkPreviews.ts b/src/app/features/room/message/hiddenLinkPreviews.ts index 7c8ed7e54..a42603963 100644 --- a/src/app/features/room/message/hiddenLinkPreviews.ts +++ b/src/app/features/room/message/hiddenLinkPreviews.ts @@ -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 , leave it alone. - const urlIndex = body.indexOf(url, offset); if (urlIndex !== -1 && body.slice(urlIndex - 1, urlIndex + url.length + 1) === `<${url}>`) { return full; } diff --git a/src/app/plugins/markdown/htmlToMarkdown.test.ts b/src/app/plugins/markdown/htmlToMarkdown.test.ts index 8ca43b6ad..7c2719366 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.test.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.test.ts @@ -67,6 +67,11 @@ describe('htmlToMarkdown', () => { expect(htmlToMarkdown(html)).toBe('[https://example.org/]()'); }); + it('does not use preview-suppressed destinations for matrix.to user mentions', () => { + const html = '

<Alice>

'; + 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 = '

<https://example.org/>

'; expect(htmlToMarkdown(html)).toBe('[https://example.org/]()'); diff --git a/src/app/plugins/markdown/htmlToMarkdown.ts b/src/app/plugins/markdown/htmlToMarkdown.ts index 967fb99b7..d0248b929 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.ts @@ -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]() 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; } diff --git a/src/app/plugins/matrix-to.test.ts b/src/app/plugins/matrix-to.test.ts index 7c0287c43..2b5b66740 100644 --- a/src/app/plugins/matrix-to.test.ts +++ b/src/app/plugins/matrix-to.test.ts @@ -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); diff --git a/src/app/plugins/matrix-to.ts b/src/app/plugins/matrix-to.ts index 3c6712e53..428100d84 100644 --- a/src/app/plugins/matrix-to.ts +++ b/src/app/plugins/matrix-to.ts @@ -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;