mv element.io @types __mocks__/ debian docker module_system/ playwright res src test webapp Dockerfile .dockerignore .eslintignore .stylelintrc.cjs babel.config.cjs recorder-worklet-loader.cjs .modernizr.json components.json config.json config.sample.json package.json project.json tsconfig.json tsconfig.module_system.json jest.config.ts playwright.config.ts webpack.config.ts build_config.sample.yaml apps/web/

mkdir apps/web/scripts
mv scripts/{cleanup.sh,ci_package.sh,copy-res.ts,deploy.py,package.sh} apps/web/scripts

And a couple of gitignore tweaks

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski
2026-02-24 15:43:58 +00:00
parent e7509c92a1
commit 91a3cb03c1
3408 changed files with 28 additions and 32 deletions
@@ -0,0 +1,162 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 from "react";
import { render, screen, act, cleanup, fireEvent, waitFor } from "jest-matrix-react";
import { mocked, type Mocked } from "jest-mock";
import {
Room,
RoomStateEvent,
type MatrixClient,
PendingEventOrdering,
type RoomMember,
} from "matrix-js-sdk/src/matrix";
import { Widget } from "matrix-widget-api";
import {
useMockedCalls,
MockedCall,
stubClient,
mkRoomMember,
setupAsyncStoreWithClient,
resetAsyncStoreWithClient,
wrapInMatrixClientContext,
useMockMediaDevices,
} from "../../../../test-utils";
import defaultDispatcher from "../../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../../src/dispatcher/actions";
import { CallEvent as UnwrappedCallEvent } from "../../../../../src/components/views/messages/CallEvent";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { CallStore } from "../../../../../src/stores/CallStore";
import { WidgetMessagingStore } from "../../../../../src/stores/widgets/WidgetMessagingStore";
import { ConnectionState } from "../../../../../src/models/Call";
import { type WidgetMessaging } from "../../../../../src/stores/widgets/WidgetMessaging";
const CallEvent = wrapInMatrixClientContext(UnwrappedCallEvent);
describe("CallEvent", () => {
let client: Mocked<MatrixClient>;
let room: Room;
let alice: RoomMember;
let bob: RoomMember;
let call: MockedCall;
let widget: Widget;
beforeEach(async () => {
jest.useFakeTimers();
jest.setSystemTime(0);
useMockMediaDevices();
useMockedCalls();
jest.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(async () => {});
stubClient();
client = mocked(MatrixClientPeg.safeGet());
client.getUserId.mockReturnValue("@alice:example.org");
room = new Room("!1:example.org", client, "@alice:example.org", {
pendingEventOrdering: PendingEventOrdering.Detached,
});
alice = mkRoomMember(room.roomId, "@alice:example.org");
bob = mkRoomMember(room.roomId, "@bob:example.org");
jest.spyOn(room, "getMember").mockImplementation(
(userId) => [alice, bob].find((member) => member.userId === userId) ?? null,
);
client.getRoom.mockImplementation((roomId) => (roomId === room.roomId ? room : null));
client.getRooms.mockReturnValue([room]);
client.reEmitter.reEmit(room, [RoomStateEvent.Events]);
await Promise.all(
[CallStore.instance, WidgetMessagingStore.instance].map((store) =>
setupAsyncStoreWithClient(store, client),
),
);
MockedCall.create(room, "1");
const maybeCall = CallStore.instance.getCall(room.roomId);
if (!(maybeCall instanceof MockedCall)) throw new Error("Failed to create call");
call = maybeCall;
widget = new Widget(call.widget);
WidgetMessagingStore.instance.storeMessaging(widget, room.roomId, {
stop: () => {},
} as unknown as WidgetMessaging);
});
afterEach(async () => {
cleanup(); // Unmount before we do any cleanup that might update the component
call.destroy();
WidgetMessagingStore.instance.stopMessaging(widget, room.roomId);
await Promise.all([CallStore.instance, WidgetMessagingStore.instance].map(resetAsyncStoreWithClient));
client.reEmitter.stopReEmitting(room, [RoomStateEvent.Events]);
jest.restoreAllMocks();
});
const renderEvent = () => {
render(<CallEvent mxEvent={call.event} />);
};
it("shows a message and duration if the call was ended", () => {
jest.advanceTimersByTime(90000);
call.destroy();
renderEvent();
screen.getByText("Video call ended");
screen.getByText("1m 30s");
});
it("shows a message if the call was redacted", () => {
const event = room.currentState.getStateEvents(MockedCall.EVENT_TYPE, "1")!;
jest.spyOn(event, "isRedacted").mockReturnValue(true);
renderEvent();
screen.getByText("Video call ended");
});
it("shows placeholder info if the call isn't loaded yet", () => {
jest.spyOn(CallStore.instance, "getCall").mockReturnValue(null);
jest.advanceTimersByTime(90000);
renderEvent();
screen.getByText("@alice:example.org started a video call");
expect(screen.getByRole("button", { name: "Join" })).toHaveAttribute("aria-disabled", "true");
});
it("shows call details and connection controls if the call is loaded", async () => {
jest.advanceTimersByTime(90000);
call.participants = new Map([
[alice, new Set(["a"])],
[bob, new Set(["b"])],
]);
renderEvent();
screen.getByText("@alice:example.org started a video call");
screen.getByLabelText("2 people joined");
// Test that the join button works
const dispatcherSpy = jest.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
fireEvent.click(screen.getByRole("button", { name: "Join" }));
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: Action.ViewRoom,
room_id: room.roomId,
view_call: true,
}),
);
defaultDispatcher.unregister(dispatcherRef);
act(() => call.setConnectionState(ConnectionState.Connected));
// Test that the leave button works
fireEvent.click(screen.getByRole("button", { name: "Leave" }));
await waitFor(() => screen.getByRole("button", { name: "Join" }));
expect(call.connectionState).toBe(ConnectionState.Disconnected);
});
});
@@ -0,0 +1,322 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 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 from "react";
import { mocked } from "jest-mock";
import { fireEvent, render, screen, waitFor } from "jest-matrix-react";
import { type TimestampToEventResponse, ConnectionError, HTTPError, MatrixError } from "matrix-js-sdk/src/matrix";
import dispatcher from "../../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../../src/dispatcher/actions";
import { type ViewRoomPayload } from "../../../../../src/dispatcher/payloads/ViewRoomPayload";
import { formatFullDateNoTime } from "../../../../../src/DateUtils";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { UIFeature } from "../../../../../src/settings/UIFeature";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import {
clearAllModals,
flushPromisesWithFakeTimers,
getMockClientWithEventEmitter,
waitEnoughCyclesForModal,
} from "../../../../test-utils";
import DateSeparator from "../../../../../src/components/views/messages/DateSeparator";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext";
import RoomContext, { type RoomContextType } from "../../../../../src/contexts/RoomContext";
jest.mock("../../../../../src/settings/SettingsStore");
describe("DateSeparator", () => {
const HOUR_MS = 3600000;
const DAY_MS = HOUR_MS * 24;
// Friday Dec 17 2021, 9:09am
const nowDate = new Date("2021-12-17T08:09:00.000Z");
const roomId = "!unused:example.org";
const defaultProps = {
ts: nowDate.getTime(),
roomId,
};
const mockRoomViewStore = {
getRoomId: jest.fn().mockReturnValue(roomId),
};
const defaultRoomContext = {
...RoomContext,
roomId,
roomViewStore: mockRoomViewStore,
} as unknown as RoomContextType;
const mockClient = getMockClientWithEventEmitter({
timestampToEvent: jest.fn(),
});
const getComponent = (props = {}) =>
render(
<MatrixClientContext.Provider value={mockClient}>
<ScopedRoomContextProvider {...defaultRoomContext}>
<DateSeparator {...defaultProps} {...props} />
</ScopedRoomContextProvider>
</MatrixClientContext.Provider>,
);
type TestCase = [string, number, string];
const testCases: TestCase[] = [
["the exact same moment", nowDate.getTime(), "today"],
["same day as current day", nowDate.getTime() - HOUR_MS, "today"],
["day before the current day", nowDate.getTime() - HOUR_MS * 12, "yesterday"],
["2 days ago", nowDate.getTime() - DAY_MS * 2, "Wednesday"],
["144 hours ago", nowDate.getTime() - HOUR_MS * 144, "Sat, Dec 11, 2021"],
[
"6 days ago, but less than 144h",
new Date("Saturday Dec 11 2021 23:59:00 GMT+0100 (Central European Standard Time)").getTime(),
"Saturday",
],
];
beforeEach(() => {
// Set a consistent fake time here so the test is always consistent
jest.useFakeTimers();
jest.setSystemTime(nowDate.getTime());
(SettingsStore.getValue as jest.Mock) = jest.fn((arg) => {
if (arg === UIFeature.TimelineEnableRelativeDates) {
return true;
}
});
mockRoomViewStore.getRoomId.mockReturnValue(roomId);
});
afterAll(() => {
jest.useRealTimers();
});
it("renders the date separator correctly", () => {
const { asFragment } = getComponent();
expect(asFragment()).toMatchSnapshot();
expect(SettingsStore.getValue).toHaveBeenCalledWith(UIFeature.TimelineEnableRelativeDates);
});
it.each(testCases)("formats date correctly when current time is %s", (_d, ts, result) => {
expect(getComponent({ ts, forExport: false }).container.textContent).toEqual(result);
});
it("renders invalid date separator correctly", () => {
const ts = new Date(-8640000000000004).getTime();
const { asFragment } = getComponent({ ts });
expect(asFragment()).toMatchSnapshot();
});
describe("when forExport is true", () => {
it.each(testCases)("formats date in full when current time is %s", (_d, ts) => {
expect(getComponent({ ts, forExport: true }).container.textContent).toEqual(
formatFullDateNoTime(new Date(ts)),
);
});
});
describe("when Settings.TimelineEnableRelativeDates is falsy", () => {
beforeEach(() => {
(SettingsStore.getValue as jest.Mock) = jest.fn((arg) => {
if (arg === UIFeature.TimelineEnableRelativeDates) {
return false;
}
});
});
it.each(testCases)("formats date in full when current time is %s", (_d, ts) => {
expect(getComponent({ ts, forExport: false }).container.textContent).toEqual(
formatFullDateNoTime(new Date(ts)),
);
});
});
describe("when feature_jump_to_date is enabled", () => {
beforeEach(() => {
jest.clearAllMocks();
mocked(SettingsStore).getValue.mockImplementation((arg): any => {
if (arg === "feature_jump_to_date") {
return true;
}
});
jest.spyOn(dispatcher, "dispatch").mockImplementation(() => {});
});
afterEach(async () => {
await clearAllModals();
});
it("renders the date separator correctly", () => {
const { asFragment } = getComponent();
expect(asFragment()).toMatchSnapshot();
});
[
{
timeDescriptor: "last week",
jumpButtonTestId: "jump-to-date-last-week",
},
{
timeDescriptor: "last month",
jumpButtonTestId: "jump-to-date-last-month",
},
{
timeDescriptor: "the beginning",
jumpButtonTestId: "jump-to-date-beginning",
},
].forEach((testCase) => {
it(`can jump to ${testCase.timeDescriptor}`, async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Jump to "x"
const returnedDate = new Date();
// Just an arbitrary date before "now"
returnedDate.setDate(nowDate.getDate() - 100);
const returnedEventId = "$abc";
mockClient.timestampToEvent.mockResolvedValue({
event_id: returnedEventId,
origin_server_ts: returnedDate.getTime(),
} satisfies TimestampToEventResponse);
const jumpToXButton = await screen.findByTestId(testCase.jumpButtonTestId);
fireEvent.click(jumpToXButton);
// Flush out the dispatcher which uses `window.setTimeout(...)` since we're
// using `jest.useFakeTimers()` in these tests.
await flushPromisesWithFakeTimers();
// Ensure that we're jumping to the event at the given date
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ViewRoom,
event_id: returnedEventId,
highlighted: true,
room_id: roomId,
metricsTrigger: undefined,
} satisfies ViewRoomPayload);
});
});
it("should not jump to date if we already switched to another room", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Mimic the outcome of switching rooms while waiting for the jump to date
// request to finish. Imagine that we started jumping to "last week", the
// network request is taking a while, so we got bored, switched rooms; we
// shouldn't jump back to the previous room after the network request
// happens to finish later.
mockRoomViewStore.getRoomId.mockReturnValue("!some-other-room");
// Jump to "last week"
mockClient.timestampToEvent.mockResolvedValue({
event_id: "$abc",
origin_server_ts: 0,
});
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Flush out the dispatcher which uses `window.setTimeout(...)` since we're
// using `jest.useFakeTimers()` in these tests.
await flushPromisesWithFakeTimers();
// We should not see any room switching going on (`Action.ViewRoom`)
expect(dispatcher.dispatch).not.toHaveBeenCalled();
});
it("should not show jump to date error if we already switched to another room", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Mimic the outcome of switching rooms while waiting for the jump to date
// request to finish. Imagine that we started jumping to "last week", the
// network request is taking a while, so we got bored, switched rooms; we
// shouldn't jump back to the previous room after the network request
// happens to finish later.
mockRoomViewStore.getRoomId.mockReturnValue("!some-other-room");
// Try to jump to "last week" but we want an error to occur and ensure that
// we don't show an error dialog for it since we already switched away to
// another room and don't care about the outcome here anymore.
mockClient.timestampToEvent.mockRejectedValue(new Error("Fake error in test"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Wait the necessary time in order to see if any modal will appear
await waitEnoughCyclesForModal({
useFakeTimers: true,
});
// We should not see any error modal dialog
//
// We have to use `queryBy` so that it can return `null` for something that does not exist.
expect(screen.queryByTestId("jump-to-date-error-content")).not.toBeInTheDocument();
});
it("should show error dialog with submit debug logs option when non-networking error occurs", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Try to jump to "last week" but we want a non-network error to occur so it
// shows the "Submit debug logs" UI
mockClient.timestampToEvent.mockRejectedValue(new Error("Fake error in test"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Expect error to be shown. We have to wait for the UI to transition.
await expect(screen.findByTestId("jump-to-date-error-content")).resolves.toBeInTheDocument();
// Expect an option to submit debug logs to be shown when a non-network error occurs
await expect(
screen.findByTestId("jump-to-date-error-submit-debug-logs-button"),
).resolves.toBeInTheDocument();
});
[
new ConnectionError("Fake connection error in test"),
new HTTPError("Fake http error in test", 418),
new MatrixError(
{ errcode: "M_FAKE_ERROR_CODE", error: "Some fake error occured" },
518,
"https://fake-url/",
),
].forEach((fakeError) => {
it(`should show error dialog without submit debug logs option when networking error (${fakeError.name}) occurs`, async () => {
// Try to jump to "last week" but we want a network error to occur
mockClient.timestampToEvent.mockRejectedValue(fakeError);
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Expect error to be shown. We have to wait for the UI to transition.
await expect(screen.findByTestId("jump-to-date-error-content")).resolves.toBeInTheDocument();
// The submit debug logs option should *NOT* be shown for network errors.
//
// We have to use `queryBy` so that it can return `null` for something that does not exist.
await waitFor(() =>
expect(screen.queryByTestId("jump-to-date-error-submit-debug-logs-button")).not.toBeInTheDocument(),
);
});
});
});
});
@@ -0,0 +1,155 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2024 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 from "react";
import { mocked } from "jest-mock";
import fetchMock from "@fetch-mock/jest";
import { fireEvent, render, screen, waitFor } from "jest-matrix-react";
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import userEvent from "@testing-library/user-event";
import { clearAllModals, stubClient } from "../../../../test-utils";
import DownloadActionButton from "../../../../../src/components/views/messages/DownloadActionButton";
import Modal from "../../../../../src/Modal";
import { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import ErrorDialog from "../../../../../src/components/views/dialogs/ErrorDialog";
jest.mock("matrix-encrypt-attachment", () => ({
decryptAttachment: jest.fn().mockResolvedValue(new Blob(["TESTFILE"], { type: "application/octet-stream" })),
}));
describe("DownloadActionButton", () => {
const plainEvent = new MatrixEvent({
room_id: "!room:id",
sender: "@user:id",
type: "m.room.message",
content: {
body: "test",
msgtype: "m.image",
url: "mxc://matrix.org/1234",
},
});
beforeEach(() => {
jest.restoreAllMocks();
});
afterEach(() => {
clearAllModals();
});
it("should show error if media API returns one", async () => {
const cli = stubClient();
// eslint-disable-next-line no-restricted-properties
mocked(cli.mxcUrlToHttp).mockImplementation(
(mxc) => `https://matrix.org/_matrix/media/r0/download/${mxc.slice(6)}`,
);
fetchMock.getOnce("https://matrix.org/_matrix/media/r0/download/matrix.org/1234", {
status: 404,
body: { errcode: "M_NOT_FOUND", error: "Not found" },
});
const mediaEventHelper = new MediaEventHelper(plainEvent);
render(<DownloadActionButton mxEvent={plainEvent} mediaEventHelperGet={() => mediaEventHelper} />);
const spy = jest.spyOn(Modal, "createDialog");
fireEvent.click(screen.getByRole("button"));
await waitFor(() =>
expect(spy).toHaveBeenCalledWith(
ErrorDialog,
expect.objectContaining({
title: "Download failed",
}),
),
);
});
it("should show download tooltip on hover", async () => {
stubClient();
const user = userEvent.setup();
fetchMock.getOnce("https://matrix.org/_matrix/media/r0/download/matrix.org/1234", "TESTFILE");
const event = new MatrixEvent({
room_id: "!room:id",
sender: "@user:id",
type: "m.room.message",
content: {
body: "test",
msgtype: "m.image",
url: "mxc://matrix.org/1234",
},
});
render(<DownloadActionButton mxEvent={event} mediaEventHelperGet={() => undefined} />);
const button = screen.getByRole("button");
await user.hover(button);
await waitFor(() => {
expect(screen.getByRole("tooltip")).toHaveTextContent("Download");
});
});
it("should show downloading tooltip while unencrypted files are downloading", async () => {
const user = userEvent.setup();
stubClient();
fetchMock.getOnce("http://this.is.a.url/matrix.org/1234", "TESTFILE");
const mediaEventHelper = new MediaEventHelper(plainEvent);
render(<DownloadActionButton mxEvent={plainEvent} mediaEventHelperGet={() => mediaEventHelper} />);
const button = screen.getByRole("button");
await user.hover(button);
await user.click(button);
await waitFor(() => {
expect(screen.getByRole("tooltip")).toHaveTextContent("Downloading");
});
});
it("should show decrypting tooltip while encrypted files are downloading", async () => {
const user = userEvent.setup();
stubClient();
fetchMock.getOnce("http://this.is.a.url/matrix.org/1234", "UFTUGJMF");
const e2eEvent = new MatrixEvent({
room_id: "!room:id",
sender: "@user:id",
type: "m.room.message",
content: {
body: "test",
msgtype: "m.image",
file: { url: "mxc://matrix.org/1234" },
},
});
const mediaEventHelper = new MediaEventHelper(e2eEvent);
render(<DownloadActionButton mxEvent={e2eEvent} mediaEventHelperGet={() => mediaEventHelper} />);
const button = screen.getByRole("button");
await user.hover(button);
await user.click(button);
await waitFor(() => {
expect(screen.getByRole("tooltip")).toHaveTextContent("Decrypting");
});
});
});
@@ -0,0 +1,85 @@
/*
Copyright 2024,2025 New Vector Ltd.
Copyright 2024 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 from "react";
import { fireEvent, render, screen } from "jest-matrix-react";
import { MatrixEvent, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { HideActionButton } from "../../../../../src/components/views/messages/HideActionButton";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { SettingLevel } from "../../../../../src/settings/SettingLevel";
import type { Settings } from "../../../../../src/settings/Settings";
import { MediaPreviewValue } from "../../../../../src/@types/media_preview";
import { getMockClientWithEventEmitter, withClientContextRenderOptions } from "../../../../test-utils";
import type { MockedObject } from "jest-mock";
function mockSetting(mediaPreviews: MediaPreviewValue, showMediaEventIds: Settings["showMediaEventIds"]["default"]) {
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName) => {
if (settingName === "mediaPreviewConfig") {
return { media_previews: mediaPreviews, invite_avatars: MediaPreviewValue.Off };
} else if (settingName === "showMediaEventIds") {
return showMediaEventIds;
}
throw Error(`Unexpected setting ${settingName}`);
});
}
const EVENT_ID = "$foo:bar";
const event = new MatrixEvent({
event_id: EVENT_ID,
room_id: "!room:id",
sender: "@user:id",
type: "m.room.message",
content: {
body: "test",
msgtype: "m.image",
url: "mxc://matrix.org/1234",
},
});
describe("HideActionButton", () => {
let cli: MockedObject<MatrixClient>;
beforeEach(() => {
cli = getMockClientWithEventEmitter({
getRoom: jest.fn(),
getUserId: jest.fn(),
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it("should show button when event is visible by showMediaEventIds setting", async () => {
mockSetting(MediaPreviewValue.Off, { [EVENT_ID]: true });
render(<HideActionButton mxEvent={event} />, withClientContextRenderOptions(cli));
expect(screen.getByRole("button")).toBeVisible();
});
it("should show button when event is visible by mediaPreviewConfig setting", async () => {
mockSetting(MediaPreviewValue.On, {});
render(<HideActionButton mxEvent={event} />, withClientContextRenderOptions(cli));
expect(screen.getByRole("button")).toBeVisible();
});
it("should hide button when event is hidden by showMediaEventIds setting", async () => {
mockSetting(MediaPreviewValue.Off, { [EVENT_ID]: false });
render(<HideActionButton mxEvent={event} />, withClientContextRenderOptions(cli));
expect(screen.queryByRole("button")).toBeNull();
});
it("should hide button when event is hidden by showImages setting", async () => {
mockSetting(MediaPreviewValue.Off, {});
render(<HideActionButton mxEvent={event} />, withClientContextRenderOptions(cli));
expect(screen.queryByRole("button")).toBeNull();
});
it("should store event as hidden when clicked", async () => {
const spy = jest.spyOn(SettingsStore, "setValue");
render(<HideActionButton mxEvent={event} />, withClientContextRenderOptions(cli));
fireEvent.click(screen.getByRole("button"));
expect(spy).toHaveBeenCalledWith("showMediaEventIds", null, SettingLevel.DEVICE, { "$foo:bar": false });
// Button should be hidden after the setting is set.
expect(screen.queryByRole("button")).toBeNull();
});
});
@@ -0,0 +1,33 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 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 from "react";
import { render } from "jest-matrix-react";
import JumpToDatePicker from "../../../../../src/components/views/messages/JumpToDatePicker";
describe("JumpToDatePicker", () => {
const nowDate = new Date("2021-12-17T08:09:00.000Z");
beforeEach(() => {
// Set a stable fake time here so the test is always consistent
jest.useFakeTimers();
jest.setSystemTime(nowDate.getTime());
});
afterAll(() => {
jest.useRealTimers();
});
it("renders the date picker correctly", () => {
const { asFragment } = render(
<JumpToDatePicker ts={new Date("2020-07-04T05:55:00.000Z").getTime()} onDatePicked={() => {}} />,
);
expect(asFragment()).toMatchSnapshot();
});
});
@@ -0,0 +1,97 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2023 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 from "react";
import { render, screen } from "jest-matrix-react";
import { CallErrorCode, CallState } from "matrix-js-sdk/src/webrtc/call";
import { type MatrixEvent } from "matrix-js-sdk/src/matrix";
import LegacyCallEvent from "../../../../../src/components/views/messages/LegacyCallEvent";
import type LegacyCallEventGrouper from "../../../../../src/components/structures/LegacyCallEventGrouper";
const THEIR_USER_ID = "@them:here";
describe("LegacyCallEvent", () => {
let callInviteEvent: Record<string, any>;
let callEventGrouper: Record<string, any>;
beforeEach(() => {
callInviteEvent = {
sender: {
userId: THEIR_USER_ID,
},
};
callEventGrouper = {
addListener: jest.fn(),
removeListener: jest.fn(),
invite: jest.fn().mockReturnValue(callInviteEvent),
};
});
const renderEvent = () => {
render(
<LegacyCallEvent
mxEvent={callInviteEvent as unknown as MatrixEvent}
callEventGrouper={callEventGrouper as unknown as LegacyCallEventGrouper}
/>,
);
};
it("shows if the call was ended", () => {
callEventGrouper.state = CallState.Ended;
callEventGrouper.gotRejected = jest.fn().mockReturnValue(true);
renderEvent();
screen.getByText("Call declined");
});
it("shows if the call was answered elsewhere", () => {
callEventGrouper.state = CallState.Ended;
callEventGrouper.hangupReason = CallErrorCode.AnsweredElsewhere;
renderEvent();
screen.getByText("Answered elsewhere");
});
it("shows if the call was missed", () => {
callEventGrouper.state = CallState.Ended;
callEventGrouper.callWasMissed = jest.fn().mockReturnValue(true);
renderEvent();
screen.getByText("Missed call");
});
it("shows if the call ended cleanly", () => {
callEventGrouper.state = CallState.Ended;
callEventGrouper.hangupReason = CallErrorCode.UserHangup;
renderEvent();
screen.getByText("Call ended");
});
it("shows if the call is connecting", () => {
callEventGrouper.state = CallState.Connecting;
renderEvent();
screen.getByText("Connecting");
});
it("shows timer if the call is connected", () => {
callEventGrouper.state = CallState.Connected;
renderEvent();
screen.getByText("00:00");
});
});
@@ -0,0 +1,48 @@
/*
* Copyright 2025 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 { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { render, screen, act } from "jest-matrix-react";
import { MockedPlayback } from "../../../audio/MockedPlayback";
import { type Playback, PlaybackState } from "../../../../../src/audio/Playback";
import MAudioBody from "../../../../../src/components/views/messages/MAudioBody";
import { PlaybackManager } from "../../../../../src/audio/PlaybackManager";
import { type MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
describe("<MAudioBody />", () => {
let event: MatrixEvent;
beforeEach(() => {
const playback = new MockedPlayback(PlaybackState.Decoding, 50, 10) as unknown as Playback;
jest.spyOn(PlaybackManager.instance, "createPlaybackInstance").mockReturnValue(playback);
event = new MatrixEvent({
room_id: "!room:server",
sender: "@alice.example.org",
type: EventType.RoomMessage,
content: {
body: "audio name ",
msgtype: "m.audio",
url: "mxc://server/audio",
},
});
});
it("should render", async () => {
const mediaEventHelper = {
sourceBlob: {
value: {
arrayBuffer: () => new ArrayBuffer(8),
},
},
} as unknown as MediaEventHelper;
await act(() => render(<MAudioBody mxEvent={event} mediaEventHelper={mediaEventHelper} />));
expect(await screen.findByRole("region", { name: "Audio player" })).toBeInTheDocument();
});
});
@@ -0,0 +1,415 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 ComponentProps } from "react";
import { act, fireEvent, render } from "jest-matrix-react";
import * as maplibregl from "maplibre-gl";
import {
BeaconEvent,
getBeaconInfoIdentifier,
RelationType,
MatrixEvent,
EventType,
Relations,
M_BEACON,
type Room,
} from "matrix-js-sdk/src/matrix";
import MBeaconBody from "../../../../../src/components/views/messages/MBeaconBody";
import {
getMockClientWithEventEmitter,
makeBeaconEvent,
makeBeaconInfoEvent,
makeRoomWithBeacons,
makeRoomWithStateEvents,
} from "../../../../test-utils";
import { type RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import { type MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import Modal from "../../../../../src/Modal";
import { TILE_SERVER_WK_KEY } from "../../../../../src/utils/WellKnownUtils";
import * as mapUtilHooks from "../../../../../src/utils/location/useMap";
import { LocationShareError } from "../../../../../src/utils/location";
describe("<MBeaconBody />", () => {
// 14.03.2022 16:15
const now = 1647270879403;
// stable date for snapshots
jest.spyOn(global.Date, "now").mockReturnValue(now);
const roomId = "!room:server";
const aliceId = "@alice:server";
const mapOptions = { container: {} as unknown as HTMLElement, style: "" };
const mockMap = new maplibregl.Map(mapOptions);
const mockMarker = new maplibregl.Marker();
const mockClient = getMockClientWithEventEmitter({
getClientWellKnown: jest.fn().mockReturnValue({
[TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" },
}),
getUserId: jest.fn().mockReturnValue(aliceId),
getRoom: jest.fn(),
redactEvent: jest.fn(),
});
const defaultEvent = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-1");
const defaultProps: ComponentProps<typeof MBeaconBody> = {
mxEvent: defaultEvent,
highlights: [],
highlightLink: "",
onMessageAllowed: jest.fn(),
// we dont use these and they pollute the snapshots
permalinkCreator: {} as unknown as RoomPermalinkCreator,
mediaEventHelper: {} as unknown as MediaEventHelper,
};
const getComponent = (props = {}) =>
render(
<MatrixClientContext.Provider value={mockClient}>
<MBeaconBody {...defaultProps} {...props} />
</MatrixClientContext.Provider>,
);
const modalSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([true]),
close: () => {},
});
beforeEach(() => {
jest.clearAllMocks();
});
const testBeaconStatuses = () => {
it("renders stopped beacon UI for an explicitly stopped beacon", () => {
const beaconInfoEvent = makeBeaconInfoEvent(aliceId, roomId, { isLive: false }, "$alice-room1-1");
makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
const component = getComponent({ mxEvent: beaconInfoEvent });
expect(component.container).toHaveTextContent("Live location ended");
});
it("renders stopped beacon UI for an expired beacon", () => {
const beaconInfoEvent = makeBeaconInfoEvent(
aliceId,
roomId,
// puts this beacons live period in the past
{ isLive: true, timestamp: now - 600000, timeout: 500 },
"$alice-room1-1",
);
makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
const component = getComponent({ mxEvent: beaconInfoEvent });
expect(component.container).toHaveTextContent("Live location ended");
});
it("renders loading beacon UI for a beacon that has not started yet", () => {
const beaconInfoEvent = makeBeaconInfoEvent(
aliceId,
roomId,
// puts this beacons start timestamp in the future
{ isLive: true, timestamp: now + 60000, timeout: 500 },
"$alice-room1-1",
);
makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
const component = getComponent({ mxEvent: beaconInfoEvent });
expect(component.container).toHaveTextContent("Loading live location…");
});
it("does not open maximised map when on click when beacon is stopped", () => {
const beaconInfoEvent = makeBeaconInfoEvent(
aliceId,
roomId,
// puts this beacons live period in the past
{ isLive: true, timestamp: now - 600000, timeout: 500 },
"$alice-room1-1",
);
makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
const component = getComponent({ mxEvent: beaconInfoEvent });
fireEvent.click(component.container.querySelector(".mx_MBeaconBody_map")!);
expect(modalSpy).not.toHaveBeenCalled();
});
it("renders stopped UI when a beacon event is not the latest beacon for a user", () => {
const aliceBeaconInfo1 = makeBeaconInfoEvent(
aliceId,
roomId,
// this one is a little older
{ isLive: true, timestamp: now - 500 },
"$alice-room1-1",
);
aliceBeaconInfo1.event.origin_server_ts = now - 500;
const aliceBeaconInfo2 = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-2");
makeRoomWithStateEvents([aliceBeaconInfo1, aliceBeaconInfo2], { roomId, mockClient });
const component = getComponent({ mxEvent: aliceBeaconInfo1 });
// beacon1 has been superceded by beacon2
expect(component.container).toHaveTextContent("Live location ended");
});
it("renders stopped UI when a beacon event is replaced", () => {
const aliceBeaconInfo1 = makeBeaconInfoEvent(
aliceId,
roomId,
// this one is a little older
{ isLive: true, timestamp: now - 500 },
"$alice-room1-1",
);
aliceBeaconInfo1.event.origin_server_ts = now - 500;
const aliceBeaconInfo2 = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-2");
const room = makeRoomWithStateEvents([aliceBeaconInfo1], { roomId, mockClient });
const component = getComponent({ mxEvent: aliceBeaconInfo1 });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo1))!;
// update alice's beacon with a new edition
// beacon instance emits
act(() => {
beaconInstance.update(aliceBeaconInfo2);
});
// beacon1 has been superceded by beacon2
expect(component.container).toHaveTextContent("Live location ended");
});
};
testBeaconStatuses();
describe("on liveness change", () => {
it("renders stopped UI when a beacon stops being live", () => {
const aliceBeaconInfo = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-1");
const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo))!;
const component = getComponent({ mxEvent: aliceBeaconInfo });
act(() => {
// @ts-ignore cheat to force beacon to not live
beaconInstance._isLive = false;
beaconInstance.emit(BeaconEvent.LivenessChange, false, beaconInstance);
});
// stopped UI
expect(component.container).toHaveTextContent("Live location ended");
});
});
describe("latestLocationState", () => {
const aliceBeaconInfo = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-1");
const location1 = makeBeaconEvent(aliceId, {
beaconInfoId: aliceBeaconInfo.getId(),
geoUri: "geo:51,41",
timestamp: now + 1,
});
const location2 = makeBeaconEvent(aliceId, {
beaconInfoId: aliceBeaconInfo.getId(),
geoUri: "geo:52,42",
timestamp: now + 10000,
});
it("renders a live beacon without a location correctly", () => {
makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
const component = getComponent({ mxEvent: aliceBeaconInfo });
expect(component.container).toHaveTextContent("Loading live location…");
});
it("does nothing on click when a beacon has no location", () => {
makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
const component = getComponent({ mxEvent: aliceBeaconInfo });
fireEvent.click(component.container.querySelector(".mx_MBeaconBody_map")!);
expect(modalSpy).not.toHaveBeenCalled();
});
it("renders a live beacon with a location correctly", () => {
const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo))!;
beaconInstance.addLocations([location1]);
const component = getComponent({ mxEvent: aliceBeaconInfo });
expect(component.container.querySelector(".maplibregl-canvas-container")).toBeDefined();
});
it("opens maximised map view on click when beacon has a live location", () => {
const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo))!;
beaconInstance.addLocations([location1]);
const component = getComponent({ mxEvent: aliceBeaconInfo });
fireEvent.click(component.container.querySelector(".mx_Map")!);
// opens modal
expect(modalSpy).toHaveBeenCalled();
});
it("updates latest location", () => {
const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
getComponent({ mxEvent: aliceBeaconInfo });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo))!;
act(() => {
beaconInstance.addLocations([location1]);
});
expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 51, lon: 41 });
expect(mockMarker.setLngLat).toHaveBeenCalledWith({ lat: 51, lon: 41 });
act(() => {
beaconInstance.addLocations([location2]);
});
expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 52, lon: 42 });
expect(mockMarker.setLngLat).toHaveBeenCalledWith({ lat: 52, lon: 42 });
});
});
describe("redaction", () => {
const makeEvents = (): {
beaconInfoEvent: MatrixEvent;
location1: MatrixEvent;
location2: MatrixEvent;
} => {
const beaconInfoEvent = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-1");
const location1 = makeBeaconEvent(
aliceId,
{ beaconInfoId: beaconInfoEvent.getId(), geoUri: "geo:51,41", timestamp: now + 1 },
roomId,
);
location1.event.event_id = "1";
const location2 = makeBeaconEvent(
aliceId,
{ beaconInfoId: beaconInfoEvent.getId(), geoUri: "geo:52,42", timestamp: now + 10000 },
roomId,
);
location2.event.event_id = "2";
return { beaconInfoEvent, location1, location2 };
};
const redactionEvent = new MatrixEvent({ type: EventType.RoomRedaction, content: { reason: "test reason" } });
const setupRoomWithBeacon = (beaconInfoEvent: MatrixEvent, locationEvents: MatrixEvent[] = []): Room => {
const room = makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(beaconInfoEvent))!;
beaconInstance.addLocations(locationEvents);
return room;
};
const mockGetRelationsForEvent = (locationEvents: MatrixEvent[] = []) => {
const relations = new Relations(RelationType.Reference, M_BEACON.name, mockClient);
jest.spyOn(relations, "getRelations").mockReturnValue(locationEvents);
const getRelationsForEvent = jest.fn().mockReturnValue(relations);
return getRelationsForEvent;
};
it("does nothing when getRelationsForEvent is falsy", () => {
const { beaconInfoEvent, location1, location2 } = makeEvents();
const room = setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);
getComponent({ mxEvent: beaconInfoEvent });
act(() => {
beaconInfoEvent.makeRedacted(redactionEvent, room);
});
// no error, no redactions
expect(mockClient.redactEvent).not.toHaveBeenCalled();
});
it("cleans up redaction listener on unmount", () => {
const { beaconInfoEvent, location1, location2 } = makeEvents();
setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);
const removeListenerSpy = jest.spyOn(beaconInfoEvent, "removeListener");
const component = getComponent({ mxEvent: beaconInfoEvent });
act(() => {
component.unmount();
});
expect(removeListenerSpy).toHaveBeenCalled();
});
it("does nothing when beacon has no related locations", async () => {
const { beaconInfoEvent } = makeEvents();
// no locations
const room = setupRoomWithBeacon(beaconInfoEvent, []);
const getRelationsForEvent = await mockGetRelationsForEvent();
getComponent({ mxEvent: beaconInfoEvent, getRelationsForEvent });
act(() => {
beaconInfoEvent.makeRedacted(redactionEvent, room);
});
expect(getRelationsForEvent).toHaveBeenCalledWith(
beaconInfoEvent.getId(),
RelationType.Reference,
M_BEACON.name,
);
expect(mockClient.redactEvent).not.toHaveBeenCalled();
});
it("redacts related locations on beacon redaction", async () => {
const { beaconInfoEvent, location1, location2 } = makeEvents();
const room = setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);
const getRelationsForEvent = await mockGetRelationsForEvent([location1, location2]);
getComponent({ mxEvent: beaconInfoEvent, getRelationsForEvent });
act(() => {
beaconInfoEvent.makeRedacted(redactionEvent, room);
});
expect(getRelationsForEvent).toHaveBeenCalledWith(
beaconInfoEvent.getId(),
RelationType.Reference,
M_BEACON.name,
);
expect(mockClient.redactEvent).toHaveBeenCalledTimes(2);
expect(mockClient.redactEvent).toHaveBeenCalledWith(roomId, location1.getId(), undefined, {
reason: "test reason",
});
expect(mockClient.redactEvent).toHaveBeenCalledWith(roomId, location2.getId(), undefined, {
reason: "test reason",
});
});
});
describe("when map display is not configured", () => {
beforeEach(() => {
// mock map utils to raise MapStyleUrlNotConfigured error
jest.spyOn(mapUtilHooks, "useMap").mockImplementation(({ onError }) => {
onError?.(new Error(LocationShareError.MapStyleUrlNotConfigured));
return mockMap;
});
});
it("renders maps unavailable error for a live beacon with location", () => {
const beaconInfoEvent = makeBeaconInfoEvent(aliceId, roomId, { isLive: true }, "$alice-room1-1");
const location1 = makeBeaconEvent(aliceId, {
beaconInfoId: beaconInfoEvent.getId(),
geoUri: "geo:51,41",
timestamp: now + 1,
});
makeRoomWithBeacons(roomId, mockClient, [beaconInfoEvent], [location1]);
const component = getComponent({ mxEvent: beaconInfoEvent });
expect(component.getByTestId("map-rendering-error")).toMatchSnapshot();
});
// test that statuses display as expected with a map display error
testBeaconStatuses();
});
});
@@ -0,0 +1,115 @@
/*
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();
});
});
@@ -0,0 +1,376 @@
/*
Copyright 2024, 2025 New Vector Ltd.
Copyright 2022 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 from "react";
import { fireEvent, render, screen, waitFor, waitForElementToBeRemoved, within } from "jest-matrix-react";
import { EventType, getHttpUriForMxc, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import fetchMock from "@fetch-mock/jest";
import encrypt from "matrix-encrypt-attachment";
import { mocked } from "jest-mock";
import fs from "fs";
import path from "path";
import userEvent from "@testing-library/user-event";
import MImageBody from "../../../../../src/components/views/messages/MImageBody";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import {
getMockClientWithEventEmitter,
mockClientMethodsCrypto,
mockClientMethodsDevice,
mockClientMethodsServer,
mockClientMethodsUser,
withClientContextRenderOptions,
} from "../../../../test-utils";
import { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { MediaPreviewValue } from "../../../../../src/@types/media_preview";
jest.mock("matrix-encrypt-attachment", () => ({
decryptAttachment: jest.fn(),
}));
describe("<MImageBody/>", () => {
const ourUserId = "@user:server";
const senderUserId = "@other_use:server";
const deviceId = "DEADB33F";
const cli = getMockClientWithEventEmitter({
...mockClientMethodsUser(ourUserId),
...mockClientMethodsServer(),
...mockClientMethodsDevice(deviceId),
...mockClientMethodsCrypto(),
getRooms: jest.fn().mockReturnValue([]),
getRoom: jest.fn(),
getIgnoredUsers: jest.fn(),
getVersions: jest.fn().mockResolvedValue({
unstable_features: {
"org.matrix.msc3882": true,
"org.matrix.msc3886": true,
},
}),
});
const url = "https://server/_matrix/media/v3/download/server/encrypted-image";
// 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 encryptedMediaEvent = new MatrixEvent({
event_id: "$foo:bar",
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
content: {
body: "alt for a test image",
info: {
w: 40,
h: 50,
mimetype: "image/png",
},
file: {
url: "mxc://server/encrypted-image",
},
},
});
const props = {
onMessageAllowed: jest.fn(),
permalinkCreator: new RoomPermalinkCreator(new Room(encryptedMediaEvent.getRoomId()!, cli, cli.getUserId()!)),
};
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
fetchMock.mockReset();
});
afterEach(() => {
SettingsStore.reset();
mocked(encrypt.decryptAttachment).mockReset();
});
it("should show a thumbnail while image is being downloaded", async () => {
fetchMock.getOnce(url, { status: 200 });
const { container } = render(
<MImageBody
{...props}
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
// thumbnail with dimensions present
expect(container).toMatchSnapshot();
});
it("should show error when encrypted media cannot be downloaded", async () => {
fetchMock.getOnce(url, { status: 500 });
render(
<MImageBody
{...props}
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
expect(fetchMock).toHaveFetched(url);
await screen.findByText("Error downloading image");
});
it("should show error when encrypted media cannot be decrypted", async () => {
fetchMock.getOnce(url, "thisistotallyanencryptedpng");
mocked(encrypt.decryptAttachment).mockRejectedValue(new Error("Failed to decrypt"));
render(
<MImageBody
{...props}
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
await screen.findByText("Error decrypting image");
});
describe("with image previews/thumbnails disabled", () => {
beforeEach(() => {
const origFn = SettingsStore.getValue;
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => {
if (setting === "mediaPreviewConfig") {
return { invite_avatars: MediaPreviewValue.Off, media_previews: MediaPreviewValue.Off };
}
return origFn(setting, ...args);
});
});
it("should not download image", async () => {
fetchMock.getOnce(url, { status: 200 });
render(
<MImageBody
{...props}
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
expect(screen.getByText("Show image")).toBeInTheDocument();
expect(fetchMock).toHaveFetchedTimes(0, url);
});
it("should render hidden image placeholder", async () => {
fetchMock.getOnce(url, { status: 200 });
render(
<MImageBody
{...props}
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
expect(screen.getByText("Show image")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button"));
expect(fetchMock).toHaveFetched(url);
// Show image is asynchronous since it applies through a settings watcher hook, so
// be sure to wait here.
await waitFor(() => {
// spinner while downloading image
expect(screen.getByRole("progressbar")).toBeInTheDocument();
});
});
});
it("should fall back to /download/ if /thumbnail/ fails", async () => {
const thumbUrl = "https://server/_matrix/media/v3/thumbnail/server/image?width=800&height=600&method=scale";
const downloadUrl = "https://server/_matrix/media/v3/download/server/image";
const event = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
content: {
body: "alt for a test image",
info: {
w: 40,
h: 50,
},
url: "mxc://server/image",
},
});
const { container } = render(
<MImageBody {...props} mxEvent={event} mediaEventHelper={new MediaEventHelper(event)} />,
withClientContextRenderOptions(cli),
);
const img = container.querySelector(".mx_MImageBody_thumbnail")!;
expect(img).toHaveProperty("src", thumbUrl);
fireEvent.error(img);
expect(img).toHaveProperty("src", downloadUrl);
});
it("should generate a thumbnail if one isn't included for animated media", async () => {
Object.defineProperty(global.Image.prototype, "src", {
set(src) {
window.setTimeout(() => this.onload?.());
},
});
Object.defineProperty(global.Image.prototype, "height", {
get() {
return 600;
},
});
Object.defineProperty(global.Image.prototype, "width", {
get() {
return 800;
},
});
mocked(global.URL.createObjectURL).mockReturnValue("blob:generated-thumb");
fetchMock.getOnce("https://server/_matrix/media/v3/download/server/image", {
body: fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "images", "animated-logo.webp")),
});
const event = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
content: {
body: "alt for a test image",
info: {
w: 40,
h: 50,
mimetype: "image/webp",
},
url: "mxc://server/image",
},
});
const { container } = render(
<MImageBody {...props} mxEvent={event} mediaEventHelper={new MediaEventHelper(event)} />,
withClientContextRenderOptions(cli),
);
// Wait for spinners to go away
await waitForElementToBeRemoved(screen.getAllByRole("progressbar"));
// thumbnail with dimensions present
expect(container).toMatchSnapshot();
});
it("should show banner on hover", async () => {
const event = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
content: {
body: "alt for a test image",
info: {
w: 40,
h: 50,
},
url: "mxc://server/image",
},
});
const { container } = render(
<MImageBody {...props} mxEvent={event} mediaEventHelper={new MediaEventHelper(event)} />,
withClientContextRenderOptions(cli),
);
const img = container.querySelector(".mx_MImageBody_thumbnail")!;
await userEvent.hover(img);
expect(container.querySelector(".mx_MImageBody_banner")).toHaveTextContent("...alt for a test image");
});
it("should render MFileBody for svg with no thumbnail", async () => {
const event = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
content: {
info: {
w: 40,
h: 50,
mimetype: "image/svg+xml",
},
file: {
url: "mxc://server/encrypted-svg",
},
},
});
const { container, asFragment } = render(
<MImageBody {...props} mxEvent={event} mediaEventHelper={new MediaEventHelper(event)} />,
withClientContextRenderOptions(cli),
);
expect(container.querySelector(".mx_MFileBody")).toHaveTextContent("Attachment");
expect(asFragment()).toMatchSnapshot();
});
it("should open ImageView using thumbnail for encrypted svg", async () => {
const url = "https://server/_matrix/media/v3/download/server/encrypted-svg";
fetchMock.getOnce(url, { status: 200 });
const thumbUrl = "https://server/_matrix/media/v3/download/server/svg-thumbnail";
fetchMock.getOnce(thumbUrl, { status: 200 });
const event = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
origin_server_ts: 1234567890,
content: {
info: {
w: 40,
h: 50,
mimetype: "image/svg+xml",
thumbnail_file: {
url: "mxc://server/svg-thumbnail",
},
thumbnail_info: { mimetype: "image/png" },
},
file: {
url: "mxc://server/encrypted-svg",
},
},
});
const mediaEventHelper = new MediaEventHelper(event);
mediaEventHelper.thumbnailUrl["prom"] = Promise.resolve(thumbUrl);
mediaEventHelper.sourceUrl["prom"] = Promise.resolve(url);
const { findByRole } = render(
<MImageBody {...props} mxEvent={event} mediaEventHelper={mediaEventHelper} />,
withClientContextRenderOptions(cli),
);
fireEvent.click(await findByRole("link"));
const dialog = await screen.findByRole("dialog");
await expect(within(dialog).findByRole("img")).resolves.toHaveAttribute(
"src",
"https://server/_matrix/media/v3/download/server/svg-thumbnail",
);
expect(dialog).toMatchSnapshot();
});
});
@@ -0,0 +1,91 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 from "react";
import { type RenderResult, render } from "jest-matrix-react";
import { type MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
import MKeyVerificationRequest from "../../../../../src/components/views/messages/MKeyVerificationRequest";
import TileErrorBoundary from "../../../../../src/components/views/messages/TileErrorBoundary";
import { Layout } from "../../../../../src/settings/enums/Layout";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import { filterConsole } from "../../../../test-utils";
describe("MKeyVerificationRequest", () => {
filterConsole(
"The above error occurred in the <MKeyVerificationRequest> component",
"Error: Attempting to render verification request without a client context!",
"Error: Verification request did not include a sender!",
"Error: Verification request did not include a room ID!",
);
it("shows an error if not wrapped in a client context", () => {
const event = new MatrixEvent({ type: "m.key.verification.request" });
const { container } = renderEventNoClient(event);
expect(container).toHaveTextContent("Can't load this message");
});
it("shows an error if the event has no sender", () => {
const { client } = setup();
const event = new MatrixEvent({ type: "m.key.verification.request" });
const { container } = renderEvent(client, event);
expect(container).toHaveTextContent("Can't load this message");
});
it("shows an error if the event has no room", () => {
const { client } = setup();
const event = new MatrixEvent({ type: "m.key.verification.request", sender: "@a:b.co" });
const { container } = renderEvent(client, event);
expect(container).toHaveTextContent("Can't load this message");
});
it("displays a request from me", () => {
const { client, myUserId } = setup();
const event = new MatrixEvent({ type: "m.key.verification.request", sender: myUserId, room_id: "!x:y.co" });
const { container } = renderEvent(client, event);
expect(container).toHaveTextContent("You sent a verification request");
});
it("displays a request from someone else to me", () => {
const otherUserId = "@other:s.uk";
const { client } = setup();
const event = new MatrixEvent({ type: "m.key.verification.request", sender: otherUserId, room_id: "!x:y.co" });
const { container } = renderEvent(client, event);
expect(container).toHaveTextContent("other:s.uk wants to verify");
});
});
function renderEventNoClient(event: MatrixEvent): RenderResult {
return render(
<TileErrorBoundary mxEvent={event} layout={Layout.Group}>
<MKeyVerificationRequest mxEvent={event} />
</TileErrorBoundary>,
);
}
function renderEvent(client: MatrixClient, event: MatrixEvent): RenderResult {
return render(
<TileErrorBoundary mxEvent={event} layout={Layout.Group}>
<MatrixClientContext.Provider value={client}>
<MKeyVerificationRequest mxEvent={event} />
</MatrixClientContext.Provider>
,
</TileErrorBoundary>,
);
}
function setup(): { client: MatrixClient; myUserId: string } {
const myUserId = "@me:s.co";
const client = {
getSafeUserId: jest.fn().mockReturnValue(myUserId),
getRoom: jest.fn(),
} as unknown as MatrixClient;
return { client, myUserId };
}
@@ -0,0 +1,161 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 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 from "react";
import { fireEvent, render, waitFor } from "jest-matrix-react";
import { LocationAssetType, ClientEvent, RoomMember, SyncState } from "matrix-js-sdk/src/matrix";
import * as maplibregl from "maplibre-gl";
import { logger } from "matrix-js-sdk/src/logger";
import { sleep } from "matrix-js-sdk/src/utils";
import MLocationBody from "../../../../../src/components/views/messages/MLocationBody";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import { type RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import { type MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import Modal from "../../../../../src/Modal";
import SdkConfig from "../../../../../src/SdkConfig";
import { TILE_SERVER_WK_KEY } from "../../../../../src/utils/WellKnownUtils";
import { makeLocationEvent } from "../../../../test-utils/location";
import { getMockClientWithEventEmitter } from "../../../../test-utils";
describe("MLocationBody", () => {
const mapOptions = { container: {} as unknown as HTMLElement, style: "" };
describe("<MLocationBody>", () => {
const roomId = "!room:server";
const userId = "@user:server";
const mockClient = getMockClientWithEventEmitter({
getClientWellKnown: jest.fn().mockReturnValue({
[TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" },
}),
isGuest: jest.fn().mockReturnValue(false),
});
const defaultEvent = makeLocationEvent("geo:51.5076,-0.1276", LocationAssetType.Pin);
const defaultProps: MLocationBody["props"] = {
mxEvent: defaultEvent,
highlights: [],
highlightLink: "",
onMessageAllowed: jest.fn(),
permalinkCreator: {} as RoomPermalinkCreator,
mediaEventHelper: {} as MediaEventHelper,
};
const getComponent = (props = {}) =>
render(
<MatrixClientContext.Provider value={mockClient}>
<MLocationBody {...defaultProps} {...props} />
</MatrixClientContext.Provider>,
);
const getMapErrorComponent = () => {
const mockMap = new maplibregl.Map(mapOptions);
mockClient.getClientWellKnown.mockReturnValue({
[TILE_SERVER_WK_KEY.name]: { map_style_url: "bad-tile-server.com" },
});
const component = getComponent();
sleep(10).then(() => {
// simulate error initialising map in maplibregl
// @ts-ignore
mockMap.emit("error", { status: 404 });
});
return component;
};
beforeEach(() => {
jest.clearAllMocks();
});
describe("with error", () => {
let sdkConfigSpy: jest.SpyInstance<any>;
beforeEach(() => {
// eat expected errors to keep console clean
jest.spyOn(logger, "error").mockImplementation(() => {});
mockClient.getClientWellKnown.mockReturnValue({});
sdkConfigSpy = jest.spyOn(SdkConfig, "get").mockReturnValue({});
});
afterAll(() => {
sdkConfigSpy.mockRestore();
jest.spyOn(logger, "error").mockRestore();
});
it("displays correct fallback content without error style when map_style_url is not configured", async () => {
const component = getComponent();
// The map code needs to be lazy loaded so this will take some time to appear
await waitFor(() =>
expect(component.container.querySelector(".mx_EventTile_body")).toBeInTheDocument(),
);
expect(component.container.querySelector(".mx_EventTile_body")).toMatchSnapshot();
});
it("displays correct fallback content when map_style_url is misconfigured", async () => {
const component = getMapErrorComponent();
await waitFor(() => expect(component.container.querySelector(".mx_EventTile_body")).toBeTruthy());
await waitFor(() => expect(component.container.querySelector(".mx_EventTile_body")).toMatchSnapshot());
});
it("should clear the error on reconnect", () => {
const component = getMapErrorComponent();
expect(component.container.querySelector(".mx_EventTile_tileError")).toBeDefined();
mockClient.emit(ClientEvent.Sync, SyncState.Reconnecting, SyncState.Error);
expect(component.container.querySelector(".mx_EventTile_tileError")).toBeFalsy();
});
});
describe("without error", () => {
beforeEach(() => {
mockClient.getClientWellKnown.mockReturnValue({
[TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" },
});
// MLocationBody uses random number for map id
// stabilise for test
jest.spyOn(global.Math, "random").mockReturnValue(0.123456);
});
afterAll(() => {
jest.spyOn(global.Math, "random").mockRestore();
});
it("renders map correctly", () => {
const mockMap = new maplibregl.Map(mapOptions);
const component = getComponent();
expect(component.asFragment()).toMatchSnapshot();
// map was centered
expect(mockMap.setCenter).toHaveBeenCalledWith({
lat: 51.5076,
lon: -0.1276,
});
});
it("opens map dialog on click", async () => {
const modalSpy = jest
.spyOn(Modal, "createDialog")
.mockReturnValue({ finished: new Promise(() => {}), close: jest.fn() });
const component = getComponent();
await fireEvent.click(component.container.querySelector(".mx_Map")!);
expect(modalSpy).toHaveBeenCalled();
});
it("renders marker correctly for a self share", () => {
const selfShareEvent = makeLocationEvent("geo:51.5076,-0.1276", LocationAssetType.Self);
const member = new RoomMember(roomId, userId);
// @ts-ignore cheat assignment to property
selfShareEvent.sender = member;
const component = getComponent({ mxEvent: selfShareEvent });
// render self locations with user avatars
expect(component.asFragment()).toMatchSnapshot();
});
});
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,87 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2023 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 from "react";
import { render, screen } from "jest-matrix-react";
import { EventType, getHttpUriForMxc, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import fetchMock from "@fetch-mock/jest";
import userEvent from "@testing-library/user-event";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import {
getMockClientWithEventEmitter,
mockClientMethodsCrypto,
mockClientMethodsDevice,
mockClientMethodsServer,
mockClientMethodsUser,
withClientContextRenderOptions,
} from "../../../../test-utils";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import MStickerBody from "../../../../../src/components/views/messages/MStickerBody";
describe("<MStickerBody/>", () => {
const userId = "@user:server";
const deviceId = "DEADB33F";
const cli = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
...mockClientMethodsDevice(deviceId),
...mockClientMethodsCrypto(),
getRoom: jest.fn(),
getRooms: jest.fn().mockReturnValue([]),
getIgnoredUsers: jest.fn(),
getVersions: jest.fn().mockResolvedValue({
unstable_features: {
"org.matrix.msc3882": true,
"org.matrix.msc3886": true,
},
}),
});
const url = "https://server/_matrix/media/v3/download/server/sticker";
// 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: "sticker description",
info: {
w: 40,
h: 50,
},
file: {
url: "mxc://server/sticker",
},
},
});
const props = {
onMessageAllowed: jest.fn(),
permalinkCreator: new RoomPermalinkCreator(new Room(mediaEvent.getRoomId()!, cli, cli.getUserId()!)),
};
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
fetchMock.mockReset();
});
it("should show a tooltip on hover", async () => {
fetchMock.getOnce(url, { status: 200 });
render(<MStickerBody {...props} mxEvent={mediaEvent} />, withClientContextRenderOptions(cli));
expect(screen.queryByRole("tooltip")).toBeNull();
await userEvent.hover(screen.getByRole("img"));
await expect(screen.findByRole("tooltip")).resolves.toHaveTextContent("sticker description");
});
});
@@ -0,0 +1,229 @@
/*
Copyright 2024, 2025 New Vector Ltd.
Copyright 2022 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 from "react";
import { EventType, getHttpUriForMxc, type IContent, type MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { fireEvent, render, screen } from "jest-matrix-react";
import fetchMock from "@fetch-mock/jest";
import { type MockedObject } from "jest-mock";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import { type RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import {
getMockClientWithEventEmitter,
mockClientMethodsCrypto,
mockClientMethodsDevice,
mockClientMethodsServer,
mockClientMethodsUser,
withClientContextRenderOptions,
} from "../../../../test-utils";
import MVideoBody from "../../../../../src/components/views/messages/MVideoBody";
import type { IBodyProps } from "../../../../../src/components/views/messages/IBodyProps";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { MediaPreviewValue } from "../../../../../src/@types/media_preview";
// Needed so we don't throw an error about failing to decrypt.
jest.mock("matrix-encrypt-attachment", () => ({
decryptAttachment: jest.fn(),
}));
describe("MVideoBody", () => {
const ourUserId = "@user:server";
const senderUserId = "@other_use:server";
const deviceId = "DEADB33F";
const thumbUrl = "https://server/_matrix/media/v3/download/server/encrypted-poster";
let cli: MockedObject<MatrixClient>;
beforeEach(() => {
cli = getMockClientWithEventEmitter({
...mockClientMethodsUser(ourUserId),
...mockClientMethodsServer(),
...mockClientMethodsDevice(deviceId),
...mockClientMethodsCrypto(),
getRoom: jest.fn(),
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);
},
);
fetchMock.mockReset();
});
const encryptedMediaEvent = new MatrixEvent({
room_id: "!room:server",
sender: senderUserId,
type: EventType.RoomMessage,
event_id: "$foo:bar",
content: {
body: "alt for a test video",
info: {
duration: 420,
w: 40,
h: 50,
thumbnail_file: {
url: "mxc://server/encrypted-poster",
},
},
file: {
url: "mxc://server/encrypted-image",
},
},
});
it("does not crash when given portrait dimensions", () => {
// Check for an unreliable crash caused by a fractional-sized
// image dimension being used for a CanvasImageData.
const content: IContent = {
info: {
"w": 720,
"h": 1280,
"mimetype": "video/mp4",
"size": 2495675,
"thumbnail_file": {
url: "",
key: { alg: "", key_ops: [], kty: "", k: "", ext: true },
iv: "",
hashes: {},
v: "",
},
"thumbnail_info": { mimetype: "" },
"xyz.amorgan.blurhash": "TrGl6bofof~paxWC?bj[oL%2fPj]",
},
url: "http://example.com",
};
const event = new MatrixEvent({
content,
});
const defaultProps: IBodyProps = {
mxEvent: event,
highlights: [],
highlightLink: "",
onMessageAllowed: jest.fn(),
permalinkCreator: {} as RoomPermalinkCreator,
mediaEventHelper: { media: { isEncrypted: false } } as MediaEventHelper,
};
const { asFragment } = render(
<MatrixClientContext.Provider value={cli}>
<MVideoBody {...defaultProps} />
</MatrixClientContext.Provider>,
withClientContextRenderOptions(cli),
);
expect(asFragment()).toMatchSnapshot();
// If we get here, we did not crash.
});
it("should show poster for encrypted media before downloading it", async () => {
fetchMock.getOnce(thumbUrl, { status: 200 });
const { asFragment } = render(
<MVideoBody mxEvent={encryptedMediaEvent} mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)} />,
withClientContextRenderOptions(cli),
);
expect(asFragment()).toMatchSnapshot();
});
describe("with video previews/thumbnails disabled", () => {
beforeEach(() => {
const origFn = SettingsStore.getValue;
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => {
if (setting === "mediaPreviewConfig") {
return { invite_avatars: MediaPreviewValue.Off, media_previews: MediaPreviewValue.Off };
}
return origFn(setting, ...args);
});
});
afterEach(() => {
SettingsStore.reset();
jest.restoreAllMocks();
});
it("should not download video", async () => {
fetchMock.getOnce(thumbUrl, { status: 200 });
render(
<MVideoBody
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
expect(screen.getByText("Show video")).toBeInTheDocument();
expect(fetchMock).toHaveFetchedTimes(0, thumbUrl);
});
it("should render video poster after user consent", async () => {
fetchMock.getOnce(thumbUrl, { status: 200 });
render(
<MVideoBody
mxEvent={encryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(encryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
const placeholderButton = screen.getByRole("button", { name: "Show video" });
expect(placeholderButton).toBeInTheDocument();
fireEvent.click(placeholderButton);
expect(fetchMock).toHaveFetched(thumbUrl);
});
it("should download video if we were the sender", async () => {
fetchMock.getOnce(thumbUrl, { status: 200 });
const ourEncryptedMediaEvent = new MatrixEvent({
room_id: "!room:server",
sender: ourUserId,
type: EventType.RoomMessage,
event_id: "$foo:bar",
content: {
body: "alt for a test video",
info: {
duration: 420,
w: 40,
h: 50,
thumbnail_file: {
url: "mxc://server/encrypted-poster",
},
},
file: {
url: "mxc://server/encrypted-image",
},
},
});
const { asFragment } = render(
<MVideoBody
mxEvent={ourEncryptedMediaEvent}
mediaEventHelper={new MediaEventHelper(ourEncryptedMediaEvent)}
/>,
withClientContextRenderOptions(cli),
);
expect(fetchMock).toHaveFetched(thumbUrl);
expect(asFragment()).toMatchSnapshot();
});
});
});
@@ -0,0 +1,59 @@
/*
* Copyright 2025 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 { EventType, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { act, render, screen } from "jest-matrix-react";
import React from "react";
import { MockedPlayback } from "../../../audio/MockedPlayback";
import { type Playback, PlaybackState } from "../../../../../src/audio/Playback";
import { PlaybackManager } from "../../../../../src/audio/PlaybackManager";
import type { MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
import MVoiceMessageBody from "../../../../../src/components/views/messages/MVoiceMessageBody";
import { PlaybackQueue } from "../../../../../src/audio/PlaybackQueue";
import { createTestClient } from "../../../../test-utils";
import { SdkContextClass } from "../../../../../src/contexts/SDKContext";
describe("<MVvoiceMessageBody />", () => {
let event: MatrixEvent;
beforeEach(() => {
const playback = new MockedPlayback(PlaybackState.Decoding, 50, 10) as unknown as Playback;
jest.spyOn(PlaybackManager.instance, "createPlaybackInstance").mockReturnValue(playback);
const matrixClient = createTestClient();
const room = new Room("!TESTROOM", matrixClient, "@alice:example.org");
const playbackQueue = new PlaybackQueue(room, SdkContextClass.instance.roomViewStore);
jest.spyOn(PlaybackQueue, "forRoom").mockReturnValue(playbackQueue);
jest.spyOn(playbackQueue, "unsortedEnqueue").mockReturnValue(undefined);
event = new MatrixEvent({
room_id: "!room:server",
sender: "@alice.example.org",
type: EventType.RoomMessage,
content: {
"body": "audio name ",
"msgtype": "m.audio",
"url": "mxc://server/audio",
"org.matrix.msc3946.voice": true,
},
});
});
it("should render", async () => {
const mediaEventHelper = {
sourceBlob: {
value: {
arrayBuffer: () => new ArrayBuffer(8),
},
},
} as unknown as MediaEventHelper;
await act(() => render(<MVoiceMessageBody mxEvent={event} mediaEventHelper={mediaEventHelper} />));
expect(await screen.findByTestId("recording-playback")).toBeInTheDocument();
});
});
@@ -0,0 +1,564 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022, 2023 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 from "react";
import { act, render, fireEvent, screen, waitFor } from "jest-matrix-react";
import {
EventType,
EventStatus,
MatrixEvent,
MatrixEventEvent,
MsgType,
Room,
FeatureSupport,
Thread,
EventTimeline,
RoomStateEvent,
} from "matrix-js-sdk/src/matrix";
import MessageActionBar from "../../../../../src/components/views/messages/MessageActionBar";
import {
getMockClientWithEventEmitter,
mockClientMethodsUser,
mockClientMethodsEvents,
makeBeaconInfoEvent,
} from "../../../../test-utils";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import RoomContext, { type RoomContextType, TimelineRenderingType } from "../../../../../src/contexts/RoomContext";
import dispatcher from "../../../../../src/dispatcher/dispatcher";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { Action } from "../../../../../src/dispatcher/actions";
import PinningUtils from "../../../../../src/utils/PinningUtils";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext.tsx";
jest.mock("../../../../../src/dispatcher/dispatcher");
describe("<MessageActionBar />", () => {
const userId = "@alice:server.org";
const roomId = "!room:server.org";
const client = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsEvents(),
getRoom: jest.fn(),
setRoomAccountData: jest.fn(),
sendStateEvent: jest.fn(),
});
const room = new Room(roomId, client, userId);
const alicesMessageEvent = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "Hello",
},
event_id: "$alices_message",
});
const bobsMessageEvent = new MatrixEvent({
type: EventType.RoomMessage,
sender: "@bob:server.org",
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "I am bob",
},
event_id: "$bobs_message",
});
const redactedEvent = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
});
redactedEvent.makeRedacted(redactedEvent, room);
const localStorageMock = (() => {
let store: Record<string, any> = {};
return {
getItem: jest.fn().mockImplementation((key) => store[key] ?? null),
setItem: jest.fn().mockImplementation((key, value) => {
store[key] = value;
}),
clear: jest.fn().mockImplementation(() => {
store = {};
}),
removeItem: jest.fn().mockImplementation((key) => delete store[key]),
};
})();
Object.defineProperty(window, "localStorage", {
value: localStorageMock,
writable: true,
});
jest.spyOn(room, "getPendingEvents").mockReturnValue([]);
client.getRoom.mockReturnValue(room);
const defaultProps = {
getTile: jest.fn(),
getReplyChain: jest.fn(),
toggleThreadExpanded: jest.fn(),
mxEvent: alicesMessageEvent,
permalinkCreator: new RoomPermalinkCreator(room),
};
const defaultRoomContext = {
...RoomContext,
timelineRenderingType: TimelineRenderingType.Room,
canSendMessages: true,
canReact: true,
room,
} as unknown as RoomContextType;
const getComponent = (props = {}, roomContext: Partial<RoomContextType> = {}) =>
render(
<ScopedRoomContextProvider {...defaultRoomContext} {...roomContext}>
<MessageActionBar {...defaultProps} {...props} />
</ScopedRoomContextProvider>,
);
beforeEach(() => {
jest.clearAllMocks();
// The base case is that we have received the remote echo and have an eventId. No sending status.
alicesMessageEvent.setStatus(null);
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
});
afterAll(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
jest.spyOn(SettingsStore, "setValue").mockRestore();
});
it("kills event listeners on unmount", () => {
const offSpy = jest.spyOn(alicesMessageEvent, "off").mockClear();
const wrapper = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
wrapper.unmount();
});
expect(offSpy.mock.calls[0][0]).toEqual(MatrixEventEvent.Status);
expect(offSpy.mock.calls[1][0]).toEqual(MatrixEventEvent.Decrypted);
expect(offSpy.mock.calls[2][0]).toEqual(MatrixEventEvent.BeforeRedaction);
expect(client.decryptEventIfNeeded).toHaveBeenCalled();
});
describe("decryption", () => {
it("decrypts event if needed", () => {
getComponent({ mxEvent: alicesMessageEvent });
expect(client.decryptEventIfNeeded).toHaveBeenCalled();
});
it("updates component on decrypted event", () => {
const decryptingEvent = new MatrixEvent({
type: EventType.RoomMessageEncrypted,
sender: userId,
room_id: roomId,
content: {},
});
jest.spyOn(decryptingEvent, "isBeingDecrypted").mockReturnValue(true);
const { queryByLabelText } = getComponent({ mxEvent: decryptingEvent });
// still encrypted event is not actionable => no reply button
expect(queryByLabelText("Reply")).toBeFalsy();
act(() => {
// ''decrypt'' the event
decryptingEvent.event.type = alicesMessageEvent.getType();
decryptingEvent.event.content = alicesMessageEvent.getContent();
decryptingEvent.emit(MatrixEventEvent.Decrypted, decryptingEvent);
});
// new available actions after decryption
expect(queryByLabelText("Reply")).toBeTruthy();
});
});
describe("status", () => {
it("updates component when event status changes", () => {
alicesMessageEvent.setStatus(EventStatus.QUEUED);
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
// pending event status, cancel action available
expect(queryByLabelText("Delete")).toBeTruthy();
act(() => {
alicesMessageEvent.setStatus(EventStatus.SENT);
});
// event is sent, no longer cancelable
expect(queryByLabelText("Delete")).toBeFalsy();
});
});
describe("redaction", () => {
// this doesn't do what it's supposed to
// because beforeRedaction event is fired... before redaction
// event is unchanged at point when this component updates
// TODO file bug
it.skip("updates component on before redaction event", () => {
const event = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "Hello",
},
});
const { queryByLabelText } = getComponent({ mxEvent: event });
// no pending redaction => no delete button
expect(queryByLabelText("Delete")).toBeFalsy();
act(() => {
const redactionEvent = new MatrixEvent({
type: EventType.RoomRedaction,
sender: userId,
room_id: roomId,
});
redactionEvent.setStatus(EventStatus.QUEUED);
event.markLocallyRedacted(redactionEvent);
});
// updated with local redaction event, delete now available
expect(queryByLabelText("Delete")).toBeTruthy();
});
});
describe("options button", () => {
it("renders options menu", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Options")).toBeTruthy();
});
it("opens message context menu on click", () => {
const { getByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent.click(queryByLabelText("Options")!);
expect(getByTestId("mx_MessageContextMenu")).toBeTruthy();
});
});
describe("reply button", () => {
it("renders reply button on own actionable event", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Reply")).toBeTruthy();
});
it("renders reply button on others actionable event", () => {
const { queryByLabelText } = getComponent({ mxEvent: bobsMessageEvent }, { canSendMessages: true });
expect(queryByLabelText("Reply")).toBeTruthy();
});
it("does not render reply button on non-actionable event", () => {
// redacted event is not actionable
const { queryByLabelText } = getComponent({ mxEvent: redactedEvent });
expect(queryByLabelText("Reply")).toBeFalsy();
});
it("does not render reply button when user cannot send messaged", () => {
// redacted event is not actionable
const { queryByLabelText } = getComponent({ mxEvent: redactedEvent }, { canSendMessages: false });
expect(queryByLabelText("Reply")).toBeFalsy();
});
it("dispatches reply event on click", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent.click(queryByLabelText("Reply")!);
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: "reply_to_event",
event: alicesMessageEvent,
context: TimelineRenderingType.Room,
});
});
});
describe("react button", () => {
it("renders react button on own actionable event", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("React")).toBeTruthy();
});
it("renders react button on others actionable event", () => {
const { queryByLabelText } = getComponent({ mxEvent: bobsMessageEvent });
expect(queryByLabelText("React")).toBeTruthy();
});
it("does not render react button on non-actionable event", () => {
// redacted event is not actionable
const { queryByLabelText } = getComponent({ mxEvent: redactedEvent });
expect(queryByLabelText("React")).toBeFalsy();
});
it("does not render react button when user cannot react", () => {
// redacted event is not actionable
const { queryByLabelText } = getComponent({ mxEvent: redactedEvent }, { canReact: false });
expect(queryByLabelText("React")).toBeFalsy();
});
it("opens reaction picker on click", () => {
const { queryByLabelText, getByTestId } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent.click(queryByLabelText("React")!);
expect(getByTestId("mx_EmojiPicker")).toBeTruthy();
});
});
describe("cancel button", () => {
it("renders cancel button for an event with a cancelable status", () => {
alicesMessageEvent.setStatus(EventStatus.QUEUED);
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Delete")).toBeTruthy();
});
it("renders cancel button for an event with a pending edit", () => {
const event = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "Hello",
},
});
event.setStatus(EventStatus.SENT);
const replacingEvent = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "replacing event body",
},
});
replacingEvent.setStatus(EventStatus.QUEUED);
event.makeReplaced(replacingEvent);
const { queryByLabelText } = getComponent({ mxEvent: event });
expect(queryByLabelText("Delete")).toBeTruthy();
});
it("renders cancel button for an event with a pending redaction", () => {
const event = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "Hello",
},
});
event.setStatus(EventStatus.SENT);
const redactionEvent = new MatrixEvent({
type: EventType.RoomRedaction,
sender: userId,
room_id: roomId,
});
redactionEvent.setStatus(EventStatus.QUEUED);
event.markLocallyRedacted(redactionEvent);
const { queryByLabelText } = getComponent({ mxEvent: event });
expect(queryByLabelText("Delete")).toBeTruthy();
});
it("renders cancel and retry button for an event with NOT_SENT status", () => {
alicesMessageEvent.setStatus(EventStatus.NOT_SENT);
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Retry")).toBeTruthy();
expect(queryByLabelText("Delete")).toBeTruthy();
});
it("only shows retry and delete buttons when event could not be sent", () => {
// Enable pin and other features
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
alicesMessageEvent.setStatus(EventStatus.NOT_SENT);
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
// Should show retry and cancel buttons
expect(queryByLabelText("Retry")).toBeTruthy();
expect(queryByLabelText("Delete")).toBeTruthy();
// Should NOT show edit, pin, react, reply buttons
expect(queryByLabelText("Edit")).toBeFalsy();
expect(queryByLabelText("Pin")).toBeFalsy();
expect(queryByLabelText("React")).toBeFalsy();
expect(queryByLabelText("Reply")).toBeFalsy();
expect(queryByLabelText("Reply in thread")).toBeFalsy();
});
it.todo("unsends event on cancel click");
it.todo("retrys event on retry click");
});
describe("thread button", () => {
beforeEach(() => {
Thread.setServerSideSupport(FeatureSupport.Stable);
});
describe("when threads feature is enabled", () => {
it("renders thread button on own actionable event", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Reply in thread")).toBeTruthy();
});
it("does not render thread button for a beacon_info event", () => {
const beaconInfoEvent = makeBeaconInfoEvent(userId, roomId);
const { queryByLabelText } = getComponent({ mxEvent: beaconInfoEvent });
expect(queryByLabelText("Reply in thread")).toBeFalsy();
});
it("opens thread on click", () => {
const { getByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent.click(getByLabelText("Reply in thread"));
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ShowThread,
rootEvent: alicesMessageEvent,
push: false,
});
});
it("opens parent thread for a thread reply message", () => {
const threadReplyEvent = new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
msgtype: MsgType.Text,
body: "this is a thread reply",
},
});
// mock the thread stuff
jest.spyOn(threadReplyEvent, "isThreadRoot", "get").mockReturnValue(false);
// set alicesMessageEvent as the root event
jest.spyOn(threadReplyEvent, "getThread").mockReturnValue({
rootEvent: alicesMessageEvent,
} as unknown as Thread);
const { getByLabelText } = getComponent({ mxEvent: threadReplyEvent });
fireEvent.click(getByLabelText("Reply in thread"));
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ShowThread,
rootEvent: alicesMessageEvent,
initialEvent: threadReplyEvent,
highlighted: true,
scroll_into_view: true,
push: false,
});
});
});
});
it.each([["React"], ["Reply"], ["Reply in thread"], ["Edit"], ["Pin"]])(
"does not show context menu when right-clicking",
(buttonLabel: string) => {
// For favourite and pin buttons
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
const event = new MouseEvent("contextmenu", {
bubbles: true,
cancelable: true,
});
event.stopPropagation = jest.fn();
event.preventDefault = jest.fn();
const { queryByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent(queryByLabelText(buttonLabel)!, event);
expect(event.stopPropagation).toHaveBeenCalled();
expect(event.preventDefault).toHaveBeenCalled();
expect(queryByTestId("mx_MessageContextMenu")).toBeFalsy();
},
);
it("does shows context menu when right-clicking options", () => {
const { queryByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
fireEvent.contextMenu(queryByLabelText("Options")!);
expect(queryByTestId("mx_MessageContextMenu")).toBeTruthy();
});
describe("pin button", () => {
beforeEach(() => {
// enable pin button
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
jest.spyOn(PinningUtils, "isPinned").mockReturnValue(false);
});
afterEach(() => {
jest.spyOn(
room.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
"mayClientSendStateEvent",
).mockRestore();
});
it("should not render pin button when user can't send state event", () => {
jest.spyOn(
room.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
"mayClientSendStateEvent",
).mockReturnValue(false);
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Pin")).toBeFalsy();
});
it("should render pin button", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
expect(queryByLabelText("Pin")).toBeTruthy();
});
it("should listen to room pinned events", async () => {
getComponent({ mxEvent: alicesMessageEvent });
expect(screen.getByLabelText("Pin")).toBeInTheDocument();
// Event is considered pinned
jest.spyOn(PinningUtils, "isPinned").mockReturnValue(true);
// Emit that the room pinned events have changed
const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;
roomState.emit(
RoomStateEvent.Events,
{
getType: () => EventType.RoomPinnedEvents,
} as MatrixEvent,
roomState,
null,
);
await waitFor(() => expect(screen.getByLabelText("Unpin")).toBeInTheDocument());
});
});
describe("expand/collapse quote buttons", () => {
it.each([
["expand", false],
["collapse", true],
])("should render %s", (state, value) => {
const { getByLabelText } = getComponent({
mxEvent: new MatrixEvent({
type: EventType.RoomMessage,
sender: userId,
room_id: roomId,
content: {
"msgtype": MsgType.Text,
"body": "Hello",
"m.relates_to": {
"m.in_reply_to": { event_id: alicesMessageEvent.getId() },
},
},
event_id: "$alices_reply",
}),
isQuoteExpanded: value,
});
expect(getByLabelText(`${state[0].toUpperCase()}${state.slice(1)} quotes`)).toBeInTheDocument();
});
});
});
@@ -0,0 +1,136 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 from "react";
import { render, type RenderResult } from "jest-matrix-react";
import { type MatrixClient, type MatrixEvent, EventType, type Room, MsgType } from "matrix-js-sdk/src/matrix";
import fetchMock from "@fetch-mock/jest";
import fs from "fs";
import path from "path";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { mkEvent, mkRoom, stubClient } from "../../../../test-utils";
import MessageEvent from "../../../../../src/components/views/messages/MessageEvent";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
jest.mock("../../../../../src/components/views/messages/UnknownBody", () => ({
__esModule: true,
default: () => <div data-testid="unknown-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MImageBody", () => ({
__esModule: true,
default: () => <div data-testid="image-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MVideoBody", () => ({
__esModule: true,
default: () => <div data-testid="video-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MFileBody", () => ({
__esModule: true,
default: () => <div data-testid="file-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MImageReplyBody", () => ({
__esModule: true,
default: () => <div data-testid="image-reply-body" />,
}));
jest.mock("../../../../../src/components/views/messages/MStickerBody", () => ({
__esModule: true,
default: () => <div data-testid="sticker-body" />,
}));
jest.mock("../../../../../src/components/views/messages/TextualBody.tsx", () => ({
__esModule: true,
default: () => <div data-testid="textual-body" />,
}));
describe("MessageEvent", () => {
let room: Room;
let client: MatrixClient;
let event: MatrixEvent;
const renderMessageEvent = (): RenderResult => {
return render(<MessageEvent mxEvent={event} permalinkCreator={new RoomPermalinkCreator(room)} />);
};
beforeEach(() => {
client = stubClient();
room = mkRoom(client, "!room:example.com");
jest.spyOn(SettingsStore, "getValue");
jest.spyOn(SettingsStore, "watchSetting");
jest.spyOn(SettingsStore, "unwatchSetting").mockImplementation(jest.fn());
});
describe("when an image with a caption is sent", () => {
let result: RenderResult;
function createEvent(mimetype: string, filename: string, msgtype: string) {
return mkEvent({
event: true,
type: EventType.RoomMessage,
user: client.getUserId()!,
room: room.roomId,
content: {
body: "caption for a test image",
format: "org.matrix.custom.html",
formatted_body: "<strong>caption for a test image</strong>",
msgtype: msgtype,
filename: filename,
info: {
w: 40,
h: 50,
mimetype: mimetype,
},
url: "mxc://server/image",
},
});
}
function mockMedia() {
fetchMock.getOnce("https://server/_matrix/media/v3/download/server/image", {
body: fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "images", "animated-logo.webp")),
});
}
it("should render a TextualBody and an ImageBody", () => {
event = createEvent("image/webp", "image.webp", MsgType.Image);
result = renderMessageEvent();
mockMedia();
result.getByTestId("image-body");
result.getByTestId("textual-body");
});
it("should render a TextualBody and a FileBody for mismatched extension", () => {
event = createEvent("image/webp", "image.exe", MsgType.Image);
result = renderMessageEvent();
mockMedia();
result.getByTestId("file-body");
result.getByTestId("textual-body");
});
it("should render a TextualBody and an VideoBody", () => {
event = createEvent("video/mp4", "video.mp4", MsgType.Video);
result = renderMessageEvent();
mockMedia();
result.getByTestId("video-body");
result.getByTestId("textual-body");
});
it("should render a TextualBody and a FileBody for non-video mimetype", () => {
event = createEvent("application/octet-stream", "video.mp4", MsgType.Video);
result = renderMessageEvent();
mockMedia();
result.getByTestId("file-body");
result.getByTestId("textual-body");
});
});
});
@@ -0,0 +1,18 @@
/*
* 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 { PinnedMessageBadge } from "../../../../../src/components/views/messages/PinnedMessageBadge.tsx";
describe("PinnedMessageBadge", () => {
it("should render", () => {
const { asFragment } = render(<PinnedMessageBadge />);
expect(asFragment()).toMatchSnapshot();
});
});
@@ -0,0 +1,546 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2023 Beeper
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 { EventType, type IContent, MatrixEvent, RelationType, Room } from "matrix-js-sdk/src/matrix";
import { fireEvent, render } from "jest-matrix-react";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import { getMockClientWithEventEmitter } from "../../../../test-utils";
import ReactionsRowButton, { type IProps } from "../../../../../src/components/views/messages/ReactionsRowButton";
import dis from "../../../../../src/dispatcher/dispatcher";
import { type Media, mediaFromMxc } from "../../../../../src/customisations/Media";
jest.mock("../../../../../src/dispatcher/dispatcher");
jest.mock("../../../../../src/customisations/Media", () => ({
mediaFromMxc: jest.fn(),
}));
jest.mock("@element-hq/web-shared-components", () => {
const actual = jest.requireActual("@element-hq/web-shared-components");
return {
...actual,
ReactionsRowButtonTooltipView: ({ children }: { children: React.ReactNode }) => <>{children}</>,
};
});
const mockMediaFromMxc = mediaFromMxc as jest.MockedFunction<typeof mediaFromMxc>;
describe("ReactionsRowButton", () => {
const userId = "@alice:server";
const roomId = "!randomcharacters:aser.ver";
const mockClient = getMockClientWithEventEmitter({
getRoom: jest.fn(),
sendEvent: jest.fn().mockResolvedValue({ event_id: "$sent_event" }),
redactEvent: jest.fn().mockResolvedValue({}),
});
const room = new Room(roomId, mockClient, userId);
const createProps = (relationContent: IContent): IProps => ({
mxEvent: new MatrixEvent({
room_id: roomId,
event_id: "$test:example.com",
content: { body: "test" },
}),
content: relationContent["m.relates_to"]?.key || "",
count: 2,
reactionEvents: [
new MatrixEvent({
type: "m.reaction",
sender: "@user1:example.com",
content: relationContent,
}),
new MatrixEvent({
type: "m.reaction",
sender: "@user2:example.com",
content: relationContent,
}),
],
customReactionImagesEnabled: true,
});
beforeEach(function () {
jest.clearAllMocks();
mockClient.credentials = { userId: userId };
mockClient.getRoom.mockImplementation((roomId: string): Room | null => {
return roomId === room.roomId ? room : null;
});
// Default mock for mediaFromMxc
mockMediaFromMxc.mockReturnValue({
srcHttp: "https://not.a.real.url",
} as unknown as Media);
});
it("renders reaction row button emojis correctly", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user2:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
expect(root.asFragment()).toMatchSnapshot();
// Try hover and make sure that the ReactionsRowButtonTooltip works
const reactionButton = root.getByRole("button");
const event = new MouseEvent("mouseover", {
bubbles: true,
cancelable: true,
});
reactionButton.dispatchEvent(event);
expect(root.asFragment()).toMatchSnapshot();
});
it("renders reaction row button custom image reactions correctly", () => {
const props = createProps({
"com.beeper.reaction.shortcode": ":test:",
"shortcode": ":test:",
"m.relates_to": {
event_id: "$user1:example.com",
key: "mxc://example.com/123456789",
rel_type: "m.annotation",
},
});
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
expect(root.asFragment()).toMatchSnapshot();
// Try hover and make sure that the ReactionsRowButtonTooltip works
const reactionButton = root.getByRole("button");
const event = new MouseEvent("mouseover", {
bubbles: true,
cancelable: true,
});
reactionButton.dispatchEvent(event);
expect(root.asFragment()).toMatchSnapshot();
});
it("renders without a room", () => {
mockClient.getRoom.mockImplementation(() => null);
const props = createProps({});
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
expect(root.asFragment()).toMatchSnapshot();
});
it("calls setProps on ViewModel when props change", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender, container } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Create new props with different values
const newMxEvent = new MatrixEvent({
room_id: roomId,
event_id: "$test2:example.com",
content: { body: "test2" },
});
const newReactionEvents = [
new MatrixEvent({
type: "m.reaction",
sender: "@user3:example.com",
content: {
"m.relates_to": {
event_id: "$user3:example.com",
key: "👎",
rel_type: "m.annotation",
},
},
}),
];
const updatedProps: IProps = {
...props,
mxEvent: newMxEvent,
content: "👎",
reactionEvents: newReactionEvents,
customReactionImagesEnabled: false,
};
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...updatedProps} />
</MatrixClientContext.Provider>,
);
// The component should have updated - verify by checking the rendered content
expect(container.querySelector(".mx_ReactionsRowButton_content")?.textContent).toBe("👎");
});
it("disposes ViewModel on unmount", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { unmount } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Unmount should not throw
expect(() => unmount()).not.toThrow();
});
it("redacts reaction when clicking with myReactionEvent", () => {
const myReactionEvent = new MatrixEvent({
type: "m.reaction",
sender: userId,
event_id: "$my_reaction:example.com",
content: {
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
},
});
const props: IProps = {
...createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
}),
myReactionEvent,
};
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
const button = root.getByRole("button");
fireEvent.click(button);
expect(mockClient.redactEvent).toHaveBeenCalledWith(roomId, "$my_reaction:example.com");
});
it("sends reaction when clicking without myReactionEvent", () => {
const props = createProps({
"m.relates_to": {
event_id: "$test:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
const button = root.getByRole("button");
fireEvent.click(button);
expect(mockClient.sendEvent).toHaveBeenCalledWith(roomId, EventType.Reaction, {
"m.relates_to": {
rel_type: RelationType.Annotation,
event_id: "$test:example.com",
key: "👍",
},
});
expect(dis.dispatch).toHaveBeenCalledWith({ action: "message_sent" });
});
it("uses reactors as label when content is empty", () => {
const props: IProps = {
mxEvent: new MatrixEvent({
room_id: roomId,
event_id: "$test:example.com",
content: { body: "test" },
}),
content: "", // Empty content
count: 2,
reactionEvents: [
new MatrixEvent({
type: "m.reaction",
sender: "@user1:example.com",
content: {},
}),
new MatrixEvent({
type: "m.reaction",
sender: "@user2:example.com",
content: {},
}),
],
customReactionImagesEnabled: true,
};
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// The button should still render
const button = root.getByRole("button");
expect(button).toBeInTheDocument();
});
it("renders custom image reaction with fallback label when no shortcode", () => {
const props: IProps = {
mxEvent: new MatrixEvent({
room_id: roomId,
event_id: "$test:example.com",
content: { body: "test" },
}),
content: "mxc://example.com/custom_image",
count: 1,
reactionEvents: [
new MatrixEvent({
type: "m.reaction",
sender: "@user1:example.com",
content: {
"m.relates_to": {
event_id: "$test:example.com",
key: "mxc://example.com/custom_image",
rel_type: "m.annotation",
},
},
}),
],
customReactionImagesEnabled: true,
};
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Should render an image element for custom reaction
const img = root.container.querySelector("img.mx_ReactionsRowButton_content");
expect(img).toBeInTheDocument();
expect(img).toHaveAttribute("src", "https://not.a.real.url");
});
it("falls back to text when mxc URL cannot be converted to HTTP", () => {
// Make mediaFromMxc return null srcHttp to simulate failed conversion
mockMediaFromMxc.mockReturnValueOnce({
srcHttp: null,
} as unknown as Media);
const props: IProps = {
mxEvent: new MatrixEvent({
room_id: roomId,
event_id: "$test:example.com",
content: { body: "test" },
}),
content: "mxc://example.com/invalid_image",
count: 1,
reactionEvents: [
new MatrixEvent({
type: "m.reaction",
sender: "@user1:example.com",
content: {
"m.relates_to": {
event_id: "$test:example.com",
key: "mxc://example.com/invalid_image",
rel_type: "m.annotation",
},
},
}),
],
customReactionImagesEnabled: true,
};
const root = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Should render span (not img) when imageSrc is null
const span = root.container.querySelector("span.mx_ReactionsRowButton_content");
expect(span).toBeInTheDocument();
const img = root.container.querySelector("img.mx_ReactionsRowButton_content");
expect(img).not.toBeInTheDocument();
});
it("updates ViewModel when only mxEvent changes", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Only change mxEvent
const newMxEvent = new MatrixEvent({
room_id: roomId,
event_id: "$test2:example.com",
content: { body: "test2" },
});
expect(() =>
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} mxEvent={newMxEvent} />
</MatrixClientContext.Provider>,
),
).not.toThrow();
});
it("updates ViewModel when only content changes", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender, container } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Only change content
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} content="👎" />
</MatrixClientContext.Provider>,
);
expect(container.querySelector(".mx_ReactionsRowButton_content")?.textContent).toBe("👎");
});
it("updates ViewModel when only reactionEvents changes", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Only change reactionEvents
const newReactionEvents = [
new MatrixEvent({
type: "m.reaction",
sender: "@user3:example.com",
content: {
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
},
}),
];
expect(() =>
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} reactionEvents={newReactionEvents} />
</MatrixClientContext.Provider>,
),
).not.toThrow();
});
it("updates ViewModel when only customReactionImagesEnabled changes", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Only change customReactionImagesEnabled
expect(() =>
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} customReactionImagesEnabled={false} />
</MatrixClientContext.Provider>,
),
).not.toThrow();
});
it("does not update ViewModel when props stay the same", () => {
const props = createProps({
"m.relates_to": {
event_id: "$user1:example.com",
key: "👍",
rel_type: "m.annotation",
},
});
const { rerender } = render(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
);
// Rerender with same props - setProps should not be called
expect(() =>
rerender(
<MatrixClientContext.Provider value={mockClient}>
<ReactionsRowButton {...props} />
</MatrixClientContext.Provider>,
),
).not.toThrow();
});
});
@@ -0,0 +1,284 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2023 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 from "react";
import { act, render, screen, waitFor } from "jest-matrix-react";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import { EventType, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import dis from "../../../../../src/dispatcher/dispatcher";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import {
guessServerNameFromRoomId,
RoomPredecessorTile,
} from "../../../../../src/components/views/messages/RoomPredecessorTile";
import { stubClient, upsertRoomStateEvents } from "../../../../test-utils/test-utils";
import { Action } from "../../../../../src/dispatcher/actions";
import { filterConsole, getRoomContext } from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext.tsx";
jest.mock("../../../../../src/dispatcher/dispatcher");
describe("<RoomPredecessorTile />", () => {
const userId = "@alice:server.org";
const roomId = "!room:server.org";
stubClient();
const client = mocked(MatrixClientPeg.safeGet());
function makeRoom({
createEventHasPredecessor = false,
predecessorEventExists = false,
predecessorEventHasEventId = false,
predecessorEventHasViaServers = false,
}): Room {
const room = new Room(roomId, client, userId);
const createInfo = {
type: EventType.RoomCreate,
state_key: "",
sender: userId,
room_id: roomId,
content: {},
event_id: "$create",
};
if (createEventHasPredecessor) {
createInfo.content = {
predecessor: { room_id: "old_room_id", event_id: "$tombstone_event_id" },
};
}
const createEvent = new MatrixEvent(createInfo);
upsertRoomStateEvents(room, [createEvent]);
if (predecessorEventExists) {
const predecessorInfo = {
type: EventType.RoomPredecessor,
state_key: "",
sender: userId,
room_id: roomId,
content: {
predecessor_room_id: "old_room_id_from_predecessor",
last_known_event_id: predecessorEventHasEventId
? "$tombstone_event_id_from_predecessor"
: undefined,
via_servers: predecessorEventHasViaServers ? ["a.example.com", "b.example.com"] : undefined,
},
event_id: "$predecessor",
};
const predecessorEvent = new MatrixEvent(predecessorInfo);
upsertRoomStateEvents(room, [predecessorEvent]);
}
return room;
}
beforeEach(() => {
jest.clearAllMocks();
mocked(dis.dispatch).mockReset();
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
stubClient();
});
afterAll(() => {
jest.spyOn(SettingsStore, "getValue").mockRestore();
jest.spyOn(SettingsStore, "setValue").mockRestore();
});
function renderTile(room: Room) {
// Find this room's create event (it should have one!)
const createEvent = room.currentState.getStateEvents("m.room.create")[0];
expect(createEvent).toBeTruthy();
return render(
<ScopedRoomContextProvider {...getRoomContext(room, {})}>
<RoomPredecessorTile mxEvent={createEvent} />
</ScopedRoomContextProvider>,
);
}
it("Renders as expected", () => {
const roomCreate = renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(roomCreate.asFragment()).toMatchSnapshot();
});
it("Links to the old version of the room", () => {
renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id/$tombstone_event_id",
);
});
describe("(filtering warnings about no predecessor)", () => {
filterConsole("RoomPredecessorTile unexpectedly used in a room with no predecessor.");
it("Shows an empty div if there is no predecessor", () => {
renderTile(makeRoom({}));
expect(screen.queryByText("Click here to see older messages.", { exact: false })).toBeNull();
});
});
it("Opens the old room on click", async () => {
renderTile(makeRoom({ createEventHasPredecessor: true }));
const link = screen.getByText("Click here to see older messages.");
await act(() => userEvent.click(link));
await waitFor(() =>
expect(dis.dispatch).toHaveBeenCalledWith({
action: Action.ViewRoom,
event_id: "$tombstone_event_id",
highlighted: true,
room_id: "old_room_id",
metricsTrigger: "Predecessor",
metricsViaKeyboard: false,
}),
);
});
it("Ignores m.predecessor if labs flag is off", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id/$tombstone_event_id",
);
});
describe("If the predecessor room is not found", () => {
filterConsole("Failed to find predecessor room with id old_room_id");
beforeEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("Shows an error if there are no via servers", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Can't find the old version of this room", { exact: false })).toBeInTheDocument();
});
});
describe("When feature_dynamic_room_predecessors = true", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
afterEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReset();
});
it("Uses the create event if there is no m.predecessor", () => {
renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id/$tombstone_event_id",
);
});
it("Uses m.predecessor when it's there", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor",
);
});
it("Links to the event in the room if event ID is provided", () => {
renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasEventId: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor/$tombstone_event_id_from_predecessor",
);
});
describe("If the predecessor room is not found", () => {
filterConsole("Failed to find predecessor room with id old_room_id");
beforeEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("Shows an error if there are no via servers", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(
screen.getByText("Can't find the old version of this room", { exact: false }),
).toBeInTheDocument();
});
it("Shows a tile if there are via servers", () => {
renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasViaServers: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor?via=a.example.com&via=b.example.com",
);
});
it("Shows a tile linking to an event if there are via servers", () => {
renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasEventId: true,
predecessorEventHasViaServers: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor/$tombstone_event_id_from_predecessor?via=a.example.com&via=b.example.com",
);
});
});
});
});
describe("guessServerNameFromRoomId", () => {
it("Extracts the domain name from a standard room ID", () => {
expect(guessServerNameFromRoomId("!436456:example.com")).toEqual("example.com");
});
it("Extracts the domain name and port when included", () => {
expect(guessServerNameFromRoomId("!436456:example.com:8888")).toEqual("example.com:8888");
});
it("Handles an IPv4 address for server name", () => {
expect(guessServerNameFromRoomId("!436456:127.0.0.1")).toEqual("127.0.0.1");
});
it("Handles an IPv4 address and port", () => {
expect(guessServerNameFromRoomId("!436456:127.0.0.1:81")).toEqual("127.0.0.1:81");
});
it("Handles an IPv6 address for server name", () => {
expect(guessServerNameFromRoomId("!436456:::1")).toEqual("::1");
});
it("Handles an IPv6 address and port", () => {
expect(guessServerNameFromRoomId("!436456:::1:8080")).toEqual("::1:8080");
});
it("Returns null when the room ID contains no colon", () => {
expect(guessServerNameFromRoomId("!436456")).toBeNull();
});
});
@@ -0,0 +1,470 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2019-2022 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 ComponentProps } from "react";
import { type MatrixClient, type MatrixEvent, PushRuleKind, type Room } from "matrix-js-sdk/src/matrix";
import { mocked, type MockedObject } from "jest-mock";
import { render, waitFor } from "jest-matrix-react";
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
import {
getMockClientWithEventEmitter,
mkEvent,
mkMessage,
mkStubRoom,
mockClientPushProcessor,
} from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import * as languageHandler from "../../../../../src/languageHandler";
import DMRoomMap from "../../../../../src/utils/DMRoomMap";
import TextualBody from "../../../../../src/components/views/messages/TextualBody";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import { RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
import { type MediaEventHelper } from "../../../../../src/utils/MediaEventHelper";
const room1Id = "!room1:example.com";
const room2Id = "!room2:example.com";
const room2Name = "Room 2";
interface MkRoomTextMessageOpts {
roomId?: string;
}
const mkRoomTextMessage = (body: string, mkRoomTextMessageOpts?: MkRoomTextMessageOpts): MatrixEvent => {
return mkMessage({
msg: body,
room: mkRoomTextMessageOpts?.roomId ?? room1Id,
user: "sender",
event: true,
});
};
const mkFormattedMessage = (body: string, formattedBody: string): MatrixEvent => {
return mkMessage({
msg: body,
formattedMsg: formattedBody,
format: "org.matrix.custom.html",
room: room1Id,
user: "sender",
event: true,
});
};
describe("<TextualBody />", () => {
afterEach(() => {
jest.spyOn(MatrixClientPeg, "get").mockRestore();
jest.spyOn(global.Math, "random").mockRestore();
});
let defaultRoom: Room;
let otherRoom: Room;
let defaultMatrixClient: MockedObject<MatrixClient>;
const defaultEvent = mkEvent({
type: "m.room.message",
room: room1Id,
user: "sender",
content: {
body: "winks",
msgtype: "m.emote",
},
event: true,
});
const defaultProps: ComponentProps<typeof TextualBody> = {
mxEvent: defaultEvent,
highlights: [] as string[],
highlightLink: "",
onMessageAllowed: jest.fn(),
mediaEventHelper: {} as MediaEventHelper,
};
beforeEach(() => {
defaultMatrixClient = getMockClientWithEventEmitter({
getRoom: (roomId: string | undefined) => {
if (roomId === room1Id) return defaultRoom;
if (roomId === room2Id) return otherRoom;
return null;
},
getRooms: () => [defaultRoom, otherRoom],
getAccountData: (): MatrixEvent | undefined => undefined,
isGuest: () => false,
mxcUrlToHttp: (s: string) => s,
getUserId: () => "@user:example.com",
fetchRoomEvent: () => {
throw new Error("MockClient event not found");
},
});
// @ts-expect-error
defaultMatrixClient.pushProcessor = new PushProcessor(defaultMatrixClient);
defaultRoom = mkStubRoom(room1Id, "test room", defaultMatrixClient);
defaultProps.permalinkCreator = new RoomPermalinkCreator(defaultRoom);
otherRoom = mkStubRoom(room2Id, room2Name, defaultMatrixClient);
mocked(defaultRoom).findEventById.mockImplementation((eventId: string) => {
if (eventId === defaultEvent.getId()) return defaultEvent;
return undefined;
});
jest.spyOn(global.Math, "random").mockReturnValue(0.123456);
});
const getComponent = (props = {}, matrixClient: MatrixClient = defaultMatrixClient, renderingFn?: any) =>
(renderingFn ?? render)(
<MatrixClientContext.Provider value={matrixClient}>
<TextualBody {...defaultProps} {...props} />
</MatrixClientContext.Provider>,
);
it("renders m.emote correctly", () => {
DMRoomMap.makeShared(defaultMatrixClient);
const ev = mkEvent({
type: "m.room.message",
room: room1Id,
user: "sender",
content: {
body: "winks",
msgtype: "m.emote",
},
event: true,
});
const { container } = getComponent({ mxEvent: ev });
expect(container).toHaveTextContent("* sender winks");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("renders m.notice correctly", () => {
DMRoomMap.makeShared(defaultMatrixClient);
const ev = mkEvent({
type: "m.room.message",
room: room1Id,
user: "bot_sender",
content: {
body: "this is a notice, probably from a bot",
msgtype: "m.notice",
},
event: true,
});
const { container } = getComponent({ mxEvent: ev });
expect(container).toHaveTextContent(ev.getContent().body);
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
describe("renders plain-text m.text correctly", () => {
beforeEach(() => {
DMRoomMap.makeShared(defaultMatrixClient);
});
it("simple message renders as expected", () => {
const ev = mkRoomTextMessage("this is a plaintext message");
const { container } = getComponent({ mxEvent: ev });
expect(container).toHaveTextContent(ev.getContent().body);
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
// If pills were rendered within a Portal/same shadow DOM then it'd be easier to test
it("linkification get applied correctly into the DOM", () => {
const ev = mkRoomTextMessage("Visit https://matrix.org/");
const { container } = getComponent({ mxEvent: ev });
expect(container).toHaveTextContent(ev.getContent().body);
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("should not pillify MXIDs", () => {
const ev = mkRoomTextMessage("Chat with @user:example.com");
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML).toMatchInlineSnapshot(
`"Chat with <a href="https://matrix.to/#/@user:example.com" class="linkified" rel="noreferrer noopener">@user:example.com</a>"`,
);
});
it("should pillify an MXID permalink", () => {
const ev = mkRoomTextMessage("Chat with https://matrix.to/#/@user:example.com");
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML).toMatchInlineSnapshot(
`"Chat with <bdi><a class="mx_Pill mx_UserPill mx_UserPill_me" href="https://matrix.to/#/@user:example.com"><span aria-label="Profile picture" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_zysgz_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_zysgz_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/image.png"></span><span class="mx_Pill_text">Member</span></a></bdi>"`,
);
});
it("should not pillify room aliases", () => {
const ev = mkRoomTextMessage("Visit #room:example.com");
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML).toMatchInlineSnapshot(
`"Visit <a href="https://matrix.to/#/#room:example.com" class="linkified" rel="noreferrer noopener">#room:example.com</a>"`,
);
});
it("should pillify a room alias permalink", () => {
const ev = mkRoomTextMessage("Visit https://matrix.to/#/#room:example.com");
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML).toMatchInlineSnapshot(
`"Visit <bdi><a class="mx_Pill mx_RoomPill" href="https://matrix.to/#/#room:example.com"><svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" fill="currentColor" viewBox="0 0 24 24" class="mx_Pill_LinkIcon mx_BaseAvatar"><path d="M12 19.071q-1.467 1.467-3.536 1.467-2.067 0-3.535-1.467t-1.467-3.535q0-2.07 1.467-3.536L7.05 9.879q.3-.3.707-.3t.707.3.301.707-.3.707l-2.122 2.121a2.9 2.9 0 0 0-.884 2.122q0 1.237.884 2.12.884.885 2.121.885t2.122-.884l2.121-2.121q.3-.3.707-.3t.707.3.3.707q0 .405-.3.707zm-1.414-4.243q-.3.3-.707.301a.97.97 0 0 1-.707-.3q-.3-.3-.301-.708 0-.405.3-.707l4.243-4.242q.3-.3.707-.3t.707.3.3.707-.3.707zm6.364-.707q-.3.3-.707.3a.97.97 0 0 1-.707-.3q-.3-.3-.301-.707 0-.405.3-.707l2.122-2.121q.884-.885.884-2.121 0-1.238-.884-2.122a2.9 2.9 0 0 0-2.121-.884q-1.237 0-2.122.884l-2.121 2.122q-.3.3-.707.3a.97.97 0 0 1-.707-.3q-.3-.3-.3-.708 0-.405.3-.707L12 4.93q1.467-1.467 3.536-1.467t3.535 1.467 1.467 3.536T19.071 12z"></path></svg><span class="mx_Pill_text">#room:example.com</span></a></bdi>"`,
);
});
it("should pillify a permalink to a message in the same room with the label »Message from Member«", () => {
const ev = mkRoomTextMessage(`Visit https://matrix.to/#/${room1Id}/${defaultEvent.getId()}`);
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML.replace(defaultEvent.getId(), "%event_id%")).toMatchSnapshot();
});
it("should pillify a permalink to an unknown message in the same room with the label »Message«", () => {
const ev = mkRoomTextMessage(`Visit https://matrix.to/#/${room1Id}/!abc123`);
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("should pillify a permalink to an event in another room with the label »Message in Room 2«", () => {
const ev = mkRoomTextMessage(`Visit https://matrix.to/#/${room2Id}/${defaultEvent.getId()}`);
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML.replace(defaultEvent.getId(), "%event_id%")).toMatchSnapshot();
});
it("should pillify a keyword responsible for triggering a notification", () => {
const ev = mkRoomTextMessage("foo bar baz");
ev.setPushDetails(undefined, {
actions: [],
pattern: "bar",
rule_id: "bar",
default: false,
enabled: true,
kind: PushRuleKind.ContentSpecific,
});
const { container } = getComponent({ mxEvent: ev });
const content = container.querySelector(".mx_EventTile_body");
expect(content.innerHTML).toMatchInlineSnapshot(
`"foo <bdi><span tabindex="0"><span class="mx_Pill mx_KeywordPill"><span class="mx_Pill_text">bar</span></span></span></bdi> baz"`,
);
});
});
describe("renders formatted m.text correctly", () => {
let matrixClient: MatrixClient;
beforeEach(() => {
matrixClient = getMockClientWithEventEmitter({
getRoom: jest.fn(),
...mockClientPushProcessor(),
getAccountData: (): MatrixEvent | undefined => undefined,
getUserId: () => "@me:my_server",
getHomeserverUrl: () => "https://my_server/",
on: (): void => undefined,
removeListener: (): void => undefined,
isGuest: () => false,
mxcUrlToHttp: (s: string) => s,
});
mocked(matrixClient.getRoom).mockReturnValue(mkStubRoom(room1Id, "room name", matrixClient));
DMRoomMap.makeShared(defaultMatrixClient);
});
it("italics, bold, underline and strikethrough render as expected", () => {
const ev = mkFormattedMessage(
"foo *baz* __bar__ <del>del</del> <u>u</u>",
"foo <em>baz</em> <strong>bar</strong> <del>del</del> <u>u</u>",
);
const { container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("foo baz bar del u");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("spoilers get injected properly into the DOM", () => {
const ev = mkFormattedMessage(
"Hey [Spoiler for movie](mxc://someserver/somefile)",
'Hey <span data-mx-spoiler="movie">the movie was awesome</span>',
);
const { container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("Hey (movie) the movie was awesome");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("linkification is not applied to code blocks", () => {
const ev = mkFormattedMessage(
"Visit `https://matrix.org/`\n```\nhttps://matrix.org/\n```",
"<p>Visit <code>https://matrix.org/</code></p>\n<pre>https://matrix.org/\n</pre>\n",
);
const { container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("Visit https://matrix.org/ 1https://matrix.org/");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("should syntax highlight code blocks", async () => {
const ev = mkFormattedMessage(
"```py\n# Python Program to calculate the square root\n\n# Note: change this value for a different result\nnum = 8 \n\n# To take the input from the user\n#num = float(input('Enter a number: '))\n\nnum_sqrt = num ** 0.5\nprint('The square root of %0.3f is %0.3f'%(num ,num_sqrt))",
"<pre><code class=\"language-py\"># Python Program to calculate the square root\n\n# Note: change this value for a different result\nnum = 8 \n\n# To take the input from the user\n#num = float(input('Enter a number: '))\n\nnum_sqrt = num ** 0.5\nprint('The square root of %0.3f is %0.3f'%(num ,num_sqrt))\n</code></pre>\n",
);
const { container } = getComponent({ mxEvent: ev }, matrixClient);
await waitFor(() => expect(container.querySelector(".hljs-built_in")).toBeInTheDocument());
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
// If pills were rendered within a Portal/same shadow DOM then it'd be easier to test
it("pills get injected correctly into the DOM", () => {
const ev = mkFormattedMessage("Hey User", 'Hey <a href="https://matrix.to/#/@user:server">Member</a>');
const { container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("Hey Member");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("pills do not appear in code blocks", () => {
const ev = mkFormattedMessage(
"`@room`\n```\n@room\n```",
"<p><code>@room</code></p>\n<pre><code>@room\n</code></pre>\n",
);
const { container } = getComponent({ mxEvent: ev });
expect(container).toHaveTextContent("@room 1@room");
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("pills do not appear for event permalinks with a custom label", () => {
const ev = mkFormattedMessage(
"An [event link](https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/" +
"$16085560162aNpaH:example.com?via=example.com) with text",
'An <a href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/' +
'$16085560162aNpaH:example.com?via=example.com">event link</a> with text',
);
const { asFragment, container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("An event link with text");
expect(asFragment()).toMatchSnapshot();
});
it("pills appear for event permalinks without a custom label", () => {
const ev = mkFormattedMessage(
"See this message https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/$16085560162aNpaH:example.com?via=example.com",
'See this message <a href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/$16085560162aNpaH:example.com?via=example.com">' +
"https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/$16085560162aNpaH:example.com?via=example.com</a>",
);
const { asFragment } = getComponent({ mxEvent: ev }, matrixClient);
expect(asFragment()).toMatchSnapshot();
});
it("pills appear for room links with vias", () => {
const ev = mkFormattedMessage(
"A [room link](https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com" +
"?via=example.com&via=bob.com) with vias",
'A <a href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com' +
'?via=example.com&amp;via=bob.com">room link</a> with vias',
);
const { asFragment, container } = getComponent({ mxEvent: ev }, matrixClient);
expect(container).toHaveTextContent("A room name with vias");
expect(asFragment()).toMatchSnapshot();
});
it("pills appear for an MXID permalink", () => {
const ev = mkFormattedMessage(
"Chat with [@user:example.com](https://matrix.to/#/@user:example.com)",
'Chat with <a href="https://matrix.to/#/@user:example.com">@user:example.com</a>',
);
const { container } = getComponent({ mxEvent: ev }, matrixClient);
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
it("renders formatted body without html correctly", () => {
const ev = mkEvent({
type: "m.room.message",
room: "room_id",
user: "sender",
content: {
body: "escaped \\*markdown\\*",
msgtype: "m.text",
format: "org.matrix.custom.html",
formatted_body: "escaped *markdown*",
},
event: true,
});
const { container } = getComponent({ mxEvent: ev }, matrixClient);
const content = container.querySelector(".mx_EventTile_body");
expect(content).toMatchSnapshot();
});
});
describe("url preview", () => {
let matrixClient: MatrixClient;
beforeEach(() => {
languageHandler.setMissingEntryGenerator((key) => key.split("|", 2)[1]);
matrixClient = getMockClientWithEventEmitter({
getRoom: jest.fn(),
getUserId: jest.fn(),
...mockClientPushProcessor(),
getAccountData: (): MatrixClient | undefined => undefined,
getUrlPreview: (url: string) => new Promise(() => {}),
isGuest: () => false,
mxcUrlToHttp: (s: string) => s,
});
mocked(matrixClient.getRoom).mockReturnValue(mkStubRoom("room_id", "room name", matrixClient));
DMRoomMap.makeShared(defaultMatrixClient);
});
it("renders url previews correctly", () => {
const ev = mkRoomTextMessage("Visit https://matrix.org/");
const { container, rerender } = getComponent({ mxEvent: ev, showUrlPreview: true }, matrixClient);
expect(container).toHaveTextContent(ev.getContent().body);
expect(container.querySelector("a")).toHaveAttribute("href", "https://matrix.org/");
// simulate an event edit and check the transition from the old URL preview to the new one
const ev2 = mkEvent({
type: "m.room.message",
room: "room_id",
user: "sender",
content: {
"m.new_content": {
body: "Visit https://vector.im/ and https://riot.im/",
msgtype: "m.text",
},
},
event: true,
});
jest.spyOn(ev, "replacingEventDate").mockReturnValue(new Date(1993, 7, 3));
ev.makeReplaced(ev2);
getComponent({ mxEvent: ev, showUrlPreview: true, replacingEventId: ev.getId() }, matrixClient, rerender);
expect(container).toHaveTextContent(ev2.getContent()["m.new_content"].body + "(edited)");
const links = ["https://vector.im/", "https://riot.im/"];
const anchorNodes = container.querySelectorAll("a");
Array.from(anchorNodes).forEach((node, index) => {
expect(node).toHaveAttribute("href", links[index]);
});
});
it("should listen to showUrlPreview change", () => {
const ev = mkRoomTextMessage("Visit https://matrix.org/");
const { container, rerender } = getComponent({ mxEvent: ev, showUrlPreview: false }, matrixClient);
expect(container.querySelector(".mx_LinkPreviewGroup")).toBeNull();
getComponent({ mxEvent: ev, showUrlPreview: true }, matrixClient, rerender);
expect(container.querySelector(".mx_LinkPreviewGroup")).toBeTruthy();
});
});
});
@@ -0,0 +1,103 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`DateSeparator renders invalid date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Invalid timestamp"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Invalid timestamp
</h2>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
exports[`DateSeparator renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="today"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
today
</h2>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
exports[`DateSeparator when feature_jump_to_date is enabled renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Fri, Dec 17, 2021"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
aria-expanded="false"
aria-haspopup="true"
aria-label="Jump to date"
class="mx_AccessibleButton mx_DateSeparator_jumpToDateMenu mx_DateSeparator_dateContent"
data-testid="jump-to-date-separator-button"
role="button"
tabindex="0"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Fri, Dec 17, 2021
</h2>
<svg
class="mx_DateSeparator_chevron"
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 14.95q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-4.6-4.6a.95.95 0 0 1-.275-.7q0-.425.275-.7a.95.95 0 0 1 .7-.275q.425 0 .7.275l3.9 3.9 3.9-3.9a.95.95 0 0 1 .7-.275q.425 0 .7.275a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-4.6 4.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063"
/>
</svg>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,41 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`JumpToDatePicker renders the date picker correctly 1`] = `
<DocumentFragment>
<form
class="mx_JumpToDatePicker_form"
>
<span
class="mx_JumpToDatePicker_label"
>
Jump to date
</span>
<div
class="mx_Field mx_Field_input mx_JumpToDatePicker_datePicker"
>
<input
id="mx_Field_1"
label="Pick a date to jump to"
max="2021-12-17"
placeholder="Pick a date to jump to"
tabindex="-1"
type="date"
value="2020-07-04"
/>
<label
for="mx_Field_1"
>
Pick a date to jump to
</label>
</div>
<button
class="mx_AccessibleButton mx_JumpToDatePicker_submitButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary"
role="button"
tabindex="-1"
type="submit"
>
Go
</button>
</form>
</DocumentFragment>
`;
@@ -0,0 +1,31 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<MBeaconBody /> when map display is not configured renders maps unavailable error for a live beacon with location 1`] = `
<div
class="mx_MapError mx_MBeaconBody_mapError mx_MBeaconBody_mapErrorInteractive mx_MapError_isMinimised"
data-testid="map-rendering-error"
>
<svg
class="mx_MapError_icon"
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 17q.424 0 .713-.288A.97.97 0 0 0 13 16a.97.97 0 0 0-.287-.713A.97.97 0 0 0 12 15a.97.97 0 0 0-.713.287A.97.97 0 0 0 11 16q0 .424.287.712.288.288.713.288m0-4q.424 0 .713-.287A.97.97 0 0 0 13 12V8a.97.97 0 0 0-.287-.713A.97.97 0 0 0 12 7a.97.97 0 0 0-.713.287A.97.97 0 0 0 11 8v4q0 .424.287.713.288.287.713.287m0 9a9.7 9.7 0 0 1-3.9-.788 10.1 10.1 0 0 1-3.175-2.137q-1.35-1.35-2.137-3.175A9.7 9.7 0 0 1 2 12q0-2.075.788-3.9a10.1 10.1 0 0 1 2.137-3.175q1.35-1.35 3.175-2.137A9.7 9.7 0 0 1 12 2q2.075 0 3.9.788a10.1 10.1 0 0 1 3.175 2.137q1.35 1.35 2.137 3.175A9.7 9.7 0 0 1 22 12a9.7 9.7 0 0 1-.788 3.9 10.1 10.1 0 0 1-2.137 3.175q-1.35 1.35-3.175 2.137A9.7 9.7 0 0 1 12 22m0-2q3.35 0 5.675-2.325T20 12t-2.325-5.675T12 4 6.325 6.325 4 12t2.325 5.675T12 20"
/>
</svg>
<h3
class="mx_Heading_h3 mx_MapError_heading"
>
Unable to load map
</h3>
<p
class="mx_MapError_message"
>
This homeserver is not configured to display maps.
</p>
</div>
`;
@@ -0,0 +1,160 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<MFileBody/> should show a download button in file rendering type 1`] = `
<div>
<span
class="mx_MFileBody"
>
<div
class="mx_MFileBody_download"
>
<a
class="_button_13vu4_8 _has-icon_13vu4_60"
data-kind="secondary"
data-size="sm"
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
</a>
</div>
</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>
`;
@@ -0,0 +1,381 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<MImageBody/> should generate a thumbnail if one isn't included for animated media 1`] = `
<div>
<div
class="mx_MImageBody"
>
<a
href="https://server/_matrix/media/v3/download/server/image"
>
<div
class="mx_MImageBody_thumbnail_container"
style="max-height: 50px; max-width: 40px; aspect-ratio: 40/50;"
>
<div
class="mx_MImageBody_placeholder"
>
<div
class="mx_Spinner"
>
<svg
aria-label="Loading…"
class="_icon_11k6c_18"
data-testid="spinner"
fill="currentColor"
height="1em"
role="progressbar"
style="width: 32px; height: 32px;"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M12 4.031a8 8 0 1 0 8 8 1 1 0 0 1 2 0c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10a1 1 0 1 1 0 2"
fill-rule="evenodd"
/>
</svg>
</div>
</div>
<div
style="max-height: 50px; max-width: 40px;"
>
<img
alt="alt for a test image"
class="mx_MImageBody_thumbnail"
src="blob:generated-thumb"
/>
<p
class="mx_MImageBody_gifLabel"
>
GIF
</p>
</div>
</div>
</a>
</div>
</div>
`;
exports[`<MImageBody/> should open ImageView using thumbnail for encrypted svg 1`] = `
<div
aria-label="Image view"
class="mx_ImageView"
data-focus-lock-disabled="false"
role="dialog"
>
<div
class="mx_ImageView_panel"
>
<div
class="mx_ImageView_info_wrapper"
>
<button
aria-label="Profile picture"
aria-live="off"
class="_avatar_zysgz_8 mx_BaseAvatar mx_Dialog_nonDialogButton _avatar-imageless_zysgz_55"
data-color="2"
data-testid="avatar-img"
data-type="round"
role="button"
style="--cpd-avatar-size: 32px;"
>
o
</button>
<div
class="mx_ImageView_info"
>
<div
class="mx_ImageView_info_sender"
>
@other_use:server
</div>
<a
aria-live="off"
class="mx_MessageTimestamp _content_kc5mt_8"
href="https://matrix.to/#/!room:server/undefined"
>
Thu, Jan 15, 1970, 06:56
</a>
</div>
</div>
<div
class="mx_ImageView_title"
>
Image
</div>
<div
class="mx_ImageView_toolbar"
>
<div
aria-label="Zoom out"
class="mx_AccessibleButton mx_ImageView_button"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13.5 9.5q.425 0 .713.287.288.288.287.713a.97.97 0 0 1-.287.713.97.97 0 0 1-.713.287h-6a.97.97 0 0 1-.713-.287.97.97 0 0 1-.287-.713q0-.425.287-.713A.97.97 0 0 1 7.5 9.5z"
/>
<path
clip-rule="evenodd"
d="M10.5 3a7.5 7.5 0 0 1 5.963 12.049l3.244 3.244a1 1 0 1 1-1.414 1.414l-3.244-3.244A7.5 7.5 0 1 1 10.5 3m0 2a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11"
fill-rule="evenodd"
/>
</svg>
</div>
<div
aria-label="Zoom in"
class="mx_AccessibleButton mx_ImageView_button"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<g
clip-path="url(#a)"
>
<path
d="M10.5 6.5q.425 0 .713.287.288.288.287.713v2h2q.425 0 .713.287.288.288.287.713a.97.97 0 0 1-.287.713.97.97 0 0 1-.713.287h-2v2a.97.97 0 0 1-.287.713.97.97 0 0 1-.713.287.97.97 0 0 1-.713-.287.97.97 0 0 1-.287-.713v-2h-2a.97.97 0 0 1-.713-.287.97.97 0 0 1-.287-.713q0-.425.287-.713A.97.97 0 0 1 7.5 9.5h2v-2q0-.425.287-.713A.97.97 0 0 1 10.5 6.5"
/>
<path
clip-rule="evenodd"
d="M10.5 3a7.5 7.5 0 0 1 5.963 12.049l3.244 3.244a1 1 0 1 1-1.414 1.414l-3.244-3.244A7.5 7.5 0 1 1 10.5 3m0 2a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11"
fill-rule="evenodd"
/>
<path
d="M15.05 16.463a7.5 7.5 0 1 1 1.414-1.414l3.243 3.244a1 1 0 0 1-1.414 1.414zM16 10.5a5.5 5.5 0 1 0-11 0 5.5 5.5 0 0 0 11 0"
/>
<path
d="M7.875 11.375h1.75v1.75q0 .372.252.623A.85.85 0 0 0 10.5 14a.85.85 0 0 0 .623-.252.85.85 0 0 0 .252-.623v-1.75h1.75a.85.85 0 0 0 .623-.252A.85.85 0 0 0 14 10.5a.85.85 0 0 0-.252-.623.85.85 0 0 0-.623-.252h-1.75v-1.75a.85.85 0 0 0-.252-.623A.85.85 0 0 0 10.5 7a.85.85 0 0 0-.623.252.85.85 0 0 0-.252.623v1.75h-1.75a.85.85 0 0 0-.623.252A.85.85 0 0 0 7 10.5q0 .372.252.623a.85.85 0 0 0 .623.252"
/>
</g>
<defs>
<clippath
id="a"
>
<path
d="M0 0h24v24H0z"
/>
</clippath>
</defs>
</svg>
</div>
<div
aria-label="Rotate Left"
class="mx_AccessibleButton mx_ImageView_button"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.56 7.98C6.1 7.52 5.31 7.6 5 8.17c-.28.51-.5 1.03-.67 1.58-.19.63.31 1.25.96 1.25h.01c.43 0 .82-.28.94-.7q.18-.6.48-1.17c.22-.37.15-.84-.16-1.15M5.31 13h-.02c-.65 0-1.15.62-.96 1.25.16.54.38 1.07.66 1.58.31.57 1.11.66 1.57.2.3-.31.38-.77.17-1.15-.2-.37-.36-.76-.48-1.16a.97.97 0 0 0-.94-.72m2.85 6.02q.765.42 1.59.66c.62.18 1.24-.32 1.24-.96v-.03c0-.43-.28-.82-.7-.94-.4-.12-.78-.28-1.15-.48a.97.97 0 0 0-1.16.17l-.03.03c-.45.45-.36 1.24.21 1.55M13 4.07v-.66c0-.89-1.08-1.34-1.71-.71L9.17 4.83c-.4.4-.4 1.04 0 1.43l2.13 2.08c.63.62 1.7.17 1.7-.72V6.09c2.84.48 5 2.94 5 5.91 0 2.73-1.82 5.02-4.32 5.75a.97.97 0 0 0-.68.94v.02c0 .65.61 1.14 1.23.96A7.976 7.976 0 0 0 20 12c0-4.08-3.05-7.44-7-7.93"
/>
</svg>
</div>
<div
aria-label="Rotate Right"
class="mx_AccessibleButton mx_ImageView_button"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<g
clip-path="url(#a)"
>
<path
d="M14.83 4.83 12.7 2.7c-.62-.62-1.7-.18-1.7.71v.66C7.06 4.56 4 7.92 4 12c0 3.64 2.43 6.71 5.77 7.68.62.18 1.23-.32 1.23-.96v-.03a.97.97 0 0 0-.68-.94A5.98 5.98 0 0 1 6 12c0-2.97 2.16-5.43 5-5.91v1.53c0 .89 1.07 1.33 1.7.71l2.13-2.08a.99.99 0 0 0 0-1.42m4.84 4.93q-.24-.825-.66-1.59c-.31-.57-1.1-.66-1.56-.2l-.01.01c-.31.31-.38.78-.17 1.16.2.37.36.76.48 1.16.12.42.51.7.94.7h.02c.65 0 1.15-.62.96-1.24M13 18.68v.02c0 .65.62 1.14 1.24.96q.825-.24 1.59-.66c.57-.31.66-1.1.2-1.56l-.02-.02a.97.97 0 0 0-1.16-.17c-.37.21-.76.37-1.16.49-.41.12-.69.51-.69.94m4.44-2.65c.46.46 1.25.37 1.56-.2.28-.51.5-1.04.67-1.59.18-.62-.31-1.24-.96-1.24h-.02c-.44 0-.82.28-.94.7q-.18.6-.48 1.17c-.21.38-.13.86.17 1.16"
/>
</g>
<defs>
<clippath
id="a"
>
<path
d="M0 0h24v24H0z"
/>
</clippath>
</defs>
</svg>
</div>
<div
aria-label="Download"
class="mx_AccessibleButton mx_ImageView_button"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
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>
</div>
<div
aria-expanded="false"
aria-haspopup="true"
aria-label="Options"
class="mx_AccessibleButton mx_ImageView_button mx_ImageView_button_more"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6 14q-.824 0-1.412-.588A1.93 1.93 0 0 1 4 12q0-.825.588-1.412A1.93 1.93 0 0 1 6 10q.824 0 1.412.588Q8 11.175 8 12t-.588 1.412A1.93 1.93 0 0 1 6 14m6 0q-.825 0-1.412-.588A1.93 1.93 0 0 1 10 12q0-.825.588-1.412A1.93 1.93 0 0 1 12 10q.825 0 1.412.588Q14 11.175 14 12t-.588 1.412A1.93 1.93 0 0 1 12 14m6 0q-.824 0-1.413-.588A1.93 1.93 0 0 1 16 12q0-.825.587-1.412A1.93 1.93 0 0 1 18 10q.824 0 1.413.588Q20 11.175 20 12t-.587 1.412A1.93 1.93 0 0 1 18 14"
/>
</svg>
</div>
<div
aria-label="Close"
class="mx_AccessibleButton mx_ImageView_button mx_ImageView_button_close"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.293 6.293a1 1 0 0 1 1.414 0L12 10.586l4.293-4.293a1 1 0 1 1 1.414 1.414L13.414 12l4.293 4.293a1 1 0 0 1-1.414 1.414L12 13.414l-4.293 4.293a1 1 0 0 1-1.414-1.414L10.586 12 6.293 7.707a1 1 0 0 1 0-1.414"
/>
</svg>
</div>
</div>
</div>
<div
class="mx_ImageView_image_wrapper"
>
<img
alt="Attachment"
class="mx_ImageView_image "
draggable="true"
src="https://server/_matrix/media/v3/download/server/svg-thumbnail"
style="transform: translateX(-512px)
translateY(NaNpx)
scale(0)
rotate(0deg); cursor: zoom-out;"
/>
</div>
</div>
`;
exports[`<MImageBody/> should render MFileBody for svg with no thumbnail 1`] = `
<DocumentFragment>
<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"
>
Attachment
</span>
</span>
</div>
</span>
</DocumentFragment>
`;
exports[`<MImageBody/> should show a thumbnail while image is being downloaded 1`] = `
<div>
<div
class="mx_MImageBody"
>
<div
class="mx_MImageBody_thumbnail_container"
style="max-height: 50px; max-width: 40px; aspect-ratio: 40/50;"
>
<div
class="mx_MImageBody_placeholder"
>
<div
class="mx_Spinner"
>
<svg
aria-label="Loading…"
class="_icon_11k6c_18"
data-testid="spinner"
fill="currentColor"
height="1em"
role="progressbar"
style="width: 32px; height: 32px;"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M12 4.031a8 8 0 1 0 8 8 1 1 0 0 1 2 0c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10a1 1 0 1 1 0 2"
fill-rule="evenodd"
/>
</svg>
</div>
</div>
<div
style="max-height: 50px; max-width: 40px;"
/>
</div>
</div>
</div>
`;
@@ -0,0 +1,112 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`MLocationBody <MLocationBody> with error displays correct fallback content when map_style_url is misconfigured 1`] = `
<div
class="mx_EventTile_body mx_MLocationBody"
>
<span
class="mx_EventTile_tileError"
>
Unable to load map: This homeserver is not configured correctly to display maps, or the configured map server may be unreachable.
</span>
<br />
Shared a location: Found at geo:51.5076,-0.1276 at 2021-12-21T12:22+0000
</div>
`;
exports[`MLocationBody <MLocationBody> with error displays correct fallback content without error style when map_style_url is not configured 1`] = `
<div
class="mx_EventTile_body mx_MLocationBody"
>
<span
class=""
>
Unable to load map: This homeserver is not configured to display maps.
</span>
<br />
Shared a location: Found at geo:51.5076,-0.1276 at 2021-12-21T12:22+0000
</div>
`;
exports[`MLocationBody <MLocationBody> without error renders map correctly 1`] = `
<DocumentFragment>
<div
class="mx_MLocationBody"
>
<div
aria-labelledby="_r_i_"
class="mx_MLocationBody_map"
>
<div
class="mx_Map mx_MLocationBody_map"
id="mx_Map_mx_MLocationBody_$2_vY7Q4uEh"
>
<span>
<div
class="mx_Marker mx_Marker_defaultColor"
id="mx_MLocationBody_$2_vY7Q4uEh-marker"
>
<div
class="mx_Marker_border"
>
<svg
class="mx_Marker_icon"
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 21.325a2.1 2.1 0 0 1-.7-.125 1.8 1.8 0 0 1-.625-.375A39 39 0 0 1 7.8 17.9q-1.25-1.425-2.087-2.762-.838-1.338-1.275-2.575Q4 11.325 4 10.2q0-3.75 2.412-5.975T12 2t5.587 2.225T20 10.2q0 1.125-.437 2.363-.438 1.237-1.275 2.574A22 22 0 0 1 16.2 17.9a39 39 0 0 1-2.875 2.925 1.8 1.8 0 0 1-.625.375 2.1 2.1 0 0 1-.7.125M12 12q.825 0 1.412-.588Q14 10.826 14 10t-.588-1.412A1.93 1.93 0 0 0 12 8q-.825 0-1.412.588A1.93 1.93 0 0 0 10 10q0 .825.588 1.412Q11.175 12 12 12"
/>
</svg>
</div>
</div>
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`MLocationBody <MLocationBody> without error renders marker correctly for a self share 1`] = `
<DocumentFragment>
<div
class="mx_MLocationBody"
>
<div
aria-labelledby="_r_u_"
class="mx_MLocationBody_map"
>
<div
class="mx_Map mx_MLocationBody_map"
id="mx_Map_mx_MLocationBody_$3_vY7Q4uEh"
>
<span>
<div
class="mx_Marker mx_Marker_defaultColor"
id="mx_MLocationBody_$3_vY7Q4uEh-marker"
>
<div
class="mx_Marker_border"
>
<span
class="_avatar_zysgz_8 mx_BaseAvatar _avatar-imageless_zysgz_55"
data-color="3"
data-testid="avatar-img"
data-type="round"
role="presentation"
style="--cpd-avatar-size: 36px;"
title="@user:server"
>
u
</span>
</div>
</div>
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,78 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`MVideoBody does not crash when given portrait dimensions 1`] = `
<DocumentFragment>
<span
class="mx_MVideoBody"
>
<div
class="mx_MVideoBody_container"
style="max-width: 182px; max-height: 324px; aspect-ratio: 720/1280;"
>
<video
class="mx_MVideoBody"
controls=""
controlslist="nodownload"
crossorigin="anonymous"
poster="data:image/png;base64,00"
preload="none"
/>
<div
style="width: 182px; height: 324px;"
/>
</div>
</span>
</DocumentFragment>
`;
exports[`MVideoBody should show poster for encrypted media before downloading it 1`] = `
<DocumentFragment>
<span
class="mx_MVideoBody"
>
<div
class="mx_MVideoBody_container"
style="max-width: 40px; max-height: 50px; aspect-ratio: 40/50;"
>
<video
class="mx_MVideoBody"
controls=""
controlslist="nodownload"
crossorigin="anonymous"
poster="https://server/_matrix/media/v3/download/server/encrypted-poster"
preload="none"
title="alt for a test video"
/>
<div
style="width: 40px; height: 50px;"
/>
</div>
</span>
</DocumentFragment>
`;
exports[`MVideoBody with video previews/thumbnails disabled should download video if we were the sender 1`] = `
<DocumentFragment>
<span
class="mx_MVideoBody"
>
<div
class="mx_MVideoBody_container"
style="max-width: 40px; max-height: 50px; aspect-ratio: 40/50;"
>
<video
class="mx_MVideoBody"
controls=""
controlslist="nodownload"
crossorigin="anonymous"
poster="https://server/_matrix/media/v3/download/server/encrypted-poster"
preload="none"
title="alt for a test video"
/>
<div
style="width: 40px; height: 50px;"
/>
</div>
</span>
</DocumentFragment>
`;
@@ -0,0 +1,22 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`PinnedMessageBadge should render 1`] = `
<DocumentFragment>
<div
class="mx_PinnedMessageBadge"
>
<svg
fill="currentColor"
height="16px"
viewBox="0 0 24 24"
width="16px"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M5.769 2.857A.5.5 0 0 1 6.119 2h11.762a.5.5 0 0 1 .35.857L16.15 4.9a.5.5 0 0 0-.15.357v4.487a.5.5 0 0 0 .15.356l3.7 3.644a.5.5 0 0 1 .15.356v1.4a.5.5 0 0 1-.5.5H13v6a1 1 0 1 1-2 0v-6H4.5a.5.5 0 0 1-.5-.5v-1.4a.5.5 0 0 1 .15-.356l3.7-3.644A.5.5 0 0 0 8 9.744V5.257a.5.5 0 0 0-.15-.357z"
/>
</svg>
Pinned message
</div>
</DocumentFragment>
`;
@@ -0,0 +1,120 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`ReactionsRowButton renders reaction row button custom image reactions correctly 1`] = `
<DocumentFragment>
<div
aria-label="@user1:example.com and @user2:example.com reacted with :test:"
class="mx_AccessibleButton mx_ReactionsRowButton"
role="button"
tabindex="0"
>
<img
alt=":test:"
class="mx_ReactionsRowButton_content"
height="16"
src="https://not.a.real.url"
width="16"
/>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_count"
>
2
</span>
</div>
</DocumentFragment>
`;
exports[`ReactionsRowButton renders reaction row button custom image reactions correctly 2`] = `
<DocumentFragment>
<div
aria-label="@user1:example.com and @user2:example.com reacted with :test:"
class="mx_AccessibleButton mx_ReactionsRowButton"
role="button"
tabindex="0"
>
<img
alt=":test:"
class="mx_ReactionsRowButton_content"
height="16"
src="https://not.a.real.url"
width="16"
/>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_count"
>
2
</span>
</div>
</DocumentFragment>
`;
exports[`ReactionsRowButton renders reaction row button emojis correctly 1`] = `
<DocumentFragment>
<div
aria-label="@user1:example.com and @user2:example.com reacted with 👍"
class="mx_AccessibleButton mx_ReactionsRowButton"
role="button"
tabindex="0"
>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_content"
>
👍
</span>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_count"
>
2
</span>
</div>
</DocumentFragment>
`;
exports[`ReactionsRowButton renders reaction row button emojis correctly 2`] = `
<DocumentFragment>
<div
aria-label="@user1:example.com and @user2:example.com reacted with 👍"
class="mx_AccessibleButton mx_ReactionsRowButton"
role="button"
tabindex="0"
>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_content"
>
👍
</span>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_count"
>
2
</span>
</div>
</DocumentFragment>
`;
exports[`ReactionsRowButton renders without a room 1`] = `
<DocumentFragment>
<div
class="mx_AccessibleButton mx_ReactionsRowButton"
role="button"
tabindex="0"
>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_content"
/>
<span
aria-hidden="true"
class="mx_ReactionsRowButton_count"
>
2
</span>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,35 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<RoomPredecessorTile /> Renders as expected 1`] = `
<DocumentFragment>
<div
class="_container_sq5fu_8 mx_EventTileBubble mx_CreateEvent"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2.95 16.3 1.5 21.25a.94.94 0 0 0 .25 1 .94.94 0 0 0 1 .25l4.95-1.45a10.2 10.2 0 0 0 2.1.712Q10.875 22 12 22a9.7 9.7 0 0 0 3.9-.788 10.1 10.1 0 0 0 3.175-2.137q1.35-1.35 2.137-3.175A9.7 9.7 0 0 0 22 12a9.7 9.7 0 0 0-.788-3.9 10.1 10.1 0 0 0-2.137-3.175q-1.35-1.35-3.175-2.137A9.7 9.7 0 0 0 12 2a9.7 9.7 0 0 0-3.9.788 10.1 10.1 0 0 0-3.175 2.137Q3.575 6.275 2.788 8.1A9.7 9.7 0 0 0 2 12q0 1.125.238 2.2.237 1.076.712 2.1"
/>
</svg>
<div
class="_title_sq5fu_34"
>
This room is a continuation of another conversation.
</div>
<div
class="_subtitle_sq5fu_35"
>
<a
href="https://matrix.to/#/old_room_id/$tombstone_event_id"
>
Click here to see older messages.
</a>
</div>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,614 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<TextualBody /> renders formatted m.text correctly italics, bold, underline and strikethrough render as expected 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
foo
<em>
baz
</em>
<strong>
bar
</strong>
<del>
del
</del>
<u>
u
</u>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly linkification is not applied to code blocks 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
<p>
Visit
<code>
https://matrix.org/
</code>
</p>
<div
class="mx_EventTile_pre_container"
>
<pre
class="mx_EventTile_collapsedCodeBlock"
>
<span
class="mx_EventTile_lineNumbers"
>
<span>
1
</span>
</span>
<div
style="display: contents;"
>
<code>
https://matrix.org/
</code>
</div>
</pre>
<div
aria-label="Copy"
class="mx_AccessibleButton mx_EventTile_button mx_EventTile_copyButton"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14 5H5v9h1a1 1 0 1 1 0 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1a1 1 0 1 1-2 0z"
/>
<path
d="M8 10a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-9a2 2 0 0 1-2-2zm2 0v9h9v-9z"
/>
</svg>
</div>
</div>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills appear for an MXID permalink 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
Chat with
<bdi>
<a
class="mx_Pill mx_UserPill"
href="https://matrix.to/#/@user:example.com"
>
<span
aria-hidden="true"
aria-label="Profile picture"
class="_avatar_zysgz_8 mx_BaseAvatar"
data-color="2"
data-testid="avatar-img"
data-type="round"
style="--cpd-avatar-size: 16px;"
>
<img
alt=""
class="_image_zysgz_43"
data-type="round"
height="16px"
loading="lazy"
referrerpolicy="no-referrer"
src="mxc://avatar.url/image.png"
width="16px"
/>
</span>
<span
class="mx_Pill_text"
>
Member
</span>
</a>
</bdi>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills appear for event permalinks without a custom label 1`] = `
<DocumentFragment>
<div
class="mx_MTextBody mx_EventTile_content"
>
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
See this message
<bdi>
<a
class="mx_Pill mx_EventPill"
href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/$16085560162aNpaH:example.com?via=example.com"
>
<span
aria-hidden="true"
aria-label="Avatar"
class="_avatar_zysgz_8 mx_BaseAvatar"
data-color="1"
data-testid="avatar-img"
data-type="round"
style="--cpd-avatar-size: 16px;"
>
<img
alt=""
class="_image_zysgz_43"
data-type="round"
height="16px"
loading="lazy"
referrerpolicy="no-referrer"
src="mxc://avatar.url/room.png"
width="16px"
/>
</span>
<span
class="mx_Pill_text"
>
Message in room name
</span>
</a>
</bdi>
</div>
</div>
</DocumentFragment>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills appear for room links with vias 1`] = `
<DocumentFragment>
<div
class="mx_MTextBody mx_EventTile_content"
>
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
A
<bdi>
<a
class="mx_Pill mx_RoomPill"
href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com?via=example.com&via=bob.com"
>
<span
aria-hidden="true"
aria-label="Avatar"
class="_avatar_zysgz_8 mx_BaseAvatar"
data-color="1"
data-testid="avatar-img"
data-type="round"
style="--cpd-avatar-size: 16px;"
>
<img
alt=""
class="_image_zysgz_43"
data-type="round"
height="16px"
loading="lazy"
referrerpolicy="no-referrer"
src="mxc://avatar.url/room.png"
width="16px"
/>
</span>
<span
class="mx_Pill_text"
>
room name
</span>
</a>
</bdi>
with vias
</div>
</div>
</DocumentFragment>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills do not appear for event permalinks with a custom label 1`] = `
<DocumentFragment>
<div
class="mx_MTextBody mx_EventTile_content"
>
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
An
<a
href="https://matrix.to/#/!ZxbRYPQXDXKGmDnJNg:example.com/$16085560162aNpaH:example.com?via=example.com"
rel="noreferrer noopener"
>
event link
</a>
with text
</div>
</div>
</DocumentFragment>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills do not appear in code blocks 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
<p>
<code>
@room
</code>
</p>
<div
class="mx_EventTile_pre_container"
>
<pre
class="mx_EventTile_collapsedCodeBlock"
>
<span
class="mx_EventTile_lineNumbers"
>
<span>
1
</span>
</span>
<div
style="display: contents;"
>
<code>
@room
</code>
</div>
</pre>
<div
aria-label="Copy"
class="mx_AccessibleButton mx_EventTile_button mx_EventTile_copyButton"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14 5H5v9h1a1 1 0 1 1 0 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1a1 1 0 1 1-2 0z"
/>
<path
d="M8 10a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-9a2 2 0 0 1-2-2zm2 0v9h9v-9z"
/>
</svg>
</div>
</div>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly pills get injected correctly into the DOM 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
Hey
<bdi>
<a
class="mx_Pill mx_UserPill"
href="https://matrix.to/#/@user:server"
>
<span
aria-hidden="true"
aria-label="Profile picture"
class="_avatar_zysgz_8 mx_BaseAvatar"
data-color="2"
data-testid="avatar-img"
data-type="round"
style="--cpd-avatar-size: 16px;"
>
<img
alt=""
class="_image_zysgz_43"
data-type="round"
height="16px"
loading="lazy"
referrerpolicy="no-referrer"
src="mxc://avatar.url/image.png"
width="16px"
/>
</span>
<span
class="mx_Pill_text"
>
Member
</span>
</a>
</bdi>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly renders formatted body without html correctly 1`] = `
<div
class="mx_EventTile_body translate"
dir="auto"
>
escaped *markdown*
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly should syntax highlight code blocks 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
<div
class="mx_EventTile_pre_container"
>
<pre
class="mx_EventTile_collapsedCodeBlock"
>
<span
class="mx_EventTile_lineNumbers"
>
<span>
1
</span>
<span>
2
</span>
<span>
3
</span>
<span>
4
</span>
<span>
5
</span>
<span>
6
</span>
<span>
7
</span>
<span>
8
</span>
<span>
9
</span>
<span>
10
</span>
</span>
<div
style="display: contents;"
>
<code
class="language-py"
>
<span
class="hljs-comment"
>
# Python Program to calculate the square root
</span>
<span
class="hljs-comment"
>
# Note: change this value for a different result
</span>
num =
<span
class="hljs-number"
>
8
</span>
<span
class="hljs-comment"
>
# To take the input from the user
</span>
<span
class="hljs-comment"
>
#num = float(input('Enter a number: '))
</span>
num_sqrt = num **
<span
class="hljs-number"
>
0.5
</span>
<span
class="hljs-built_in"
>
print
</span>
(
<span
class="hljs-string"
>
'The square root of %0.3f is %0.3f'
</span>
%(num ,num_sqrt))
</code>
</div>
</pre>
<span
class="mx_EventTile_button"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M21 3.997a1 1 0 0 0-.29-.702l-.005-.004A1 1 0 0 0 20 3h-8a1 1 0 1 0 0 2h5.586L5 17.586V12a1 1 0 1 0-2 0v8.003a1 1 0 0 0 .29.702l.005.004c.18.18.43.291.705.291h8a1 1 0 1 0 0-2H6.414L19 6.414V12a1 1 0 1 0 2 0z"
/>
</svg>
</span>
<div
aria-label="Copy"
class="mx_AccessibleButton mx_EventTile_button mx_EventTile_copyButton mx_EventTile_buttonBottom"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14 5H5v9h1a1 1 0 1 1 0 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1a1 1 0 1 1-2 0z"
/>
<path
d="M8 10a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-9a2 2 0 0 1-2-2zm2 0v9h9v-9z"
/>
</svg>
</div>
</div>
</div>
`;
exports[`<TextualBody /> renders formatted m.text correctly spoilers get injected properly into the DOM 1`] = `
<div
class="mx_EventTile_body markdown-body translate"
dir="auto"
>
Hey
<button
class="mx_EventTile_spoiler"
>
<span
class="mx_EventTile_spoiler_reason"
>
(movie)
</span>
 
<span
class="mx_EventTile_spoiler_content"
>
the movie was awesome
</span>
</button>
</div>
`;
exports[`<TextualBody /> renders m.emote correctly 1`] = `
<span
class="mx_EventTile_body translate"
>
winks
</span>
`;
exports[`<TextualBody /> renders m.notice correctly 1`] = `
<div
class="mx_EventTile_body translate"
dir="auto"
>
this is a notice, probably from a bot
</div>
`;
exports[`<TextualBody /> renders plain-text m.text correctly linkification get applied correctly into the DOM 1`] = `
<div
class="mx_EventTile_body translate"
dir="auto"
>
Visit
<a
class="linkified"
href="https://matrix.org/"
rel="noreferrer noopener"
target="_blank"
>
https://matrix.org/
</a>
</div>
`;
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to a message in the same room with the label »Message from Member« 1`] = `"Visit <bdi><a class="mx_Pill mx_EventPill" href="https://matrix.to/#/!room1:example.com/%event_id%"><span aria-label="Profile picture" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_zysgz_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_zysgz_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/image.png"></span><span class="mx_Pill_text">Message from Member</span></a></bdi>"`;
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to an event in another room with the label »Message in Room 2« 1`] = `"Visit <bdi><a class="mx_Pill mx_EventPill" href="https://matrix.to/#/!room2:example.com/%event_id%"><span aria-label="Avatar" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_zysgz_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_zysgz_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/room.png"></span><span class="mx_Pill_text">Message in Room 2</span></a></bdi>"`;
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to an unknown message in the same room with the label »Message« 1`] = `
<div
class="mx_EventTile_body translate"
dir="auto"
>
Visit
<bdi>
<a
class="mx_Pill mx_EventPill"
href="https://matrix.to/#/!room1:example.com/!abc123"
>
<svg
class="mx_Pill_LinkIcon mx_BaseAvatar"
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 19.071q-1.467 1.467-3.536 1.467-2.067 0-3.535-1.467t-1.467-3.535q0-2.07 1.467-3.536L7.05 9.879q.3-.3.707-.3t.707.3.301.707-.3.707l-2.122 2.121a2.9 2.9 0 0 0-.884 2.122q0 1.237.884 2.12.884.885 2.121.885t2.122-.884l2.121-2.121q.3-.3.707-.3t.707.3.3.707q0 .405-.3.707zm-1.414-4.243q-.3.3-.707.301a.97.97 0 0 1-.707-.3q-.3-.3-.301-.708 0-.405.3-.707l4.243-4.242q.3-.3.707-.3t.707.3.3.707-.3.707zm6.364-.707q-.3.3-.707.3a.97.97 0 0 1-.707-.3q-.3-.3-.301-.707 0-.405.3-.707l2.122-2.121q.884-.885.884-2.121 0-1.238-.884-2.122a2.9 2.9 0 0 0-2.121-.884q-1.237 0-2.122.884l-2.121 2.122q-.3.3-.707.3a.97.97 0 0 1-.707-.3q-.3-.3-.3-.708 0-.405.3-.707L12 4.93q1.467-1.467 3.536-1.467t3.535 1.467 1.467 3.536T19.071 12z"
/>
</svg>
<span
class="mx_Pill_text"
>
Message
</span>
</a>
</bdi>
</div>
`;
exports[`<TextualBody /> renders plain-text m.text correctly simple message renders as expected 1`] = `
<div
class="mx_EventTile_body translate"
dir="auto"
>
this is a plaintext message
</div>
`;
@@ -0,0 +1,25 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 from "react";
import { render } from "jest-matrix-react";
import MediaProcessingError from "../../../../../../src/components/views/messages/shared/MediaProcessingError";
describe("<MediaProcessingError />", () => {
const defaultProps = {
className: "test-classname",
children: "Something went wrong",
};
const getComponent = (props = {}) => render(<MediaProcessingError {...defaultProps} {...props} />);
it("renders", () => {
const { container } = getComponent();
expect(container).toMatchSnapshot();
});
});
@@ -0,0 +1,26 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`<MediaProcessingError /> renders 1`] = `
<div>
<span
class="test-classname"
>
<svg
class="mx_MediaProcessingError_Icon"
fill="currentColor"
height="16"
viewBox="0 0 24 24"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6 22q-.824 0-1.412-.587A1.93 1.93 0 0 1 4 20V4q0-.824.588-1.412A1.93 1.93 0 0 1 6 2h7.175a1.98 1.98 0 0 1 1.4.575l4.85 4.85q.275.275.425.638.15.361.15.762v3.516A6 6 0 0 0 18 12V9h-4a.97.97 0 0 1-.713-.287A.97.97 0 0 1 13 8V4H6v16h6.341c.264.745.67 1.423 1.187 2z"
/>
<path
d="M18 14a1 1 0 0 1 1 1v3a1 1 0 1 1-2 0v-3a1 1 0 0 1 1-1m-1 7a1 1 0 1 1 2 0 1 1 0 0 1-2 0"
/>
</svg>
Something went wrong
</span>
</div>
`;