Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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);
}
}
2 changes: 2 additions & 0 deletions src/modules/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import { overwriteAccountAuth } from "./Auth.ts";
import { ElementWebExtrasApi } from "./ExtrasApi.ts";
import { ElementWebBuiltinsApi } from "./BuiltinsApi.tsx";
import { ClientApi } from "./ClientApi.ts";

const legacyCustomisationsFactory = <T extends object>(baseCustomisations: T) => {
let used = false;
Expand Down Expand Up @@ -73,7 +74,7 @@
legacyCustomisationsFactory(WidgetVariableCustomisations);
/* eslint-enable @typescript-eslint/naming-convention */

public readonly navigation = new NavigationApi();

Check failure on line 77 in src/modules/Api.ts

View workflow job for this annotation

GitHub Actions / Typescript Syntax Check

Property 'navigation' in type 'ModuleApi' is not assignable to the same property in base type 'Api'.
public readonly openDialog = openDialog;
public readonly overwriteAccountAuth = overwriteAccountAuth;
public readonly profile = new WatchableProfile();
Expand All @@ -84,6 +85,7 @@
public readonly extras = new ElementWebExtrasApi();
public readonly builtins = new ElementWebBuiltinsApi();
public readonly rootNode = document.getElementById("matrixchat")!;
public readonly client = new ClientApi();

public createRoot(element: Element): Root {
return createRoot(element);
Expand Down
25 changes: 25 additions & 0 deletions src/modules/ClientApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
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 {
private accountDataApi?: AccountDataApi;

public getRoom(roomId: string): Room | null {
const sdkRoom = MatrixClientPeg.safeGet().getRoom(roomId);
if (sdkRoom) return new ModuleRoom(sdkRoom);
return null;
}

public get accountData(): AccountDataApi {
this.accountDataApi ??= new AccountDataApi();
return this.accountDataApi;
}
}
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);
});
});
20 changes: 20 additions & 0 deletions test/unit-tests/modules/ClientApi-test.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 { 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");
});
});
50 changes: 50 additions & 0 deletions test/unit-tests/modules/models/Room-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
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();

room.name.watch(fn);
expect(sdkRoom.on).toHaveBeenCalledTimes(1);

room.name.unwatch(fn);
expect(sdkRoom.off).toHaveBeenCalledTimes(1);
});
});
});
Loading