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,72 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { ClientEvent } from "matrix-js-sdk/src/matrix";
import { AccountDataApi } from "../../../src/modules/AccountDataApi";
import { mkEvent, stubClient } from "../../test-utils/test-utils";
describe("AccountDataApi", () => {
describe("AccountDataWatchable", () => {
it("should return content of account data event on get()", () => {
const cli = stubClient();
const api = new AccountDataApi();
// Mock cli to return a event
const content = { foo: "bar" };
const event = mkEvent({ content, type: "m.test", user: "@foobar:matrix.org", event: true });
cli.getAccountData = () => event;
expect(api.get("m.test").value).toStrictEqual(content);
});
it("should update value on event", () => {
const cli = stubClient();
const api = new AccountDataApi();
// Mock cli to return a event
const content = { foo: "bar" };
const event = mkEvent({ content, type: "m.test", user: "@foobar:matrix.org", event: true });
cli.getAccountData = () => event;
const watchable = api.get("m.test");
expect(watchable.value).toStrictEqual(content);
const fn = jest.fn();
watchable.watch(fn);
// Let's say that the account data event changed
const event2 = mkEvent({
content: { foo: "abc" },
type: "m.test",
user: "@foobar:matrix.org",
event: true,
});
cli.emit(ClientEvent.AccountData, event2);
// Watchable value should have been updated
expect(watchable.value).toStrictEqual({ foo: "abc" });
// Watched callbacks should be called
expect(fn).toHaveBeenCalledTimes(1);
// Make sure unwatch removed the event listener
cli.off = jest.fn();
watchable.unwatch(fn);
expect(cli.off).toHaveBeenCalledTimes(1);
});
});
it("should set account data via js-sdk on set()", async () => {
const cli = stubClient();
const api = new AccountDataApi();
await api.set("m.test", { foo: "bar" });
expect(cli.setAccountData).toHaveBeenCalledTimes(1);
});
it("should delete account data via js-sdk on set()", async () => {
const cli = stubClient();
const api = new AccountDataApi();
await api.delete("m.test");
expect(cli.deleteAccountData).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,28 @@
/*
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 { MockModule } from "./MockModule";
import { AppModule } from "../../../src/modules/AppModule";
describe("AppModule", () => {
describe("constructor", () => {
it("should call the factory immediately", () => {
let module: MockModule | undefined;
const appModule = new AppModule((api) => {
if (module) {
throw new Error("State machine error: Factory called twice");
}
module = new MockModule(api);
return module;
});
expect(appModule.module).toBeDefined();
expect(appModule.module).toBe(module);
expect(appModule.api).toBeDefined();
});
});
});
@@ -0,0 +1,30 @@
/*
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 defaultDispatcher from "../../../src/dispatcher/dispatcher.ts";
import { overwriteAccountAuth } from "../../../src/modules/Auth.ts";
describe("overwriteAccountAuth", () => {
it("should call overwrite login with accountInfo", () => {
const spy = jest.spyOn(defaultDispatcher, "dispatch");
const accountInfo = {
userId: "@user:server.com",
deviceId: "DEVICEID",
accessToken: "TOKEN",
homeserverUrl: "https://server.com",
};
overwriteAccountAuth(accountInfo);
expect(spy).toHaveBeenCalledWith(
{
action: "overwrite_login",
credentials: expect.objectContaining(accountInfo),
},
true,
);
});
});
@@ -0,0 +1,69 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render } from "jest-matrix-react";
import { ElementWebBuiltinsApi } from "../../../src/modules/BuiltinsApi.tsx";
import { stubClient } from "../../test-utils/test-utils";
const Avatar: React.FC<{ room: { roomId: string }; size: string }> = ({ room, size }) => {
return (
<div>
Avatar, {room.roomId}, {size}
</div>
);
};
describe("ElementWebBuiltinsApi", () => {
it("returns the RoomView component thats been set", () => {
const builtinsApi = new ElementWebBuiltinsApi();
const sentinel = {};
builtinsApi.setComponents({ roomView: sentinel, roomAvatar: Avatar } as any);
expect(builtinsApi.getRoomViewComponent()).toBe(sentinel);
});
it("returns rendered RoomView component", () => {
const builtinsApi = new ElementWebBuiltinsApi();
const RoomView = () => <div>hello world</div>;
builtinsApi.setComponents({ roomView: RoomView, roomAvatar: Avatar } as any);
const { container } = render(<> {builtinsApi.renderRoomView("!foo:m.org")}</>);
expect(container).toHaveTextContent("hello world");
});
it("returns rendered RoomAvatar component", () => {
stubClient();
const builtinsApi = new ElementWebBuiltinsApi();
builtinsApi.setComponents({ roomView: {}, roomAvatar: Avatar } as any);
const { container } = render(<> {builtinsApi.renderRoomAvatar("!foo:m.org", "50")}</>);
expect(container).toHaveTextContent("Avatar");
expect(container).toHaveTextContent("!foo:m.org");
expect(container).toHaveTextContent("50");
});
it("returns rendered NotificationDecoration component", () => {
stubClient();
const builtinsApi = new ElementWebBuiltinsApi();
const NotificationDecoration = () => <div>notification decoration</div>;
builtinsApi.setComponents({
roomView: {},
roomAvatar: Avatar,
notificationDecoration: NotificationDecoration,
} as any);
const { container } = render(<> {builtinsApi.renderNotificationDecoration("!foo:m.org")}</>);
expect(container).toHaveTextContent("notification decoration");
});
it("should throw error if called before components are set", () => {
stubClient();
const builtinsApi = new ElementWebBuiltinsApi();
expect(() => builtinsApi.renderRoomAvatar("!foo:m.org")).toThrow("No RoomAvatar component has been set");
expect(() => builtinsApi.renderRoomView("!foo:m.org")).toThrow("No RoomView component has been set");
expect(() => builtinsApi.renderNotificationDecoration("!foo:m.org")).toThrow(
"No NotificationDecoration component has been set",
);
});
});
@@ -0,0 +1,20 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { ClientApi } from "../../../src/modules/ClientApi";
import { Room } from "../../../src/modules/models/Room";
import { stubClient } from "../../test-utils/test-utils";
describe("ClientApi", () => {
it("should return module room from getRoom()", () => {
stubClient();
const client = new ClientApi();
const moduleRoom = client.getRoom("!foo:matrix.org");
expect(moduleRoom).toBeInstanceOf(Room);
expect(moduleRoom?.id).toStrictEqual("!foo:matrix.org");
});
});
@@ -0,0 +1,23 @@
/*
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 { screen } from "jest-matrix-react";
import { openDialog } from "../../../src/modules/Dialog.tsx";
describe("openDialog", () => {
it("should open a dialog with the expected title", async () => {
const Dialog = () => <>Dialog Content</>;
const title = "Test Dialog";
openDialog({ title }, Dialog, {});
await expect(screen.findByText("Test Dialog")).resolves.toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
});
});
@@ -0,0 +1,130 @@
/*
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 { RuntimeModule } from "@matrix-org/react-sdk-module-api/lib/RuntimeModule";
import { type ModuleApi } from "@matrix-org/react-sdk-module-api/lib/ModuleApi";
import { type AllExtensions } from "@matrix-org/react-sdk-module-api/lib/types/extensions";
import { type ProvideCryptoSetupExtensions } from "@matrix-org/react-sdk-module-api/lib/lifecycles/CryptoSetupExtensions";
import { type ProvideExperimentalExtensions } from "@matrix-org/react-sdk-module-api/lib/lifecycles/ExperimentalExtensions";
import { ModuleRunner } from "../../../src/modules/ModuleRunner";
export class MockModule extends RuntimeModule {
public get apiInstance(): ModuleApi {
return this.moduleApi;
}
public constructor(moduleApi: ModuleApi) {
super(moduleApi);
}
}
/**
* Register a mock module
*
* @returns The registered module.
*/
export function registerMockModule(): MockModule {
let module: MockModule | undefined;
ModuleRunner.instance.registerModule((api) => {
if (module) {
throw new Error("State machine error: ModuleRunner created the module twice");
}
module = new MockModule(api);
return module;
});
if (!module) {
throw new Error("State machine error: ModuleRunner did not create module");
}
return module;
}
class MockModuleWithCryptoSetupExtension extends RuntimeModule {
public get apiInstance(): ModuleApi {
return this.moduleApi;
}
moduleName: string = MockModuleWithCryptoSetupExtension.name;
extensions: AllExtensions = {
cryptoSetup: {
SHOW_ENCRYPTION_SETUP_UI: true,
examineLoginResponse: jest.fn(),
persistCredentials: jest.fn(),
getSecretStorageKey: jest.fn().mockReturnValue(Uint8Array.from([0x11, 0x22, 0x99])),
createSecretStorageKey: jest.fn(),
catchAccessSecretStorageError: jest.fn(),
setupEncryptionNeeded: jest.fn(),
getDehydrationKeyCallback: jest.fn(),
} as ProvideCryptoSetupExtensions,
};
public constructor(moduleApi: ModuleApi) {
super(moduleApi);
}
}
class MockModuleWithExperimentalExtension extends RuntimeModule {
public get apiInstance(): ModuleApi {
return this.moduleApi;
}
moduleName: string = MockModuleWithExperimentalExtension.name;
extensions: AllExtensions = {
experimental: {
experimentalMethod: jest.fn().mockReturnValue(Uint8Array.from([0x22, 0x44, 0x88])),
} as ProvideExperimentalExtensions,
};
public constructor(moduleApi: ModuleApi) {
super(moduleApi);
}
}
/**
* Register a mock module which implements the cryptoSetup extension.
*
* @returns The registered module.
*/
export function registerMockModuleWithCryptoSetupExtension(): MockModuleWithCryptoSetupExtension {
let module: MockModuleWithCryptoSetupExtension | undefined;
ModuleRunner.instance.registerModule((api) => {
if (module) {
throw new Error("State machine error: ModuleRunner created the module twice");
}
module = new MockModuleWithCryptoSetupExtension(api);
return module;
});
if (!module) {
throw new Error("State machine error: ModuleRunner did not create module");
}
return module;
}
/**
* Register a mock module which implements the experimental extension.
*
* @returns The registered module.
*/
export function registerMockModuleWithExperimentalExtension(): MockModuleWithExperimentalExtension {
let module: MockModuleWithExperimentalExtension | undefined;
ModuleRunner.instance.registerModule((api) => {
if (module) {
throw new Error("State machine error: ModuleRunner created the module twice");
}
module = new MockModuleWithExperimentalExtension(api);
return module;
});
if (!module) {
throw new Error("State machine error: ModuleRunner did not create module");
}
return module;
}
@@ -0,0 +1,33 @@
/*
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 { TextInputField } from "@matrix-org/react-sdk-module-api/lib/components/TextInputField";
import { Spinner as ModuleSpinner } from "@matrix-org/react-sdk-module-api/lib/components/Spinner";
import "../../../src/modules/ModuleRunner";
describe("Module Components", () => {
// Note: we're not testing to see if there's components that are missing a renderFactory()
// but rather that the renderFactory() for components we do know about is actually defined
// and working.
//
// We do this by deliberately not importing the ModuleComponents file itself, relying on the
// ModuleRunner import to do its job (as per documentation in ModuleComponents).
it("should override the factory for a TextInputField", () => {
const { asFragment } = render(<TextInputField label="My Label" value="My Value" onChange={() => {}} />);
expect(asFragment()).toMatchSnapshot();
});
it("should override the factory for a ModuleSpinner", () => {
const { asFragment } = render(<ModuleSpinner />);
expect(asFragment()).toMatchSnapshot();
});
});
@@ -0,0 +1,96 @@
/*
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 {
type RoomPreviewOpts,
RoomViewLifecycle,
} from "@matrix-org/react-sdk-module-api/lib/lifecycles/RoomViewLifecycle";
import {
type MockModule,
registerMockModule,
registerMockModuleWithCryptoSetupExtension,
registerMockModuleWithExperimentalExtension,
} from "./MockModule";
import { ModuleRunner } from "../../../src/modules/ModuleRunner";
describe("ModuleRunner", () => {
afterEach(() => {
ModuleRunner.instance.reset();
});
// Translations implicitly tested by ProxiedModuleApi integration tests.
describe("invoke", () => {
it("should invoke to every registered module", async () => {
const module1 = registerMockModule();
const module2 = registerMockModule();
const wrapEmit = (module: MockModule) =>
new Promise((resolve) => {
module.on(RoomViewLifecycle.PreviewRoomNotLoggedIn, (val1, val2) => {
resolve([val1, val2]);
});
});
const promises = Promise.all([wrapEmit(module1), wrapEmit(module2)]);
const roomId = "!room:example.org";
const opts: RoomPreviewOpts = { canJoin: false };
ModuleRunner.instance.invoke(RoomViewLifecycle.PreviewRoomNotLoggedIn, opts, roomId);
const results = await promises;
expect(results).toEqual([
[opts, roomId], // module 1
[opts, roomId], // module 2
]);
});
});
describe("extensions", () => {
it("should return default values when no crypto-setup extensions are provided by a registered module", async () => {
registerMockModule();
const result = ModuleRunner.instance.extensions.cryptoSetup.getSecretStorageKey();
expect(result).toBeNull();
});
it("should return default values when no experimental extensions are provided by a registered module", async () => {
registerMockModule();
const result = ModuleRunner.instance.extensions?.experimental.experimentalMethod();
expect(result).toBeNull();
});
it("should return value from crypto-setup-extensions provided by a registered module", async () => {
registerMockModuleWithCryptoSetupExtension();
const result = ModuleRunner.instance.extensions.cryptoSetup.getSecretStorageKey();
expect(result).toEqual(Uint8Array.from([0x11, 0x22, 0x99]));
});
it("should return value from experimental-extensions provided by a registered module", async () => {
registerMockModuleWithExperimentalExtension();
const result = ModuleRunner.instance.extensions.experimental.experimentalMethod();
expect(result).toEqual(Uint8Array.from([0x22, 0x44, 0x88]));
});
it("must not allow multiple modules to provide cryptoSetup extension", async () => {
registerMockModuleWithCryptoSetupExtension();
const t = () => registerMockModuleWithCryptoSetupExtension();
expect(t).toThrow(Error);
expect(t).toThrow(
"adding cryptoSetup extension implementation from module MockModuleWithCryptoSetupExtension but an implementation was already provided",
);
});
it("must not allow multiple modules to provide experimental extension", async () => {
registerMockModuleWithExperimentalExtension();
const t = () => registerMockModuleWithExperimentalExtension();
expect(t).toThrow(Error);
expect(t).toThrow(
"adding experimental extension implementation from module MockModuleWithExperimentalExtension but an implementation was already provided",
);
});
});
});
@@ -0,0 +1,61 @@
/*
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 * as navigator from "../../../src/utils/permalinks/navigator";
import { NavigationApi } from "../../../src/modules/Navigation.ts";
import defaultDispatcher from "../../../src/dispatcher/dispatcher.ts";
describe("NavigationApi", () => {
const api = new NavigationApi();
describe("toMatrixToLink", () => {
it.each([
["roomId", "https://matrix.to/#/!roomId:server.com"],
["roomAlias", "https://matrix.to/#/#alias:server.com"],
["user", "https://matrix.to/#/@user:server.com"],
])("should call navigateToPermalink with the correct parameters for %s", async (_type, link) => {
const spy = jest.spyOn(navigator, "navigateToPermalink");
await api.toMatrixToLink(link);
expect(spy).toHaveBeenCalledWith(link);
});
it("should set auto_join to true when join=true", async () => {
const link = "https://matrix.to/#/#alias:server.com?via=server.com";
const spy = jest.spyOn(defaultDispatcher, "dispatch");
await api.toMatrixToLink(link, true);
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
action: "view_room",
room_alias: "#alias:server.com",
auto_join: true,
}),
);
});
it("should dispatch correct action on openRoom", () => {
const spy = jest.spyOn(defaultDispatcher, "dispatch");
// Non alias
api.openRoom("!foo:m.org");
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
action: "view_room",
room_id: "!foo:m.org",
}),
);
// Alias
api.openRoom("#bar:m.org");
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
action: "view_room",
room_alias: "#bar:m.org",
}),
);
});
});
});
@@ -0,0 +1,391 @@
/*
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 TranslationStringsObject } from "@matrix-org/react-sdk-module-api/lib/types/translations";
import { type AccountAuthInfo } from "@matrix-org/react-sdk-module-api/lib/types/AccountAuthInfo";
import { DialogContent, type DialogProps } from "@matrix-org/react-sdk-module-api/lib/components/DialogContent";
import { screen, within } from "jest-matrix-react";
import userEvent from "@testing-library/user-event";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type Mocked } from "jest-mock";
import { ProxiedModuleApi } from "../../../src/modules/ProxiedModuleApi";
import { getMockClientWithEventEmitter, mkRoom, stubClient } from "../../test-utils";
import { setLanguage } from "../../../src/languageHandler";
import { ModuleRunner } from "../../../src/modules/ModuleRunner";
import { registerMockModule } from "./MockModule";
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
import { Action } from "../../../src/dispatcher/actions";
import WidgetStore, { type IApp } from "../../../src/stores/WidgetStore";
import { Container, WidgetLayoutStore } from "../../../src/stores/widgets/WidgetLayoutStore";
import * as navigator from "../../../src/utils/permalinks/navigator.ts";
describe("ProxiedApiModule", () => {
afterEach(() => {
ModuleRunner.instance.reset();
});
// Note: Remainder is implicitly tested from end-to-end tests of modules.
describe("translations", () => {
it("should cache translations", () => {
const api = new ProxiedModuleApi();
expect(api.translations).toBeFalsy();
const translations: TranslationStringsObject = {
["custom string"]: {
en: "custom string",
fr: "custom french string",
},
};
api.registerTranslations(translations);
expect(api.translations).toBe(translations);
});
it("should overwriteAccountAuth", async () => {
const dispatchSpy = jest.spyOn(defaultDispatcher, "dispatch");
const api = new ProxiedModuleApi();
const accountInfo = {} as unknown as AccountAuthInfo;
const promise = api.overwriteAccountAuth(accountInfo);
expect(dispatchSpy).toHaveBeenCalledWith(
expect.objectContaining({
action: Action.OverwriteLogin,
credentials: {
...accountInfo,
guest: false,
},
}),
expect.anything(),
);
defaultDispatcher.fire(Action.OnLoggedIn);
await expect(promise).resolves.toBeUndefined();
});
describe("integration", () => {
it("should translate strings using translation system", async () => {
// Test setup
stubClient();
// Set up a module to pull translations through
const module = registerMockModule();
const en = "custom string";
const de = "custom german string";
const enVars = "custom variable %(var)s";
const varVal = "string";
const deVars = "custom german variable %(var)s";
const deFull = `custom german variable ${varVal}`;
expect(module.apiInstance).toBeInstanceOf(ProxiedModuleApi);
module.apiInstance.registerTranslations({
[en]: {
en: en,
de: de,
},
[enVars]: {
en: enVars,
de: deVars,
},
});
await setLanguage("de"); // calls `registerCustomTranslations()` for us
// See if we can pull the German string out
expect(module.apiInstance.translateString(en)).toEqual(de);
expect(module.apiInstance.translateString(enVars, { var: varVal })).toEqual(deFull);
});
afterEach(async () => {
await setLanguage("en"); // reset the language
});
});
});
describe("openDialog", () => {
it("should open dialog with a custom title and default options", async () => {
class MyDialogContent extends DialogContent {
public constructor(props: DialogProps) {
super(props);
}
trySubmit = async () => ({ result: true });
render = () => <p>This is my example content.</p>;
}
const api = new ProxiedModuleApi();
const resultPromise = api.openDialog<{ result: boolean }, DialogProps, MyDialogContent>(
"My Dialog Title",
(props, ref) => <MyDialogContent ref={ref} {...props} />,
);
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByRole("heading", { name: "My Dialog Title" })).toBeInTheDocument();
expect(within(dialog).getByText("This is my example content.")).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeInTheDocument();
await userEvent.click(within(dialog).getByRole("button", { name: "OK" }));
expect(await resultPromise).toEqual({
didOkOrSubmit: true,
model: { result: true },
});
expect(dialog).not.toBeInTheDocument();
});
it("should open dialog with custom options", async () => {
class MyDialogContent extends DialogContent {
public constructor(props: DialogProps) {
super(props);
}
trySubmit = async () => ({ result: true });
render = () => <p>This is my example content.</p>;
}
const api = new ProxiedModuleApi();
const resultPromise = api.openDialog<{ result: boolean }, DialogProps, MyDialogContent>(
{
title: "My Custom Dialog Title",
actionLabel: "Submit it",
cancelLabel: "Cancel it",
canSubmit: false,
},
(props, ref) => <MyDialogContent ref={ref} {...props} />,
);
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByRole("heading", { name: "My Custom Dialog Title" })).toBeInTheDocument();
expect(within(dialog).getByText("This is my example content.")).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Submit it" })).toBeDisabled();
await userEvent.click(within(dialog).getByRole("button", { name: "Cancel it" }));
expect(await resultPromise).toEqual({ didOkOrSubmit: false });
expect(dialog).not.toBeInTheDocument();
});
it("should update the options from the opened dialog", async () => {
class MyDialogContent extends DialogContent {
public constructor(props: DialogProps) {
super(props);
}
trySubmit = async () => ({ result: true });
render = () => {
const onClick = () => {
this.props.setOptions({
title: "My New Title",
actionLabel: "New Action",
cancelLabel: "New Cancel",
});
// check if delta updates work
this.props.setOptions({
canSubmit: false,
});
};
return (
<button type="button" onClick={onClick}>
Change the settings!
</button>
);
};
}
const api = new ProxiedModuleApi();
const resultPromise = api.openDialog<{ result: boolean }, DialogProps, MyDialogContent>(
"My Dialog Title",
(props, ref) => <MyDialogContent ref={ref} {...props} />,
);
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByRole("heading", { name: "My Dialog Title" })).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "OK" })).toBeEnabled();
await userEvent.click(within(dialog).getByRole("button", { name: "Change the settings!" }));
expect(within(dialog).getByRole("heading", { name: "My New Title" })).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "New Action" })).toBeDisabled();
await userEvent.click(within(dialog).getByRole("button", { name: "New Cancel" }));
expect(await resultPromise).toEqual({
didOkOrSubmit: false,
model: undefined,
});
expect(dialog).not.toBeInTheDocument();
});
it("should cancel the dialog from within the dialog", async () => {
class MyDialogContent extends DialogContent {
public constructor(props: DialogProps) {
super(props);
}
trySubmit = async () => ({ result: true });
render = () => (
<button type="button" onClick={this.props.cancel}>
No need for action
</button>
);
}
const api = new ProxiedModuleApi();
const resultPromise = api.openDialog<{ result: boolean }, DialogProps, MyDialogContent>(
"My Dialog Title",
(props, ref) => <MyDialogContent ref={ref} {...props} />,
);
const dialog = await screen.findByRole("dialog");
await userEvent.click(within(dialog).getByRole("button", { name: "No need for action" }));
expect(await resultPromise).toEqual({
didOkOrSubmit: false,
model: undefined,
});
expect(dialog).not.toBeInTheDocument();
});
});
describe("getApps", () => {
it("should return apps from the widget store", () => {
const api = new ProxiedModuleApi();
const app = {} as unknown as IApp;
const apps: IApp[] = [app];
jest.spyOn(WidgetStore.instance, "getApps").mockReturnValue(apps);
expect(api.getApps("!room:example.com")).toEqual(apps);
});
});
describe("getAppAvatarUrl", () => {
const app = {} as unknown as IApp;
const avatarUrl = "https://example.com/avatar.png";
let api: ProxiedModuleApi;
let client: Mocked<MatrixClient>;
beforeEach(() => {
api = new ProxiedModuleApi();
client = getMockClientWithEventEmitter({ mxcUrlToHttp: jest.fn().mockReturnValue(avatarUrl) });
});
it("should return null if the app has no avatar URL", () => {
expect(api.getAppAvatarUrl(app)).toBeNull();
});
it("should return the app avatar URL", () => {
expect(api.getAppAvatarUrl({ ...app, avatar_url: avatarUrl })).toBe(avatarUrl);
});
it("should support optional thumbnail params", () => {
api.getAppAvatarUrl({ ...app, avatar_url: avatarUrl }, 1, 2, "3");
// eslint-disable-next-line no-restricted-properties
expect(client.mxcUrlToHttp).toHaveBeenCalledWith(avatarUrl, 1, 2, "3");
});
});
describe("isAppInContainer", () => {
const app = {} as unknown as IApp;
const roomId = "!room:example.com";
let api: ProxiedModuleApi;
let client: MatrixClient;
beforeEach(() => {
api = new ProxiedModuleApi();
client = stubClient();
jest.spyOn(WidgetLayoutStore.instance, "isInContainer");
});
it("should return false if there is no room", () => {
client.getRoom = jest.fn().mockReturnValue(null);
expect(api.isAppInContainer(app, Container.Top, roomId)).toBe(false);
expect(WidgetLayoutStore.instance.isInContainer).not.toHaveBeenCalled();
});
it("should return false if the app is not in the container", () => {
jest.spyOn(WidgetLayoutStore.instance, "isInContainer").mockReturnValue(false);
expect(api.isAppInContainer(app, Container.Top, roomId)).toBe(false);
});
it("should return true if the app is in the container", () => {
jest.spyOn(WidgetLayoutStore.instance, "isInContainer").mockReturnValue(true);
expect(api.isAppInContainer(app, Container.Top, roomId)).toBe(true);
});
});
describe("moveAppToContainer", () => {
const app = {} as unknown as IApp;
const roomId = "!room:example.com";
let api: ProxiedModuleApi;
let client: MatrixClient;
beforeEach(() => {
api = new ProxiedModuleApi();
client = stubClient();
jest.spyOn(WidgetLayoutStore.instance, "moveToContainer");
});
it("should not move if there is no room", () => {
client.getRoom = jest.fn().mockReturnValue(null);
api.moveAppToContainer(app, Container.Top, roomId);
expect(WidgetLayoutStore.instance.moveToContainer).not.toHaveBeenCalled();
});
it("should move if there is a room", () => {
const room = mkRoom(client, roomId);
client.getRoom = jest.fn().mockReturnValue(room);
api.moveAppToContainer(app, Container.Top, roomId);
expect(WidgetLayoutStore.instance.moveToContainer).toHaveBeenCalledWith(room, app, Container.Top);
});
});
describe("navigatePermalink", () => {
const api = new ProxiedModuleApi();
it("should call navigateToPermalink with the correct parameters", async () => {
const link = "https://matrix.to/#/!roomId:server.com";
const spy = jest.spyOn(navigator, "navigateToPermalink");
await api.navigatePermalink(link);
expect(spy).toHaveBeenCalledWith(link);
});
it("should set auto_join to true when join=true", async () => {
const link = "https://matrix.to/#/#alias:server.com";
const spy = jest.spyOn(defaultDispatcher, "dispatch");
await api.navigatePermalink(link, true);
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
action: "view_room",
room_alias: "#alias:server.com",
auto_join: true,
}),
);
});
});
});
@@ -0,0 +1,84 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { waitFor } from "jest-matrix-react";
import { type RoomListStoreApi, StoresApi } from "../../../src/modules/StoresApi";
import RoomListStoreV3, {
LISTS_LOADED_EVENT,
LISTS_UPDATE_EVENT,
} from "../../../src/stores/room-list-v3/RoomListStoreV3";
import { mkRoom, stubClient } from "../../test-utils/test-utils";
import { Room } from "../../../src/modules/models/Room";
import {} from "../../../src/stores/room-list/algorithms/Algorithm";
describe("StoresApi", () => {
describe("RoomListStoreApi", () => {
it("should return promise that resolves when RLS is ready", async () => {
jest.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(true);
const store = new StoresApi();
let hasResolved = false;
// The following async function will set hasResolved to false
// only when waitForReady resolves.
(async () => {
await store.roomListStore.waitForReady();
hasResolved = true;
})();
// Shouldn't have resolved yet.
expect(hasResolved).toStrictEqual(false);
// Wait for the module to load so that we can test the listener.
await (store.roomListStore as RoomListStoreApi).moduleLoadPromise;
// Emit the loaded event.
RoomListStoreV3.instance.emit(LISTS_LOADED_EVENT);
// Should resolve now.
await waitFor(() => {
expect(hasResolved).toStrictEqual(true);
});
});
describe("getRooms()", () => {
it("should return rooms from RLS", async () => {
const cli = stubClient();
const room1 = mkRoom(cli, "!foo1:m.org");
const room2 = mkRoom(cli, "!foo2:m.org");
const room3 = mkRoom(cli, "!foo3:m.org");
jest.spyOn(RoomListStoreV3.instance, "getSortedRooms").mockReturnValue([room1, room2, room3]);
jest.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(false);
const store = new StoresApi();
await store.roomListStore.waitForReady();
const watchable = store.roomListStore.getRooms();
expect(watchable.value).toHaveLength(3);
expect(watchable.value[0]).toBeInstanceOf(Room);
});
it("should update from RLS", async () => {
const cli = stubClient();
const room1 = mkRoom(cli, "!foo1:m.org");
const room2 = mkRoom(cli, "!foo2:m.org");
const rooms = [room1, room2];
jest.spyOn(RoomListStoreV3.instance, "getSortedRooms").mockReturnValue(rooms);
jest.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(false);
const store = new StoresApi();
await store.roomListStore.waitForReady();
const watchable = store.roomListStore.getRooms();
const fn = jest.fn();
watchable.watch(fn);
expect(watchable.value).toHaveLength(2);
const room3 = mkRoom(cli, "!foo3:m.org");
rooms.push(room3);
RoomListStoreV3.instance.emit(LISTS_UPDATE_EVENT);
expect(fn).toHaveBeenCalledTimes(1);
expect(watchable.value).toHaveLength(3);
});
});
});
});
@@ -0,0 +1,50 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`Module Components should override the factory for a ModuleSpinner 1`] = `
<DocumentFragment>
<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>
</DocumentFragment>
`;
exports[`Module Components should override the factory for a TextInputField 1`] = `
<DocumentFragment>
<div
class="mx_Field mx_Field_input"
>
<input
autocomplete="off"
id="mx_Field_1"
label="My Label"
placeholder="My Label"
type="text"
value="My Value"
/>
<label
for="mx_Field_1"
>
My Label
</label>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,33 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render, screen } from "jest-matrix-react";
import type { Room } from "matrix-js-sdk/src/matrix";
import { ModuleNotificationDecoration } from "../../../../src/modules/components/ModuleNotificationDecoration";
import { mkStubRoom, stubClient } from "../../../test-utils";
import { NotificationLevel } from "../../../../src/stores/notifications/NotificationLevel";
import { RoomNotificationStateStore } from "../../../../src/stores/notifications/RoomNotificationStateStore";
import { RoomNotificationState } from "../../../../src/stores/notifications/RoomNotificationState";
class MockedNotificationState extends RoomNotificationState {
public constructor(room: Room, level: NotificationLevel, count: number) {
super(room, false);
this._level = level;
this._count = count;
}
}
it("Should be able to render component just with room as prop", () => {
const cli = stubClient();
const room = mkStubRoom("!foo:matrix.org", "Foo Room", cli);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(
new MockedNotificationState(room, NotificationLevel.Notification, 5),
);
render(<ModuleNotificationDecoration room={room} />);
expect(screen.getByTestId("notification-decoration")).toBeInTheDocument();
});
@@ -0,0 +1,52 @@
/*
Copyright 2025 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { Room } from "../../../../src/modules/models/Room";
import { mkRoom, stubClient } from "../../../test-utils";
describe("Room", () => {
it("should return id from sdk room", () => {
const cli = stubClient();
const sdkRoom = mkRoom(cli, "!foo:m.org");
const room = new Room(sdkRoom);
expect(room.id).toStrictEqual("!foo:m.org");
});
it("should return last timestamp from sdk room", () => {
const cli = stubClient();
const sdkRoom = mkRoom(cli, "!foo:m.org");
const room = new Room(sdkRoom);
expect(room.getLastActiveTimestamp()).toStrictEqual(sdkRoom.getLastActiveTimestamp());
});
describe("watchableName", () => {
it("should return name from sdkRoom", () => {
const cli = stubClient();
const sdkRoom = mkRoom(cli, "!foo:m.org");
sdkRoom.name = "Foo Name";
const room = new Room(sdkRoom);
expect(room.name.value).toStrictEqual("Foo Name");
});
it("should add/remove event listener on sdk room", () => {
const cli = stubClient();
const sdkRoom = mkRoom(cli, "!foo:m.org");
sdkRoom.name = "Foo Name";
const room = new Room(sdkRoom);
const fn = jest.fn();
const onSpy = jest.spyOn(sdkRoom, "on");
const offSpy = jest.spyOn(sdkRoom, "off");
room.name.watch(fn);
expect(onSpy).toHaveBeenCalledTimes(1);
room.name.unwatch(fn);
expect(offSpy).toHaveBeenCalledTimes(1);
});
});
});