Refactor MFileBody using MVVM and move to shared-components (#32730)

* Refactor MFileBody using MVVM and move to shared component

* Simplyfing rendering properties

* Create a first version of view model for the component

* Simplifying component properties and make it possible to override module css using data-* attributes

* Create a MBodyFactory in element-web and use it to render MFileBodyView from MessageEvent

* Use <MediaBody instead of <button to support legacy rendering

* Updated styling and comments

* Refactoring className from snapshot to component property

* Rename MFileBody* to FileBody*

* Rename MFileBody* to FileBody*

* Refactoring render branches to allow for displaying nothing

* Fix styling issues

* Fix lint errors

* Fix for css selectors in playwright tests

* Remove the MFileBody component and change all callers to use MBodyFactory:FileBodyView

* Remove unused strings in element-web

* Revert to render text in story iframes

* Fix for prettier error

* Fix playwright test css selectors

* Apply legacy styling in element-web

* Add legacy styling for mx_MFileBody

* Restore file

* Change from <div to <button

* Calculate span width ad update screenshots

* Remove width calculation and update snapshots

* Fix for letter-spacing and better content in story

* Updated playwright screenshots

* Updated snapshots

* Fixing Sonar errors/warnings

* Removed extra parentheses

* Changes after review

* Change border-radius to px and updated snapshots

* Fix typo in description

* And another typo fix

* Changes after review
This commit is contained in:
rbondesson
2026-03-16 08:47:23 +00:00
committed by GitHub
parent 394356c4df
commit d791e3fe8a
46 changed files with 2316 additions and 695 deletions
@@ -245,9 +245,9 @@ test.describe("Audio player", { tag: ["@no-firefox", "@no-webkit"] }, () => {
await expect(tile.getByRole("region", { name: "Audio player" })).toBeVisible();
// Assert that replied audio file is rendered as file button inside ReplyChain
const button = tile.locator(".mx_ReplyChain_wrapper .mx_MFileBody_info[role='button']");
const button = tile.locator(".mx_ReplyChain_wrapper .mx_MFileBody [role='button']");
// Assert that the file button has file name
await expect(button.locator(".mx_MFileBody_info_filename")).toBeVisible();
await expect(button.locator("span")).toBeVisible();
await takeSnapshots(page, app, "Selected EventTile of audio player with a reply");
},
@@ -307,9 +307,7 @@ test.describe("Audio player", { tag: ["@no-firefox", "@no-webkit"] }, () => {
// Assert that the file button contains the name of the file sent at first
await expect(
replyChain
.locator(".mx_MFileBody_info[role='button']")
.locator(".mx_MFileBody_info_filename", { hasText: "upload-first.ogg" }),
replyChain.locator(".mx_MFileBody [role='button']").locator("span", { hasText: "upload-first.ogg" }),
).toBeVisible();
// Take snapshots
@@ -357,9 +355,7 @@ test.describe("Audio player", { tag: ["@no-firefox", "@no-webkit"] }, () => {
const composer = thread.locator(".mx_MessageComposer--compact");
// Assert that the reply preview contains audio ReplyTile the file info button
await expect(
composer.locator(".mx_ReplyPreview .mx_ReplyTile .mx_MFileBody_info[role='button']"),
).toBeVisible();
await expect(composer.locator(".mx_ReplyPreview .mx_ReplyTile .mx_MFileBody [role='button']")).toBeVisible();
// Select :smile: emoji and send it
await composer.getByTestId("basicmessagecomposer").fill(":smile:");
@@ -367,6 +363,6 @@ test.describe("Audio player", { tag: ["@no-firefox", "@no-webkit"] }, () => {
await composer.getByTestId("basicmessagecomposer").press("Enter");
// Assert that the file name is rendered on the file button
await expect(threadTile.locator(".mx_ReplyTile .mx_MFileBody_info[role='button']")).toBeVisible();
await expect(threadTile.locator(".mx_ReplyTile .mx_MFileBody [role='button']")).toBeVisible();
});
});
@@ -85,7 +85,7 @@ test.describe("FilePanel", () => {
await expect(filePanelMessageList.locator(".mx_EventTile")).toHaveCount(3);
// Assert that the download links are rendered
await expect(filePanelMessageList.locator(".mx_MFileBody_download,.mx_MFileBody_info")).toHaveCount(3);
await expect(filePanelMessageList.locator(".mx_MFileBody")).toHaveCount(3);
// Assert that the sender of the files is rendered on all of the tiles
await expect(filePanelMessageList.getByText(NAME)).toHaveCount(3);
@@ -103,9 +103,7 @@ test.describe("FilePanel", () => {
// Detect the JSON file
// Assert that the tile is rendered as a button
const file = filePanelMessageList.locator(
".mx_EventTile_mediaLine .mx_MFileBody .mx_MFileBody_info[role='button'] .mx_MFileBody_info_filename",
);
const file = filePanelMessageList.locator(".mx_EventTile_mediaLine .mx_MFileBody [role='button']");
// Assert that the file name is rendered inside the button with ellipsis
await expect(file.getByText(/matrix.*?\.json/)).toBeVisible();
@@ -177,8 +175,7 @@ test.describe("FilePanel", () => {
const tile = page.locator(".mx_FilePanel .mx_EventTile");
// Assert that the file size is displayed in kibibytes, not kilobytes (1000 bytes)
// See: https://github.com/vector-im/element-web/issues/24866
await expect(tile.locator(".mx_MFileBody_info_filename", { hasText: size })).toBeVisible();
await expect(tile.locator(".mx_MFileBody_info", { hasText: size })).toBeVisible();
await expect(tile.locator(".mx_MFileBody [data-type='info']", { hasText: size })).toBeVisible();
});
});
@@ -194,7 +191,7 @@ test.describe("FilePanel", () => {
".mx_FilePanel .mx_RoomView_MessageList .mx_EventTile_mediaLine.mx_EventTile_image .mx_MImageBody",
);
const link = imageBody.locator(".mx_MFileBody_download a");
const link = imageBody.locator(".mx_MFileBody a");
const downloadPromise = page.waitForEvent("download");
@@ -779,7 +779,7 @@ test.describe("Timeline", () => {
// Assert that the file size is displayed in kibibytes (1024 bytes), not kilobytes (1000 bytes)
// See: https://github.com/vector-im/element-web/issues/24866
await expect(
page.locator(".mx_EventTile_last .mx_MFileBody_info_filename").getByText(/1.12 KB/),
page.locator(".mx_EventTile_last .mx_MFileBody [data-type='info']").getByText(/1.12 KB/),
).toBeVisible();
});
@@ -103,7 +103,7 @@ async function expectTimelineSticker(page: Page, serverName: string, roomId: str
}
async function expectFileTile(page: Page, roomId: string, contentUri: string) {
await expect(page.locator(".mx_MFileBody_info_filename")).toContainText(STICKER_NAME);
await expect(page.locator(".mx_MFileBody [data-type='info']")).toContainText(STICKER_NAME);
}
async function setWidgetAccountData(
+1 -1
View File
@@ -41,7 +41,7 @@ Please see LICENSE files in the repository root for full details.
padding-inline-start: 0;
}
.mx_MFileBody_download {
.mx_MFileBody [data-type="download"] {
margin-top: var(--cpd-space-4x);
}
@@ -41,7 +41,7 @@ Please see LICENSE files in the repository root for full details.
/* We also hide download links to not encourage users to try interacting */
.mx_EventTile_msgOption,
.mx_EventTile_e2eIcon,
.mx_MFileBody_download {
.mx_MFileBody [data-type="download"] {
display: none;
}
}
+14 -47
View File
@@ -6,56 +6,23 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details.
*/
.mx_MFileBody_download {
.mx_MFileBody [data-type="download"] {
color: $accent;
height: var(--cpd-space-9x);
}
.mx_MFileBody_download object {
margin-left: -16px;
padding-right: 4px;
margin-top: -4px;
vertical-align: middle;
pointer-events: none;
}
/* Remove the border and padding for iframes for download links. */
.mx_MFileBody_download iframe {
margin: 0px;
padding: 0px;
border: none;
width: 100%;
}
.mx_MFileBody_info {
cursor: pointer;
.mx_MFileBody_info_icon {
background-color: $system;
border-radius: 20px;
display: inline-block;
width: 16px;
height: 16px;
padding: var(--cpd-space-2x);
vertical-align: middle;
margin-right: 12px;
svg {
color: $secondary-content;
width: inherit;
height: inherit;
display: block;
}
}
.mx_MFileBody_info_filename {
font: var(--cpd-font-body-md-regular);
color: var(--cpd-color-text-primary);
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
display: inline-block;
width: calc(100% - 32px - 12px); /* 32px icon, 12px margin on the icon */
& object {
margin-left: -16px;
padding-right: 4px;
margin-top: -4px;
vertical-align: middle;
pointer-events: none;
}
}
.mx_MFileBody [data-type="info"] {
svg {
color: $secondary-content !important;
background-color: $system !important;
border-radius: 20px !important;
}
}
@@ -15,12 +15,12 @@ import { AudioPlayerView, useCreateAutoDisposedViewModel } from "@element-hq/web
import { type Playback } from "../../../audio/Playback";
import InlineSpinner from "../elements/InlineSpinner";
import { _t } from "../../../languageHandler";
import MFileBody from "./MFileBody";
import { type IBodyProps } from "./IBodyProps";
import { PlaybackManager } from "../../../audio/PlaybackManager";
import RoomContext, { TimelineRenderingType } from "../../../contexts/RoomContext";
import MediaProcessingError from "./shared/MediaProcessingError";
import { AudioPlayerViewModel } from "../../../viewmodels/audio/AudioPlayerViewModel";
import { FileBodyViewFactory, renderMBody } from "./MBodyFactory";
interface IState {
error?: boolean;
@@ -111,7 +111,7 @@ export default class MAudioBody extends React.PureComponent<IBodyProps, IState>
return (
<span className="mx_MAudioBody">
<AudioPlayer playback={this.state.playback} mediaName={this.props.mxEvent.getContent().body} />
{this.showFileBody && <MFileBody {...this.props} showGenericPlaceholder={false} />}
{this.showFileBody && renderMBody({ ...this.props, showFileInfo: false }, FileBodyViewFactory)}
</span>
);
}
@@ -0,0 +1,83 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type JSX, type RefObject, useContext, useEffect, useRef } from "react";
import { MsgType } from "matrix-js-sdk/src/matrix";
import { FileBodyView, useCreateAutoDisposedViewModel } from "@element-hq/web-shared-components";
import { type IBodyProps } from "./IBodyProps";
import RoomContext from "../../../contexts/RoomContext";
import { FileBodyViewModel } from "../../../viewmodels/message-body/FileBodyViewModel";
interface FileBodyViewProps {
/*
* Whether file-style message bodies should render their info row/placeholder.
* Used by file-body rendering paths (for example FileBodyViewModel via MBodyFactory).
*/
showFileInfo?: boolean;
}
type MBodyComponent = React.ComponentType<IBodyProps & FileBodyViewProps>;
// Adapter that binds RoomContext data and lifecycle updates to the
// FileBody view model before rendering the shared view component.
function FileBodyViewWrapped({
mxEvent,
mediaEventHelper,
forExport,
showFileInfo,
}: IBodyProps & FileBodyViewProps): JSX.Element {
const { timelineRenderingType } = useContext(RoomContext);
const refIFrame = useRef<HTMLIFrameElement>(null) as RefObject<HTMLIFrameElement>;
const refLink = useRef<HTMLAnchorElement>(null) as RefObject<HTMLAnchorElement>;
const vm = useCreateAutoDisposedViewModel(
() =>
new FileBodyViewModel({
mxEvent,
mediaEventHelper,
forExport,
showFileInfo,
timelineRenderingType,
refIFrame,
refLink,
}),
);
useEffect(() => {
vm.setProps({
mxEvent,
mediaEventHelper,
forExport,
showFileInfo,
timelineRenderingType,
});
}, [mxEvent, mediaEventHelper, forExport, showFileInfo, timelineRenderingType, vm]);
return <FileBodyView vm={vm} refIFrame={refIFrame} refLink={refLink} className="mx_MFileBody" />;
}
// Exported for explicit fallback usage where callers want file-body rendering.
export const FileBodyViewFactory: MBodyComponent = (props) => <FileBodyViewWrapped {...props} />;
// Message body factory registry.
// Start small: only m.file currently routes to the new FileBodyView path.
const MESSAGE_BODY_TYPES = new Map<string, MBodyComponent>([[MsgType.File, FileBodyViewFactory]]);
// Render a body using the picked factory.
// Falls back to the provided factory when msgtype has no specific handler.
export function renderMBody(
props: IBodyProps & FileBodyViewProps,
fallbackFactory?: MBodyComponent,
): JSX.Element | null {
const BodyType = MESSAGE_BODY_TYPES.get(props.mxEvent.getContent().msgtype as string) ?? fallbackFactory;
if (!BodyType) {
return null;
}
return <BodyType {...props} />;
}
@@ -1,347 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2015-2021 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type AllHTMLAttributes, createRef } from "react";
import { logger } from "matrix-js-sdk/src/logger";
import { type MediaEventContent } from "matrix-js-sdk/src/types";
import { MsgType } from "matrix-js-sdk/src/matrix";
import { Button } from "@vector-im/compound-web";
import {
AttachmentIcon,
DownloadIcon,
VideoCallSolidIcon,
VolumeOnSolidIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import { _t } from "../../../languageHandler";
import Modal from "../../../Modal";
import AccessibleButton from "../elements/AccessibleButton";
import { mediaFromContent } from "../../../customisations/Media";
import ErrorDialog from "../dialogs/ErrorDialog";
import { downloadLabelForFile, presentableTextForFile } from "../../../utils/FileUtils";
import { type IBodyProps } from "./IBodyProps";
import { FileDownloader } from "../../../utils/FileDownloader";
import TextWithTooltip from "../elements/TextWithTooltip";
import RoomContext, { TimelineRenderingType } from "../../../contexts/RoomContext";
export let DOWNLOAD_ICON_URL: string; // cached copy of the download.svg asset for the sandboxed iframe later on
async function cacheDownloadIcon(): Promise<void> {
if (DOWNLOAD_ICON_URL) return; // cached already
// eslint-disable-next-line @typescript-eslint/no-require-imports
const svg = await fetch(require("@vector-im/compound-design-tokens/icons/download.svg").default).then((r) =>
r.text(),
);
DOWNLOAD_ICON_URL = "data:image/svg+xml;base64," + window.btoa(svg);
}
// Cache the asset immediately
// noinspection JSIgnoredPromiseFromCall
cacheDownloadIcon();
// User supplied content can contain scripts, we have to be careful that
// we don't accidentally run those script within the same origin as the
// client. Otherwise those scripts written by remote users can read
// the access token and end-to-end keys that are in local storage.
//
// For attachments downloaded directly from the homeserver we can use
// Content-Security-Policy headers to disable script execution.
//
// But attachments with end-to-end encryption are more difficult to handle.
// We need to decrypt the attachment on the client and then display it.
// To display the attachment we need to turn the decrypted bytes into a URL.
//
// There are two ways to turn bytes into URLs, data URL and blob URLs.
// Data URLs aren't suitable for downloading a file because Chrome has a
// 2MB limit on the size of URLs that can be viewed in the browser or
// downloaded. This limit does not seem to apply when the url is used as
// the source attribute of an image tag.
//
// Blob URLs are generated using window.URL.createObjectURL and unfortunately
// for our purposes they inherit the origin of the page that created them.
// This means that any scripts that run when the URL is viewed will be able
// to access local storage.
//
// The easiest solution is to host the code that generates the blob URL on
// a different domain to the client.
// Another possibility is to generate the blob URL within a sandboxed iframe.
// The downside of using a second domain is that it complicates hosting,
// the downside of using a sandboxed iframe is that the browers are overly
// restrictive in what you are allowed to do with the generated URL.
/**
* Get the current CSS style for a DOMElement.
* @param {HTMLElement} element The element to get the current style of.
* @return {string} The CSS style encoded as a string.
*/
export function computedStyle(element: HTMLElement | null): string {
if (!element) {
return "";
}
const style = window.getComputedStyle(element, null);
let cssText = style.cssText;
// noinspection EqualityComparisonWithCoercionJS
if (cssText == "") {
// Firefox doesn't implement ".cssText" for computed styles.
// https://bugzilla.mozilla.org/show_bug.cgi?id=137687
for (const rule of style) {
cssText += rule + ":";
cssText += style.getPropertyValue(rule) + ";";
}
}
return cssText;
}
interface IProps extends IBodyProps {
/* whether or not to show the default placeholder for the file. Defaults to true. */
showGenericPlaceholder?: boolean;
}
interface IState {
decryptedBlob?: Blob;
}
export default class MFileBody extends React.Component<IProps, IState> {
public static contextType = RoomContext;
declare public context: React.ContextType<typeof RoomContext>;
public state: IState = {};
private iframe = createRef<HTMLIFrameElement>();
private dummyLink = createRef<HTMLAnchorElement>();
private userDidClick = false;
private fileDownloader: FileDownloader = new FileDownloader(() => this.iframe.current);
private getContentUrl(): string | null {
if (this.props.forExport) return null;
const media = mediaFromContent(this.props.mxEvent.getContent());
return media.srcHttp;
}
private get content(): MediaEventContent {
return this.props.mxEvent.getContent<MediaEventContent>();
}
private get fileName(): string {
return this.props.mediaEventHelper?.fileName || _t("common|attachment");
}
private get linkText(): string {
return downloadLabelForFile(this.content, true);
}
private downloadFile(fileName: string, text: string): void {
if (!this.state.decryptedBlob) return;
this.fileDownloader.download({
blob: this.state.decryptedBlob,
name: fileName,
autoDownload: this.userDidClick,
opts: {
imgSrc: DOWNLOAD_ICON_URL,
imgStyle: null,
style: computedStyle(this.dummyLink.current),
textContent: text,
},
});
}
private decryptFile = async (): Promise<void> => {
if (this.state.decryptedBlob) {
return;
}
try {
this.userDidClick = true;
this.setState({
decryptedBlob: await this.props.mediaEventHelper!.sourceBlob.value,
});
} catch (err) {
logger.warn("Unable to decrypt attachment: ", err);
Modal.createDialog(ErrorDialog, {
title: _t("common|error"),
description: _t("timeline|m.file|error_decrypting"),
});
}
};
private onPlaceholderClick = async (): Promise<void> => {
const mediaHelper = this.props.mediaEventHelper;
if (mediaHelper?.media.isEncrypted) {
await this.decryptFile();
this.downloadFile(this.fileName, this.linkText);
} else {
// As a button we're missing the `download` attribute for styling reasons, so
// download with the file downloader.
this.fileDownloader.download({
blob: await mediaHelper!.sourceBlob.value,
name: this.fileName,
});
}
};
public render(): React.ReactNode {
const isEncrypted = this.props.mediaEventHelper?.media.isEncrypted;
const contentUrl = this.getContentUrl();
const fileType = this.content.info?.mimetype ?? "application/octet-stream";
// defaultProps breaks types on IBodyProps, so instead define the default here.
const showGenericPlaceholder = this.props.showGenericPlaceholder ?? true;
let showDownloadLink =
!showGenericPlaceholder ||
(this.context.timelineRenderingType !== TimelineRenderingType.Room &&
this.context.timelineRenderingType !== TimelineRenderingType.Search &&
this.context.timelineRenderingType !== TimelineRenderingType.Pinned);
let placeholder: React.ReactNode = null;
if (showGenericPlaceholder) {
let icon = <AttachmentIcon />;
// MFileBody is not generally used for Audio/Video but can be as part of ReplyTile
if (this.content.msgtype === MsgType.Audio) {
icon = <VolumeOnSolidIcon />;
} else if (this.content.msgtype === MsgType.Video) {
icon = <VideoCallSolidIcon />;
}
placeholder = (
<AccessibleButton className="mx_MediaBody mx_MFileBody_info" onClick={this.onPlaceholderClick}>
<span className="mx_MFileBody_info_icon">{icon}</span>
<TextWithTooltip tooltip={presentableTextForFile(this.content, _t("common|attachment"), true)}>
<span className="mx_MFileBody_info_filename">
{presentableTextForFile(this.content, _t("common|attachment"), true, true)}
</span>
</TextWithTooltip>
</AccessibleButton>
);
showDownloadLink = false;
}
if (this.props.forExport) {
const content = this.props.mxEvent.getContent();
// During export, the content url will point to the MSC, which will later point to a local url
return (
<span className="mx_MFileBody">
<a href={content.file?.url || content.url}>{placeholder}</a>
</span>
);
}
if (this.context.timelineRenderingType === TimelineRenderingType.Thread) {
showDownloadLink = false;
}
if (isEncrypted) {
if (!this.state.decryptedBlob) {
// Need to decrypt the attachment
// Wait for the user to click on the link before downloading
// and decrypting the attachment.
// This button should actually Download because usercontent/ will try to click itself
// but it is not guaranteed between various browsers' settings.
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
<Button size="sm" kind="secondary" Icon={DownloadIcon} onClick={this.decryptFile}>
{this.linkText}
</Button>
</div>
)}
</span>
);
}
const url = "usercontent/"; // XXX: this path should probably be passed from the skin
// If the attachment is encrypted then put the link inside an iframe.
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
<div aria-hidden style={{ display: "none" }}>
{/*
* Add dummy copy of the button
* We'll use it to learn how the download button
* would have been styled if it was rendered inline.
*/}
{/* this violates multiple eslint rules
so ignore it completely */}
<Button size="sm" kind="secondary" Icon={DownloadIcon} as="a" ref={this.dummyLink} />
</div>
{/*
TODO: Move iframe (and dummy link) into FileDownloader.
We currently have it set up this way because of styles applied to the iframe
itself which cannot be easily handled/overridden by the FileDownloader. In
future, the download link may disappear entirely at which point it could also
be suitable to just remove this bit of code.
*/}
<iframe
aria-hidden
title={presentableTextForFile(this.content, _t("common|attachment"), true, true)}
src={url}
onLoad={() => this.downloadFile(this.fileName, this.linkText)}
ref={this.iframe}
sandbox="allow-scripts allow-downloads"
/>
</div>
)}
</span>
);
} else if (contentUrl) {
const downloadProps: Pick<
AllHTMLAttributes<HTMLAnchorElement>,
"target" | "rel" | "href" | "onClick" | "download"
> = {
target: "_blank",
rel: "noreferrer noopener",
// We cannot rely on href+download to download media due to the authenticated media API as it relies
// on authentication via headers, so we'll have to download the file into memory and then download it.
onClick: (e) => {
logger.log(`Downloading ${fileType} as blob (unencrypted)`);
// Avoid letting the <a> do its thing
e.preventDefault();
e.stopPropagation();
// Start a fetch for the download
// Based upon https://stackoverflow.com/a/49500465
this.props.mediaEventHelper?.sourceBlob.value.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
// We have to create an anchor to download the file
const tempAnchor = document.createElement("a");
tempAnchor.download = this.fileName;
tempAnchor.href = blobUrl;
document.body.appendChild(tempAnchor); // for firefox: https://stackoverflow.com/a/32226068
tempAnchor.click();
tempAnchor.remove();
});
},
};
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
<Button size="sm" kind="secondary" Icon={DownloadIcon} as="a" {...downloadProps}>
{this.linkText}
</Button>
</div>
)}
</span>
);
} else {
return (
<span className="mx_MFileBody">
{placeholder}
{_t("timeline|m.file|error_invalid")}
</span>
);
}
}
}
@@ -17,7 +17,6 @@ import { type ImageContent } from "matrix-js-sdk/src/types";
import { Tooltip } from "@vector-im/compound-web";
import { ImageErrorIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import MFileBody from "./MFileBody";
import Modal from "../../../Modal";
import { _t } from "../../../languageHandler";
import SettingsStore from "../../../settings/SettingsStore";
@@ -37,6 +36,7 @@ import { DecryptError, DownloadError } from "../../../utils/DecryptFile";
import { HiddenMediaPlaceholder } from "./HiddenMediaPlaceholder";
import { useMediaVisible } from "../../../hooks/useMediaVisible";
import { isMimeTypeAllowed } from "../../../utils/blobs.ts";
import { FileBodyViewFactory, renderMBody } from "./MBodyFactory";
enum Placeholder {
NoImage,
@@ -651,20 +651,20 @@ export class MImageBodyInner extends React.Component<IProps, IState> {
this.context.timelineRenderingType === TimelineRenderingType.Thread ||
this.context.timelineRenderingType === TimelineRenderingType.ThreadsList;
if (!hasMessageActionBar) {
return <MFileBody {...this.props} showGenericPlaceholder={false} />;
return renderMBody({ ...this.props, showFileInfo: false }, FileBodyViewFactory);
}
}
public render(): React.ReactNode {
const content = this.props.mxEvent.getContent<ImageContent>();
// Fall back to MFileBody if we are unable to render this image e.g. in the case of a blob svg
// Fall back to file-body view if we are unable to render this image e.g. in the case of a blob svg
if (
this.props.mediaEventHelper?.media.isEncrypted &&
!isMimeTypeAllowed(content.info?.mimetype ?? "") &&
!content.info?.thumbnail_info
) {
return <MFileBody {...this.props} />;
return renderMBody(this.props, FileBodyViewFactory);
}
if (this.state.error) {
@@ -17,12 +17,12 @@ import InlineSpinner from "../elements/InlineSpinner";
import { mediaFromContent } from "../../../customisations/Media";
import { BLURHASH_FIELD } from "../../../utils/image-media";
import { type IBodyProps } from "./IBodyProps";
import MFileBody from "./MFileBody";
import { type ImageSize, suggestedSize as suggestedVideoSize } from "../../../settings/enums/ImageSize";
import RoomContext, { TimelineRenderingType } from "../../../contexts/RoomContext";
import MediaProcessingError from "./shared/MediaProcessingError";
import { HiddenMediaPlaceholder } from "./HiddenMediaPlaceholder";
import { useMediaVisible } from "../../../hooks/useMediaVisible";
import { FileBodyViewFactory, renderMBody } from "./MBodyFactory";
interface IState {
decryptedUrl: string | null;
@@ -246,7 +246,7 @@ class MVideoBodyInner extends React.PureComponent<IProps, IState> {
private getFileBody = (): ReactNode => {
if (this.props.forExport) return null;
return this.showFileBody && <MFileBody {...this.props} showGenericPlaceholder={false} />;
return this.showFileBody && renderMBody({ ...this.props, showFileInfo: false }, FileBodyViewFactory);
};
public render(): React.ReactNode {
@@ -12,12 +12,12 @@ import InlineSpinner from "../elements/InlineSpinner";
import { _t } from "../../../languageHandler";
import RecordingPlayback from "../audio_messages/RecordingPlayback";
import MAudioBody from "./MAudioBody";
import MFileBody from "./MFileBody";
import MediaProcessingError from "./shared/MediaProcessingError";
import { isVoiceMessage } from "../../../utils/EventUtils";
import { PlaybackQueue } from "../../../audio/PlaybackQueue";
import { type Playback } from "../../../audio/Playback";
import RoomContext from "../../../contexts/RoomContext";
import { FileBodyViewFactory, renderMBody } from "./MBodyFactory";
export default class MVoiceMessageBody extends MAudioBody {
public static contextType = RoomContext;
@@ -54,7 +54,7 @@ export default class MVoiceMessageBody extends MAudioBody {
return (
<span className="mx_MVoiceMessageBody">
<RecordingPlayback playback={this.state.playback} />
{this.showFileBody && <MFileBody {...this.props} showGenericPlaceholder={false} />}
{this.showFileBody && renderMBody({ ...this.props, showFileInfo: false }, FileBodyViewFactory)}
</span>
);
}
@@ -30,7 +30,6 @@ import { MediaEventHelper } from "../../../utils/MediaEventHelper";
import { type IBodyProps } from "./IBodyProps";
import TextualBody from "./TextualBody";
import MImageBody from "./MImageBody";
import MFileBody from "./MFileBody";
import MVoiceOrAudioBody from "./MVoiceOrAudioBody";
import MVideoBody from "./MVideoBody";
import MStickerBody from "./MStickerBody";
@@ -40,6 +39,7 @@ import MjolnirBody from "./MjolnirBody";
import MBeaconBody from "./MBeaconBody";
import { type GetRelationsForEvent, type IEventTileOps } from "../rooms/EventTile";
import { DecryptionFailureBodyViewModel } from "../../../viewmodels/message-body/DecryptionFailureBodyViewModel";
import { FileBodyViewFactory, renderMBody } from "./MBodyFactory";
// onMessageAllowed is handled internally
interface IProps extends Omit<IBodyProps, "onMessageAllowed" | "mediaEventHelper"> {
@@ -67,7 +67,7 @@ const baseBodyTypes = new Map<string, React.ComponentType<IBodyProps>>([
[MsgType.Notice, TextualBody],
[MsgType.Emote, TextualBody],
[MsgType.Image, MImageBody],
[MsgType.File, MFileBody],
[MsgType.File, (props: IBodyProps) => renderMBody(props, FileBodyViewFactory)!],
[MsgType.Audio, MVoiceOrAudioBody],
[MsgType.Video, MVideoBody],
]);
@@ -256,7 +256,7 @@ export default class MessageEvent extends React.Component<IProps> implements IMe
} else if (msgtype && this.bodyTypes.has(msgtype)) {
BodyType = this.bodyTypes.get(msgtype)!;
} else if (content.url) {
// Fallback to MFileBody if there's a content URL
// Fallback to file body if there's a content URL
BodyType = this.bodyTypes.get(MsgType.File)!;
} else {
// Fallback to UnknownBody otherwise if not redacted
@@ -19,7 +19,6 @@ import SenderProfile from "../messages/SenderProfile";
import MImageReplyBody from "../messages/MImageReplyBody";
import { isVoiceMessage } from "../../../utils/EventUtils";
import { getEventDisplayInfo } from "../../../utils/EventRenderingUtils";
import MFileBody from "../messages/MFileBody";
import MemberAvatar from "../avatars/MemberAvatar";
import MVoiceMessageBody from "../messages/MVoiceMessageBody";
import { type ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
@@ -27,6 +26,7 @@ import { renderReplyTile } from "../../../events/EventTileFactory";
import { type GetRelationsForEvent } from "../rooms/EventTile";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import { type IBodyProps } from "../messages/IBodyProps";
import { FileBodyViewFactory, renderMBody } from "../messages/MBodyFactory";
interface IProps {
mxEvent: MatrixEvent;
@@ -130,11 +130,13 @@ export default class ReplyTile extends React.PureComponent<IProps> {
);
}
const ReplyTileFileBody: React.ComponentType<IBodyProps> = (props) => renderMBody(props, FileBodyViewFactory);
const msgtypeOverrides: Record<string, React.ComponentType<IBodyProps>> = {
[MsgType.Image]: MImageReplyBody,
// Override audio and video body with file body. We also hide the download/decrypt button using CSS
[MsgType.Audio]: isVoiceMessage(mxEvent) ? MVoiceMessageBody : MFileBody,
[MsgType.Video]: MFileBody,
[MsgType.Audio]: isVoiceMessage(mxEvent) ? MVoiceMessageBody : ReplyTileFileBody,
[MsgType.Video]: ReplyTileFileBody,
};
const evOverrides: Record<string, React.ComponentType<IBodyProps>> = {
// Use MImageReplyBody so that the sticker isn't taking up a lot of space
+1 -2
View File
@@ -3399,8 +3399,7 @@
"voice_call_unsupported": "%(senderName)s placed a voice call. (not supported by this browser)"
},
"m.file": {
"error_decrypting": "Error decrypting attachment",
"error_invalid": "Invalid file"
"error_decrypting": "Error decrypting attachment"
},
"m.image": {
"error": "Unable to show image due to error",
@@ -348,7 +348,7 @@ export default class HTMLExporter extends Exporter {
const mxc = mxEv.getContent().url ?? mxEv.getContent().file?.url;
eventTileMarkup = eventTileMarkup.split(mxc).join(filePath);
}
eventTileMarkup = eventTileMarkup.replace(/<span class="mx_MFileBody_info_icon".*?>.*?<\/span>/, "");
eventTileMarkup = eventTileMarkup.replace(/<span class="mx_MFileBody".*?>.*?<\/span>/, "");
if (hasAvatar) {
eventTileMarkup = eventTileMarkup.replace(
encodeURI(avatarUrl).replace(/&/g, "&amp;"),
@@ -0,0 +1,311 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import { type MouseEvent, type RefObject } from "react";
import { logger } from "matrix-js-sdk/src/logger";
import { MsgType, type MatrixEvent } from "matrix-js-sdk/src/matrix";
import { type MediaEventContent } from "matrix-js-sdk/src/types";
import {
BaseViewModel,
FileBodyViewState,
FileBodyViewInfoIcon,
type FileBodyViewSnapshot,
type FileBodyViewModel as FileBodyViewModelInterface,
} from "@element-hq/web-shared-components";
import Modal from "../../Modal";
import { _t } from "../../languageHandler";
import { mediaFromContent } from "../../customisations/Media";
import { downloadLabelForFile, presentableTextForFile } from "../../utils/FileUtils";
import { FileDownloader } from "../../utils/FileDownloader";
import { type MediaEventHelper } from "../../utils/MediaEventHelper";
import { TimelineRenderingType } from "../../contexts/RoomContext";
import ErrorDialog from "../../components/views/dialogs/ErrorDialog";
export interface FileBodyViewModelProps {
mxEvent: MatrixEvent;
mediaEventHelper?: MediaEventHelper;
forExport?: boolean;
showFileInfo?: boolean;
timelineRenderingType: TimelineRenderingType;
refIFrame: RefObject<HTMLIFrameElement>;
refLink: RefObject<HTMLAnchorElement>;
}
// Cached copy of the download.svg asset for the sandboxed iframe.
const downloadIconCache = { url: "" };
async function cacheDownloadIcon(): Promise<string> {
if (downloadIconCache.url) return downloadIconCache.url;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const svg = await fetch(require("@vector-im/compound-design-tokens/icons/download.svg").default).then((r) =>
r.text(),
);
downloadIconCache.url = "data:image/svg+xml;base64," + window.btoa(svg);
return downloadIconCache.url;
}
// Cache the asset immediately
// noinspection JSIgnoredPromiseFromCall
cacheDownloadIcon();
// User supplied content can contain scripts, we have to be careful that
// we don't accidentally run those script within the same origin as the
// client. Otherwise those scripts written by remote users can read
// the access token and end-to-end keys that are in local storage.
//
// For attachments downloaded directly from the homeserver we can use
// Content-Security-Policy headers to disable script execution.
//
// But attachments with end-to-end encryption are more difficult to handle.
// We need to decrypt the attachment on the client and then display it.
// To display the attachment we need to turn the decrypted bytes into a URL.
//
// There are two ways to turn bytes into URLs, data URL and blob URLs.
// Data URLs aren't suitable for downloading a file because Chrome has a
// 2MB limit on the size of URLs that can be viewed in the browser or
// downloaded. This limit does not seem to apply when the url is used as
// the source attribute of an image tag.
//
// Blob URLs are generated using window.URL.createObjectURL and unfortunately
// for our purposes they inherit the origin of the page that created them.
// This means that any scripts that run when the URL is viewed will be able
// to access local storage.
//
// The easiest solution is to host the code that generates the blob URL on
// a different domain to the client.
// Another possibility is to generate the blob URL within a sandboxed iframe.
// The downside of using a second domain is that it complicates hosting,
// the downside of using a sandboxed iframe is that the browers are overly
// restrictive in what you are allowed to do with the generated URL.
/**
* Get the current CSS style for a DOMElement.
* @param {HTMLElement} element The element to get the current style of.
* @return {string} The CSS style encoded as a string.
*/
function computedStyle(element: HTMLElement | null): string {
if (!element) {
return "";
}
const style = window.getComputedStyle(element, null);
let cssText = style.cssText;
// noinspection EqualityComparisonWithCoercionJS
if (cssText === "") {
// Firefox doesn't implement ".cssText" for computed styles.
// https://bugzilla.mozilla.org/show_bug.cgi?id=137687
for (const rule of style) {
cssText += rule + ":";
cssText += style.getPropertyValue(rule) + ";";
}
}
return cssText;
}
export class FileBodyViewModel
extends BaseViewModel<FileBodyViewSnapshot, FileBodyViewModelProps>
implements FileBodyViewModelInterface
{
private readonly refIFrame: RefObject<HTMLIFrameElement>;
private readonly refLink: RefObject<HTMLAnchorElement>;
private decryptedBlob?: Blob;
private userDidClick = false;
private readonly fileDownloader: FileDownloader;
public constructor(props: FileBodyViewModelProps) {
super(props, FileBodyViewModel.computeSnapshot(props));
this.refIFrame = props.refIFrame;
this.refLink = props.refLink;
this.fileDownloader = new FileDownloader(() => this.refIFrame.current);
}
private static getInfoIcon(content: MediaEventContent): FileBodyViewInfoIcon {
if (content.msgtype === MsgType.Audio) {
return FileBodyViewInfoIcon.AUDIO;
} else if (content.msgtype === MsgType.Video) {
return FileBodyViewInfoIcon.VIDEO;
}
return FileBodyViewInfoIcon.ATTACHMENT;
}
private static computeSnapshot(props: FileBodyViewModelProps, decryptedBlob?: Blob): FileBodyViewSnapshot {
const content = props.mxEvent.getContent<MediaEventContent>();
const media = mediaFromContent(content);
const isEncrypted = props.mediaEventHelper?.media.isEncrypted === true;
//Whether or not to show the default placeholder for the file. Defaults to true.
const showFileInfo = props.showFileInfo ?? true;
const showDownload =
!showFileInfo &&
props.timelineRenderingType !== TimelineRenderingType.Room &&
props.timelineRenderingType !== TimelineRenderingType.Search &&
props.timelineRenderingType !== TimelineRenderingType.Pinned &&
props.timelineRenderingType !== TimelineRenderingType.Thread;
const fileInfoLabel = showFileInfo
? presentableTextForFile(content, _t("common|attachment"), true, true)
: undefined;
const fileInfoTooltip = showFileInfo
? presentableTextForFile(content, _t("common|attachment"), true)
: undefined;
const fileInfoIcon = showFileInfo ? FileBodyViewModel.getInfoIcon(content) : undefined;
const downloadLabel = showDownload ? downloadLabelForFile(content, true) : undefined;
const downloadTitle = showDownload
? presentableTextForFile(content, _t("common|attachment"), true, true)
: undefined;
if (props.forExport) {
return {
state: FileBodyViewState.EXPORT,
showInfo: showFileInfo,
infoLabel: fileInfoLabel,
infoTooltip: fileInfoTooltip,
infoIcon: fileInfoIcon,
infoHref: content.file?.url || content.url,
};
}
if (isEncrypted) {
const state = decryptedBlob ? FileBodyViewState.ENCRYPTED : FileBodyViewState.DECRYPTION_PENDING;
return {
state,
showInfo: showFileInfo,
infoLabel: fileInfoLabel,
infoTooltip: fileInfoTooltip,
infoIcon: fileInfoIcon,
showDownload,
downloadLabel,
downloadTitle: downloadTitle,
};
}
if (media.srcHttp) {
return {
state: FileBodyViewState.UNENCRYPTED,
showInfo: showFileInfo,
infoLabel: fileInfoLabel,
infoTooltip: fileInfoTooltip,
infoIcon: fileInfoIcon,
showDownload,
downloadLabel,
downloadTitle: downloadTitle,
downloadHref: media.srcHttp,
};
}
return {
state: FileBodyViewState.INVALID,
showInfo: showFileInfo,
infoLabel: fileInfoLabel,
infoTooltip: fileInfoTooltip,
infoIcon: fileInfoIcon,
infoHref: content.file?.url || content.url,
};
}
private get content(): MediaEventContent {
return this.props.mxEvent.getContent<MediaEventContent>();
}
private get fileName(): string {
return this.props.mediaEventHelper?.fileName || _t("common|attachment");
}
private get linkText(): string {
return downloadLabelForFile(this.content, true);
}
private downloadFile(fileName: string, text: string): void {
if (!this.decryptedBlob) return;
this.fileDownloader.download({
blob: this.decryptedBlob,
name: fileName,
autoDownload: this.userDidClick,
opts: {
imgSrc: downloadIconCache.url,
imgStyle: null,
style: computedStyle(this.refLink.current),
textContent: text,
},
});
}
private decryptFile = async (): Promise<void> => {
if (this.decryptedBlob || !this.props.mediaEventHelper) {
return;
}
try {
this.userDidClick = true;
this.decryptedBlob = await this.props.mediaEventHelper.sourceBlob.value;
this.snapshot.set(FileBodyViewModel.computeSnapshot(this.props, this.decryptedBlob));
} catch (err) {
logger.warn("Unable to decrypt attachment: ", err);
Modal.createDialog(ErrorDialog, {
title: _t("common|error"),
description: _t("timeline|m.file|error_decrypting"),
});
}
};
public onInfoClick = async (): Promise<void> => {
if (this.props.forExport || !(this.props.showFileInfo ?? true) || !this.props.mediaEventHelper) {
return;
}
if (this.props.mediaEventHelper.media.isEncrypted) {
await this.decryptFile();
this.downloadFile(this.fileName, this.linkText);
return;
}
this.fileDownloader.download({
blob: await this.props.mediaEventHelper.sourceBlob.value,
name: this.fileName,
});
};
public onDownloadClick = (): Promise<void> => this.decryptFile();
public onDownloadLinkClick = (event: MouseEvent<HTMLAnchorElement>): void => {
event.preventDefault();
event.stopPropagation();
if (!this.props.mediaEventHelper) return;
const fileType = this.content.info?.mimetype ?? "application/octet-stream";
logger.log(`Downloading ${fileType} as blob (unencrypted)`);
this.props.mediaEventHelper.sourceBlob.value.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
const tempAnchor = document.createElement("a");
tempAnchor.download = this.fileName;
tempAnchor.href = blobUrl;
document.body.appendChild(tempAnchor);
tempAnchor.click();
tempAnchor.remove();
});
};
public onDownloadIframeLoad = (): void => {
this.downloadFile(this.fileName, this.linkText);
};
public setProps(newProps: Partial<FileBodyViewModelProps>): void {
const oldEvent = this.props.mxEvent;
this.props = { ...this.props, ...newProps };
if (this.props.mxEvent !== oldEvent) {
this.decryptedBlob = undefined;
this.userDidClick = false;
}
this.snapshot.set(FileBodyViewModel.computeSnapshot(this.props, this.decryptedBlob));
}
}
@@ -0,0 +1,151 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render } from "jest-matrix-react";
import { EventType, getHttpUriForMxc, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import {
getMockClientWithEventEmitter,
mockClientMethodsCrypto,
mockClientMethodsDevice,
mockClientMethodsServer,
mockClientMethodsUser,
} from "../../../../test-utils";
import { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { FileBodyViewFactory, renderMBody } from "../../../../../src/components/views/messages/MBodyFactory";
import { TimelineRenderingType } from "../../../../../src/contexts/RoomContext.ts";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext.tsx";
jest.mock("matrix-encrypt-attachment", () => ({
decryptAttachment: jest.fn(),
}));
describe("MBodyFactory", () => {
const userId = "@user:server";
const deviceId = "DEADB33F";
const cli = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
...mockClientMethodsDevice(deviceId),
...mockClientMethodsCrypto(),
getRooms: jest.fn().mockReturnValue([]),
getIgnoredUsers: jest.fn(),
getVersions: jest.fn().mockResolvedValue({
unstable_features: {
"org.matrix.msc3882": true,
"org.matrix.msc3886": true,
},
}),
});
// eslint-disable-next-line no-restricted-properties
cli.mxcUrlToHttp.mockImplementation(
(mxcUrl: string, width?: number, height?: number, resizeMethod?: string, allowDirectLinks?: boolean) => {
return getHttpUriForMxc("https://server", mxcUrl, width, height, resizeMethod, allowDirectLinks);
},
);
const props = {
onMessageAllowed: jest.fn(),
permalinkCreator: new RoomPermalinkCreator(new Room("!room:server", cli, cli.getUserId()!)),
};
const mkEvent = (msgtype?: string): MatrixEvent =>
new MatrixEvent({
room_id: "!room:server",
sender: userId,
type: EventType.RoomMessage,
content: {
body: "alt",
...(msgtype ? { msgtype } : {}),
url: "mxc://server/file",
},
});
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
});
describe("renderMBody", () => {
it("renders download button for m.file in file rendering type", () => {
const mediaEvent = mkEvent("m.file");
const { container, getByRole } = render(
<ScopedRoomContextProvider {...({ timelineRenderingType: TimelineRenderingType.File } as any)}>
{renderMBody({
...props,
mxEvent: mediaEvent,
mediaEventHelper: new MediaEventHelper(mediaEvent),
showFileInfo: false,
})}
</ScopedRoomContextProvider>,
);
expect(getByRole("link", { name: "Download" })).toBeInTheDocument();
expect(container).toMatchSnapshot();
});
it.each(["m.audio", "m.video", "m.text"])("returns null for unsupported msgtype %s", (msgtype) => {
expect(renderMBody({ ...props, mxEvent: mkEvent(msgtype) })).toBeNull();
});
it("returns null when msgtype is missing", () => {
expect(renderMBody({ ...props, mxEvent: mkEvent() })).toBeNull();
});
it("falls back to file body for unsupported msgtypes", () => {
const mediaEvent = mkEvent("m.audio");
const { getByRole } = render(
<ScopedRoomContextProvider {...({ timelineRenderingType: TimelineRenderingType.File } as any)}>
{renderMBody(
{
...props,
mxEvent: mediaEvent,
mediaEventHelper: new MediaEventHelper(mediaEvent),
},
FileBodyViewFactory,
)}
</ScopedRoomContextProvider>,
);
expect(getByRole("button", { name: "alt" })).toBeInTheDocument();
});
});
it.each(["m.file", "m.audio", "m.video"])(
"renderMBody fallback shows %s generic placeholder when showFileInfo is true",
async (msgtype) => {
const mediaEvent = new MatrixEvent({
room_id: "!room:server",
sender: userId,
type: EventType.RoomMessage,
content: {
body: "alt",
msgtype,
url: "mxc://server/image",
},
});
const { container, getByRole } = render(
<ScopedRoomContextProvider {...({ timelineRenderingType: TimelineRenderingType.File } as any)}>
{renderMBody(
{
...props,
mxEvent: mediaEvent,
mediaEventHelper: new MediaEventHelper(mediaEvent),
showFileInfo: true,
},
FileBodyViewFactory,
)}
</ScopedRoomContextProvider>,
);
expect(getByRole("button", { name: "alt" })).toBeInTheDocument();
expect(container).toMatchSnapshot();
},
);
});
@@ -1,115 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render } from "jest-matrix-react";
import { EventType, getHttpUriForMxc, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import {
getMockClientWithEventEmitter,
mockClientMethodsCrypto,
mockClientMethodsDevice,
mockClientMethodsServer,
mockClientMethodsUser,
} from "../../../../test-utils";
import { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import MFileBody from "../../../../../src/components/views/messages/MFileBody.tsx";
import { TimelineRenderingType } from "../../../../../src/contexts/RoomContext.ts";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext.tsx";
jest.mock("matrix-encrypt-attachment", () => ({
decryptAttachment: jest.fn(),
}));
describe("<MFileBody/>", () => {
const userId = "@user:server";
const deviceId = "DEADB33F";
const cli = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
...mockClientMethodsDevice(deviceId),
...mockClientMethodsCrypto(),
getRooms: jest.fn().mockReturnValue([]),
getIgnoredUsers: jest.fn(),
getVersions: jest.fn().mockResolvedValue({
unstable_features: {
"org.matrix.msc3882": true,
"org.matrix.msc3886": true,
},
}),
});
// eslint-disable-next-line no-restricted-properties
cli.mxcUrlToHttp.mockImplementation(
(mxcUrl: string, width?: number, height?: number, resizeMethod?: string, allowDirectLinks?: boolean) => {
return getHttpUriForMxc("https://server", mxcUrl, width, height, resizeMethod, allowDirectLinks);
},
);
const mediaEvent = new MatrixEvent({
room_id: "!room:server",
sender: userId,
type: EventType.RoomMessage,
content: {
body: "alt for a image",
msgtype: "m.image",
url: "mxc://server/image",
},
});
const props = {
onMessageAllowed: jest.fn(),
permalinkCreator: new RoomPermalinkCreator(new Room(mediaEvent.getRoomId()!, cli, cli.getUserId()!)),
};
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
});
it("should show a download button in file rendering type", async () => {
const { container, getByRole } = render(
<ScopedRoomContextProvider {...({ timelineRenderingType: TimelineRenderingType.File } as any)}>
<MFileBody
{...props}
mxEvent={mediaEvent}
mediaEventHelper={new MediaEventHelper(mediaEvent)}
showGenericPlaceholder={false}
/>
</ScopedRoomContextProvider>,
);
expect(getByRole("link", { name: "Download" })).toBeInTheDocument();
expect(container).toMatchSnapshot();
});
it.each(["m.file", "m.audio", "m.video"])("should show %s generic placeholder", async (msgtype) => {
const mediaEvent = new MatrixEvent({
room_id: "!room:server",
sender: userId,
type: EventType.RoomMessage,
content: {
body: "alt",
msgtype,
url: "mxc://server/image",
},
});
const { container, getByRole } = render(
<ScopedRoomContextProvider {...({ timelineRenderingType: TimelineRenderingType.File } as any)}>
<MFileBody
{...props}
mxEvent={mediaEvent}
mediaEventHelper={new MediaEventHelper(mediaEvent)}
showGenericPlaceholder={true}
/>
</ScopedRoomContextProvider>,
);
expect(getByRole("button", { name: "alt" })).toBeInTheDocument();
expect(container).toMatchSnapshot();
});
});
@@ -33,9 +33,10 @@ jest.mock("../../../../../src/components/views/messages/MVideoBody", () => ({
default: () => <div data-testid="video-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MFileBody", () => ({
jest.mock("../../../../../src/components/views/messages/MBodyFactory", () => ({
__esModule: true,
default: () => <div data-testid="file-body" />,
FileBodyViewFactory: () => <div data-testid="file-body" />,
renderMBody: () => <div data-testid="file-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MImageReplyBody", () => ({
@@ -1,17 +1,135 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<MFileBody/> should show a download button in file rendering type 1`] = `
exports[`MBodyFactory renderMBody fallback shows m.audio generic placeholder when showFileInfo is true 1`] = `
<div>
<span
class="mx_MFileBody"
class="_content_f1s5h_8 mx_MFileBody"
>
<div
class="mx_MFileBody_download"
class="mx_MediaBody _mediaBody_rgndh_8"
data-type="info"
>
<button
aria-label="alt"
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
role="button"
tabindex="0"
>
<svg
aria-hidden="true"
fill="currentColor"
height="20"
viewBox="0 0 24 24"
width="20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M3 14v-4a2 2 0 0 1 2-2h2l3.293-3.293c.63-.63 1.707-.184 1.707.707v13.172c0 .89-1.077 1.337-1.707.707L7 16H5a2 2 0 0 1-2-2m11.122-5.536a1 1 0 0 1 1.414 0A5 5 0 0 1 17 12c0 1.38-.56 2.632-1.464 3.536a1 1 0 0 1-1.415-1.415 3 3 0 0 0 .88-2.121c0-.829-.335-1.577-.88-2.121a1 1 0 0 1 0-1.415"
/>
<path
d="M16.95 5.636a1 1 0 0 1 1.414 0A8.98 8.98 0 0 1 21 12a8.98 8.98 0 0 1-2.636 6.364 1 1 0 0 1-1.414-1.414A6.98 6.98 0 0 0 19 12a6.98 6.98 0 0 0-2.05-4.95 1 1 0 0 1 0-1.414"
/>
</svg>
<span>
alt
</span>
</button>
</div>
</span>
</div>
`;
exports[`MBodyFactory renderMBody fallback shows m.file generic placeholder when showFileInfo is true 1`] = `
<div>
<span
class="_content_f1s5h_8 mx_MFileBody"
>
<div
class="mx_MediaBody _mediaBody_rgndh_8"
data-type="info"
>
<button
aria-label="alt"
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
role="button"
tabindex="0"
>
<svg
aria-hidden="true"
fill="currentColor"
height="20"
viewBox="0 0 24 24"
width="20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M11.5 22q-2.3 0-3.9-1.6T6 16.5V6q0-1.65 1.175-2.825T10 2t2.825 1.175T14 6v9.5q0 1.05-.725 1.775T11.5 18t-1.775-.725T9 15.5V6.75A.73.73 0 0 1 9.75 6a.73.73 0 0 1 .75.75v8.75q0 .424.287.712.288.288.713.288.424 0 .713-.288a.97.97 0 0 0 .287-.712V6q0-1.05-.725-1.775T10 3.5t-1.775.725T7.5 6v10.5q0 1.65 1.175 2.825T11.5 20.5t2.825-1.175T15.5 16.5V6.75a.73.73 0 0 1 .75-.75.73.73 0 0 1 .75.75v9.75q0 2.3-1.6 3.9T11.5 22"
/>
</svg>
<span>
alt
</span>
</button>
</div>
</span>
</div>
`;
exports[`MBodyFactory renderMBody fallback shows m.video generic placeholder when showFileInfo is true 1`] = `
<div>
<span
class="_content_f1s5h_8 mx_MFileBody"
>
<div
class="mx_MediaBody _mediaBody_rgndh_8"
data-type="info"
>
<button
aria-label="alt"
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
role="button"
tabindex="0"
>
<svg
aria-hidden="true"
fill="currentColor"
height="20"
viewBox="0 0 24 24"
width="20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6 4h10a2 2 0 0 1 2 2v4.286l3.35-2.871a1 1 0 0 1 1.65.76v7.65a1 1 0 0 1-1.65.76L18 13.715V18a2 2 0 0 1-2 2H6a4 4 0 0 1-4-4V8a4 4 0 0 1 4-4"
/>
</svg>
<span>
alt
</span>
</button>
</div>
</span>
</div>
`;
exports[`MBodyFactory renderMBody renders download button for m.file in file rendering type 1`] = `
<div>
<span
class="_content_f1s5h_8 mx_MFileBody"
>
<div
data-type="download"
>
<a
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
href="https://server/_matrix/media/v3/download/server/file"
rel="noreferrer noopener"
role="link"
tabindex="0"
@@ -35,126 +153,3 @@ exports[`<MFileBody/> should show a download button in file rendering type 1`] =
</span>
</div>
`;
exports[`<MFileBody/> should show m.audio generic placeholder 1`] = `
<div>
<span
class="mx_MFileBody"
>
<div
class="mx_AccessibleButton mx_MediaBody mx_MFileBody_info"
role="button"
tabindex="0"
>
<span
class="mx_MFileBody_info_icon"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M3 14v-4a2 2 0 0 1 2-2h2l3.293-3.293c.63-.63 1.707-.184 1.707.707v13.172c0 .89-1.077 1.337-1.707.707L7 16H5a2 2 0 0 1-2-2m11.122-5.536a1 1 0 0 1 1.414 0A5 5 0 0 1 17 12c0 1.38-.56 2.632-1.464 3.536a1 1 0 0 1-1.415-1.415 3 3 0 0 0 .88-2.121c0-.829-.335-1.577-.88-2.121a1 1 0 0 1 0-1.415"
/>
<path
d="M16.95 5.636a1 1 0 0 1 1.414 0A8.98 8.98 0 0 1 21 12a8.98 8.98 0 0 1-2.636 6.364 1 1 0 0 1-1.414-1.414A6.98 6.98 0 0 0 19 12a6.98 6.98 0 0 0-2.05-4.95 1 1 0 0 1 0-1.414"
/>
</svg>
</span>
<span
aria-labelledby="_r_6_"
tabindex="0"
>
<span
class="mx_MFileBody_info_filename"
>
alt
</span>
</span>
</div>
</span>
</div>
`;
exports[`<MFileBody/> should show m.file generic placeholder 1`] = `
<div>
<span
class="mx_MFileBody"
>
<div
class="mx_AccessibleButton mx_MediaBody mx_MFileBody_info"
role="button"
tabindex="0"
>
<span
class="mx_MFileBody_info_icon"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M11.5 22q-2.3 0-3.9-1.6T6 16.5V6q0-1.65 1.175-2.825T10 2t2.825 1.175T14 6v9.5q0 1.05-.725 1.775T11.5 18t-1.775-.725T9 15.5V6.75A.73.73 0 0 1 9.75 6a.73.73 0 0 1 .75.75v8.75q0 .424.287.712.288.288.713.288.424 0 .713-.288a.97.97 0 0 0 .287-.712V6q0-1.05-.725-1.775T10 3.5t-1.775.725T7.5 6v10.5q0 1.65 1.175 2.825T11.5 20.5t2.825-1.175T15.5 16.5V6.75a.73.73 0 0 1 .75-.75.73.73 0 0 1 .75.75v9.75q0 2.3-1.6 3.9T11.5 22"
/>
</svg>
</span>
<span
aria-labelledby="_r_0_"
tabindex="0"
>
<span
class="mx_MFileBody_info_filename"
>
alt
</span>
</span>
</div>
</span>
</div>
`;
exports[`<MFileBody/> should show m.video generic placeholder 1`] = `
<div>
<span
class="mx_MFileBody"
>
<div
class="mx_AccessibleButton mx_MediaBody mx_MFileBody_info"
role="button"
tabindex="0"
>
<span
class="mx_MFileBody_info_icon"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6 4h10a2 2 0 0 1 2 2v4.286l3.35-2.871a1 1 0 0 1 1.65.76v7.65a1 1 0 0 1-1.65.76L18 13.715V18a2 2 0 0 1-2 2H6a4 4 0 0 1-4-4V8a4 4 0 0 1 4-4"
/>
</svg>
</span>
<span
aria-labelledby="_r_c_"
tabindex="0"
>
<span
class="mx_MFileBody_info_filename"
>
alt
</span>
</span>
</div>
</span>
</div>
`;
@@ -300,38 +300,36 @@ exports[`<MImageBody/> should open ImageView using thumbnail for encrypted svg 1
exports[`<MImageBody/> should render MFileBody for svg with no thumbnail 1`] = `
<DocumentFragment>
<span
class="mx_MFileBody"
class="_content_f1s5h_8 mx_MFileBody"
>
<div
class="mx_AccessibleButton mx_MediaBody mx_MFileBody_info"
role="button"
tabindex="0"
class="mx_MediaBody _mediaBody_rgndh_8"
data-type="info"
>
<span
class="mx_MFileBody_info_icon"
<button
aria-label="Attachment"
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
role="button"
tabindex="0"
>
<svg
aria-hidden="true"
fill="currentColor"
height="1em"
height="20"
viewBox="0 0 24 24"
width="1em"
width="20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M11.5 22q-2.3 0-3.9-1.6T6 16.5V6q0-1.65 1.175-2.825T10 2t2.825 1.175T14 6v9.5q0 1.05-.725 1.775T11.5 18t-1.775-.725T9 15.5V6.75A.73.73 0 0 1 9.75 6a.73.73 0 0 1 .75.75v8.75q0 .424.287.712.288.288.713.288.424 0 .713-.288a.97.97 0 0 0 .287-.712V6q0-1.05-.725-1.775T10 3.5t-1.775.725T7.5 6v10.5q0 1.65 1.175 2.825T11.5 20.5t2.825-1.175T15.5 16.5V6.75a.73.73 0 0 1 .75-.75.73.73 0 0 1 .75.75v9.75q0 2.3-1.6 3.9T11.5 22"
/>
</svg>
</span>
<span
aria-labelledby="_r_0_"
tabindex="0"
>
<span
class="mx_MFileBody_info_filename"
>
<span>
Attachment
</span>
</span>
</button>
</div>
</span>
</DocumentFragment>
@@ -238,7 +238,7 @@ describe("export", function () {
it("checks if the icons' html corresponds to export regex", function () {
const exporter = new HTMLExporter(mockRoom, ExportType.Beginning, mockExportOptions, setProgressText);
const fileRegex = /<span class="mx_MFileBody_info_icon">.*?<\/span>/;
const fileRegex = /<span class="[^"]*\bmx_MFileBody\b[^"]*">.*?<\/span>/;
expect(fileRegex.test(renderToString(exporter.getEventTile(mkFileEvent(), true)))).toBeTruthy();
});
@@ -0,0 +1,306 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { createRef, type RefObject } from "react";
import { FileBodyViewInfoIcon, FileBodyViewState } from "@element-hq/web-shared-components";
import Modal from "../../../src/Modal";
import { TimelineRenderingType } from "../../../src/contexts/RoomContext";
import { type MediaEventHelper } from "../../../src/utils/MediaEventHelper";
import { FileBodyViewModel } from "../../../src/viewmodels/message-body/FileBodyViewModel";
import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog";
const mockDownload = jest.fn();
jest.mock("../../../src/utils/FileDownloader", () => ({
FileDownloader: jest.fn().mockImplementation(() => ({
download: mockDownload,
})),
}));
jest.mock("../../../src/customisations/Media", () => ({
mediaFromContent: jest.fn((content: { file?: unknown; url?: string }) => ({
isEncrypted: !!content.file,
srcHttp: content.url ?? null,
})),
}));
describe("FileBodyViewModel", () => {
const mkMediaEvent = (
content: Partial<{ body: string; msgtype: string; url: string; file: Record<string, unknown> }>,
): MatrixEvent =>
new MatrixEvent({
room_id: "!room:server",
sender: "@user:server",
type: EventType.RoomMessage,
content: {
body: "alt",
msgtype: "m.file",
url: "https://server/file",
...content,
},
});
const mkMediaEventHelper = ({
encrypted,
blob = new Blob(["content"], { type: "text/plain" }),
fileName = "file.txt",
}: {
encrypted: boolean;
blob?: Blob;
fileName?: string;
}): MediaEventHelper =>
({
media: { isEncrypted: encrypted },
sourceBlob: { value: Promise.resolve(blob) },
fileName,
}) as unknown as MediaEventHelper;
const createVm = (overrides: Partial<ConstructorParameters<typeof FileBodyViewModel>[0]> = {}): FileBodyViewModel =>
new FileBodyViewModel({
mxEvent: mkMediaEvent({}),
mediaEventHelper: mkMediaEventHelper({ encrypted: false }),
showFileInfo: false,
forExport: false,
timelineRenderingType: TimelineRenderingType.File,
refIFrame: createRef<HTMLIFrameElement>() as RefObject<HTMLIFrameElement>,
refLink: createRef<HTMLAnchorElement>() as RefObject<HTMLAnchorElement>,
...overrides,
});
beforeEach(() => {
jest.clearAllMocks();
});
it("shows unencrypted download snapshot in file rendering type", () => {
const vm = createVm();
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.UNENCRYPTED,
showInfo: false,
showDownload: true,
downloadHref: "https://server/file",
});
});
it.each([
{ msgtype: "m.file", expectedIcon: FileBodyViewInfoIcon.ATTACHMENT },
{ msgtype: "m.audio", expectedIcon: FileBodyViewInfoIcon.AUDIO },
{ msgtype: "m.video", expectedIcon: FileBodyViewInfoIcon.VIDEO },
])("shows generic placeholder info for $msgtype", ({ msgtype, expectedIcon }) => {
const vm = createVm({
mxEvent: mkMediaEvent({ msgtype }),
showFileInfo: true,
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.UNENCRYPTED,
showInfo: true,
infoLabel: "alt",
infoIcon: expectedIcon,
showDownload: false,
});
});
it("shows export snapshot with export href", () => {
const vm = createVm({
forExport: true,
showFileInfo: true,
mxEvent: mkMediaEvent({ url: "https://server/export-file" }),
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.EXPORT,
showInfo: true,
infoLabel: "alt",
infoHref: "https://server/export-file",
});
});
it("downloads unencrypted placeholder content on info click", async () => {
const blob = new Blob(["placeholder"], { type: "text/plain" });
const vm = createVm({
showFileInfo: true,
mediaEventHelper: mkMediaEventHelper({ encrypted: false, blob, fileName: "placeholder.txt" }),
});
await vm.onInfoClick();
expect(mockDownload).toHaveBeenCalledWith({
blob,
name: "placeholder.txt",
});
});
it("decrypts encrypted content and downloads on iframe load", async () => {
const blob = new Blob(["encrypted"], { type: "application/octet-stream" });
const vm = createVm({
mediaEventHelper: mkMediaEventHelper({ encrypted: true, blob, fileName: "encrypted.bin" }),
mxEvent: mkMediaEvent({ file: { url: "mxc://server/file" } }),
});
await vm.onDownloadClick();
expect(vm.getSnapshot().state).toBe(FileBodyViewState.ENCRYPTED);
vm.onDownloadIframeLoad();
expect(mockDownload).toHaveBeenCalledWith(
expect.objectContaining({
blob,
name: "encrypted.bin",
autoDownload: true,
opts: expect.objectContaining({
textContent: expect.any(String),
}),
}),
);
});
it("downloads unencrypted source as blob in onDownloadLinkClick", async () => {
const blob = new Blob(["direct-download"], { type: "text/plain" });
const vm = createVm({
mediaEventHelper: mkMediaEventHelper({ encrypted: false, blob, fileName: "direct.txt" }),
mxEvent: mkMediaEvent({ msgtype: "m.file", url: "https://server/direct.txt" }),
});
const click = jest.spyOn(HTMLAnchorElement.prototype, "click");
const event = {
preventDefault: jest.fn(),
stopPropagation: jest.fn(),
} as any;
vm.onDownloadLinkClick(event);
await Promise.resolve();
expect(event.preventDefault).toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalled();
expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
expect(click).toHaveBeenCalled();
});
it("shows decrypt error dialog when decrypt fails", async () => {
const vm = createVm({
mediaEventHelper: {
media: { isEncrypted: true },
sourceBlob: { value: Promise.reject(new Error("decrypt failed")) },
fileName: "broken.bin",
} as unknown as MediaEventHelper,
mxEvent: mkMediaEvent({ file: { url: "mxc://server/file" } }),
});
const warnSpy = jest.spyOn(logger, "warn").mockImplementation(() => {});
const dialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({ close: jest.fn() } as any);
await vm.onDownloadClick();
expect(warnSpy).toHaveBeenCalled();
expect(dialogSpy).toHaveBeenCalledWith(
ErrorDialog,
expect.objectContaining({
title: "Error",
description: expect.stringMatching(/decrypt/i),
}),
);
expect(vm.getSnapshot().state).toBe(FileBodyViewState.DECRYPTION_PENDING);
});
it("resets decrypted state when mxEvent changes", async () => {
const vm = createVm({
mediaEventHelper: mkMediaEventHelper({ encrypted: true }),
mxEvent: mkMediaEvent({ file: { url: "mxc://server/file-a" } }),
});
await vm.onDownloadClick();
expect(vm.getSnapshot().state).toBe(FileBodyViewState.ENCRYPTED);
vm.setProps({
mxEvent: mkMediaEvent({ body: "new", file: { url: "mxc://server/file-b" } }),
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.DECRYPTION_PENDING,
});
});
it("keeps decrypted state when non-event props change", async () => {
const vm = createVm({
mediaEventHelper: mkMediaEventHelper({ encrypted: true }),
mxEvent: mkMediaEvent({ file: { url: "mxc://server/file-a" } }),
});
await vm.onDownloadClick();
expect(vm.getSnapshot().state).toBe(FileBodyViewState.ENCRYPTED);
vm.setProps({
timelineRenderingType: TimelineRenderingType.Thread,
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.ENCRYPTED,
showDownload: false,
});
});
it("uses filename-like downloadTitle in encrypted mode when showFileInfo is false", () => {
const vm = createVm({
showFileInfo: false,
mediaEventHelper: mkMediaEventHelper({ encrypted: true }),
mxEvent: mkMediaEvent({ body: "my-file.pdf", file: { url: "mxc://server/file" } }),
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.DECRYPTION_PENDING,
downloadTitle: "my-file.pdf",
});
});
it("hides download in thread rendering even when showFileInfo is false", () => {
const vm = createVm({
showFileInfo: false,
timelineRenderingType: TimelineRenderingType.Thread,
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.UNENCRYPTED,
showDownload: false,
});
});
it("returns INVALID snapshot when content URL is missing", () => {
const vm = createVm({
mxEvent: mkMediaEvent({ url: undefined }),
showFileInfo: true,
});
expect(vm.getSnapshot()).toMatchObject({
state: FileBodyViewState.INVALID,
showInfo: true,
infoLabel: "alt",
infoIcon: FileBodyViewInfoIcon.ATTACHMENT,
});
});
it("does not download on info click when showFileInfo is false", async () => {
const vm = createVm({ showFileInfo: false });
await vm.onInfoClick();
expect(mockDownload).not.toHaveBeenCalled();
});
it("keeps unencrypted snapshot when download is clicked without mediaEventHelper", async () => {
const vm = createVm({
mediaEventHelper: undefined,
mxEvent: mkMediaEvent({ file: { url: "mxc://server/file" } }),
});
await vm.onDownloadClick();
expect(vm.getSnapshot().state).toBe(FileBodyViewState.UNENCRYPTED);
});
});