fix matrixto link rendering

This commit is contained in:
7w1 committed 2026-05-05 16:18:20 -05:00
1 parent 2e08ac3ac7
commit 7ef0f61d94
5 files changed
+163 -3

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fixed message links being rendered as full links.
+41
View File
@@ -3,6 +3,7 @@ import {
getMatrixToRoom,
getMatrixToRoomEvent,
getMatrixToUser,
isRedundantMatrixToAnchorText,
parseMatrixToRoom,
parseMatrixToRoomEvent,
parseMatrixToUser,
@@ -229,3 +230,43 @@ describe('parseMatrixToRoomEvent', () => {
});
});
});
describe('isRedundantMatrixToAnchorText', () => {
it('treats empty anchor text as redundant', () => {
expect(isRedundantMatrixToAnchorText('https://matrix.to/#/!r:example.org', undefined)).toBe(
true
);
expect(isRedundantMatrixToAnchorText('https://matrix.to/#/!r:example.org', '')).toBe(true);
expect(isRedundantMatrixToAnchorText('https://matrix.to/#/!r:example.org', ' ')).toBe(true);
});
it('treats anchor text that repeats the same permalink as redundant', () => {
const url =
'https://matrix.to/#/!a6sXbRuOyyc7MKutmy:sable.moe/$6C-iT549tGKwcQy3Vmb-GgwVZPXiyQ4paJY8-IN2ohs?via=matrix.org&via=unredacted.org&via=4d2.org';
expect(isRedundantMatrixToAnchorText(url, url)).toBe(true);
});
it('treats http vs https with the same fragment as redundant', () => {
const httpsUrl = 'https://matrix.to/#/!room:example.com/$event123';
const httpUrl = 'http://matrix.to/#/!room:example.com/$event123';
expect(isRedundantMatrixToAnchorText(httpsUrl, httpUrl)).toBe(true);
});
it('does not treat different permalinks as redundant', () => {
expect(
isRedundantMatrixToAnchorText(
'https://matrix.to/#/!a:example.com/$e1',
'https://matrix.to/#/!b:example.com/$e2'
)
).toBe(false);
});
it('does not treat plain-language anchor text as redundant', () => {
expect(
isRedundantMatrixToAnchorText(
'https://matrix.to/#/!room:example.com/$event123',
'read this post'
)
).toBe(false);
});
});
+43
View File
@@ -118,3 +118,46 @@ export const parseMatrixToRoomEvent = (href: string): MatrixToRoomEvent | undefi
viaServers: viaServers.length === 0 ? undefined : viaServers,
};
};
const tryDecodeUriComponent = (s: string): string => {
try {
return decodeURIComponent(s);
} catch {
return s;
}
};
/**
* Normalized Matrix permalink fragment (path after `#/`, lowercased), for comparing href vs anchor text.
*/
export const matrixPermalinkFragmentKey = (url: string): string | undefined => {
const trimmed = url.trim();
const decoded = tryDecodeUriComponent(trimmed);
const candidate = testMatrixTo(trimmed) ? trimmed : testMatrixTo(decoded) ? decoded : undefined;
if (!candidate) return undefined;
try {
const u = new URL(candidate);
const frag = u.hash.startsWith('#') ? u.hash.slice(1) : '';
const key = frag.replace(/^\/+/u, '').replace(/\/+$/u, '').toLowerCase();
return key || undefined;
} catch {
return undefined;
}
};
/**
* True when anchor text is empty or only repeats the same permalink as `href` (e.g. pasted full URL).
*/
export const isRedundantMatrixToAnchorText = (
href: string,
anchorText: string | undefined
): boolean => {
if (anchorText == null || anchorText.trim() === '') return true;
const keyHref = matrixPermalinkFragmentKey(href);
if (!keyHref) return false;
const t = anchorText.trim();
const keyText =
matrixPermalinkFragmentKey(t) ?? matrixPermalinkFragmentKey(tryDecodeUriComponent(t));
if (!keyText) return false;
return keyHref === keyText;
};
@@ -255,6 +255,50 @@ describe('react custom html parser', () => {
expect(link.querySelector('[aria-hidden="true"]')).not.toBeNull();
});
it('uses room name when formatted body uses the full matrix.to URL as link text', () => {
const url = 'https://matrix.to/#/!room:example.org';
const mx = createMatrixClient({
getRoom: (id: string) =>
id === '!room:example.org' ? { roomId: '!room:example.org', name: 'Lobby' } : undefined,
});
renderParsedHtml(`<a href="${url}">${url}</a>`, { sanitize: false, mx });
expect(screen.getByRole('link', { name: '#Lobby' })).toHaveAttribute('href', url);
});
it('uses message snippet for event permalinks when the event is in the store', () => {
const url = 'https://matrix.to/#/!room:example.org/$eventABC';
const mx = createMatrixClient({
getRoom: () => ({
roomId: '!room:example.org',
name: 'Lobby',
findEventById: (id: string) =>
id === '$eventABC'
? {
getContent: () => ({
body: `${'Hello world '.repeat(12)}tail`,
}),
}
: null,
}),
});
renderParsedHtml(`<a href="${url}">${url}</a>`, { sanitize: false, mx });
const link = screen.getByRole('link', { name: /#Lobby: Hello world/ });
expect(link).toHaveAttribute('data-mention-event-id', '$eventABC');
expect(link.textContent).toMatch(/…/);
});
it('keeps custom link text when it is not just the permalink URL', () => {
const url = 'https://matrix.to/#/!room:example.org/$event123';
const mx = createMatrixClient({
getRoom: () => ({ roomId: '!room:example.org', name: 'Lobby' }),
});
renderParsedHtml(`<a href="${url}">see this thread</a>`, { sanitize: false, mx });
expect(screen.getByRole('link', { name: 'see this thread' })).toBeInTheDocument();
});
it('translates Matrix color data attributes into rendered styles', () => {
renderParsedHtml('<span data-mx-color="#ff0000" data-mx-bg-color="#00ff00">colored</span>');
+30 -3
View File
@@ -29,6 +29,7 @@ import { getSettingsLinkChipLabel, parseSettingsLink } from '$features/settings/
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
import { CodeHighlightRenderer } from '$components/code-highlight';
import {
isRedundantMatrixToAnchorText,
parseMatrixToRoom,
parseMatrixToRoomEvent,
parseMatrixToUser,
@@ -148,6 +149,18 @@ export const makeMentionCustomProps = (
children: content,
});
const matrixPermalinkDisplayLabel = (
href: string,
customChildren: ReactNode | undefined,
fallback: ReactNode
): ReactNode => {
if (customChildren === undefined || customChildren === null) return fallback;
if (typeof customChildren === 'string') {
return isRedundantMatrixToAnchorText(href, customChildren) ? fallback : customChildren;
}
return customChildren;
};
export const renderMatrixMention = (
mx: MatrixClient,
currentRoomId: string | undefined,
@@ -182,6 +195,7 @@ export const renderMatrixMention = (
);
const fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias;
const label = matrixPermalinkDisplayLabel(href, customProps.children, fallbackContent);
return (
<a
@@ -193,7 +207,7 @@ export const renderMatrixMention = (
data-mention-id={mentionRoom?.roomId ?? roomIdOrAlias}
data-mention-via={viaServers?.join(',')}
>
{customProps.children ? customProps.children : fallbackContent}
{label}
</a>
);
}
@@ -204,7 +218,20 @@ export const renderMatrixMention = (
const mentionRoom = mx.getRoom(
isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias
);
const fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias;
let fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias;
if (mentionRoom) {
const linkedEvent = mentionRoom.findEventById?.(eventId);
if (linkedEvent) {
const raw = linkedEvent.getContent() as { body?: unknown };
const body = typeof raw.body === 'string' ? raw.body.trim() : '';
if (body) {
const singleLine = body.replace(/\s+/g, ' ');
const short = singleLine.length > 72 ? `${singleLine.slice(0, 69)}…` : singleLine;
fallbackContent = `#${mentionRoom.name}: ${short}`;
}
}
}
const label = matrixPermalinkDisplayLabel(href, customProps.children, fallbackContent);
return (
<a
@@ -223,7 +250,7 @@ export const renderMatrixMention = (
<span aria-hidden="true" className={css.MentionIcon}>
<Icon size="50" src={Icons.Message} />
</span>
{customProps.children ? customProps.children : fallbackContent}
{label}
</a>
);
}