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
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, "&"),
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -71,6 +71,9 @@ const config: StorybookConfig = {
|
||||
// Dynamically generate a languages.json file based on what files are available
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify(languages));
|
||||
} else if (req.url === "/usercontent/" || req.url === "/usercontent") {
|
||||
// Mock usercontent endpoint used by encrypted download iframes.
|
||||
res.end("This is where /usercontent/ is loaded.");
|
||||
} else if (req.url?.startsWith("/i18n/")) {
|
||||
// Serve the individual language files, which annoyingly can't be a simple
|
||||
// static dir because the directory structure in src doesn't match what
|
||||
|
||||
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 18 KiB |
@@ -7,6 +7,7 @@
|
||||
|
||||
.audioPlayer {
|
||||
padding: var(--cpd-space-4x) var(--cpd-space-3x) var(--cpd-space-3x) var(--cpd-space-3x) !important;
|
||||
border-radius: 8px !important;
|
||||
}
|
||||
|
||||
.mediaInfo {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"back": "Back",
|
||||
"delete": "Delete",
|
||||
"dismiss": "Dismiss",
|
||||
"download": "Download",
|
||||
"edit": "Edit",
|
||||
"explore_rooms": "Explore rooms",
|
||||
"go": "Go",
|
||||
@@ -22,6 +23,7 @@
|
||||
"start_chat": "Start chat"
|
||||
},
|
||||
"common": {
|
||||
"attachment": "Attachment",
|
||||
"encryption_enabled": "Encryption enabled",
|
||||
"preferences": "Preferences",
|
||||
"state_encryption_enabled": "Experimental state encryption enabled"
|
||||
@@ -168,6 +170,9 @@
|
||||
"error_downloading_audio": "Error downloading audio",
|
||||
"unnamed_audio": "Unnamed audio"
|
||||
},
|
||||
"m.file": {
|
||||
"error_invalid": "Invalid file"
|
||||
},
|
||||
"m.room.encryption": {
|
||||
"disable_attempt": "Ignored attempt to disable encryption",
|
||||
"disabled": "Encryption not enabled",
|
||||
|
||||
@@ -20,6 +20,7 @@ export * from "./message-body/EventContentBody";
|
||||
export * from "./message-body/MediaBody";
|
||||
export * from "./message-body/MessageTimestampView";
|
||||
export * from "./message-body/DecryptionFailureBodyView";
|
||||
export * from "./message-body/FileBodyView";
|
||||
export * from "./message-body/PinnedMessageBadge";
|
||||
export * from "./message-body/ReactionsRowButtonTooltip";
|
||||
export * from "./message-body/ReactionsRowButton";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
gap: var(--cpd-space-2x);
|
||||
|
||||
& a {
|
||||
display: flex;
|
||||
flex-grow: 1;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.content [data-type="info"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
& button {
|
||||
display: flex;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
border: none;
|
||||
width: 100%;
|
||||
min-block-size: unset;
|
||||
color: inherit;
|
||||
background-color: inherit;
|
||||
gap: var(--cpd-space-3x);
|
||||
|
||||
& svg {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: var(--cpd-space-2x);
|
||||
}
|
||||
|
||||
& span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-align: start;
|
||||
font: var(--cpd-font-body-md-regular);
|
||||
letter-spacing: var(--cpd-font-letter-spacing-body-md);
|
||||
color: var(--cpd-color-text-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.content [data-type="download"] {
|
||||
align-items: center;
|
||||
color: var(--cpd-color-text-action-accent);
|
||||
|
||||
& iframe {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.invalid {
|
||||
color: var(--cpd-color-text-critical-primary);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* 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 ReactNode } from "react";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import {
|
||||
FileBodyView,
|
||||
FileBodyViewInfoIcon,
|
||||
FileBodyViewState,
|
||||
type FileBodyViewActions,
|
||||
type FileBodyViewSnapshot,
|
||||
} from "./FileBodyView";
|
||||
import { useMockedViewModel } from "../../viewmodel/useMockedViewModel";
|
||||
import { withViewDocs } from "../../../.storybook/withViewDocs";
|
||||
|
||||
type FileBodyViewProps = FileBodyViewSnapshot & FileBodyViewActions;
|
||||
|
||||
const FileBodyViewWrapperImpl = ({
|
||||
onInfoClick,
|
||||
onDownloadClick,
|
||||
onDownloadLinkClick,
|
||||
onDownloadIframeLoad,
|
||||
className,
|
||||
...snapshotProps
|
||||
}: FileBodyViewProps & { className?: string }): ReactNode => {
|
||||
const vm = useMockedViewModel(snapshotProps, {
|
||||
onInfoClick,
|
||||
onDownloadClick,
|
||||
onDownloadLinkClick,
|
||||
onDownloadIframeLoad,
|
||||
});
|
||||
|
||||
return <FileBodyView vm={vm} className={className} />;
|
||||
};
|
||||
|
||||
const FileBodyViewWrapper = withViewDocs(FileBodyViewWrapperImpl, FileBodyView);
|
||||
|
||||
const meta = {
|
||||
title: "MessageBody/FileBodyView",
|
||||
component: FileBodyViewWrapper,
|
||||
tags: ["autodocs"],
|
||||
argTypes: {
|
||||
state: {
|
||||
options: Object.entries(FileBodyViewState)
|
||||
.filter(([key, value]) => key === value)
|
||||
.map(([key]) => key),
|
||||
control: { type: "select" },
|
||||
},
|
||||
infoIcon: {
|
||||
options: Object.entries(FileBodyViewInfoIcon)
|
||||
.filter(([key, value]) => key === value)
|
||||
.map(([key]) => key),
|
||||
control: { type: "select" },
|
||||
},
|
||||
showInfo: { control: "boolean" },
|
||||
showDownload: { control: "boolean" },
|
||||
className: { control: "text" },
|
||||
},
|
||||
args: {
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showInfo: true,
|
||||
infoLabel: "spec.pdf",
|
||||
infoTooltip: "spec.pdf (22 KB)",
|
||||
infoIcon: FileBodyViewInfoIcon.ATTACHMENT,
|
||||
infoHref: "https://example.org/spec.pdf",
|
||||
showDownload: true,
|
||||
downloadLabel: "Download file",
|
||||
downloadTitle: "Download title",
|
||||
downloadHref: "https://example.org/download/spec.pdf",
|
||||
className: undefined,
|
||||
},
|
||||
} satisfies Meta<typeof FileBodyViewWrapper>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Default: Story = {};
|
||||
|
||||
export const Export: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.EXPORT,
|
||||
},
|
||||
};
|
||||
|
||||
export const Invalid: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.INVALID,
|
||||
},
|
||||
};
|
||||
|
||||
export const LongFilenameInfo: Story = {
|
||||
args: {
|
||||
showDownload: false,
|
||||
infoLabel: "a very long filename to show ellipsis.pdf",
|
||||
infoTooltip: "a very long filename to show ellipsis.pdf (12 kB)",
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.hover(canvas.getByText("a very long filename to show ellipsis.pdf"));
|
||||
await expect(
|
||||
within(canvasElement.ownerDocument.body).findByText("a very long filename to show ellipsis.pdf (12 kB)"),
|
||||
).resolves.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const AudioInfo: Story = {
|
||||
args: {
|
||||
showDownload: false,
|
||||
infoIcon: FileBodyViewInfoIcon.AUDIO,
|
||||
infoLabel: "voice-message.ogg",
|
||||
},
|
||||
};
|
||||
|
||||
export const VideoInfo: Story = {
|
||||
args: {
|
||||
showDownload: false,
|
||||
infoIcon: FileBodyViewInfoIcon.VIDEO,
|
||||
infoLabel: "clip.mp4",
|
||||
},
|
||||
};
|
||||
|
||||
export const UnencryptedDownload: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showInfo: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const EncryptedIframeDownload: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.ENCRYPTED,
|
||||
showInfo: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const DecryptionPendingDownload: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.DECRYPTION_PENDING,
|
||||
showInfo: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const LongFilenameDownload: Story = {
|
||||
args: {
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showInfo: false,
|
||||
showDownload: true,
|
||||
downloadLabel: "a very long filename that show no ellipsis.pdf",
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,288 @@
|
||||
/*
|
||||
* 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 MouseEvent } from "react";
|
||||
import { composeStories } from "@storybook/react-vite";
|
||||
import { fireEvent, render, screen } from "@test-utils";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { FileBodyView, FileBodyViewState, type FileBodyViewActions, type FileBodyViewSnapshot } from "./FileBodyView";
|
||||
import { MockViewModel } from "../../viewmodel/MockViewModel";
|
||||
import { I18nApi } from "../../index";
|
||||
import { I18nContext } from "../../utils/i18nContext";
|
||||
import * as stories from "./FileBodyView.stories";
|
||||
|
||||
const renderWithI18n = (ui: React.ReactElement): ReturnType<typeof render> =>
|
||||
render(ui, {
|
||||
wrapper: ({ children }) => <I18nContext.Provider value={new I18nApi()}>{children}</I18nContext.Provider>,
|
||||
});
|
||||
|
||||
const {
|
||||
Default,
|
||||
Export,
|
||||
Invalid,
|
||||
AudioInfo,
|
||||
VideoInfo,
|
||||
LongFilenameInfo,
|
||||
UnencryptedDownload,
|
||||
EncryptedIframeDownload,
|
||||
DecryptionPendingDownload,
|
||||
LongFilenameDownload,
|
||||
} = composeStories(stories);
|
||||
|
||||
const defaultSnapshot: FileBodyViewSnapshot = {
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showInfo: true,
|
||||
};
|
||||
|
||||
class TestViewModel extends MockViewModel<FileBodyViewSnapshot> implements FileBodyViewActions {
|
||||
public onInfoClick?: () => void;
|
||||
public onDownloadClick?: () => void;
|
||||
public onDownloadLinkClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
|
||||
public onDownloadIframeLoad?: () => void;
|
||||
|
||||
public constructor(snapshot: FileBodyViewSnapshot, actions: FileBodyViewActions = {}) {
|
||||
super(snapshot);
|
||||
this.onInfoClick = actions.onInfoClick;
|
||||
this.onDownloadClick = actions.onDownloadClick;
|
||||
this.onDownloadLinkClick = actions.onDownloadLinkClick;
|
||||
this.onDownloadIframeLoad = actions.onDownloadIframeLoad;
|
||||
}
|
||||
}
|
||||
|
||||
describe("FileBodyView", () => {
|
||||
it.each([
|
||||
["default", Default],
|
||||
["export", Export],
|
||||
["invalid", Invalid],
|
||||
["long-filename-info", LongFilenameInfo],
|
||||
["audio-info", AudioInfo],
|
||||
["video-info", VideoInfo],
|
||||
["unencrypted-download", UnencryptedDownload],
|
||||
["encrypted-iframe-download", EncryptedIframeDownload],
|
||||
["decryption-pending-download", DecryptionPendingDownload],
|
||||
["long-filename-download", LongFilenameDownload],
|
||||
])("matches snapshot for %s story", (_name, Story) => {
|
||||
const { container } = renderWithI18n(<Story />);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("renders info row in info-only mode", () => {
|
||||
const vm = new TestViewModel(defaultSnapshot);
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Attachment" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Download" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders info row in info-only mode using label and tooltip", () => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
infoLabel: "spec.pdf",
|
||||
infoTooltip: "spec.pdf (22 KB)",
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "spec.pdf" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Attachment" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Download" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses href in export mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
state: FileBodyViewState.EXPORT,
|
||||
showInfo: true,
|
||||
infoHref: "https://example.org/export.pdf",
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
const link = screen.getByRole("link");
|
||||
expect(link).toHaveAttribute("href", "https://example.org/export.pdf");
|
||||
});
|
||||
|
||||
it("uses href in unencrypted download mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showDownload: true,
|
||||
downloadHref: "https://example.org/download.pdf",
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
const link = screen.getByRole("link", { name: "Download" });
|
||||
expect(link).toHaveAttribute("href", "https://example.org/download.pdf");
|
||||
expect(link).toHaveAttribute("target", "_blank");
|
||||
expect(link).toHaveAttribute("rel", "noreferrer noopener");
|
||||
});
|
||||
|
||||
it("renders safely when href is missing in EXPORT mode", () => {
|
||||
const vm = new TestViewModel({ state: FileBodyViewState.EXPORT, showInfo: true });
|
||||
|
||||
const { container } = renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Attachment" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("link")).not.toBeInTheDocument();
|
||||
expect(container.querySelector("a")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders safely when href is missing in UNENCRYPTED mode", () => {
|
||||
const vm = new TestViewModel({ state: FileBodyViewState.UNENCRYPTED, showDownload: true });
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByText("Download")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses label as fallback tooltip content", () => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
infoLabel: "spec.pdf",
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "spec.pdf" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders download button in decryption-pending mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.DECRYPTION_PENDING,
|
||||
showDownload: true,
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Download" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "spec.pdf" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("invokes onInfoClick when info row is clicked", () => {
|
||||
const onInfoClick = vi.fn();
|
||||
const vm = new TestViewModel(defaultSnapshot, { onInfoClick });
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Attachment" }));
|
||||
expect(onInfoClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("invokes onDownloadClick in encrypted-pending mode", () => {
|
||||
const onDownloadClick = vi.fn();
|
||||
const vm = new TestViewModel(
|
||||
{
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.DECRYPTION_PENDING,
|
||||
showDownload: true,
|
||||
},
|
||||
{ onDownloadClick },
|
||||
);
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Download" }));
|
||||
expect(onDownloadClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("invokes onDownloadLinkClick in unencrypted-download mode", () => {
|
||||
const onDownloadLinkClick = vi.fn((event: MouseEvent<HTMLAnchorElement>) => event.preventDefault());
|
||||
const vm = new TestViewModel(
|
||||
{
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.UNENCRYPTED,
|
||||
showDownload: true,
|
||||
},
|
||||
{ onDownloadLinkClick },
|
||||
);
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("link", { name: "Download" }));
|
||||
expect(onDownloadLinkClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("invokes onDownloadIframeLoad in encrypted-iframe-download mode", () => {
|
||||
const onDownloadIframeLoad = vi.fn();
|
||||
const vm = new TestViewModel(
|
||||
{
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.ENCRYPTED,
|
||||
showDownload: true,
|
||||
},
|
||||
{ onDownloadIframeLoad },
|
||||
);
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
const iframe = screen.getByTitle("Download");
|
||||
fireEvent.load(iframe);
|
||||
expect(onDownloadIframeLoad).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("wires refLink in encrypted-iframe-download mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.ENCRYPTED,
|
||||
showDownload: true,
|
||||
});
|
||||
const refLink = React.createRef<HTMLAnchorElement>() as React.RefObject<HTMLAnchorElement>;
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} refLink={refLink} />);
|
||||
|
||||
expect(refLink.current).toBeInstanceOf(HTMLAnchorElement);
|
||||
});
|
||||
|
||||
it("wires refIFrame in encrypted-iframe-download mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
state: FileBodyViewState.ENCRYPTED,
|
||||
showDownload: true,
|
||||
});
|
||||
const refIFrame = React.createRef<HTMLIFrameElement>() as React.RefObject<HTMLIFrameElement>;
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} refIFrame={refIFrame} />);
|
||||
|
||||
expect(refIFrame.current).toBeInstanceOf(HTMLIFrameElement);
|
||||
});
|
||||
|
||||
it.each([FileBodyViewState.UNENCRYPTED, FileBodyViewState.DECRYPTION_PENDING, FileBodyViewState.ENCRYPTED])(
|
||||
"hides info row in %s mode",
|
||||
(state) => {
|
||||
const vm = new TestViewModel({
|
||||
...defaultSnapshot,
|
||||
state,
|
||||
showInfo: false,
|
||||
showDownload: true,
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Attachment" })).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it("shows message in invalid mode", () => {
|
||||
const vm = new TestViewModel({
|
||||
state: FileBodyViewState.INVALID,
|
||||
});
|
||||
|
||||
renderWithI18n(<FileBodyView vm={vm} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Attachment" })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Invalid file")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("applies extra class names to the root element", () => {
|
||||
const vm = new TestViewModel(defaultSnapshot);
|
||||
|
||||
const { container } = renderWithI18n(<FileBodyView vm={vm} className="custom-file-body another-class" />);
|
||||
expect(container.firstElementChild).toHaveClass("custom-file-body", "another-class");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,315 @@
|
||||
/*
|
||||
* 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 ComponentType, type JSX, type MouseEvent } from "react";
|
||||
import classNames from "classnames";
|
||||
import { Button, Tooltip } from "@vector-im/compound-web";
|
||||
import {
|
||||
AttachmentIcon,
|
||||
DownloadIcon,
|
||||
VideoCallSolidIcon,
|
||||
VolumeOnSolidIcon,
|
||||
} from "@vector-im/compound-design-tokens/assets/web/icons";
|
||||
|
||||
import styles from "./FileBodyView.module.css";
|
||||
import { type ViewModel } from "../../viewmodel/ViewModel";
|
||||
import { useViewModel } from "../../viewmodel/useViewModel";
|
||||
import { useI18n } from "../../utils/i18nContext";
|
||||
import { MediaBody } from "../MediaBody";
|
||||
|
||||
/**
|
||||
* Which visual state to render for the component.
|
||||
*/
|
||||
export enum FileBodyViewState {
|
||||
/** Export-only rendering where the info row links to the source file. */
|
||||
EXPORT = "EXPORT",
|
||||
/** Encrypted file before decryption has completed; shows the button that starts the flow. */
|
||||
DECRYPTION_PENDING = "DECRYPTION_PENDING",
|
||||
/** Encrypted file after decryption; renders the sandboxed iframe download path. */
|
||||
ENCRYPTED = "ENCRYPTED",
|
||||
/** Unencrypted file with a direct download link. */
|
||||
UNENCRYPTED = "UNENCRYPTED",
|
||||
/** Fallback for missing or unusable file metadata. */
|
||||
INVALID = "INVALID",
|
||||
}
|
||||
|
||||
/**
|
||||
* Which info icon to render.
|
||||
*/
|
||||
export enum FileBodyViewInfoIcon {
|
||||
ATTACHMENT = "ATTACHMENT",
|
||||
AUDIO = "AUDIO",
|
||||
DOWNLOAD = "DOWNLOAD",
|
||||
VIDEO = "VIDEO",
|
||||
}
|
||||
|
||||
export interface FileBodyViewSnapshot {
|
||||
/**
|
||||
* Primary rendering branch for the component.
|
||||
* Controls the overall state (export, encrypted, unencrypted, invalid).
|
||||
*/
|
||||
state: FileBodyViewState;
|
||||
/**
|
||||
* Whether to render the info row (icon + label + tooltip).
|
||||
*/
|
||||
showInfo?: boolean;
|
||||
/**
|
||||
* Optional info label (normally the file name). Defaults to 'Attachment'.
|
||||
*/
|
||||
infoLabel?: string;
|
||||
/**
|
||||
* Optional tooltip for info button. Defaults to infoLabel.
|
||||
*/
|
||||
infoTooltip?: string;
|
||||
/**
|
||||
* Optional icon. Defaults to `ATTACHMENT`.
|
||||
*/
|
||||
infoIcon?: FileBodyViewInfoIcon;
|
||||
/**
|
||||
* Optional URL used by the info row in `EXPORT`.
|
||||
*/
|
||||
infoHref?: string;
|
||||
/**
|
||||
* Whether to render download controls for the current rendering branch.
|
||||
*/
|
||||
showDownload?: boolean;
|
||||
/**
|
||||
* Optional download label (normally file/action text). Defaults to 'Download'.
|
||||
*/
|
||||
downloadLabel?: string;
|
||||
/**
|
||||
* Optional title for encrypted iframe download flow.
|
||||
* Defaults to `downloadLabel`.
|
||||
*/
|
||||
downloadTitle?: string;
|
||||
/**
|
||||
* Optional URL used for `UNENCRYPTED` download links.
|
||||
*/
|
||||
downloadHref?: string;
|
||||
}
|
||||
|
||||
export interface FileBodyViewActions {
|
||||
/**
|
||||
* Click handler for the info row.
|
||||
*/
|
||||
onInfoClick?: () => void;
|
||||
/**
|
||||
* Click handler for a download button.
|
||||
*/
|
||||
onDownloadClick?: () => void;
|
||||
/**
|
||||
* Click handler for the unencrypted download anchor.
|
||||
*/
|
||||
onDownloadLinkClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
|
||||
/**
|
||||
* Load handler for encrypted-download iframe.
|
||||
*/
|
||||
onDownloadIframeLoad?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The view model for the control.
|
||||
*/
|
||||
export type FileBodyViewModel = ViewModel<FileBodyViewSnapshot> & FileBodyViewActions;
|
||||
|
||||
interface FileBodyViewProps {
|
||||
/**
|
||||
* The view model for the component.
|
||||
*/
|
||||
vm: FileBodyViewModel;
|
||||
|
||||
/**
|
||||
* Optional CSS class for host-level styling.
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* Optional iframe ref for encrypted download flow
|
||||
*/
|
||||
refIFrame?: React.RefObject<HTMLIFrameElement>;
|
||||
|
||||
/**
|
||||
* Optional hidden anchor ref used for encrypted download flow
|
||||
*/
|
||||
refLink?: React.RefObject<HTMLAnchorElement>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the correct icon to render in the view
|
||||
*/
|
||||
function getInfoIcon(infoIcon?: FileBodyViewInfoIcon): ComponentType<React.SVGAttributes<SVGElement>> {
|
||||
if (infoIcon === FileBodyViewInfoIcon.AUDIO) {
|
||||
return VolumeOnSolidIcon;
|
||||
} else if (infoIcon === FileBodyViewInfoIcon.DOWNLOAD) {
|
||||
return DownloadIcon;
|
||||
} else if (infoIcon === FileBodyViewInfoIcon.VIDEO) {
|
||||
return VideoCallSolidIcon;
|
||||
}
|
||||
return AttachmentIcon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the body of a file message for info, export, and download flows.
|
||||
*
|
||||
* Rendering is selected by `snapshot.state` from the view model and supports:
|
||||
* - export link (`EXPORT`)
|
||||
* - encrypted download flows (`DECRYPTION_PENDING`, `ENCRYPTED`)
|
||||
* - unencrypted download flow (`UNENCRYPTED`)
|
||||
* - invalid-file fallback (`INVALID`)
|
||||
*
|
||||
* Visibility/content for the info row and download controls are driven by snapshot fields:
|
||||
* - `showInfo`, `infoLabel`, `infoTooltip`, `infoIcon`, `infoHref`
|
||||
* - `showDownload`, `downloadLabel`, `downloadTitle`, `downloadHref`
|
||||
*
|
||||
* Common usage patterns:
|
||||
* - info-only display: set `showInfo: true`, `showDownload: false`
|
||||
* - export link (`EXPORT`)
|
||||
* - download-only display: set `showInfo: false`, `showDownload: true`
|
||||
*
|
||||
* Note on using the encrypted iframe, `ENCRYPTED`:
|
||||
* To make this rendering branch work, it is expected that a `usercontent/` target
|
||||
* is available relative to the root of the application as is described in detail here,
|
||||
* https://github.com/element-hq/element-web/blob/develop/docs/usercontent.md
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <FileBodyView vm={fileBodyViewModel} />
|
||||
* ```
|
||||
*/
|
||||
export function FileBodyView({ vm, refIFrame, refLink, className }: Readonly<FileBodyViewProps>): JSX.Element {
|
||||
const { translate: _t } = useI18n();
|
||||
|
||||
const {
|
||||
state,
|
||||
showInfo,
|
||||
infoLabel,
|
||||
infoTooltip,
|
||||
infoIcon,
|
||||
infoHref,
|
||||
showDownload,
|
||||
downloadLabel,
|
||||
downloadTitle,
|
||||
downloadHref,
|
||||
} = useViewModel(vm);
|
||||
|
||||
const resolvedInfoLabel = infoLabel ?? _t("common|attachment");
|
||||
const resolvedInfoTooltip = infoTooltip ?? resolvedInfoLabel;
|
||||
const resolvedInfoIcon = getInfoIcon(infoIcon);
|
||||
|
||||
const info = showInfo ? (
|
||||
<Tooltip description={resolvedInfoTooltip} placement="right">
|
||||
<MediaBody data-type="info">
|
||||
<Button
|
||||
as="button"
|
||||
size="sm"
|
||||
kind="secondary"
|
||||
aria-label={resolvedInfoLabel}
|
||||
Icon={resolvedInfoIcon}
|
||||
onClick={vm.onInfoClick}
|
||||
>
|
||||
<span>{resolvedInfoLabel}</span>
|
||||
</Button>
|
||||
</MediaBody>
|
||||
</Tooltip>
|
||||
) : null;
|
||||
|
||||
const classes = classNames(styles.content, className);
|
||||
|
||||
const resolvedDownloadLabel = downloadLabel ?? _t("action|download");
|
||||
const resolvedDownloadTitle = downloadTitle ?? resolvedDownloadLabel;
|
||||
|
||||
switch (state) {
|
||||
case FileBodyViewState.EXPORT:
|
||||
return (
|
||||
<span className={classes}>
|
||||
<a href={infoHref}>{info}</a>
|
||||
</span>
|
||||
);
|
||||
|
||||
case FileBodyViewState.DECRYPTION_PENDING:
|
||||
return (
|
||||
<span className={classes}>
|
||||
{info}
|
||||
{showDownload && (
|
||||
<div data-type="download">
|
||||
{/* Decrypt/download is triggered by the view model action, not by an anchor `href`. */}
|
||||
<Button size="sm" kind="secondary" Icon={DownloadIcon} onClick={vm.onDownloadClick}>
|
||||
{resolvedDownloadLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
|
||||
case FileBodyViewState.ENCRYPTED:
|
||||
return (
|
||||
<span className={classes}>
|
||||
{info}
|
||||
{showDownload && (
|
||||
<div data-type="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={refLink} />
|
||||
</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={resolvedDownloadTitle}
|
||||
src="usercontent/"
|
||||
onLoad={vm.onDownloadIframeLoad}
|
||||
ref={refIFrame}
|
||||
sandbox="allow-scripts allow-downloads"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
|
||||
case FileBodyViewState.UNENCRYPTED:
|
||||
return (
|
||||
<span className={classes}>
|
||||
{info}
|
||||
{showDownload && (
|
||||
<div data-type="download">
|
||||
{/* Unencrypted media uses an anchor element with VM-controlled click behavior. */}
|
||||
<Button
|
||||
size="sm"
|
||||
kind="secondary"
|
||||
Icon={DownloadIcon}
|
||||
as="a"
|
||||
href={downloadHref}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
onClick={vm.onDownloadLinkClick}
|
||||
>
|
||||
{resolvedDownloadLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
|
||||
case FileBodyViewState.INVALID:
|
||||
default:
|
||||
return (
|
||||
<>
|
||||
<span className={classes}>{info}</span>
|
||||
<span className={classNames(classes, styles.invalid)}>{_t("timeline|m.file|error_invalid")}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`FileBodyView > matches snapshot for audio-info story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="voice-message.ogg"
|
||||
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>
|
||||
voice-message.ogg
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for decryption-pending-download story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
data-type="download"
|
||||
>
|
||||
<button
|
||||
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="M12 15.575q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-3.6-3.6a.95.95 0 0 1-.275-.7q0-.425.275-.7.274-.275.712-.288t.713.263L11 12.15V5q0-.424.287-.713A.97.97 0 0 1 12 4q.424 0 .713.287Q13 4.576 13 5v7.15l1.875-1.875q.274-.274.713-.263.437.014.712.288a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-3.6 3.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063M6 20q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 18v-2q0-.424.287-.713A.97.97 0 0 1 5 15q.424 0 .713.287Q6 15.576 6 16v2h12v-2q0-.424.288-.713A.97.97 0 0 1 19 15q.424 0 .712.287.288.288.288.713v2q0 .824-.587 1.413A1.93 1.93 0 0 1 18 20z"
|
||||
/>
|
||||
</svg>
|
||||
Download file
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for default story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="spec.pdf"
|
||||
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>
|
||||
spec.pdf
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
data-type="download"
|
||||
>
|
||||
<a
|
||||
class="_button_13vu4_8 _has-icon_13vu4_60"
|
||||
data-kind="secondary"
|
||||
data-size="sm"
|
||||
href="https://example.org/download/spec.pdf"
|
||||
rel="noreferrer noopener"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
target="_blank"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="currentColor"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
width="20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M12 15.575q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-3.6-3.6a.95.95 0 0 1-.275-.7q0-.425.275-.7.274-.275.712-.288t.713.263L11 12.15V5q0-.424.287-.713A.97.97 0 0 1 12 4q.424 0 .713.287Q13 4.576 13 5v7.15l1.875-1.875q.274-.274.713-.263.437.014.712.288a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-3.6 3.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063M6 20q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 18v-2q0-.424.287-.713A.97.97 0 0 1 5 15q.424 0 .713.287Q6 15.576 6 16v2h12v-2q0-.424.288-.713A.97.97 0 0 1 19 15q.424 0 .712.287.288.288.288.713v2q0 .824-.587 1.413A1.93 1.93 0 0 1 18 20z"
|
||||
/>
|
||||
</svg>
|
||||
Download file
|
||||
</a>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for encrypted-iframe-download story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
data-type="download"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
style="display: none;"
|
||||
>
|
||||
<a
|
||||
class="_button_13vu4_8 _has-icon_13vu4_60"
|
||||
data-kind="secondary"
|
||||
data-size="sm"
|
||||
role="link"
|
||||
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="M12 15.575q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-3.6-3.6a.95.95 0 0 1-.275-.7q0-.425.275-.7.274-.275.712-.288t.713.263L11 12.15V5q0-.424.287-.713A.97.97 0 0 1 12 4q.424 0 .713.287Q13 4.576 13 5v7.15l1.875-1.875q.274-.274.713-.263.437.014.712.288a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-3.6 3.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063M6 20q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 18v-2q0-.424.287-.713A.97.97 0 0 1 5 15q.424 0 .713.287Q6 15.576 6 16v2h12v-2q0-.424.288-.713A.97.97 0 0 1 19 15q.424 0 .712.287.288.288.288.713v2q0 .824-.587 1.413A1.93 1.93 0 0 1 18 20z"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
<iframe
|
||||
aria-hidden="true"
|
||||
sandbox="allow-scripts allow-downloads"
|
||||
src="usercontent/"
|
||||
title="Download title"
|
||||
/>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for export story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<a
|
||||
href="https://example.org/spec.pdf"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="spec.pdf"
|
||||
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>
|
||||
spec.pdf
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for invalid story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="spec.pdf"
|
||||
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>
|
||||
spec.pdf
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
<span
|
||||
class="content invalid"
|
||||
>
|
||||
Invalid file
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for long-filename-download story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
data-type="download"
|
||||
>
|
||||
<a
|
||||
class="_button_13vu4_8 _has-icon_13vu4_60"
|
||||
data-kind="secondary"
|
||||
data-size="sm"
|
||||
href="https://example.org/download/spec.pdf"
|
||||
rel="noreferrer noopener"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
target="_blank"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="currentColor"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
width="20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M12 15.575q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-3.6-3.6a.95.95 0 0 1-.275-.7q0-.425.275-.7.274-.275.712-.288t.713.263L11 12.15V5q0-.424.287-.713A.97.97 0 0 1 12 4q.424 0 .713.287Q13 4.576 13 5v7.15l1.875-1.875q.274-.274.713-.263.437.014.712.288a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-3.6 3.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063M6 20q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 18v-2q0-.424.287-.713A.97.97 0 0 1 5 15q.424 0 .713.287Q6 15.576 6 16v2h12v-2q0-.424.288-.713A.97.97 0 0 1 19 15q.424 0 .712.287.288.288.288.713v2q0 .824-.587 1.413A1.93 1.93 0 0 1 18 20z"
|
||||
/>
|
||||
</svg>
|
||||
a very long filename that show no ellipsis.pdf
|
||||
</a>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for long-filename-info story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="a very long filename to show ellipsis.pdf"
|
||||
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>
|
||||
a very long filename to show ellipsis.pdf
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for unencrypted-download story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
data-type="download"
|
||||
>
|
||||
<a
|
||||
class="_button_13vu4_8 _has-icon_13vu4_60"
|
||||
data-kind="secondary"
|
||||
data-size="sm"
|
||||
href="https://example.org/download/spec.pdf"
|
||||
rel="noreferrer noopener"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
target="_blank"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="currentColor"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
width="20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M12 15.575q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-3.6-3.6a.95.95 0 0 1-.275-.7q0-.425.275-.7.274-.275.712-.288t.713.263L11 12.15V5q0-.424.287-.713A.97.97 0 0 1 12 4q.424 0 .713.287Q13 4.576 13 5v7.15l1.875-1.875q.274-.274.713-.263.437.014.712.288a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-3.6 3.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063M6 20q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 18v-2q0-.424.287-.713A.97.97 0 0 1 5 15q.424 0 .713.287Q6 15.576 6 16v2h12v-2q0-.424.288-.713A.97.97 0 0 1 19 15q.424 0 .712.287.288.288.288.713v2q0 .824-.587 1.413A1.93 1.93 0 0 1 18 20z"
|
||||
/>
|
||||
</svg>
|
||||
Download file
|
||||
</a>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`FileBodyView > matches snapshot for video-info story 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="content"
|
||||
>
|
||||
<div
|
||||
class="mx_MediaBody mediaBody"
|
||||
data-type="info"
|
||||
>
|
||||
<button
|
||||
aria-label="clip.mp4"
|
||||
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>
|
||||
clip.mp4
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export {
|
||||
FileBodyView,
|
||||
FileBodyViewState,
|
||||
FileBodyViewInfoIcon,
|
||||
type FileBodyViewActions,
|
||||
type FileBodyViewSnapshot,
|
||||
type FileBodyViewModel,
|
||||
} from "./FileBodyView";
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
.mediaBody {
|
||||
background-color: var(--cpd-color-bg-subtle-secondary);
|
||||
border-radius: var(--cpd-space-2x) !important;
|
||||
border-radius: 12px;
|
||||
max-width: 243px; /* use max-width instead of width so it fits within right panels */
|
||||
|
||||
font: var(--cpd-font-body-md-regular);
|
||||
|
||||