Ongoing call tiles - Implement the view-models and store (#34198)

* Add a common view snapshot type

This will contain the common snapshot values used by both dm ongoing
call tile view and room ongoing call tile view.

* Implement the common join button component

* Implement the call icon component

* Implement the common container component

* Support single digit minutes in existing clock component

* Implement the view for duration component

* Add static profile pics to be used in storybook tests

* Implement view for member avatar component

* Implement view for face pile component

* Implement RoomOngoingCallTileView

* Implement DmOngoingCallTileView

* Support the new tiles in RootTileView

* Export all the views

* Update all the screenshots

* Implement view model for duration view

* Implement vm for face pile view

* Implement vm for member avatar view

* Expose call store via the sdk context

* Add method to get all calls in store

* Add store to track latest notification event per room

* Also expose new store via sdk context

* Create a base vm for both tiles

* Implement the room ongoing call tile vm

* Implement the dm ongoing call tile vm

* Support new tile vms in the root tile vm

* Rename getCallInRoom -> getCallOrThrow

* Change confusing comment in test

* Check existing events first and use decryption promise

* Clarify recompute vs update in code comment

* Use vi.mocked instead of ts-ignore

* Change type of size to number

* Import only the type

* Pass size as number instead of string

* Check if call is jistsi call in root tile

* Add more tests

* Rename isCallIgnored -> isCallDeclined

* Add a comment about the 10px margin

* Add comments to explain css heights and widths
This commit is contained in:
R Midhun Suresh
2026-07-13 20:22:16 +05:30
committed by GitHub
parent a6c8a14b74
commit c4606c19f8
20 changed files with 1449 additions and 9 deletions
@@ -9,10 +9,15 @@
import { it, describe, expect, vi } from "vitest";
import { type EventTimeline, EventType, type MatrixEvent, type RoomState } from "matrix-js-sdk/src/matrix";
import { EventEmitter } from "node:stream";
import { mkEvent, mkMessage, mkRoomMember, mkStubRoom, stubClient } from "../../../../../../test/test-utils";
import { getMockedRtcNotificationEvent, MockedCall, MockedCallStore } from "./call-mocks";
import { RootCallTileViewModel } from "./RootCallTileViewModel";
import {
LatestRtcNotificationEventUpdate,
type LatestRtcNotificationEventStore,
} from "../../../../../stores/LatestRtcNotificationEventStore";
function getEvents(): MatrixEvent[] {
const message1 = mkMessage({
@@ -80,21 +85,65 @@ function getMocked(userIds: string[]) {
} as unknown as EventTimeline;
});
return { callStore, cli, mxEvent, call };
const latestRtcNotificationEventStore = new EventEmitter() as unknown as LatestRtcNotificationEventStore;
latestRtcNotificationEventStore.getLatestEventId = () => undefined;
return { callStore, latestRtcNotificationEventStore, cli, mxEvent, call };
}
describe("RootCallTileViewModel", () => {
it("computes correct tileType for ongoing call in DM", () => {
const { callStore, cli, mxEvent, latestRtcNotificationEventStore } = getMocked(["@alice:m.org", "@bob:m.org"]);
latestRtcNotificationEventStore.getLatestEventId = () => "new-event";
const vm = new RootCallTileViewModel({ latestRtcNotificationEventStore, callStore, cli, mxEvent });
expect(vm.getSnapshot().tileType).toStrictEqual("ongoing-call-dm");
});
it("computes correct tileType for ongoing call in Room", () => {
const { callStore, cli, mxEvent, latestRtcNotificationEventStore } = getMocked([
"@alice:m.org",
"@bob:m.org",
"@jack:m.org",
]);
latestRtcNotificationEventStore.getLatestEventId = () => "new-event";
const vm = new RootCallTileViewModel({ latestRtcNotificationEventStore, callStore, cli, mxEvent });
expect(vm.getSnapshot().tileType).toStrictEqual("ongoing-call-room");
});
it("computes correct tileType for tombstone call in DM", () => {
const { cli, mxEvent } = getMocked(["@alice:m.org", "@bob:m.org"]);
const vm = new RootCallTileViewModel({ cli, mxEvent });
// When there's an ongoing call
const { callStore, cli, mxEvent, latestRtcNotificationEventStore } = getMocked(["@alice:m.org", "@bob:m.org"]);
const vm = new RootCallTileViewModel({ latestRtcNotificationEventStore, callStore, cli, mxEvent });
expect(vm.getSnapshot().tileType).toStrictEqual("tombstone-call-dm");
});
it("computes correct tileType for tombstone call in Room", () => {
const { cli, mxEvent } = getMocked(["@alice:m.org", "@bob:m.org", "@jack:m.org"]);
const vm = new RootCallTileViewModel({ cli, mxEvent });
// When there's an ongoing call
const { callStore, cli, mxEvent, latestRtcNotificationEventStore } = getMocked([
"@alice:m.org",
"@bob:m.org",
"@jack:m.org",
]);
const vm = new RootCallTileViewModel({ latestRtcNotificationEventStore, callStore, cli, mxEvent });
expect(vm.getSnapshot().tileType).toStrictEqual("tombstone-call-room");
});
it("recomputes snapshot on event from LatestRtcNotificationEventUpdate", () => {
// When there's an ongoing call
const { callStore, cli, mxEvent, latestRtcNotificationEventStore } = getMocked([
"@alice:m.org",
"@bob:m.org",
"@jack:m.org",
]);
const vm = new RootCallTileViewModel({ latestRtcNotificationEventStore, callStore, cli, mxEvent });
expect(vm.getSnapshot().tileType).toStrictEqual("tombstone-call-room");
// Tile type should update on event
latestRtcNotificationEventStore.getLatestEventId = () => "new-event";
latestRtcNotificationEventStore.emit(LatestRtcNotificationEventUpdate, "!my-room:m.org", "new-event");
expect(vm.getSnapshot().tileType).toStrictEqual("ongoing-call-room");
});
});
@@ -6,11 +6,19 @@
*/
import { type MatrixClient, type MatrixEvent } from "matrix-js-sdk/src/matrix";
import { BaseViewModel, type RootCallTileViewSnapshot } from "@element-hq/web-shared-components";
import { BaseViewModel, type ViewModel, type RootCallTileViewSnapshot } from "@element-hq/web-shared-components";
import type { GetRelationsForEvent } from "../../../../../components/views/rooms/EventTile";
import { type CallStore, CallStoreEvent } from "../../../../../stores/CallStore";
import { RoomOngoingCallTileViewModel } from "./tiles/ongoing/RoomOngoingCallTileViewModel";
import { DmOngoingCallTileViewModel } from "./tiles/ongoing/DmOngoingCallTileViewModel";
import { DmTombstoneCallTileViewModel } from "./tiles/tombstone/DmTombstoneCallTileViewModel";
import { RoomTombstoneCallTileViewModel } from "./tiles/tombstone/RoomTombstoneCallTileViewModel";
import {
LatestRtcNotificationEventUpdate,
type LatestRtcNotificationEventStore,
} from "../../../../../stores/LatestRtcNotificationEventStore";
import { JitsiCall } from "../../../../../models/Call";
interface Props {
/**
@@ -27,6 +35,16 @@ interface Props {
* The {@link MatrixClient} object to access js-sdk API.
*/
cli: MatrixClient;
/**
* {@link CallStore} to access calls in a room.
*/
callStore: CallStore;
/**
* {@link LatestRtcNotificationEventStore} to track the latest notification event id.
*/
latestRtcNotificationEventStore: LatestRtcNotificationEventStore;
}
function computeSnapshot(props: Props): RootCallTileViewSnapshot {
@@ -39,9 +57,47 @@ function computeSnapshot(props: Props): RootCallTileViewSnapshot {
const room = cli.getRoom(roomId);
if (!room) throw new Error(`No room with id ${roomId}`);
const lastId = props.latestRtcNotificationEventStore.getLatestEventId(roomId);
const isLastNotificationEvent = lastId === notificationEvent.getId();
const isLocalEvent = notificationEvent.getId()?.startsWith("~");
// Check if there's an ongoing call
const call = props.callStore.getCall(roomId);
const hasOngoingCall = !!call && !(call instanceof JitsiCall);
// This is the same logic used for hiding/showing the voice call button.
const isDmRoom = room.getMembers().length <= 2;
/**
* We know we should render the ongoing tile if:
* - There's an ongoing call in this room
* - This is the last call tile in the room or a local call tile.
*/
if ((isLastNotificationEvent || isLocalEvent) && hasOngoingCall) {
if (isDmRoom) {
return {
tileType: "ongoing-call-dm",
tileViewModel: new DmOngoingCallTileViewModel({
mxEvent: notificationEvent,
roomId,
getRelationsForEvent: props.getRelationsForEvent,
callStore: props.callStore,
cli: props.cli,
}),
};
}
return {
tileType: "ongoing-call-room",
tileViewModel: new RoomOngoingCallTileViewModel({
roomId,
mxEvent: notificationEvent,
getRelationsForEvent: props.getRelationsForEvent,
callStore: props.callStore,
cli: props.cli,
}),
};
}
if (isDmRoom) {
return {
tileType: "tombstone-call-dm",
@@ -65,5 +121,53 @@ export class RootCallTileViewModel extends BaseViewModel<RootCallTileViewSnapsho
public constructor(props: Props) {
const snapshot = computeSnapshot(props);
super(props, snapshot);
this.trackViewModel(snapshot.tileViewModel);
this.addListener();
}
private addListener(): void {
// Recompute the state on changes to the call in this room
this.disposables.trackListener(
this.props.callStore,
CallStoreEvent.Call,
this.onCallStoreEvent as (...args: unknown[]) => void,
);
// Recompute the state when the latest rtc notification event in this room changes
this.disposables.trackListener(this.props.latestRtcNotificationEventStore, LatestRtcNotificationEventUpdate, ((
roomId: string,
eventId: string,
) => {
if (roomId === this.props.mxEvent.getRoomId() && eventId === this.props.mxEvent.getId()) {
this.recomputeSnapshot();
}
}) as (...args: unknown[]) => void);
}
private onCallStoreEvent = (_: unknown, roomId: string): void => {
if (roomId === this.props.mxEvent.getRoomId()) {
this.recomputeSnapshot();
}
};
private recomputeSnapshot(): void {
const snapshot = computeSnapshot(this.props);
const currentTileType = this.getSnapshot().tileType;
if (currentTileType === snapshot.tileType) {
/**
* We're already rendering the correct vm if the tile type did not change.
* So dispose thew new vm and return.
*/
(snapshot.tileViewModel as BaseViewModel<unknown, unknown>).dispose();
return;
}
this.trackViewModel(snapshot.tileViewModel);
this.snapshot.set(snapshot);
}
private trackViewModel(vm: ViewModel<unknown>): void {
// ViewModel type has no dispose method, so this needs a type assertion.
this.disposables.track(vm as BaseViewModel<unknown, unknown>);
}
}
@@ -8,7 +8,7 @@
import { EventEmitter } from "events";
import { type RoomMember, type MatrixEvent, EventType } from "matrix-js-sdk/src/matrix";
import { mkEvent } from "../../../../../../test/test-utils";
import { mkEvent, mkRoomMember } from "../../../../../../test/test-utils";
import { type ElementCall } from "../../../../../models/Call";
import type { CallStore } from "../../../../../stores/CallStore";
import type { CallMembership, MatrixRTCSession } from "matrix-js-sdk/src/matrixrtc";
@@ -49,6 +49,12 @@ export function getMockedRtcDeclineEvent(rtcNotificationEvent: MatrixEvent, send
return mockEvent;
}
export function getMockedMember(roomId: string, userId: string, name: string): RoomMember {
const member = mkRoomMember(roomId, userId);
member.name = name;
return member;
}
interface MockCallStoreType extends CallStore {
withActiveCall(): this;
isActiveCall: boolean;
@@ -0,0 +1,159 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
// @vitest-environment happy-dom
import { it, describe, expect, vi } from "vitest";
import { CallDirection, CallType } from "@element-hq/web-shared-components";
import { BaseOngoingCallViewModel } from "./BaseOngoingCallTileViewModel";
import { mkRoom, stubClient } from "../../../../../../../../test/test-utils";
import { CallEvent } from "../../../../../../../models/Call";
import type { RootCallTileViewModel } from "../../RootCallTileViewModel";
import { getMockedMember, getMockedRtcNotificationEvent, MockedCall, MockedCallStore } from "../../call-mocks";
import type { EventTimeline, RoomState } from "matrix-js-sdk/src/matrix";
import { placeCall } from "../../../../../../../utils/room/placeCall";
import { PlatformCallType } from "../../../../../../../hooks/room/useRoomCall";
/**
* There's a nasty circular dependency in useRoomCall so that we end up with:
* BaseOngoingCallViewModel -> useRoomCall -> ... -> EventTileFactory
* -> RootCallTileViewModel -> RoomOngoingCallTileViewModel -> BaseOngoingCallViewModel
*/
//@ts-ignore
vi.mock(import("../../RootCallTileViewModel"), () => {
return {
RootCallTileViewModel: class {} as unknown as RootCallTileViewModel,
};
});
vi.mock(import("../../../../../../../utils/room/placeCall"), () => {
return {
placeCall: vi.fn(),
};
});
const roomId = "!my-room:m.org";
describe("BaseOngoingCallViewModel", () => {
describe("should compute the correct snapshot", () => {
it("startedByDisplayName", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create();
const callStore = MockedCallStore.create(call);
const vm = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().startedByDisplayName).toStrictEqual("Alice");
});
it("isJoined", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const bob = getMockedMember(roomId, "@bob:m.org", "Bob");
const call = MockedCall.create().withParticipants([bob]);
const callStore = MockedCallStore.create(call);
// Alice hasn't joined the call yet
const vm = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().isJoined).toStrictEqual(false);
// Alice has joined call
callStore.withActiveCall();
call.withParticipants([mxEvent.sender, bob]);
call.emit(CallEvent.Participants, call.participants, new Map());
expect(vm.getSnapshot().isJoined).toStrictEqual(true);
});
it("callDirection", () => {
const cli = stubClient();
vi.spyOn(cli, "getUserId").mockReturnValue("@bob:m.org");
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100, "@alice:m.org");
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create();
const callStore = MockedCallStore.create(call);
const vm1 = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm1.getSnapshot().callDirection).toStrictEqual(CallDirection.Incoming);
vi.spyOn(cli, "getUserId").mockReturnValue("@alice:m.org");
const vm2 = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm2.getSnapshot().callDirection).toStrictEqual(CallDirection.Outgoing);
});
it("callHasOtherParticipants", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create().withParticipants([mxEvent.sender]);
const callStore = MockedCallStore.create(call);
// Call has no other participants other than alice
const vm = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().callHasOtherParticipants).toStrictEqual(false);
// Let's say others join
const bob = getMockedMember(roomId, "@bob:m.org", "Bob");
const james = getMockedMember(roomId, "@james:m.org", "James");
call.withParticipants([mxEvent.sender, bob, james]);
call.emit(CallEvent.Participants, call.participants, new Map());
expect(vm.getSnapshot().callHasOtherParticipants).toStrictEqual(true);
});
it("isJoinable", () => {
const cli = stubClient();
const room = mkRoom(cli, roomId);
// @ts-ignore
room.getLiveTimeline = (): EventTimeline => {
return {
getState: (): RoomState => {
return {
mayClientSendStateEvent: () => true,
} as unknown as RoomState;
},
} as unknown as EventTimeline;
};
cli.getRoom = () => room;
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create();
const callStore = MockedCallStore.create(call);
const vm = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().isJoinable).toStrictEqual(true);
});
});
it("should join call on join()", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("video", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create().withParticipants([mxEvent.sender]);
const callStore = MockedCallStore.create(call);
const vm = new BaseOngoingCallViewModel({ mxEvent, cli, callStore, roomId });
vm.join();
const [room, callType, platformCallType] = vi.mocked(placeCall).mock.calls[0];
expect(room.roomId).toStrictEqual(roomId);
expect(callType).toStrictEqual(CallType.Video);
expect(platformCallType).toStrictEqual(PlatformCallType.ElementCall);
});
});
@@ -0,0 +1,184 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import {
BaseViewModel,
CallDirection,
CallType as SharedComponentsCallType,
type CommonOngoingCallTileViewSnapshot,
} from "@element-hq/web-shared-components";
import {
EventTimeline,
EventType,
type RoomMember,
type MatrixEvent,
type MatrixClient,
} from "matrix-js-sdk/src/matrix";
import { CallType } from "matrix-js-sdk/src/webrtc/call";
import { type CallStore } from "../../../../../../../stores/CallStore";
import { MemberAvatarViewModel } from "../../../../../../../components/viewmodels/avatars/MemberAvatarViewModel";
import { FacePileViewModel } from "../../../../../../../components/viewmodels/avatars/FacePileViewModel";
import { CallEvent, type ElementCall } from "../../../../../../../models/Call";
import { placeCall } from "../../../../../../../utils/room/placeCall";
import { PlatformCallType } from "../../../../../../../hooks/room/useRoomCall";
import { type GetRelationsForEvent } from "../../../../../../../components/views/rooms/EventTile";
import { getIntentFromEvent } from "../../common";
import { DurationViewModel } from "./components/DurationViewModel";
export interface Props {
/**
* The id of the room.
*/
roomId: string;
/**
* Event of type `org.matrix.msc4075.rtc.notification`.
*/
mxEvent: MatrixEvent;
/**
* Helper to fetch related events from a given event.
*/
getRelationsForEvent?: GetRelationsForEvent;
/**
* The {@link MatrixClient} object to access js-sdk API.
*/
cli: MatrixClient;
/**
* {@link CallStore} to access calls in a room.
*/
callStore: CallStore;
}
function getCallOrThrow(store: CallStore, roomId: string): ElementCall {
const call = store.getCall(roomId);
if (!call) {
throw new Error(`No call in room ${roomId}`);
}
return call as ElementCall;
}
/**
* Whether this call has participants other than who started the call.
*/
function doesCallHaveOtherParticipants(notificationEvent: MatrixEvent, participants: RoomMember[]): boolean {
return Array.from(participants).some((participant) => participant.userId !== notificationEvent.sender?.userId);
}
function computeSnapshot(props: Props): CommonOngoingCallTileViewSnapshot {
const mxEvent = props.mxEvent;
const callStore = props.callStore;
const cli = props.cli;
const roomId = mxEvent.getRoomId();
if (!roomId) {
throw new Error("RTCNotification event has no room associated with it!");
}
// Get the call in the room
const call = getCallOrThrow(callStore, roomId);
// Find the mx-id of the user who started this call
const startedUserId = mxEvent.getSender();
if (!startedUserId) {
throw new Error("RTCNotification event has no sender associated with it!");
}
// Get room-member from mx-id
const participants = Array.from(call.participants.keys());
const callHasOtherParticipants = doesCallHaveOtherParticipants(props.mxEvent, participants);
const room = cli.getRoom(roomId);
if (!room) {
throw new Error(`Cannot find room ${roomId}`);
}
const startedMember = mxEvent.sender;
if (!startedMember) {
// This should never happen but just to be safe ...
throw new Error("Event does not have a sender!");
}
const startedByDisplayName = startedMember.name;
// We know we're joined to this call if there's an active call in the room
const isJoined = !!callStore.getActiveCall(roomId);
const callDirection = cli.getUserId() === startedUserId ? CallDirection.Outgoing : CallDirection.Incoming;
// Create the avatar vms
const facePileViewModel = new FacePileViewModel({ size: 20, members: participants, cli });
const memberAvatarViewModel = new MemberAvatarViewModel({ member: startedMember, size: 20, cli });
const isJoinable = !!room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.mayClientSendStateEvent(EventType.GroupCallMemberPrefix, room.client);
const callStartTs = call.session.getOldestMembership()?.createdTs();
let durationViewModel: DurationViewModel | undefined;
if (callStartTs) {
durationViewModel = new DurationViewModel({ callStartTs });
}
return {
startedByDisplayName,
isJoined,
isJoinable,
facePileViewModel,
memberAvatarViewModel,
callDirection,
durationViewModel,
callHasOtherParticipants,
};
}
/**
* A base view model for an ongoing call in the timeline.
*/
export class BaseOngoingCallViewModel<
T extends CommonOngoingCallTileViewSnapshot = CommonOngoingCallTileViewSnapshot,
> extends BaseViewModel<T, Props> {
public constructor(props: Props, extraSnapshot: Partial<T> = {}) {
const snapshot = { ...computeSnapshot(props), ...extraSnapshot };
super(props, snapshot as T);
this.disposables.track(snapshot.facePileViewModel as BaseViewModel<unknown, unknown>);
this.disposables.track(snapshot.memberAvatarViewModel as BaseViewModel<unknown, unknown>);
this.setupListener();
}
private setupListener(): void {
const call = getCallOrThrow(this.props.callStore, this.props.roomId);
this.disposables.trackListener(call, CallEvent.Participants, ((participants: Map<RoomMember, Set<string>>) => {
this.onParticipantsChange(participants);
}) as (...args: unknown[]) => void);
}
/**
* Join the call associated with this tile.
* @param event The button click event
*/
public join(event?: React.MouseEvent<HTMLButtonElement>): void {
const roomId = this.props.roomId;
const room = this.props.cli.getRoom(roomId);
if (!room) {
throw new Error(`Cannot find room ${roomId}`);
}
const callType = getIntentFromEvent(this.props.mxEvent);
const type = callType === SharedComponentsCallType.Voice ? CallType.Voice : CallType.Video;
placeCall(room, type, PlatformCallType.ElementCall, event?.shiftKey || undefined, type === CallType.Voice);
}
/**
* Recomputes the snapshot when the call participants are updated.
*/
protected onParticipantsChange(participants: Map<RoomMember, Set<string>>, extraSnapshot: Partial<T> = {}): void {
const roomId = this.props.roomId;
const isJoined = !!this.props.callStore.getActiveCall(roomId);
const members = Array.from(participants.keys());
const callHasOtherParticipants = doesCallHaveOtherParticipants(this.props.mxEvent, members);
(this.getSnapshot().facePileViewModel as FacePileViewModel).updateMembers(members);
this.snapshot.merge({ isJoined, callHasOtherParticipants, ...extraSnapshot } as Partial<T>);
}
}
@@ -0,0 +1,49 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
// @vitest-environment happy-dom
import { it, describe, expect } from "vitest";
import { CallType } from "@element-hq/web-shared-components";
import { stubClient } from "../../../../../../../../test/test-utils";
import { getMockedMember, getMockedRtcNotificationEvent, MockedCall, MockedCallStore } from "../../call-mocks";
import { DmOngoingCallTileViewModel } from "./DmOngoingCallTileViewModel";
const roomId = "!my-room:m.org";
describe("DmOngoingCallTileViewModel", () => {
describe("should compute the correct snapshot", () => {
describe("callType", () => {
it("voice", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create().withParticipants([mxEvent.sender]);
const callStore = MockedCallStore.create(call);
const vm = new DmOngoingCallTileViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().callType).toStrictEqual(CallType.Voice);
});
it("video", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("video", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create().withParticipants([mxEvent.sender]);
const callStore = MockedCallStore.create(call);
const vm = new DmOngoingCallTileViewModel({ mxEvent, cli, callStore, roomId });
expect(vm.getSnapshot().callType).toStrictEqual(CallType.Video);
});
});
});
});
@@ -0,0 +1,27 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import {
type CommonOngoingCallTileViewAction,
type DmOngoingCallTileViewSnapshot,
} from "@element-hq/web-shared-components";
import { type Props, BaseOngoingCallViewModel } from "./BaseOngoingCallTileViewModel";
import { getIntentFromEvent } from "../../common";
/**
* View model for an ongoing call in a DM room.
*/
export class DmOngoingCallTileViewModel
extends BaseOngoingCallViewModel<DmOngoingCallTileViewSnapshot>
implements CommonOngoingCallTileViewAction
{
public constructor(props: Props) {
const callType = getIntentFromEvent(props.mxEvent);
super(props, { callType });
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
// @vitest-environment happy-dom
import { it, describe, expect, vi } from "vitest";
import { EventType, MatrixEventEvent } from "matrix-js-sdk/src/matrix";
import { stubClient } from "../../../../../../../../test/test-utils";
import {
getMockedMember,
getMockedRtcDeclineEvent,
getMockedRtcNotificationEvent,
MockedCall,
MockedCallStore,
} from "../../call-mocks";
import { RoomOngoingCallTileViewModel } from "./RoomOngoingCallTileViewModel";
import { CallEvent } from "../../../../../../../models/Call";
const roomId = "!my-room:m.org";
describe("RoomOngoingCallTileViewModel", () => {
describe("should compute the correct snapshot", () => {
it("totalParticipants", () => {
const cli = stubClient();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const bob = getMockedMember(roomId, "@bob:m.org", "Bob");
const james = getMockedMember(roomId, "@james:m.org", "James");
const call = MockedCall.create().withParticipants([mxEvent.sender, bob, james]);
const callStore = MockedCallStore.create(call);
const vm = new RoomOngoingCallTileViewModel({ mxEvent, cli, callStore, roomId });
// Call has 3 participants now
expect(vm.getSnapshot().totalParticipants).toStrictEqual(3);
// Peter also joins the call
const peter = getMockedMember(roomId, "@peter:m.org", "Peter");
call.withParticipants([mxEvent.sender, bob, james, peter]);
call.emit(CallEvent.Participants, call.participants, new Map());
// Now there should be 4 participants
expect(vm.getSnapshot().totalParticipants).toStrictEqual(4);
});
it("isCallIgnored", () => {
const cli = stubClient();
vi.spyOn(cli, "getUserId").mockReturnValue("@alice:m.org");
const getRelationsForEvent = vi.fn();
const mxEvent = getMockedRtcNotificationEvent("audio", 100, 100);
mxEvent.sender = getMockedMember(roomId, "@alice:m.org", "Alice");
const call = MockedCall.create().withParticipants([mxEvent.sender]);
const callStore = MockedCallStore.create(call);
const vm = new RoomOngoingCallTileViewModel({ mxEvent, cli, callStore, roomId, getRelationsForEvent });
// Call hasn't been ignored yet
expect(vm.getSnapshot().isCallIgnored).toStrictEqual(false);
// Ignore the call
const declineEvent = getMockedRtcDeclineEvent(mxEvent, "@alice:m.org");
getRelationsForEvent.mockReturnValue({ getRelations: () => [declineEvent] });
mxEvent.emit(MatrixEventEvent.RelationsCreated, "m.reference", EventType.RTCDecline);
// Call should be ignored
expect(vm.getSnapshot().isCallIgnored).toStrictEqual(true);
});
});
});
@@ -0,0 +1,71 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import {
type CommonOngoingCallTileViewAction,
type RoomOngoingCallTileViewSnapshot,
} from "@element-hq/web-shared-components";
import { MatrixEventEvent, type MatrixEvent, type RoomMember, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type Props, BaseOngoingCallViewModel } from "./BaseOngoingCallTileViewModel";
import { getDeclinedEvents } from "../../common";
import { type GetRelationsForEvent } from "../../../../../../../components/views/rooms/EventTile";
/**
* Check if this call is declined by our user.
*/
function isCallDeclinedByOwnUser(
notificationEvent: MatrixEvent,
getRelationsForEvent: GetRelationsForEvent | undefined,
cli: MatrixClient,
): boolean {
const declinedEvents = getDeclinedEvents(notificationEvent, getRelationsForEvent);
const ownUserId = cli.getUserId();
return declinedEvents?.some((event) => event.getSender() === ownUserId) ?? false;
}
/**
* View model for an ongoing call in a non DM room.
*/
export class RoomOngoingCallTileViewModel
extends BaseOngoingCallViewModel<RoomOngoingCallTileViewSnapshot>
implements CommonOngoingCallTileViewAction
{
public constructor(props: Props) {
// Get the call in the room
const call = props.callStore.getCall(props.roomId);
if (!call) {
throw new Error(`No call in room ${props.roomId}`);
}
const totalParticipants = call.participants.size;
const isCallDeclined = isCallDeclinedByOwnUser(props.mxEvent, props.getRelationsForEvent, props.cli);
super(props, { totalParticipants, isCallIgnored: isCallDeclined });
// When a relation is added to the event, recompute the state.
this.disposables.trackListener(props.mxEvent, MatrixEventEvent.RelationsCreated, () => {
this.onRelationsCreated();
});
}
/**
* Recompute the snapshot when a relation is added to the notification event.
* We do this so that we know if our user has declined (ignored) this call.
*/
private onRelationsCreated(): void {
const isCallIgnored = isCallDeclinedByOwnUser(
this.props.mxEvent,
this.props.getRelationsForEvent,
this.props.cli,
);
this.snapshot.merge({ isCallIgnored });
}
protected onParticipantsChange(participants: Map<RoomMember, Set<string>>): void {
const totalParticipants = participants.size;
super.onParticipantsChange(participants, { totalParticipants });
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import { describe, it, beforeEach, afterEach, vi, expect } from "vitest";
import { DurationViewModel } from "./DurationViewModel";
describe("DurationViewModel", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.clearAllMocks();
});
it("should compute duration correctly", () => {
const callStartTs = Date.now();
vi.advanceTimersByTime(100 * 1000);
const vm = new DurationViewModel({ callStartTs });
// Time elapsed from callStartTs is 100 seconds, so expect duration to be 100
expect(vm.getSnapshot().duration).toStrictEqual(100);
// Snapshot must update as time goes on
vi.advanceTimersByTime(100 * 1000);
expect(vm.getSnapshot().duration).toStrictEqual(200);
});
});
@@ -0,0 +1,47 @@
/*
* Copyright 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
* Please see LICENSE files in the repository root for full details.
*/
import { BaseViewModel, type DurationViewSnapshot } from "@element-hq/web-shared-components";
interface Props {
/**
* The timestamp of when this call started.
*/
callStartTs: number;
}
/**
* Get the duration of the call in seconds
* @param timestamp The timestamp at which the call started
*/
function getDurationInSeconds(timestamp: number): number {
const durationInMs = Date.now() - timestamp;
const durationInSeconds = Math.floor(durationInMs * 0.001);
return durationInSeconds;
}
/**
* View model for showing the duration of an ongoing call.
*/
export class DurationViewModel extends BaseViewModel<DurationViewSnapshot, Props> {
public constructor(props: Props) {
super(props, { duration: getDurationInSeconds(props.callStartTs) });
this.setupInterval();
}
/**
* Update the duration every second.
*/
private setupInterval(): void {
const intervalRef = setInterval(() => {
this.snapshot.set({ duration: getDurationInSeconds(this.props.callStartTs) });
}, 1000);
this.disposables.track(() => {
clearInterval(intervalRef);
});
}
}