feat: add bundled link embeds

This commit is contained in:
Erwan Leboucher committed 2026-08-01 21:27:52 +02:00
1 parent f3f71642aa
commit b96442d47e
8 files changed
+292 -46

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
sable: minor
---
Allow generating and removing bundled link embeds.
@@ -20,7 +20,12 @@ vi.mock('./url-preview', () => ({
UrlPreviewHolder: ({ children }: { children: React.ReactNode }) => (
<div data-testid="url-preview-holder">{children}</div>
),
UrlPreviewCard: ({ url }: { url: string }) => <div data-testid="url-preview-card">{url}</div>,
UrlPreviewCard: ({ url, bundle }: { url: string; bundle?: unknown }) => (
<div data-testid="url-preview-card">
{bundle ? 'bundle:' : 'dynamic:'}
{url}
</div>
),
ClientPreview: ({ url }: { url: string }) => <div data-testid="client-preview">{url}</div>,
youtubeUrl: () => false,
}));
@@ -72,6 +77,77 @@ afterEach(() => {
});
describe('RenderMessageContent', () => {
it('does not render previews when the sender supplied an empty bundle', () => {
render(
<ClientConfigProvider value={{}}>
<RenderMessageContent
displayName="Alice"
msgType={MsgType.Text}
ts={0}
bundledPreview
urlPreview
getContent={() =>
({ body: 'https://example.com', 'com.beeper.linkpreviews': [] }) as never
}
htmlReactParserOptions={{}}
linkifyOpts={{}}
/>
</ClientConfigProvider>
);
expect(screen.queryByTestId('url-preview-card')).not.toBeInTheDocument();
});
it('renders bundled metadata without fetching the URL again', () => {
render(
<ClientConfigProvider value={{}}>
<RenderMessageContent
displayName="Alice"
msgType={MsgType.Text}
ts={0}
bundledPreview
urlPreview
getContent={() =>
({
body: 'https://example.com',
'com.beeper.linkpreviews': [
{ matched_url: 'https://example.com', 'og:title': 'Example' },
],
}) as never
}
htmlReactParserOptions={{}}
linkifyOpts={{}}
/>
</ClientConfigProvider>
);
expect(screen.getByTestId('url-preview-card')).toHaveTextContent('bundle:https://example.com');
});
it('keeps dynamic previews for URL-only bundle markers', () => {
render(
<ClientConfigProvider value={{}}>
<RenderMessageContent
displayName="Alice"
msgType={MsgType.Text}
ts={0}
bundledPreview
urlPreview
getContent={() =>
({
body: 'https://example.com',
'com.beeper.linkpreviews': [{ matched_url: 'https://example.com' }],
}) as never
}
htmlReactParserOptions={{}}
linkifyOpts={{}}
/>
</ClientConfigProvider>
);
expect(screen.getByTestId('url-preview-card')).toHaveTextContent('dynamic:https://example.com');
});
it('does not render url previews for settings links', () => {
renderMessage(
'https://app.example/settings/account?focus=status&moe.sable.client.action=settings'
+6 -8
View File
@@ -197,14 +197,12 @@ function RenderMessageContentInternal({
const renderBundledPreviews = useCallback(
(bundles: IPreviewUrlResponse[]) => (
<UrlPreviewHolder>
{bundles.map((bundle) => (
<UrlPreviewCard
urlPreview={urlPreview === true}
key={bundle['og:url']}
url={bundle['og:url']}
bundle={bundle}
/>
))}
{bundles.map((bundle) => {
const matchedUrl = (bundle as IPreviewUrlResponse & { matched_url?: string }).matched_url;
const url = bundle['og:url'] ?? matchedUrl;
if (!url) return null;
return <UrlPreviewCard urlPreview={false} key={url} url={url} bundle={bundle} />;
})}
</UrlPreviewHolder>
),
[urlPreview]
+40 -30
View File
@@ -171,13 +171,23 @@ const getUrlsFromContent = (
urls = urls.filter((url) => safeUrlsSet.has(url) && !url.startsWith(MATRIX_TO_BASE));
}
let bundleContent = content[
prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME
] as BundleContent[];
const rawBundleContent = content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME];
let bundleContent = Array.isArray(rawBundleContent)
? (rawBundleContent as BundleContent[])
: undefined;
try {
bundleContent = bundleContent?.filter((bundle) => !!urls?.includes(bundle.matched_url));
if (renderUrlsPreview && bundleContent)
urls = bundleContent.map((bundle) => bundle.matched_url);
if (bundleContent) {
const bundledUrls = new Set(bundleContent.map((bundle) => bundle.matched_url));
urls = urls?.filter((url) => bundledUrls.has(url));
bundleContent = bundleContent.filter((bundle) =>
Object.keys(bundle).some((key) => key.startsWith('og:'))
);
if (renderUrlsPreview && bundleContent.length > 0) {
const completeUrls = new Set(bundleContent.map((bundle) => bundle.matched_url));
urls = urls?.filter((url) => !completeUrls.has(url));
}
}
} catch {
urls = [];
}
@@ -264,11 +274,11 @@ export function MText({
})}
{edited && <MessageEditedContent />}
</MessageTextBody>
{(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) ||
(renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))}
{renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[])}
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
</>
);
}
@@ -281,11 +291,11 @@ export function MText({
customBody: unwrappedForwardedContent,
})}
{edited && <MessageEditedContent />}
{(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) ||
(renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))}
{renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[])}
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
</MessageTextBody>
);
}
@@ -303,11 +313,11 @@ export function MText({
})}
{edited && <MessageEditedContent />}
</MessageTextBody>
{(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) ||
(renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))}
{renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[])}
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
</>
);
}
@@ -360,11 +370,11 @@ export function MEmote({
})}
{edited && <MessageEditedContent />}
</MessageTextBody>
{(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) ||
(renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))}
{renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[])}
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
</>
);
}
@@ -414,11 +424,11 @@ export function MNotice({
})}
{edited && <MessageEditedContent />}
</MessageTextBody>
{(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) ||
(renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))}
{renderBundledPreviews &&
bundleContent &&
bundleContent.length > 0 &&
renderBundledPreviews(bundleContent as IPreviewUrlResponse[])}
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
</>
);
}
+136 -6
View File
@@ -18,6 +18,7 @@ import type {
MatrixEvent,
Room,
IEventRelation,
IPreviewUrlResponse,
RoomMessageEventContent,
StickerEventContent,
} from '$types/matrix-sdk';
@@ -28,6 +29,7 @@ import { Editor, Point, Range, Transforms } from 'slate';
import type { RectCords } from 'folds';
import {
Box,
Button,
color,
config,
Dialog,
@@ -112,6 +114,7 @@ import type { EditorButtonId } from '$state/settings';
import { settingsAtom } from '$state/settings';
import { matchesShortcut } from '../../keyboard/shortcuts';
import { getEditedEvent, getMentionContent, getThreadReplyEvents } from '$utils/room/relations';
import { isServerUrlPreviewEnabled } from '$utils/room/urlPreview';
import { buildReplacementContent } from './buildReplacementContent';
import { htmlToMarkdown } from '$plugins/markdown';
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands';
@@ -141,6 +144,7 @@ import {
} from '$utils/delayedEvents';
import { timeHourMinute, timeDayMonthYear, daysToMs } from '$utils/time';
import { stopPropagation } from '$utils/keyboard';
import { UrlPreviewCard } from '$components/url-preview';
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
import { useRoomCreators } from '$hooks/useRoomCreators';
@@ -273,6 +277,12 @@ export const getReplyContent = (
const log = createLogger('RoomInput');
const debugLog = createDebugLogger('RoomInput');
type BundledPreview = IPreviewUrlResponse & { matched_url: string };
type BundledPreviewStatus =
| { status: 'loading' }
| { status: 'ready'; bundle: BundledPreview }
| { status: 'error' }
| { status: 'dismissed' };
interface ReplyEventContent {
'm.relates_to'?: IEventRelation;
}
@@ -322,6 +332,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
const [mentionInReplies] = useSetting(settingsAtom, 'mentionInReplies');
const [urlPreview] = useSetting(settingsAtom, 'urlPreview');
const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview');
const serverEmbedsEnabled = isServerUrlPreviewEnabled(
room.hasEncryptionStateEvent(),
urlPreview,
encUrlPreview
);
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
const commands = useCommands(mx, room);
const imagePacksUsedRef = useRef(new SerializableMap<string, MSC4459ImagePackReference>());
@@ -495,10 +512,66 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const handlePaste = useFilePasteHandler(handleFiles);
const dropZoneVisible = useFileDropZone(fileDropContainerRef, handleFiles);
const [hasText, setHasText] = useState(false);
const [, setComposerRevision] = useState(0);
const handleEditorChange = useCallback(() => {
setHasText(!isEmptyEditor(editor));
setComposerRevision((revision) => revision + 1);
}, [editor]);
const hasContent = hasText || selectedFiles.length > 0;
const composerLinks = getLinks(editor.children) ?? [];
const composerLinksKey = composerLinks.join('\n');
const [bundledPreviews, setBundledPreviews] = useState<Record<string, BundledPreviewStatus>>(
{}
);
const bundledPreviewRequestsRef = useRef(new Set<string>());
const bundledPreviewGenerationRef = useRef(0);
useEffect(() => {
const links = new Set(composerLinksKey ? composerLinksKey.split('\n') : []);
setBundledPreviews((current) => {
const next = Object.fromEntries(Object.entries(current).filter(([url]) => links.has(url)));
return Object.keys(next).length === Object.keys(current).length ? current : next;
});
}, [composerLinksKey]);
const generateBundledPreview = useCallback(
(url: string) => {
if (!serverEmbedsEnabled) return;
const generation = bundledPreviewGenerationRef.current;
const requestKey = `${generation}:${url}`;
if (bundledPreviewRequestsRef.current.has(requestKey)) return;
bundledPreviewRequestsRef.current.add(requestKey);
setBundledPreviews((current) => ({ ...current, [url]: { status: 'loading' } }));
mx.getUrlPreview(url, Date.now())
.then(
(preview) => {
if (generation !== bundledPreviewGenerationRef.current) return;
setBundledPreviews((current) => ({
...current,
[url]: { status: 'ready', bundle: { ...preview, matched_url: url } },
}));
},
() => {
if (generation !== bundledPreviewGenerationRef.current) return;
setBundledPreviews((current) => ({ ...current, [url]: { status: 'error' } }));
}
)
.finally(() => bundledPreviewRequestsRef.current.delete(requestKey));
},
[mx, serverEmbedsEnabled]
);
useEffect(() => {
if (!serverEmbedsEnabled) {
bundledPreviewGenerationRef.current += 1;
setBundledPreviews((current) => (Object.keys(current).length === 0 ? current : {}));
return;
}
const links = composerLinksKey ? composerLinksKey.split('\n') : [];
links.forEach((url) => {
if (bundledPreviews[url] === undefined) generateBundledPreview(url);
});
}, [composerLinksKey, bundledPreviews, generateBundledPreview, serverEmbedsEnabled]);
const isComposing = useComposingCheck();
@@ -1333,12 +1406,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
imagePacksUsedRef.current.toJSON();
const links = getLinks(serializedChildren);
content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = [];
links?.forEach((link) =>
content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME].push({
matched_url: link,
})
);
const bundles = links?.flatMap((link) => {
const preview = bundledPreviews[link];
return preview?.status === 'ready' ? [preview.bundle] : [];
});
if (serverEmbedsEnabled && bundles && bundles.length > 0) {
content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = bundles;
}
if (replyDraft || !customHtmlEqualsPlainText(formattedBody, body)) {
content.format = 'org.matrix.custom.html';
@@ -1402,6 +1476,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
resetEditorHistory(editor);
setInputKey((prev) => prev + 1);
imagePacksUsedRef.current.clear();
setBundledPreviews({});
setReplyDraft(replyDraftBase);
sendTypingStatus(false);
};
@@ -1538,6 +1613,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
getEditingContent,
onCancelEdit,
latchedPersona,
bundledPreviews,
serverEmbedsEnabled,
]);
const handleKeyDown: KeyboardEventHandler = useCallback(
@@ -1901,6 +1978,59 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
)}
</UploadBoard>
)}
{serverEmbedsEnabled && composerLinks.length > 0 && (
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
{composerLinks.map((url) => {
const preview = bundledPreviews[url];
if (preview?.status === 'dismissed') return null;
if (preview?.status === 'ready') {
return (
<Box key={url} direction="Column" gap="100">
<UrlPreviewCard urlPreview={false} url={url} bundle={preview.bundle} />
<Button
size="300"
variant="Secondary"
fill="Soft"
radii="300"
onClick={() =>
setBundledPreviews((current) => ({
...current,
[url]: { status: 'dismissed' },
}))
}
>
Remove embed
</Button>
</Box>
);
}
if (preview?.status === 'error') {
return (
<Box key={url} alignItems="Center" gap="200">
<Button
size="300"
variant="Secondary"
fill="Soft"
radii="300"
onClick={() => generateBundledPreview(url)}
>
Retry embed
</Button>
<Text size="T200" style={{ color: color.Critical.Main }}>
Could not generate this embed.
</Text>
</Box>
);
}
return (
<Box key={url} alignItems="Center" gap="200">
<Spinner variant="Secondary" size="300" />
<Text size="T300">Generating embed...</Text>
</Box>
);
})}
</Box>
)}
{scheduledTime && (
<div>
<Box
@@ -20,6 +20,7 @@ import { buildAbbrReplaceTextNode } from '$components/message/RenderBody';
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
import { useRoomCreators } from '$hooks/useRoomCreators';
import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { isServerUrlPreviewEnabled } from '$utils/room/urlPreview';
import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag';
import { useMemberEventParser } from '$hooks/useMemberEventParser';
import type { ResolvedHiddenEventSettings } from '$state/hooks/settings';
@@ -100,7 +101,11 @@ export function useTimelineRendererContext(room: Room): TimelineRendererContextV
// Derived settings
const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap;
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
const showUrlPreview = isServerUrlPreviewEnabled(
room.hasEncryptionStateEvent(),
urlPreview,
encUrlPreview
);
const showClientUrlPreview = room.hasEncryptionStateEvent()
? clientUrlPreview && encClientUrlPreview
: clientUrlPreview;
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { isServerUrlPreviewEnabled } from './urlPreview';
describe('isServerUrlPreviewEnabled', () => {
it.each([
[false, false, false, false],
[false, true, false, true],
[true, false, false, false],
[true, true, false, false],
[true, false, true, true],
])(
'uses the setting for the room encryption state',
(isEncrypted, urlPreview, encUrlPreview, expected) => {
expect(isServerUrlPreviewEnabled(isEncrypted, urlPreview, encUrlPreview)).toBe(expected);
}
);
});
+5
View File
@@ -0,0 +1,5 @@
export const isServerUrlPreviewEnabled = (
isEncrypted: boolean,
urlPreview: boolean,
encUrlPreview: boolean
) => (isEncrypted ? encUrlPreview : urlPreview);