Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/modules/AccountDataApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
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 { Watchable, type AccountDataApi as IAccountDataApi } from "@element-hq/element-web-module-api";
import { ClientEvent, type MatrixEvent, type MatrixClient } from "matrix-js-sdk/src/matrix";

import { MatrixClientPeg } from "../MatrixClientPeg";

export class AccountDataApi implements IAccountDataApi {
public get(eventType: string): Watchable<unknown> {
const cli = MatrixClientPeg.safeGet();
return new AccountDataWatchable(cli, eventType);
}

public async set(eventType: string, content: any): Promise<void> {
const cli = MatrixClientPeg.safeGet();
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
await cli.setAccountData(eventType, content);
}

public async delete(eventType: string): Promise<void> {
const cli = MatrixClientPeg.safeGet();
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
await cli.deleteAccountData(eventType);
}
}

class AccountDataWatchable extends Watchable<unknown> {
public constructor(
private cli: MatrixClient,
private eventType: string,
) {
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
super(cli.getAccountData(eventType)?.getContent());
}

private onAccountData = (event: MatrixEvent): void => {
if (event.getType() === this.eventType) {
this.value = event.getContent();
}
};

protected onFirstWatch(): void {
this.cli.on(ClientEvent.AccountData, this.onAccountData);
}

protected onLastWatch(): void {
this.cli.off(ClientEvent.AccountData, this.onAccountData);
}
}
4 changes: 4 additions & 0 deletions src/modules/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import { openDialog } from "./Dialog.tsx";
import { overwriteAccountAuth } from "./Auth.ts";
import { ElementWebExtrasApi } from "./ExtrasApi.ts";
import { ElementWebBuiltinsApi } from "./BuiltinsApi.tsx";
import { ClientApi } from "./ClientApi.ts";
import { StoresApi } from "./StoresApi.ts";

const legacyCustomisationsFactory = <T extends object>(baseCustomisations: T) => {
let used = false;
Expand Down Expand Up @@ -84,6 +86,8 @@ export class ModuleApi implements Api {
public readonly extras = new ElementWebExtrasApi();
public readonly builtins = new ElementWebBuiltinsApi();
public readonly rootNode = document.getElementById("matrixchat")!;
public readonly client = new ClientApi();
public readonly stores = new StoresApi();

public createRoot(element: Element): Root {
return createRoot(element);
Expand Down
20 changes: 20 additions & 0 deletions src/modules/ClientApi.ts
Original file line number Diff line number Diff line change
@@ -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 type { ClientApi as IClientApi, Room } from "@element-hq/element-web-module-api";
import { Room as ModuleRoom } from "./models/Room";
import { AccountDataApi } from "./AccountDataApi";
import { MatrixClientPeg } from "../MatrixClientPeg";

export class ClientApi implements IClientApi {
public readonly accountData = new AccountDataApi();

public getRoom(roomId: string): Room | null {
const sdkRoom = MatrixClientPeg.safeGet().getRoom(roomId);
if (sdkRoom) return new ModuleRoom(sdkRoom);
return null;
}
}
39 changes: 20 additions & 19 deletions src/modules/Navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details.
*/

import { type LocationRenderFunction, type NavigationApi as INavigationApi } from "@element-hq/element-web-module-api";

import type {
LocationRenderFunction,
NavigationApi as INavigationApi,
OpenRoomOptions,
} from "@element-hq/element-web-module-api";
import { navigateToPermalink } from "../utils/permalinks/navigator.ts";
import { parsePermalink } from "../utils/permalinks/Permalinks.ts";
import dispatcher from "../dispatcher/dispatcher.ts";
Expand All @@ -21,27 +24,25 @@ export class NavigationApi implements INavigationApi {

const parts = parsePermalink(link);
if (parts?.roomIdOrAlias) {
if (parts.roomIdOrAlias.startsWith("#")) {
dispatcher.dispatch<ViewRoomPayload>({
action: Action.ViewRoom,
room_alias: parts.roomIdOrAlias,
via_servers: parts.viaServers ?? undefined,
auto_join: join,
metricsTrigger: undefined,
});
} else {
dispatcher.dispatch<ViewRoomPayload>({
action: Action.ViewRoom,
room_id: parts.roomIdOrAlias,
via_servers: parts.viaServers ?? undefined,
auto_join: join,
metricsTrigger: undefined,
});
}
this.openRoom(parts.roomIdOrAlias, {
viaServers: parts.viaServers ?? undefined,
autoJoin: join,
});
}
}

public registerLocationRenderer(path: string, renderer: LocationRenderFunction): void {
this.locationRenderers.set(path, renderer);
}

public openRoom(roomIdOrAlias: string, opts: OpenRoomOptions = {}): void {
const key = roomIdOrAlias.startsWith("#") ? "room_alias" : "room_id";
dispatcher.dispatch<ViewRoomPayload>({
action: Action.ViewRoom,
[key]: roomIdOrAlias,
via_servers: opts.viaServers,
auto_join: opts.autoJoin,
metricsTrigger: undefined,
});
}
}
106 changes: 106 additions & 0 deletions src/modules/StoresApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
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 {
type StoresApi as IStoresApi,
type RoomListStoreApi as IRoomListStore,
type Room,
Watchable,
} from "@element-hq/element-web-module-api";

import type { RoomListStoreV3Class, RoomListStoreV3Event } from "../stores/room-list-v3/RoomListStoreV3";
import { Room as ModuleRoom } from "./models/Room";

interface RlsEvents {
LISTS_LOADED_EVENT: RoomListStoreV3Event.ListsLoaded;
LISTS_UPDATE_EVENT: RoomListStoreV3Event.ListsUpdate;
}

export class RoomListStoreApi implements IRoomListStore {
private rls?: RoomListStoreV3Class;
private LISTS_LOADED_EVENT?: RoomListStoreV3Event.ListsLoaded;
private LISTS_UPDATE_EVENT?: RoomListStoreV3Event.ListsUpdate;
public readonly moduleLoadPromise: Promise<void>;

public constructor() {
this.moduleLoadPromise = this.init();
}

/**
* Load the RLS through a dynamic import. This is necessary to prevent
* circular dependency issues.
*/
private async init(): Promise<void> {
const module = await import("../stores/room-list-v3/RoomListStoreV3");
this.rls = module.default.instance;
this.LISTS_LOADED_EVENT = module.LISTS_LOADED_EVENT;
this.LISTS_UPDATE_EVENT = module.LISTS_UPDATE_EVENT;
}

public getRooms(): RoomsWatchable {
return new RoomsWatchable(this.roomListStore, this.events);
}

private get events(): RlsEvents {
if (!this.LISTS_LOADED_EVENT || !this.LISTS_UPDATE_EVENT) {
throw new Error("Event type was not loaded correctly, did you forget to await waitForReady()?");
}
return { LISTS_LOADED_EVENT: this.LISTS_LOADED_EVENT, LISTS_UPDATE_EVENT: this.LISTS_UPDATE_EVENT };
}

private get roomListStore(): RoomListStoreV3Class {
if (!this.rls) {
throw new Error("rls is undefined, did you forget to await waitForReady()?");
}
return this.rls;
}

public async waitForReady(): Promise<void> {
// Wait for the module to load first
await this.moduleLoadPromise;

// Check if RLS is already loaded
if (!this.roomListStore.isLoadingRooms) return;

// Await a promise that resolves when RLS has loaded
const { promise, resolve } = Promise.withResolvers<void>();
const { LISTS_LOADED_EVENT } = this.events;
this.roomListStore.once(LISTS_LOADED_EVENT, resolve);
await promise;
}
}

class RoomsWatchable extends Watchable<Room[]> {
public constructor(
private readonly rls: RoomListStoreV3Class,
private readonly events: RlsEvents,
) {
super(rls.getSortedRooms().map((sdkRoom) => new ModuleRoom(sdkRoom)));
}

private onRlsUpdate = (): void => {
this.value = this.rls.getSortedRooms().map((sdkRoom) => new ModuleRoom(sdkRoom));
};

protected onFirstWatch(): void {
this.rls.on(this.events.LISTS_UPDATE_EVENT, this.onRlsUpdate);
}

protected onLastWatch(): void {
this.rls.off(this.events.LISTS_UPDATE_EVENT, this.onRlsUpdate);
}
}

export class StoresApi implements IStoresApi {
private roomListStoreApi?: IRoomListStore;

public get roomListStore(): IRoomListStore {
if (!this.roomListStoreApi) {
this.roomListStoreApi = new RoomListStoreApi();
}
return this.roomListStoreApi;
}
}
45 changes: 45 additions & 0 deletions src/modules/models/Room.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
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 { type Room as IRoom, Watchable } from "@element-hq/element-web-module-api";
import { RoomEvent, type Room as SdkRoom } from "matrix-js-sdk/src/matrix";

export class Room implements IRoom {
public name: Watchable<string>;

public constructor(private sdkRoom: SdkRoom) {
this.name = new WatchableName(sdkRoom);
}

public getLastActiveTimestamp(): number {
return this.sdkRoom.getLastActiveTimestamp();
}

public get id(): string {
return this.sdkRoom.roomId;
}
}

/**
* A custom watchable for room name.
*/
class WatchableName extends Watchable<string> {
public constructor(private sdkRoom: SdkRoom) {
super(sdkRoom.name);
}

private onNameUpdate = (): void => {
super.value = this.sdkRoom.name;
};
protected onFirstWatch(): void {
this.sdkRoom.on(RoomEvent.Name, this.onNameUpdate);
}

protected onLastWatch(): void {
this.sdkRoom.off(RoomEvent.Name, this.onNameUpdate);
}
}
1 change: 1 addition & 0 deletions test/test-utils/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,7 @@ export function mkStubRoom(
getJoinedMembers: jest.fn().mockReturnValue([]),
getLiveTimeline: jest.fn().mockReturnValue(stubTimeline),
getLastLiveEvent: jest.fn().mockReturnValue(undefined),
getLastActiveTimestamp: jest.fn().mockReturnValue(1183140000),
getMember: jest.fn().mockReturnValue({
userId: "@member:domain.bla",
name: "Member",
Expand Down
72 changes: 72 additions & 0 deletions test/unit-tests/modules/AccountDataApi-test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading