mirror of
https://github.com/vector-im/element-call.git
synced 2026-12-01 10:11:09 +08:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43710aeaa4 | ||
|
|
6cc56d3613 | ||
|
|
24592744df | ||
|
|
30227a6a05 | ||
|
|
c18ced6455 | ||
|
|
c2cedb343f | ||
|
|
79746ba64d | ||
|
|
8bed69aa36 | ||
|
|
6623576dc7 |
@@ -172,6 +172,12 @@
|
||||
"login_auth_links_prompt": "Not registered yet?",
|
||||
"login_subheading": "To continue to Element",
|
||||
"login_title": "Login",
|
||||
"low_bandwidth_mode": {
|
||||
"camera_unavailable": "You can't turn on your camera while Low bandwidth mode is on. Turn it off in Developer options.",
|
||||
"screen_share_unavailable": "You can't share your screen while Low bandwidth mode is on. Turn it off in Developer options.",
|
||||
"switch_description": "Stop all video for this call, so that audio keeps flowing on a slow network. Lasts until the call ends.",
|
||||
"switch_label": "Low bandwidth mode"
|
||||
},
|
||||
"microphone_level": {
|
||||
"label": "Microphone level",
|
||||
"no_device": "No microphone found. Connect one, then try again.",
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Browser, expect, type Page, test } from "@playwright/test";
|
||||
|
||||
import { SpaHelpers } from "./spa-helpers.ts";
|
||||
import {
|
||||
expectInboundVideo,
|
||||
expectNoInboundVideo,
|
||||
recordPeerConnections,
|
||||
setLowBandwidthMode,
|
||||
} from "./utils/low-bandwidth-mode.ts";
|
||||
|
||||
test.describe("Low bandwidth mode", () => {
|
||||
test.skip(
|
||||
({ browserName }) => browserName !== "chromium",
|
||||
"Reads inbound video from Chromium's statistics, and shares a fake screen",
|
||||
);
|
||||
test.slow();
|
||||
|
||||
test("receives and sends no video, and gives the camera back", async ({
|
||||
browser,
|
||||
}) => {
|
||||
const { alice, bob } = await twoInACall(browser);
|
||||
await expectInboundVideo(alice);
|
||||
|
||||
await setLowBandwidthMode(alice, true);
|
||||
|
||||
// Bob's camera looks off to Alice, and nothing of it arrives
|
||||
await expect(tileOf(alice, "Bob")).toHaveAttribute(
|
||||
"data-video-enabled",
|
||||
"false",
|
||||
);
|
||||
await expectNoInboundVideo(alice);
|
||||
// Alice's camera is off, for her and for Bob
|
||||
await expect(
|
||||
alice.getByRole("switch", { name: "Start video" }),
|
||||
).toHaveAttribute("aria-disabled", "true");
|
||||
await expect(tileOf(bob, "Alice")).toHaveAttribute(
|
||||
"data-video-enabled",
|
||||
"false",
|
||||
);
|
||||
|
||||
// Bob's screen share keeps its place on Alice's stage, blank
|
||||
await bob.getByRole("switch", { name: "Share screen" }).click();
|
||||
await expect(alice.getByRole("radio", { name: "Spotlight" })).toBeChecked();
|
||||
await expectNoInboundVideo(alice);
|
||||
|
||||
await setLowBandwidthMode(alice, false);
|
||||
const firstFrameMs = await expectInboundVideo(alice);
|
||||
test.info().annotations.push({
|
||||
type: "video back after turning the mode off",
|
||||
description: `${firstFrameMs} ms`,
|
||||
});
|
||||
await expect(
|
||||
alice.getByRole("switch", { name: "Stop video" }),
|
||||
).toBeVisible();
|
||||
await expect(tileOf(alice, "Bob")).toHaveAttribute(
|
||||
"data-video-enabled",
|
||||
"true",
|
||||
);
|
||||
});
|
||||
|
||||
test("stays on through a reconnection, and can be turned off during one", async ({
|
||||
browser,
|
||||
}) => {
|
||||
const { alice } = await twoInACall(browser);
|
||||
await setLowBandwidthMode(alice, true);
|
||||
await expectNoInboundVideo(alice);
|
||||
|
||||
await alice.context().setOffline(true);
|
||||
await expect(
|
||||
alice.getByRole("dialog", { name: "Reconnecting…" }),
|
||||
).toBeVisible({ timeout: 30000 });
|
||||
await alice.context().setOffline(false);
|
||||
await expect(
|
||||
alice.getByRole("dialog", { name: "Reconnecting…" }),
|
||||
).not.toBeVisible({ timeout: 30000 });
|
||||
await expectNoInboundVideo(alice);
|
||||
|
||||
// The switch is reachable over the reconnecting backdrop
|
||||
await alice.context().setOffline(true);
|
||||
await expect(
|
||||
alice.getByRole("dialog", { name: "Reconnecting…" }),
|
||||
).toBeVisible({ timeout: 30000 });
|
||||
await setLowBandwidthMode(alice, false);
|
||||
await alice.context().setOffline(false);
|
||||
await expectInboundVideo(alice);
|
||||
});
|
||||
});
|
||||
|
||||
async function twoInACall(
|
||||
browser: Browser,
|
||||
): Promise<{ alice: Page; bob: Page }> {
|
||||
const aliceContext = await browser.newContext({ reducedMotion: "reduce" });
|
||||
await recordPeerConnections(aliceContext);
|
||||
const alice = await aliceContext.newPage();
|
||||
await alice.goto("/");
|
||||
await SpaHelpers.createCall(alice, "Alice", "Low bandwidth", true);
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(alice);
|
||||
|
||||
const bob = await (await browser.newContext()).newPage();
|
||||
await SpaHelpers.joinCallFromInviteLink(bob, inviteLink, "Bob");
|
||||
await SpaHelpers.expectVideoTilesCount(alice, 2);
|
||||
return { alice, bob };
|
||||
}
|
||||
|
||||
function tileOf(page: Page, name: string): ReturnType<Page["getByTestId"]> {
|
||||
return page
|
||||
.getByTestId("videoTile")
|
||||
.filter({ has: page.getByTestId("name_tag").filter({ hasText: name }) })
|
||||
.first();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { SpaHelpers } from "../spa-helpers.ts";
|
||||
import { setLowBandwidthMode } from "../utils/low-bandwidth-mode.ts";
|
||||
|
||||
test("@mobile a tap on the camera button in Low bandwidth mode says why it stays off", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "John Doe", "Low bandwidth", true);
|
||||
await expect(page.getByTestId("name_tag")).toContainText("John Doe");
|
||||
|
||||
await setLowBandwidthMode(page, true);
|
||||
const camera = page.getByTestId("incall_videomute");
|
||||
await expect(camera).toHaveAttribute("aria-disabled", "true");
|
||||
|
||||
await camera.tap();
|
||||
|
||||
await expect(page.getByRole("tooltip")).toHaveText(
|
||||
"You can't turn on your camera while Low bandwidth mode is on. Turn it off in Developer options.",
|
||||
);
|
||||
await expect(camera).toHaveAttribute("aria-checked", "false");
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
type BrowserContext,
|
||||
expect,
|
||||
type FrameLocator,
|
||||
type Page,
|
||||
} from "@playwright/test";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
peerConnections?: RTCPeerConnection[];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps every peer connection the pages of `context` open, so that what
|
||||
* they receive can be read from the browser's own statistics. Install before
|
||||
* the call loads.
|
||||
*/
|
||||
export async function recordPeerConnections(
|
||||
context: BrowserContext,
|
||||
): Promise<void> {
|
||||
await context.addInitScript(() => {
|
||||
const Original = window.RTCPeerConnection;
|
||||
window.peerConnections = [];
|
||||
window.RTCPeerConnection = class extends Original {
|
||||
public constructor(config?: RTCConfiguration) {
|
||||
super(config);
|
||||
window.peerConnections!.push(this);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Bytes of video received so far, over every peer connection on the page. */
|
||||
export async function inboundVideoBytes(
|
||||
target: Page | FrameLocator,
|
||||
): Promise<number> {
|
||||
const read = async (): Promise<number> => {
|
||||
let bytes = 0;
|
||||
for (const connection of window.peerConnections ?? []) {
|
||||
if (connection.connectionState === "closed") continue;
|
||||
const report = await connection.getStats();
|
||||
report.forEach((stat: RTCInboundRtpStreamStats) => {
|
||||
if (stat.type === "inbound-rtp" && stat.kind === "video")
|
||||
bytes += stat.bytesReceived ?? 0;
|
||||
});
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
return "evaluate" in target
|
||||
? target.evaluate(read)
|
||||
: target.locator(":root").evaluate(read);
|
||||
}
|
||||
|
||||
/** Expects no video to arrive for `forMs`. */
|
||||
export async function expectNoInboundVideo(
|
||||
target: Page | FrameLocator,
|
||||
forMs = 3000,
|
||||
): Promise<void> {
|
||||
// What was in flight when the subscription ended may still land
|
||||
await new Promise((settled) => setTimeout(settled, 1000));
|
||||
const before = await inboundVideoBytes(target);
|
||||
await new Promise((settled) => setTimeout(settled, forMs));
|
||||
expect(await inboundVideoBytes(target)).toBe(before);
|
||||
}
|
||||
|
||||
/** Expects video to be arriving, and returns how long it took to start. */
|
||||
export async function expectInboundVideo(
|
||||
target: Page | FrameLocator,
|
||||
): Promise<number> {
|
||||
const start = Date.now();
|
||||
const before = await inboundVideoBytes(target);
|
||||
await expect
|
||||
.poll(async () => inboundVideoBytes(target), { timeout: 20000 })
|
||||
.toBeGreaterThan(before);
|
||||
return Date.now() - start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns Low bandwidth mode on or off from the call's developer options,
|
||||
* turning developer mode on first if needed.
|
||||
*/
|
||||
export async function setLowBandwidthMode(
|
||||
target: Page | FrameLocator,
|
||||
on: boolean,
|
||||
): Promise<void> {
|
||||
await target
|
||||
.getByRole("button", { name: "Settings" })
|
||||
.filter({ visible: true })
|
||||
.first()
|
||||
.click();
|
||||
await target.getByRole("tab", { name: "Preferences" }).click();
|
||||
await target.getByText("Developer mode", { exact: true }).check();
|
||||
await target.getByRole("tab", { name: "Developer" }).click();
|
||||
// By its label: the box itself can sit outside the dialog's scrolled view
|
||||
const toggle = target.getByText("Low bandwidth mode", { exact: true });
|
||||
if (on) await toggle.check();
|
||||
else await toggle.uncheck();
|
||||
await target.getByTestId("modal_close").click();
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { widgetTest } from "../fixtures/widget-user.ts";
|
||||
import { HOST1, TestHelpers } from "./test-helpers.ts";
|
||||
import {
|
||||
expectNoInboundVideo,
|
||||
recordPeerConnections,
|
||||
setLowBandwidthMode,
|
||||
} from "../utils/low-bandwidth-mode.ts";
|
||||
|
||||
widgetTest(
|
||||
"Low bandwidth mode in Element Web",
|
||||
async ({ addUser, browserName }) => {
|
||||
test.skip(
|
||||
browserName === "firefox",
|
||||
"Reads inbound video from Chromium's statistics, and shares a fake screen",
|
||||
);
|
||||
test.slow();
|
||||
|
||||
const valere = await addUser("Valere", HOST1);
|
||||
const timo = await addUser("Timo", HOST1);
|
||||
await recordPeerConnections(valere.page.context());
|
||||
|
||||
const callRoom = "LowBandwidthRoom";
|
||||
await TestHelpers.createRoom(callRoom, valere.page, [timo.mxId]);
|
||||
await TestHelpers.createRoom("Elsewhere", valere.page);
|
||||
await TestHelpers.acceptRoomInvite(callRoom, timo.page);
|
||||
await TestHelpers.switchToRoomNamed(valere.page, callRoom);
|
||||
|
||||
await TestHelpers.startCallInCurrentRoom(valere.page, false);
|
||||
await TestHelpers.joinCallFromLobby(valere.page);
|
||||
await TestHelpers.joinCallInCurrentRoom(timo.page);
|
||||
|
||||
const valereCall = valere.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
const timoCall = timo.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await expect(valereCall.locator("video")).toHaveCount(2, {
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// A share started before the mode stops when it comes on
|
||||
await valereCall.getByRole("switch", { name: "Share screen" }).click();
|
||||
await expect(
|
||||
timoCall.locator('video[data-source="screenShare"]'),
|
||||
).toHaveCount(1, { timeout: 10000 });
|
||||
|
||||
// Reached from the call's own footer
|
||||
await setLowBandwidthMode(valereCall, true);
|
||||
await expect(
|
||||
valereCall.getByRole("switch", { name: "Share screen", checked: false }),
|
||||
).toHaveAttribute("aria-disabled", "true");
|
||||
await expect(
|
||||
timoCall.locator('video[data-source="screenShare"]'),
|
||||
).toHaveCount(0, { timeout: 10000 });
|
||||
await expectNoInboundVideo(valereCall);
|
||||
|
||||
// Timo shares: Valere keeps the share on the stage, blank
|
||||
await timoCall.getByRole("switch", { name: "Share screen" }).click();
|
||||
await expect(
|
||||
valereCall.getByRole("radio", { name: "Spotlight" }),
|
||||
).toBeChecked({ timeout: 10000 });
|
||||
|
||||
// Leaving the room puts the call in Element Web's PiP, which shows Timo
|
||||
// as a call with no video would, not the blank share
|
||||
await TestHelpers.expandRoomList(valere.page);
|
||||
await TestHelpers.switchToRoomNamed(valere.page, "Elsewhere");
|
||||
await expect(valere.page.getByTestId("widget-pip-container")).toBeVisible();
|
||||
await expect(valereCall.getByTestId("videoTile")).toHaveCount(1);
|
||||
await expect(
|
||||
valereCall.getByTestId("videoTile").getByTestId("name_tag"),
|
||||
).toContainText("Timo");
|
||||
await expect(
|
||||
valereCall.getByTestId("videoTile").getByRole("img"),
|
||||
).toBeVisible();
|
||||
},
|
||||
);
|
||||
@@ -228,6 +228,8 @@ export interface MatrixRTCClientOptions {
|
||||
timings?: Partial<SessionTimings>;
|
||||
/** Limits on what is published; LiveKit's defaults otherwise. */
|
||||
mediaQuality?: MediaQuality;
|
||||
/** Whether remote video is received from the first connection on; true when left out. */
|
||||
receiveVideo?: boolean;
|
||||
/** Use this transport instead of asking the homeserver. */
|
||||
transport?: Transport;
|
||||
/** Use this transport when the homeserver advertises none of the backend's type. */
|
||||
@@ -343,6 +345,13 @@ export interface MatrixRTCClient {
|
||||
*/
|
||||
setAudioOutputDeviceId(deviceId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Whether remote video is received. While false no remote video track is
|
||||
* subscribed on any transport, including transports connected later and
|
||||
* after a reconnection; audio is unaffected. Defaults to true.
|
||||
*/
|
||||
setReceiveVideo(receive: boolean): void;
|
||||
|
||||
/**
|
||||
* Sends a short text to every member on the local transport, over a
|
||||
* reliable data channel beside the media. A packet holds about 15 KiB;
|
||||
|
||||
@@ -105,6 +105,7 @@ interface FakeBackend {
|
||||
connectionState$: BehaviorSubject<MediaConnectionState | Error>;
|
||||
data$: Subject<DataPacket>;
|
||||
setPublishing: Mock<(publish: boolean) => void>;
|
||||
setReceiveVideo: Mock<(receive: boolean) => void>;
|
||||
delegateDelayedLeave: Mock<(delayId: string) => Promise<void>>;
|
||||
mediaFor: Mock<(scope: ObservableScope, member: RTCMember) => MemberMedia>;
|
||||
}
|
||||
@@ -152,6 +153,7 @@ function setup(
|
||||
),
|
||||
data$: new Subject<DataPacket>(),
|
||||
setPublishing: vi.fn(),
|
||||
setReceiveVideo: vi.fn(),
|
||||
delegateDelayedLeave: vi.fn(async () => Promise.resolve()),
|
||||
mediaFor: vi.fn(() => ({
|
||||
tracks$: constant(null),
|
||||
@@ -178,6 +180,7 @@ function setup(
|
||||
mediaFor: fake.mediaFor,
|
||||
connections$: constant([]),
|
||||
setAudioOutputDeviceId: vi.fn(),
|
||||
setReceiveVideo: fake.setReceiveVideo,
|
||||
sendData: vi.fn(),
|
||||
data$: fake.data$,
|
||||
};
|
||||
@@ -375,6 +378,21 @@ describe("createRTCParticipation", () => {
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("hands the receive video choice to the backend, from the join options on", () => {
|
||||
const { participation, fake, scope } = setup({ receiveVideo: false });
|
||||
expect(fake.setReceiveVideo.mock.calls).toEqual([[false]]);
|
||||
|
||||
participation.setReceiveVideo(true);
|
||||
expect(fake.setReceiveVideo).toHaveBeenLastCalledWith(true);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("leaves the backend receiving video when the join options say nothing", () => {
|
||||
const { fake, scope } = setup();
|
||||
expect(fake.setReceiveVideo).not.toHaveBeenCalled();
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("gives the backend the keys the session holds and the ones that follow", () => {
|
||||
const { fake, session, mockedSession, scope } = setup();
|
||||
const keys: MediaKey[] = [];
|
||||
|
||||
@@ -151,6 +151,7 @@ export function createRTCParticipation(
|
||||
timings,
|
||||
logger,
|
||||
});
|
||||
if (options.receiveVideo === false) backend.setReceiveVideo(false);
|
||||
|
||||
// If the backend is LiveKit, we check it for transports as well, as a
|
||||
// fallback: another member's SFU may let us publish (MSC4195). LiveKit only,
|
||||
@@ -320,6 +321,7 @@ export function createRTCParticipation(
|
||||
connectedTransports$: transports.connected$,
|
||||
setAudioOutputDeviceId: async (deviceId) =>
|
||||
backend.setAudioOutputDeviceId(deviceId),
|
||||
setReceiveVideo: (receive) => backend.setReceiveVideo(receive),
|
||||
sendData: async (topic, text) => backend.sendData(topic, text),
|
||||
data$,
|
||||
},
|
||||
|
||||
@@ -92,6 +92,7 @@ function idleBackend(): MediaBackend {
|
||||
mediaFor: vi.fn(),
|
||||
connections$: constant([]),
|
||||
setAudioOutputDeviceId: vi.fn(),
|
||||
setReceiveVideo: vi.fn(),
|
||||
sendData: vi.fn(),
|
||||
data$: EMPTY,
|
||||
};
|
||||
|
||||
@@ -127,6 +127,11 @@ export interface RTCParticipationOptions {
|
||||
timings?: Partial<SessionTimings>;
|
||||
/** Limits on what is published; LiveKit's defaults otherwise. */
|
||||
mediaQuality?: MediaQuality;
|
||||
/**
|
||||
* Whether remote video is received from the first connection on, as
|
||||
* `setReceiveVideo` would set it. True when left out.
|
||||
*/
|
||||
receiveVideo?: boolean;
|
||||
/**
|
||||
* Use this transport instead of asking the homeserver. Any shape the
|
||||
* backend serves: for LiveKit a `url`, a `livekit_service_url` or both.
|
||||
@@ -216,6 +221,13 @@ export interface RTCParticipation {
|
||||
*/
|
||||
setAudioOutputDeviceId(deviceId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Whether remote video is received. While false no remote video track is
|
||||
* subscribed on any transport, including transports connected later and
|
||||
* after a reconnection; audio is unaffected. Defaults to true.
|
||||
*/
|
||||
setReceiveVideo(receive: boolean): void;
|
||||
|
||||
/**
|
||||
* Sends a short text to every member on the local transport, over a
|
||||
* reliable data channel beside the media. A packet holds about 15 KiB;
|
||||
|
||||
@@ -159,6 +159,13 @@ export interface MediaBackend {
|
||||
*/
|
||||
setAudioOutputDeviceId(deviceId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Whether remote video is subscribed. Remembered across connections: every
|
||||
* connection, existing or created later, follows it, including after a
|
||||
* reconnection. Audio is always subscribed. True until first set.
|
||||
*/
|
||||
setReceiveVideo(receive: boolean): void;
|
||||
|
||||
/**
|
||||
* A text channel beside the media: sent on the local transport, received on every one.
|
||||
* This could well be just another track kind. Not needed for element call. just for the sdk target.
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
} from "livekit-client";
|
||||
import fetchMock from "fetch-mock";
|
||||
import EventEmitter from "events";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
import { MatrixError } from "matrix-js-sdk";
|
||||
import { logger, type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
@@ -52,6 +53,7 @@ let testScope: ObservableScope;
|
||||
let client: MockedObject<ClientGetTokenParts & ClientOpenIDParts>;
|
||||
|
||||
let fakeLivekitRoom: MockedObject<LivekitRoom>;
|
||||
let receiveVideo$: BehaviorSubject<boolean>;
|
||||
|
||||
let localParticipantEventEmiter: EventEmitter;
|
||||
let fakeLocalParticipant: MockedObject<LocalParticipant>;
|
||||
@@ -79,12 +81,14 @@ function connectionOpts(): ConnectionOpts {
|
||||
serverName: "m.localhost",
|
||||
scope: testScope,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
receiveVideo$,
|
||||
livekitRoomFactory: () => fakeLivekitRoom,
|
||||
};
|
||||
}
|
||||
|
||||
function setupTest(): void {
|
||||
testScope = new ObservableScope();
|
||||
receiveVideo$ = new BehaviorSubject(true);
|
||||
client = vi.mocked<ClientGetTokenParts & ClientOpenIDParts>({
|
||||
getOpenIdToken: vi.fn().mockResolvedValue({
|
||||
access_token: "rYsmGUEwNjKgJYyeNUkZseJN",
|
||||
@@ -383,6 +387,7 @@ describe("Start connection states", () => {
|
||||
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
|
||||
"wss://sfu",
|
||||
testJWTToken,
|
||||
{ autoSubscribe: true },
|
||||
);
|
||||
expect(connection.livekitAlias).toBe("!example_room_id");
|
||||
});
|
||||
@@ -616,6 +621,169 @@ describe("remote participants", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("receiving video", () => {
|
||||
it("connects without subscribing while video is not received", async () => {
|
||||
setupTest();
|
||||
receiveVideo$.next(false);
|
||||
const connection = setupRemoteConnection();
|
||||
|
||||
await connection.start();
|
||||
|
||||
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
{ autoSubscribe: false },
|
||||
);
|
||||
});
|
||||
|
||||
it("subscribes audio and not video as tracks are published", () => {
|
||||
setupTest();
|
||||
receiveVideo$.next(false);
|
||||
new Connection(connectionOpts(), logger);
|
||||
const { bob, publications } = remoteParticipantWithTracks(undefined);
|
||||
|
||||
for (const publication of Object.values(publications))
|
||||
fakeLivekitRoom.emit(RoomEvent.TrackPublished, publication, bob);
|
||||
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
|
||||
});
|
||||
|
||||
it("unsubscribes the video of a participant who connects while video is not received", () => {
|
||||
setupTest();
|
||||
receiveVideo$.next(false);
|
||||
new Connection(connectionOpts(), logger);
|
||||
// Published under autoSubscribe, as after a full reconnect
|
||||
const { bob, publications } = remoteParticipantWithTracks(undefined);
|
||||
|
||||
fakeLivekitRoom.emit(RoomEvent.ParticipantConnected, bob);
|
||||
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
|
||||
});
|
||||
|
||||
it.each([RoomEvent.Connected, RoomEvent.Reconnected])(
|
||||
"sweeps every remote publication on %s",
|
||||
(event) => {
|
||||
setupTest();
|
||||
receiveVideo$.next(false);
|
||||
new Connection(connectionOpts(), logger);
|
||||
const { publications } = remoteParticipantWithTracks(undefined);
|
||||
|
||||
fakeLivekitRoom.emit(event);
|
||||
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
|
||||
},
|
||||
);
|
||||
|
||||
it("follows every change of the choice, without resending what is already asked", () => {
|
||||
setupTest();
|
||||
new Connection(connectionOpts(), logger);
|
||||
const { publications } = remoteParticipantWithTracks(undefined);
|
||||
|
||||
receiveVideo$.next(false);
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
|
||||
expect(publications.microphone.setSubscribed).not.toHaveBeenCalled();
|
||||
|
||||
receiveVideo$.next(true);
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_ON);
|
||||
});
|
||||
|
||||
it("subscribes video again on a connection made while video was not received", () => {
|
||||
setupTest();
|
||||
receiveVideo$.next(false);
|
||||
new Connection(connectionOpts(), logger);
|
||||
// Published under autoSubscribe: false
|
||||
const { publications } = remoteParticipantWithTracks(false);
|
||||
fakeLivekitRoom.emit(RoomEvent.Connected);
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
|
||||
|
||||
receiveVideo$.next(true);
|
||||
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_ON);
|
||||
});
|
||||
|
||||
it("stops following the choice once its scope ends", () => {
|
||||
setupTest();
|
||||
new Connection(connectionOpts(), logger);
|
||||
const { publications } = remoteParticipantWithTracks(undefined);
|
||||
testScope.end();
|
||||
|
||||
receiveVideo$.next(false);
|
||||
fakeLivekitRoom.emit(RoomEvent.Reconnected);
|
||||
|
||||
expect(subscriptions(publications)).toEqual(VIDEO_ON);
|
||||
});
|
||||
});
|
||||
|
||||
const VIDEO_OFF = {
|
||||
microphone: true,
|
||||
camera: false,
|
||||
screenShare: false,
|
||||
screenShareAudio: true,
|
||||
};
|
||||
const VIDEO_ON = {
|
||||
microphone: true,
|
||||
camera: true,
|
||||
screenShare: true,
|
||||
screenShareAudio: true,
|
||||
};
|
||||
|
||||
type MockPublication = RemoteTrackPublication & {
|
||||
setSubscribed: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
type Publications = Record<keyof typeof VIDEO_ON, MockPublication>;
|
||||
|
||||
/**
|
||||
* Bob in the room with a microphone, a camera and a screen share with audio,
|
||||
* each with the subscription LiveKit gave it: undefined under autoSubscribe.
|
||||
*/
|
||||
function remoteParticipantWithTracks(subscribed: boolean | undefined): {
|
||||
bob: RemoteParticipant;
|
||||
publications: Publications;
|
||||
} {
|
||||
const publications: Publications = {
|
||||
microphone: mockPublication(Track.Kind.Audio, subscribed),
|
||||
camera: mockPublication(Track.Kind.Video, subscribed),
|
||||
screenShare: mockPublication(Track.Kind.Video, subscribed),
|
||||
screenShareAudio: mockPublication(Track.Kind.Audio, subscribed),
|
||||
};
|
||||
const bob = mockRemoteParticipant({
|
||||
identity: "@bob:example.org:DEV111",
|
||||
trackPublications: new Map(
|
||||
Object.entries(publications) as [string, RemoteTrackPublication][],
|
||||
),
|
||||
});
|
||||
fakeLivekitRoom.remoteParticipants.set(bob.identity, bob);
|
||||
return { bob, publications };
|
||||
}
|
||||
|
||||
function mockPublication(
|
||||
kind: Track.Kind,
|
||||
subscribed: boolean | undefined,
|
||||
): MockPublication {
|
||||
const publication = {
|
||||
kind,
|
||||
subscribed,
|
||||
get isDesired(): boolean {
|
||||
return this.subscribed !== false;
|
||||
},
|
||||
setSubscribed: vi.fn((value: boolean) => {
|
||||
publication.subscribed = value;
|
||||
}),
|
||||
};
|
||||
return publication as unknown as MockPublication;
|
||||
}
|
||||
|
||||
function subscriptions(
|
||||
publications: Publications,
|
||||
): Record<keyof Publications, boolean> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(publications).map(([name, publication]) => [
|
||||
name,
|
||||
publication.isDesired,
|
||||
]),
|
||||
) as Record<keyof Publications, boolean>;
|
||||
}
|
||||
|
||||
describe("remote track logging", () => {
|
||||
it("logs remote participant and track events on the connection logger", () => {
|
||||
setupTest();
|
||||
|
||||
@@ -19,13 +19,14 @@ import {
|
||||
type RemoteParticipant,
|
||||
type RemoteTrackPublication,
|
||||
type Room as LivekitRoom,
|
||||
type RoomConnectOptions,
|
||||
RoomEvent,
|
||||
type SubscriptionError,
|
||||
type Track,
|
||||
Track,
|
||||
type TrackPublication,
|
||||
} from "livekit-client";
|
||||
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
import { BehaviorSubject, distinctUntilChanged, skip } from "rxjs";
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
|
||||
|
||||
@@ -64,6 +65,11 @@ export interface ConnectionOpts {
|
||||
slotId: string;
|
||||
/** The observable scope to use for this connection. */
|
||||
scope: ObservableScope;
|
||||
/**
|
||||
* Whether remote video is subscribed. Read at connect and followed for the
|
||||
* connection's lifetime; audio is always subscribed.
|
||||
*/
|
||||
receiveVideo$: Behavior<boolean>;
|
||||
|
||||
/** Optional factory to create the LiveKit room, mainly for testing purposes. */
|
||||
livekitRoomFactory: () => LivekitRoom;
|
||||
@@ -138,6 +144,7 @@ export class Connection {
|
||||
private readonly slotId: string;
|
||||
private readonly logger: Logger;
|
||||
private readonly ownMembershipIdentity: CallMembershipIdentityParts;
|
||||
private readonly receiveVideo$: Behavior<boolean>;
|
||||
/**
|
||||
* Creates a new connection to a matrix RTC LiveKit backend.
|
||||
*
|
||||
@@ -161,12 +168,14 @@ export class Connection {
|
||||
this.transport = transport;
|
||||
this.serverName = serverName;
|
||||
this.client = client;
|
||||
this.receiveVideo$ = opts.receiveVideo$;
|
||||
|
||||
this.remoteParticipants$ = scope.behavior(
|
||||
// Only tracks remote participants
|
||||
connectedParticipantsObserver(this.livekitRoom),
|
||||
);
|
||||
this.logRemoteTrackEvents();
|
||||
this.applyReceivePolicy();
|
||||
|
||||
scope.onEnd(() => {
|
||||
this.logger.info(`Connection scope ended, stopping connection`);
|
||||
@@ -174,6 +183,45 @@ export class Connection {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps every remote publication subscribed or not as `receiveVideo$` asks.
|
||||
* A full reconnect recreates the remote participants with the subscriptions
|
||||
* the room first connected with, and events for participants already in the
|
||||
* room are not emitted while it connects, so the whole room is swept again
|
||||
* on `Connected` and `Reconnected`.
|
||||
*/
|
||||
private applyReceivePolicy(): void {
|
||||
const room = this.livekitRoom;
|
||||
const reconcile = (publication: RemoteTrackPublication): void => {
|
||||
const wanted =
|
||||
publication.kind !== Track.Kind.Video || this.receiveVideo$.value;
|
||||
// Every call sends a subscription update, wanted or not
|
||||
if (publication.isDesired !== wanted) publication.setSubscribed(wanted);
|
||||
};
|
||||
const reconcileParticipant = (participant: RemoteParticipant): void =>
|
||||
participant.trackPublications.forEach(reconcile);
|
||||
const reconcileAll = (): void =>
|
||||
room.remoteParticipants.forEach(reconcileParticipant);
|
||||
const onTrackPublished = (publication: RemoteTrackPublication): void =>
|
||||
reconcile(publication);
|
||||
|
||||
room
|
||||
.on(RoomEvent.TrackPublished, onTrackPublished)
|
||||
.on(RoomEvent.ParticipantConnected, reconcileParticipant)
|
||||
.on(RoomEvent.Connected, reconcileAll)
|
||||
.on(RoomEvent.Reconnected, reconcileAll);
|
||||
this.receiveVideo$
|
||||
.pipe(distinctUntilChanged(), skip(1), this.scope.bind())
|
||||
.subscribe(reconcileAll);
|
||||
this.scope.onEnd(() => {
|
||||
room
|
||||
.off(RoomEvent.TrackPublished, onTrackPublished)
|
||||
.off(RoomEvent.ParticipantConnected, reconcileParticipant)
|
||||
.off(RoomEvent.Connected, reconcileAll)
|
||||
.off(RoomEvent.Reconnected, reconcileAll);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the lifecycle of remote participants and their tracks as seen by
|
||||
* livekit-client, so that rageshakes show what a tile should have been
|
||||
@@ -385,7 +433,7 @@ export class Connection {
|
||||
|
||||
private async connectLivekitRoom(url: string, jwt: string): Promise<void> {
|
||||
try {
|
||||
await this.livekitRoom.connect(url, jwt);
|
||||
await this.livekitRoom.connect(url, jwt, this.connectOptions());
|
||||
} catch (e) {
|
||||
// Behind a proxy, Firefox fails the first WebSocket to a host after trying
|
||||
// it over HTTP/2, so a join that fails on the WebSocket gets a second try.
|
||||
@@ -396,10 +444,15 @@ export class Connection {
|
||||
e.reason === ConnectionErrorReason.WebSocket;
|
||||
if (this.stopped || !failedOnFirefoxWebSocket) throw e;
|
||||
this.logger.info(`livekitRoom.connect RETRY ${url}`, e);
|
||||
await this.livekitRoom.connect(url, jwt);
|
||||
await this.livekitRoom.connect(url, jwt, this.connectOptions());
|
||||
}
|
||||
}
|
||||
|
||||
/** A connection made while video is not received never asks the SFU for it. */
|
||||
private connectOptions(): RoomConnectOptions {
|
||||
return { autoSubscribe: this.receiveVideo$.value };
|
||||
}
|
||||
|
||||
protected async getSFUConfig(): Promise<SFUConfig> {
|
||||
return await getSFUConfig({
|
||||
client: this.client,
|
||||
|
||||
@@ -7,15 +7,19 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import {
|
||||
ConnectionState as LivekitConnectionState,
|
||||
type RemoteParticipant,
|
||||
type RemoteTrackPublication,
|
||||
type RoomOptions,
|
||||
Track,
|
||||
} from "livekit-client";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { type MediaQuality } from "../../config";
|
||||
import { type PublishRequest } from "../../media-api";
|
||||
import { constant } from "../../reactive/Behavior";
|
||||
import { type Behavior, constant } from "../../reactive/Behavior";
|
||||
import { ownMemberMock, testScope } from "../../utils/test";
|
||||
import { testJWTToken } from "../../utils/test-fixtures";
|
||||
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
|
||||
@@ -47,6 +51,7 @@ function create(
|
||||
mediaQuality?: MediaQuality,
|
||||
audioOutputDeviceId?: string,
|
||||
transport = exampleTransport,
|
||||
receiveVideo$: Behavior<boolean> = constant(true),
|
||||
): { connection: ResolvedConnection; options: RoomOptions } {
|
||||
const factory = new LivekitConnectionFactory(
|
||||
client(),
|
||||
@@ -54,6 +59,7 @@ function create(
|
||||
"m.call#ROOM",
|
||||
publish,
|
||||
constant(audioOutputDeviceId),
|
||||
receiveVideo$,
|
||||
undefined,
|
||||
mediaQuality,
|
||||
);
|
||||
@@ -69,6 +75,29 @@ function create(
|
||||
}
|
||||
|
||||
describe("LivekitConnectionFactory", () => {
|
||||
it("gives each connection the receive video choice to follow", () => {
|
||||
const receiveVideo$ = new BehaviorSubject(true);
|
||||
const { connection } = create(
|
||||
[],
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
receiveVideo$,
|
||||
);
|
||||
const camera = {
|
||||
kind: Track.Kind.Video,
|
||||
isDesired: true,
|
||||
setSubscribed: vi.fn(),
|
||||
} as unknown as RemoteTrackPublication;
|
||||
connection.livekitRoom.remoteParticipants.set("@bob:example.org:DEV", {
|
||||
trackPublications: new Map([["camera", camera]]),
|
||||
} as unknown as RemoteParticipant);
|
||||
|
||||
receiveVideo$.next(false);
|
||||
|
||||
expect(camera.setSubscribed).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("builds the room on the defaults where nothing is requested", () => {
|
||||
const { options } = create([]);
|
||||
|
||||
|
||||
@@ -106,6 +106,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
|
||||
private readonly slotId: string,
|
||||
private readonly publish: PublishRequest[],
|
||||
private readonly audioOutputDeviceId$: Behavior<string | undefined>,
|
||||
private readonly receiveVideo$: Behavior<boolean>,
|
||||
private readonly keyProvider: BaseKeyProvider | undefined,
|
||||
private readonly mediaQuality: MediaQuality | undefined,
|
||||
) {}
|
||||
@@ -127,6 +128,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
|
||||
serverName,
|
||||
client: this.client,
|
||||
scope,
|
||||
receiveVideo$: this.receiveVideo$,
|
||||
livekitRoomFactory: () =>
|
||||
new LivekitRoom(
|
||||
roomOptions(
|
||||
|
||||
@@ -169,6 +169,10 @@ describe("createLivekitBackend", () => {
|
||||
participants$: BehaviorSubject<RemoteParticipant[]>;
|
||||
state$: BehaviorSubject<ConnectionState>;
|
||||
}[];
|
||||
/** What the backend built the factory with. */
|
||||
let factoryArgs: ConstructorParameters<
|
||||
typeof connectionFactory.LivekitConnectionFactory
|
||||
>;
|
||||
const connected: ConnectionState = {
|
||||
state: "authenticated",
|
||||
livekitState: LivekitConnectionState.Connected,
|
||||
@@ -177,7 +181,13 @@ describe("createLivekitBackend", () => {
|
||||
/** Stands in for the factory: connections whose state and participants the test drives. */
|
||||
function stubFactory(initialState: ConnectionState): void {
|
||||
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
|
||||
function (this: unknown) {
|
||||
function (
|
||||
this: unknown,
|
||||
...args: ConstructorParameters<
|
||||
typeof connectionFactory.LivekitConnectionFactory
|
||||
>
|
||||
) {
|
||||
factoryArgs = args;
|
||||
return {
|
||||
createConnection: (
|
||||
scope: ObservableScope,
|
||||
@@ -258,6 +268,17 @@ describe("createLivekitBackend", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("hands every connection the factory makes the receive video choice, true until set", () => {
|
||||
const b = backend();
|
||||
const receiveVideo$ = factoryArgs[5];
|
||||
expect(receiveVideo$.value).toBe(true);
|
||||
|
||||
b.setReceiveVideo(false);
|
||||
expect(receiveVideo$.value).toBe(false);
|
||||
b.setReceiveVideo(true);
|
||||
expect(receiveVideo$.value).toBe(true);
|
||||
});
|
||||
|
||||
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
|
||||
// Our own homeserver would delegate, so only the SFU being remote can
|
||||
// explain delegation being skipped
|
||||
|
||||
@@ -107,12 +107,14 @@ export function createLivekitBackend(
|
||||
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const receiveVideo$ = new BehaviorSubject(true);
|
||||
const connectionFactory = new LivekitConnectionFactory(
|
||||
client,
|
||||
roomId,
|
||||
slotId,
|
||||
publish,
|
||||
audioOutputDeviceId$,
|
||||
receiveVideo$,
|
||||
keyProvider,
|
||||
mediaQuality,
|
||||
);
|
||||
@@ -287,6 +289,7 @@ export function createLivekitBackend(
|
||||
mediaFor,
|
||||
connections$,
|
||||
setAudioOutputDeviceId: localMedia_.setAudioOutputDeviceId,
|
||||
setReceiveVideo: (receive) => receiveVideo$.next(receive),
|
||||
sendData,
|
||||
data$,
|
||||
};
|
||||
|
||||
@@ -32,6 +32,7 @@ export function mockRemoteParticipant(
|
||||
({}) as Partial<RemoteTrackPublication> as RemoteTrackPublication,
|
||||
// this will only get used for `getTrackPublications().length`
|
||||
getTrackPublications: () => [0],
|
||||
trackPublications: new Map(),
|
||||
...mockEmitter(),
|
||||
...participant,
|
||||
} as RemoteParticipant;
|
||||
|
||||
+86
-5
@@ -5,7 +5,14 @@ Copyright 2026 Element Creations Ltd.
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
import { type ComponentPropsWithoutRef, type FC } from "react";
|
||||
import {
|
||||
cloneElement,
|
||||
type ComponentPropsWithoutRef,
|
||||
type FC,
|
||||
type ReactElement,
|
||||
useId,
|
||||
useState,
|
||||
} from "react";
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
@@ -30,6 +37,7 @@ import {
|
||||
import styles from "./Button.module.css";
|
||||
import callFooterStyles from "../components/CallFooter.module.css";
|
||||
import { platform } from "../Platform";
|
||||
import { useAnnouncement } from "../useAnnouncement";
|
||||
|
||||
interface MicButtonProps extends ComponentPropsWithoutRef<"button"> {
|
||||
enabled: boolean;
|
||||
@@ -63,15 +71,25 @@ export const MicButton: FC<MicButtonProps> = ({ enabled, busy, ...props }) => {
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* What a button does is unavailable for now, and why. The button stays
|
||||
* reachable and says why on hover, focus and activation, instead of doing it.
|
||||
*/
|
||||
export interface Unavailable {
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface VideoButtonProps extends ComponentPropsWithoutRef<"button"> {
|
||||
enabled: boolean;
|
||||
busy?: boolean;
|
||||
size?: "md" | "lg";
|
||||
unavailable?: Unavailable;
|
||||
}
|
||||
|
||||
export const VideoButton: FC<VideoButtonProps> = ({
|
||||
enabled,
|
||||
busy,
|
||||
unavailable,
|
||||
...props
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -85,7 +103,7 @@ export const VideoButton: FC<VideoButtonProps> = ({
|
||||
: t("start_video_button_label");
|
||||
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<UnavailableTooltip label={label} unavailable={unavailable}>
|
||||
<CpdButton
|
||||
iconOnly
|
||||
Icon={Icon}
|
||||
@@ -99,17 +117,19 @@ export const VideoButton: FC<VideoButtonProps> = ({
|
||||
})}
|
||||
disabled={props.disabled || busy}
|
||||
/>
|
||||
</Tooltip>
|
||||
</UnavailableTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
interface ShareScreenButtonProps extends ComponentPropsWithoutRef<"button"> {
|
||||
enabled: boolean;
|
||||
size: "md" | "lg";
|
||||
unavailable?: Unavailable;
|
||||
}
|
||||
|
||||
export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
|
||||
enabled,
|
||||
unavailable,
|
||||
...props
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -118,7 +138,7 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
|
||||
: t("screenshare_button_label");
|
||||
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<UnavailableTooltip label={label} unavailable={unavailable}>
|
||||
<CpdButton
|
||||
iconOnly
|
||||
Icon={ShareScreenSolidIcon}
|
||||
@@ -127,7 +147,68 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
|
||||
aria-checked={enabled}
|
||||
{...props}
|
||||
/>
|
||||
</Tooltip>
|
||||
</UnavailableTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
interface UnavailableTooltipProps {
|
||||
label: string;
|
||||
unavailable: Unavailable | undefined;
|
||||
children: ReactElement<ComponentPropsWithoutRef<"button">>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The button's tooltip: its label, or while it is unavailable the reason.
|
||||
* The button is then not disabled: a disabled button drops its clicks, and a
|
||||
* tap is the only way a touch screen has to ask why.
|
||||
*/
|
||||
const UnavailableTooltip: FC<UnavailableTooltipProps> = ({
|
||||
label,
|
||||
unavailable,
|
||||
children,
|
||||
}) => {
|
||||
const descriptionId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [liveRegion, announce] = useAnnouncement();
|
||||
if (unavailable === undefined)
|
||||
return <Tooltip label={label}>{children}</Tooltip>;
|
||||
|
||||
const { description } = unavailable;
|
||||
// The hover and focus Compound gives a tooltip are off once it is
|
||||
// controlled, which it has to be to open on a tap
|
||||
const button = cloneElement(children, {
|
||||
"aria-label": label,
|
||||
"aria-disabled": true,
|
||||
"aria-describedby": descriptionId,
|
||||
disabled: undefined,
|
||||
onClick: () => {
|
||||
setOpen(true);
|
||||
announce(description);
|
||||
},
|
||||
onPointerEnter: (e) => {
|
||||
if (e.pointerType !== "touch") setOpen(true);
|
||||
},
|
||||
onPointerLeave: (e) => {
|
||||
if (e.pointerType !== "touch") setOpen(false);
|
||||
},
|
||||
onFocus: () => setOpen(true),
|
||||
onBlur: () => setOpen(false),
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<Tooltip
|
||||
description={description}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
maxLines={4}
|
||||
>
|
||||
{button}
|
||||
</Tooltip>
|
||||
<span id={descriptionId} hidden>
|
||||
{description}
|
||||
</span>
|
||||
{liveRegion}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
|
||||
/**
|
||||
* Checks, in a story, that a button whose action is unavailable stays
|
||||
* reachable and says why with every input it accepts, and never acts.
|
||||
*
|
||||
* @param touch - Tap it as a touch screen does, which has no hover or focus
|
||||
* to show the reason first.
|
||||
*/
|
||||
export async function expectExplainsUnavailable(
|
||||
button: HTMLElement,
|
||||
description: string,
|
||||
acted: () => unknown,
|
||||
{ touch = false }: { touch?: boolean } = {},
|
||||
): Promise<void> {
|
||||
await expect(button).toHaveAttribute("aria-disabled", "true");
|
||||
await expect(button).not.toHaveAttribute("disabled");
|
||||
await expect(button).toHaveAttribute("aria-checked", "false");
|
||||
await expect(button).toHaveAccessibleDescription(description);
|
||||
|
||||
if (!touch) {
|
||||
await userEvent.hover(button);
|
||||
await expectTooltip(description);
|
||||
await userEvent.unhover(button);
|
||||
await expectNoTooltip();
|
||||
|
||||
await expect(button.tabIndex).toBe(0);
|
||||
button.focus();
|
||||
await expectTooltip(description);
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await expectNoTooltip();
|
||||
button.blur();
|
||||
}
|
||||
|
||||
if (touch)
|
||||
await userEvent.pointer([
|
||||
{ keys: "[TouchA]", target: button },
|
||||
{ keys: "[/TouchA]", target: button },
|
||||
]);
|
||||
else await userEvent.click(button);
|
||||
await expectTooltip(description);
|
||||
await expect(liveRegionTexts()).toContain(description);
|
||||
await expect(acted).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
async function expectTooltip(description: string): Promise<void> {
|
||||
const tooltip = await within(document.body).findByRole("tooltip");
|
||||
await expect(tooltip).toHaveTextContent(description);
|
||||
// Not cut short by the tooltip's line clamp
|
||||
const text = tooltip.querySelector("span")!;
|
||||
await expect(text.scrollHeight).toBeLessThanOrEqual(text.clientHeight + 1);
|
||||
}
|
||||
|
||||
async function expectNoTooltip(): Promise<void> {
|
||||
await waitFor(async () =>
|
||||
expect(within(document.body).queryByRole("tooltip")).toBeNull(),
|
||||
);
|
||||
}
|
||||
|
||||
function liveRegionTexts(): string[] {
|
||||
return [...document.querySelectorAll('[aria-live="polite"]')].map((region) =>
|
||||
region.textContent.trim(),
|
||||
);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { globalScope } from "../state/ObservableScope";
|
||||
import { constant } from "../state/Behavior";
|
||||
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
|
||||
import { type MediaMenuSnapshot } from "./MediaMenuViewModel";
|
||||
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
|
||||
|
||||
// consts for tests
|
||||
const reactionIdentifier = "@user:example.com:DEVICE";
|
||||
@@ -38,12 +39,15 @@ const mediaDevices = new MediaDevices(globalScope, {
|
||||
function menu(
|
||||
kind: "audio" | "video",
|
||||
withDevices: boolean,
|
||||
lowBandwidthMode = false,
|
||||
): MediaMenuSnapshot {
|
||||
const device = kind === "audio" ? "Microphone" : "Camera";
|
||||
const heldOff = kind === "video" && lowBandwidthMode;
|
||||
return {
|
||||
enabled: true,
|
||||
enabled: !heldOff,
|
||||
busy: false,
|
||||
toggle: fn(),
|
||||
unavailableReason: heldOff ? "lowBandwidthMode" : undefined,
|
||||
options: withDevices
|
||||
? [
|
||||
{ id: "1", label: { type: "name", name: `${device} 1` } },
|
||||
@@ -106,7 +110,9 @@ function CallFooterStoryWrapper({
|
||||
withDevices: boolean;
|
||||
}): ReactNode {
|
||||
const audioMenuVm = useStaticViewModel(menu("audio", withDevices));
|
||||
const cameraMenuVm = useStaticViewModel(menu("video", withDevices));
|
||||
const cameraMenuVm = useStaticViewModel(
|
||||
menu("video", withDevices, vmSnapshot.screenShareUnavailable),
|
||||
);
|
||||
const vm = useStaticViewModel({
|
||||
...vmSnapshot,
|
||||
layoutSwitchVm: layout && { layout$: constant(layout), setLayout },
|
||||
@@ -178,6 +184,7 @@ export const Default: Story = {
|
||||
asOverlay: false,
|
||||
showModals: true,
|
||||
sharingScreen: false,
|
||||
screenShareUnavailable: false,
|
||||
audioOutputSwitcher: undefined,
|
||||
reactionIdentifier: undefined,
|
||||
reactionData: undefined,
|
||||
@@ -342,3 +349,55 @@ export const LobbyRecentButtonMobile: Story = {
|
||||
...Default.parameters,
|
||||
},
|
||||
};
|
||||
|
||||
const screenShareExplanation =
|
||||
"You can't share your screen while Low bandwidth mode is on. Turn it off in Developer options.";
|
||||
|
||||
/** The camera and screen share both held, each saying why. */
|
||||
export const LowBandwidthMode: Story = {
|
||||
...Default,
|
||||
args: {
|
||||
...Default.args,
|
||||
screenShareUnavailable: true,
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByRole("switch", { name: "Start video" }),
|
||||
).toHaveAttribute("aria-disabled", "true");
|
||||
await expectExplainsUnavailable(
|
||||
canvas.getByRole("switch", { name: "Share screen" }),
|
||||
screenShareExplanation,
|
||||
args.toggleScreenSharing!,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const LowBandwidthModeMobile: Story = {
|
||||
...LowBandwidthMode,
|
||||
globals: {
|
||||
viewport: { value: "mobile2", isRotated: false },
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
await expectExplainsUnavailable(
|
||||
within(canvasElement).getByRole("switch", { name: "Share screen" }),
|
||||
screenShareExplanation,
|
||||
args.toggleScreenSharing!,
|
||||
{ touch: true },
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** Where no share can be started there is no button, and nothing to explain. */
|
||||
export const LowBandwidthModeWithoutScreenSharing: Story = {
|
||||
...LowBandwidthMode,
|
||||
args: {
|
||||
...LowBandwidthMode.args,
|
||||
toggleScreenSharing: undefined,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await expect(
|
||||
within(canvasElement).queryByRole("switch", { name: "Share screen" }),
|
||||
).toBeNull();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { type FC, type JSX, type Ref, useMemo } from "react";
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import LogoMark from "../icons/LogoMark.svg?react";
|
||||
import LogoType from "../icons/LogoType.svg?react";
|
||||
@@ -75,6 +76,8 @@ export interface FooterState {
|
||||
layoutSwitchVm: LayoutSwitchViewModel | null;
|
||||
|
||||
sharingScreen: boolean;
|
||||
/** Whether starting a screen share is unavailable, and explained instead. */
|
||||
screenShareUnavailable: boolean;
|
||||
|
||||
/** Also controls if the audio output button is visible */
|
||||
audioOutputSwitcher: AudioOutputSwitcher | undefined;
|
||||
@@ -100,6 +103,7 @@ export const CallFooter: FC<FooterProps> = ({
|
||||
children,
|
||||
vm,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const asOverlay = useBehavior(vm.asOverlay$);
|
||||
const showFooter = useBehavior(vm.showFooter$);
|
||||
const hideControls = useBehavior(vm.hideControls$);
|
||||
@@ -110,6 +114,7 @@ export const CallFooter: FC<FooterProps> = ({
|
||||
const openSettings = useBehavior(vm.openSettings$);
|
||||
const sharingScreen = useBehavior(vm.sharingScreen$);
|
||||
const toggleScreenSharing = useBehavior(vm.toggleScreenSharing$);
|
||||
const screenShareUnavailable = useBehavior(vm.screenShareUnavailable$);
|
||||
const reactionIdentifier = useBehavior(vm.reactionIdentifier$);
|
||||
const reactionData = useBehavior(vm.reactionData$);
|
||||
const audioOutputSwitcher = useBehavior(vm.audioOutputSwitcher$);
|
||||
@@ -157,6 +162,11 @@ export const CallFooter: FC<FooterProps> = ({
|
||||
className={styles.shareScreen}
|
||||
enabled={sharingScreen ?? false}
|
||||
onClick={toggleScreenSharing}
|
||||
unavailable={
|
||||
screenShareUnavailable
|
||||
? { description: t("low_bandwidth_mode.screen_share_unavailable") }
|
||||
: undefined
|
||||
}
|
||||
data-testid="incall_screenshare"
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -102,6 +102,7 @@ describe("createCallFooterViewModel", () => {
|
||||
testScope(),
|
||||
buildMinimalCallViewModel(layout),
|
||||
mockMuteStates(),
|
||||
constant(false),
|
||||
devices,
|
||||
pipeline,
|
||||
/* reactionIdentifier */ undefined,
|
||||
@@ -121,6 +122,7 @@ describe("createCallFooterViewModel", () => {
|
||||
testScope(),
|
||||
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
|
||||
mockMuteStates(),
|
||||
constant(false),
|
||||
devices,
|
||||
pipeline,
|
||||
/* reactionIdentifier */ undefined,
|
||||
|
||||
@@ -30,6 +30,8 @@ import {
|
||||
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
|
||||
* @param callModel - The root CallViewModel; provides layout, grid mode, reactions, etc.
|
||||
* @param muteStates - Audio and video mute state + toggles.
|
||||
* @param lowBandwidthMode$ - Whether the call's low bandwidth mode is on,
|
||||
* which makes the camera and screen sharing unavailable.
|
||||
* @param mediaDevices - Available and selected input devices.
|
||||
* @param backgroundEffectsState$ - The background pipeline's state: whether
|
||||
* effects run here, and the wait for the first.
|
||||
@@ -42,6 +44,7 @@ export function createCallFooterViewModel(
|
||||
scope: ObservableScope,
|
||||
callModel: CallViewModel,
|
||||
muteStates: MuteStates,
|
||||
lowBandwidthMode$: Behavior<boolean>,
|
||||
mediaDevices: MediaDevices,
|
||||
backgroundEffectsState$: Observable<BackgroundEffectsState>,
|
||||
reactionIdentifier: string | undefined,
|
||||
@@ -73,6 +76,7 @@ export function createCallFooterViewModel(
|
||||
disableDeviceSwitcher$,
|
||||
backgroundEffectsState$,
|
||||
callModel.camera$,
|
||||
lowBandwidthMode$,
|
||||
),
|
||||
),
|
||||
// candidat to move into the FooterViewModel
|
||||
@@ -104,6 +108,7 @@ export function createCallFooterViewModel(
|
||||
|
||||
sharingScreen$: callModel.sharingScreen$,
|
||||
toggleScreenSharing$: constant(callModel.toggleScreenSharing ?? undefined),
|
||||
screenShareUnavailable$: lowBandwidthMode$,
|
||||
|
||||
audioOutputSwitcher$: scope.behavior(
|
||||
callModel.audioOutputSwitcher$.pipe(
|
||||
@@ -168,6 +173,7 @@ export function createLobbyFooterViewModel(
|
||||
debugTileLayout: false,
|
||||
showFooter: true,
|
||||
toggleScreenSharing: undefined,
|
||||
screenShareUnavailable: false,
|
||||
layoutSwitchVm: null,
|
||||
sharingScreen: false,
|
||||
audioOutputSwitcher: undefined,
|
||||
@@ -187,6 +193,7 @@ export function createLobbyFooterViewModel(
|
||||
constant(false),
|
||||
backgroundEffectsState$,
|
||||
camera$,
|
||||
constant(false),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useStaticViewModel } from "../state/ViewModel";
|
||||
import { MediaDevicesContext } from "../MediaDevicesContext";
|
||||
import { MediaDevices } from "../state/MediaDevices";
|
||||
import { globalScope } from "../state/ObservableScope";
|
||||
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
|
||||
|
||||
const mediaDevices = new MediaDevices(globalScope, {
|
||||
controlledAudioDevices: false,
|
||||
@@ -44,6 +45,7 @@ export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
const empty = {
|
||||
unavailableReason: undefined,
|
||||
outputOptions: [],
|
||||
selectedOutput: undefined,
|
||||
selectOutput: undefined,
|
||||
@@ -114,6 +116,50 @@ export const CameraBusy: Story = {
|
||||
args: { ...Camera.args, busy: true },
|
||||
};
|
||||
|
||||
const lowBandwidthExplanation =
|
||||
"You can't turn on your camera while Low bandwidth mode is on. Turn it off in Developer options.";
|
||||
|
||||
/** Held off, and saying why, with a menu beside it. */
|
||||
export const CameraUnavailableInLowBandwidthMode: Story = {
|
||||
args: {
|
||||
...Camera.args,
|
||||
enabled: false,
|
||||
// Undefined in a call; set here to show the button never calls it
|
||||
toggle: fn(),
|
||||
unavailableReason: "lowBandwidthMode",
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
await expectExplainsUnavailable(
|
||||
within(canvasElement).getByRole("switch", { name: "Start video" }),
|
||||
lowBandwidthExplanation,
|
||||
args.toggle!,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** Held off, and saying why, as a plain button. */
|
||||
export const PlainCameraUnavailableInLowBandwidthMode: Story = {
|
||||
args: {
|
||||
...CameraUnavailableInLowBandwidthMode.args,
|
||||
options: [],
|
||||
},
|
||||
play: CameraUnavailableInLowBandwidthMode.play,
|
||||
};
|
||||
|
||||
/** A tap says why, where there is no hover to say it first. */
|
||||
export const CameraUnavailableInLowBandwidthModeMobile: Story = {
|
||||
args: CameraUnavailableInLowBandwidthMode.args,
|
||||
globals: { viewport: { value: "mobile2", isRotated: false } },
|
||||
play: async ({ args, canvasElement }) => {
|
||||
await expectExplainsUnavailable(
|
||||
within(canvasElement).getByRole("switch", { name: "Start video" }),
|
||||
lowBandwidthExplanation,
|
||||
args.toggle!,
|
||||
{ touch: true },
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** Opens the effects, for the stories that check what they say. */
|
||||
async function openEffects(canvasElement: HTMLElement): Promise<HTMLElement> {
|
||||
await userEvent.click(
|
||||
|
||||
@@ -29,6 +29,7 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
const enabled = useBehavior(vm.enabled$);
|
||||
const busy = useBehavior(vm.busy$);
|
||||
const toggle = useBehavior(vm.toggle$);
|
||||
const unavailableReason = useBehavior(vm.unavailableReason$);
|
||||
const options = useBehavior(vm.options$);
|
||||
const selected = useBehavior(vm.selected$);
|
||||
const select = useBehavior(vm.select$);
|
||||
@@ -72,6 +73,11 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
}
|
||||
}, [refusal, t]);
|
||||
|
||||
const unavailable =
|
||||
unavailableReason === "lowBandwidthMode"
|
||||
? { description: t("low_bandwidth_mode.camera_unavailable") }
|
||||
: undefined;
|
||||
|
||||
if (options.length === 0) {
|
||||
const PlainButton = kind === "audio" ? MicButton : VideoButton;
|
||||
return (
|
||||
@@ -81,6 +87,7 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
busy={busy}
|
||||
onClick={toggle}
|
||||
disabled={busy || toggle === undefined}
|
||||
unavailable={unavailable}
|
||||
data-testid={testId}
|
||||
/>
|
||||
);
|
||||
@@ -106,6 +113,7 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
enabled={enabled}
|
||||
busy={busy}
|
||||
onMuteClick={toggle}
|
||||
unavailable={unavailable}
|
||||
options={options}
|
||||
selectedOption={selected}
|
||||
onSelect={select}
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
mockMediaDevices,
|
||||
mockVideoTrack,
|
||||
} from "../utils/test";
|
||||
import { constant } from "../state/Behavior";
|
||||
import { type Behavior, constant } from "../state/Behavior";
|
||||
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
|
||||
import type { DeviceLabel } from "../state/MediaDevices";
|
||||
import {
|
||||
@@ -97,11 +97,13 @@ function cameraMenu({
|
||||
disableSwitcher = false,
|
||||
pipeline$ = constant({ supported, processor: undefined }),
|
||||
camera$ = constant(null),
|
||||
lowBandwidthMode$ = constant(false),
|
||||
}: {
|
||||
supported?: boolean;
|
||||
disableSwitcher?: boolean;
|
||||
pipeline$?: Observable<BackgroundEffectsState>;
|
||||
camera$?: Observable<LocalVideoMediaTrack | null>;
|
||||
lowBandwidthMode$?: Behavior<boolean>;
|
||||
} = {}): MediaMenuViewModel {
|
||||
return createCameraMenuViewModel(
|
||||
testScope(),
|
||||
@@ -110,6 +112,7 @@ function cameraMenu({
|
||||
constant(disableSwitcher),
|
||||
pipeline$,
|
||||
camera$,
|
||||
lowBandwidthMode$,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,11 @@ export interface MediaMenuSnapshot {
|
||||
busy: boolean;
|
||||
/** Turns the device on or off. Undefined while it can't be toggled. (disable interaction state) */
|
||||
toggle: (() => void) | undefined;
|
||||
/**
|
||||
* Why the device can't be turned on, where the user is to be told. Camera
|
||||
* only.
|
||||
*/
|
||||
unavailableReason: "lowBandwidthMode" | undefined;
|
||||
options: MenuOptions[];
|
||||
selected: string | undefined;
|
||||
select: ((id: string) => void) | undefined;
|
||||
@@ -131,7 +136,10 @@ export function createAudioMenuViewModel(
|
||||
): MediaMenuViewModel {
|
||||
const { audio } = muteStates;
|
||||
return {
|
||||
...createStaticViewModel(noBackgroundEffects),
|
||||
...createStaticViewModel({
|
||||
...noBackgroundEffects,
|
||||
unavailableReason: undefined,
|
||||
}),
|
||||
enabled$: audio.enabled$,
|
||||
busy$: audio.syncing$,
|
||||
toggle$: scope.behavior(audio.toggle$.pipe(map((t) => t ?? undefined))),
|
||||
@@ -164,6 +172,8 @@ export function createAudioMenuViewModel(
|
||||
* @param backgroundEffectsState$ - The background pipeline's state: whether
|
||||
* effects run here, and the wait for the first.
|
||||
* @param camera$ - The camera as the pipeline has it, for the preview.
|
||||
* @param lowBandwidthMode$ - Whether the call's low bandwidth mode is on,
|
||||
* which holds the camera off.
|
||||
*/
|
||||
export function createCameraMenuViewModel(
|
||||
scope: ObservableScope,
|
||||
@@ -172,6 +182,7 @@ export function createCameraMenuViewModel(
|
||||
disableSwitcher$: Behavior<boolean>,
|
||||
backgroundEffectsState$: Observable<BackgroundEffectsState>,
|
||||
camera$: Observable<LocalVideoMediaTrack | null | undefined>,
|
||||
lowBandwidthMode$: Behavior<boolean>,
|
||||
): MediaMenuViewModel {
|
||||
const { video } = muteStates;
|
||||
// Also false once the pipeline has failed to build this session.
|
||||
@@ -205,6 +216,11 @@ export function createCameraMenuViewModel(
|
||||
enabled$: video.enabled$,
|
||||
busy$: video.syncing$,
|
||||
toggle$: scope.behavior(video.toggle$.pipe(map((t) => t ?? undefined))),
|
||||
unavailableReason$: scope.behavior(
|
||||
lowBandwidthMode$.pipe(
|
||||
map((on) => (on ? ("lowBandwidthMode" as const) : undefined)),
|
||||
),
|
||||
),
|
||||
options$: scope.behavior(
|
||||
options$(disableSwitcher$, mediaDevices.videoInput.available$),
|
||||
),
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { MediaMuteAndSwitchButton } from "./MediaMuteAndSwitchButton";
|
||||
import styles from "./MediaMuteAndSwitchButton.module.css";
|
||||
import { type BackgroundEffectGridItem } from "./BackgroundEffectGrid";
|
||||
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
|
||||
import { SelfPreview } from "./SelfPreview";
|
||||
import { shippedBackgrounds } from "../tracks/backgroundEffectCatalog";
|
||||
import meterStyles from "./MicrophoneLevelMeter.module.css";
|
||||
@@ -221,6 +222,31 @@ export const VideoMute: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Held off by Low bandwidth mode: the mute half says why, the menu still opens. */
|
||||
export const VideoUnavailableInLowBandwidthMode: Story = {
|
||||
args: {
|
||||
...VideoMute.args,
|
||||
onMuteClick: fn(),
|
||||
onSelect: fn(),
|
||||
unavailable: {
|
||||
description:
|
||||
"You can't turn on your camera while Low bandwidth mode is on. Turn it off in Developer options.",
|
||||
},
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expectExplainsUnavailable(
|
||||
canvas.getByTestId("incall_videomute"),
|
||||
args.unavailable!.description,
|
||||
args.onMuteClick!,
|
||||
);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Camera" }));
|
||||
await expect(
|
||||
await within(document.body).findByRole("menu"),
|
||||
).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
const effects: BackgroundEffectGridItem[] = [
|
||||
{ id: "none", kind: "none" },
|
||||
{ id: "blur", kind: "blur" },
|
||||
|
||||
@@ -37,7 +37,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { distinctUntilChanged, map } from "rxjs";
|
||||
|
||||
import styles from "./MediaMuteAndSwitchButton.module.css";
|
||||
import { MicButton, VideoButton } from "../button";
|
||||
import { MicButton, type Unavailable, VideoButton } from "../button";
|
||||
import {
|
||||
type AudioOutputDeviceLabel,
|
||||
type DeviceLabel,
|
||||
@@ -61,6 +61,8 @@ export interface MediaMuteAndSwitchButtonProps {
|
||||
enabled?: boolean;
|
||||
/** Callback if the mute button is clicked */
|
||||
onMuteClick?: () => void;
|
||||
/** Why the mute button can't turn the device on, explained instead. Camera only. */
|
||||
unavailable?: Unavailable;
|
||||
/** True while mute/unmute operation is syncing. */
|
||||
busy?: boolean;
|
||||
iconsAndLabels: "video" | "audio";
|
||||
@@ -123,6 +125,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
enabled,
|
||||
busy,
|
||||
onMuteClick,
|
||||
unavailable,
|
||||
iconsAndLabels,
|
||||
options,
|
||||
selectedOption,
|
||||
@@ -284,6 +287,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
e.stopPropagation();
|
||||
}}
|
||||
disabled={isBusy || onMuteClick === undefined}
|
||||
unavailable={audioMeter ? undefined : unavailable}
|
||||
data-testid={audioMeter ? "incall_mute" : "incall_videomute"}
|
||||
/>
|
||||
);
|
||||
|
||||
+28
-2
@@ -73,6 +73,10 @@ import { useMuteStates } from "../state/useMuteStates.ts";
|
||||
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
|
||||
import { useLocalMedia } from "../useLocalMedia.ts";
|
||||
import { ObservableScope } from "../state/ObservableScope.ts";
|
||||
import {
|
||||
createLowBandwidthMode,
|
||||
type LowBandwidthMode,
|
||||
} from "../state/LowBandwidthMode.ts";
|
||||
import { type CallNotificationWrapper } from "../state/CallViewModel/CallNotificationLifecycle.ts";
|
||||
import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
|
||||
|
||||
@@ -146,6 +150,15 @@ export const CallView: FC<Props> = ({
|
||||
// rebuilt.
|
||||
const [joined, setJoined] = useState(false);
|
||||
const muteStates = useMuteStates();
|
||||
// Held here too, so that it also survives the call failing and being
|
||||
// reconnected. The lobby starts every new call with it off
|
||||
const [lowBandwidthMode, setLowBandwidthMode] =
|
||||
useState<LowBandwidthMode | null>(null);
|
||||
useEffect(() => {
|
||||
const scope = new ObservableScope();
|
||||
setLowBandwidthMode(createLowBandwidthMode(scope));
|
||||
return (): void => scope.end();
|
||||
}, []);
|
||||
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
|
||||
|
||||
// One slot for every join of this call: leaving and joining again, to
|
||||
@@ -166,7 +179,8 @@ export const CallView: FC<Props> = ({
|
||||
return (): void => scope.end();
|
||||
}, [backend, e2eeSystem, externalRtcSession]);
|
||||
|
||||
if (muteStates === null || slot === null) return null;
|
||||
if (muteStates === null || slot === null || lowBandwidthMode === null)
|
||||
return null;
|
||||
|
||||
return (
|
||||
<LoadedCallView
|
||||
@@ -180,6 +194,7 @@ export const CallView: FC<Props> = ({
|
||||
joined={joined}
|
||||
setJoined={setJoined}
|
||||
muteStates={muteStates}
|
||||
lowBandwidthMode={lowBandwidthMode}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -249,6 +264,7 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
|
||||
joined: boolean;
|
||||
setJoined: (value: boolean) => void;
|
||||
muteStates: MuteStates;
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,6 +297,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
joined,
|
||||
setJoined,
|
||||
muteStates,
|
||||
lowBandwidthMode,
|
||||
}) => {
|
||||
// Used to thread through any errors that occur outside the error boundary
|
||||
const [externalError, setExternalError] = useState<ElementCallError | null>(
|
||||
@@ -310,6 +327,11 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => lowBandwidthMode.bind(muteStates),
|
||||
[lowBandwidthMode, muteStates],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
logger.info("[Lifecycle] CallView Component mounted");
|
||||
return (): void => {
|
||||
@@ -587,7 +609,10 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
matrixInfo={matrixInfo}
|
||||
media={media}
|
||||
muteStates={muteStates}
|
||||
onEnter={() => setJoined(true)}
|
||||
onEnter={() => {
|
||||
lowBandwidthMode.reset();
|
||||
setJoined(true);
|
||||
}}
|
||||
confineToRoom={confineToRoom}
|
||||
hideHeader={header !== HeaderStyle.Standard}
|
||||
participantCount={participantCount}
|
||||
@@ -618,6 +643,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
onLeft={onLeft}
|
||||
media={media}
|
||||
muteStates={muteStates}
|
||||
lowBandwidthMode={lowBandwidthMode}
|
||||
e2eeSystem={e2eeSystem}
|
||||
//otelGroupCallMembership={otelGroupCallMembership}
|
||||
onShareClick={onShareClick}
|
||||
|
||||
@@ -21,6 +21,10 @@ import { TooltipProvider } from "@vector-im/compound-web";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
import { ActiveCall, InCallView } from "./InCallView";
|
||||
import {
|
||||
createLowBandwidthMode,
|
||||
type LowBandwidthMode,
|
||||
} from "../state/LowBandwidthMode";
|
||||
import {
|
||||
mockMediaDevices,
|
||||
mockMuteStates,
|
||||
@@ -127,16 +131,23 @@ interface CreateInCallViewArgs {
|
||||
}
|
||||
function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
|
||||
vm: CallViewModel;
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
} {
|
||||
const mediaDevices = args.mediaDevices ?? mockMediaDevices({});
|
||||
const muteState = mockMuteStates();
|
||||
const { vm, footerVm, developerSettingsVm, matrixRoom, client } =
|
||||
getBasicCallViewModelEnvironment(
|
||||
[local, alice],
|
||||
undefined,
|
||||
mediaDevices,
|
||||
args.callViewModelOptions,
|
||||
);
|
||||
const {
|
||||
vm,
|
||||
footerVm,
|
||||
developerSettingsVm,
|
||||
lowBandwidthMode,
|
||||
matrixRoom,
|
||||
client,
|
||||
} = getBasicCallViewModelEnvironment(
|
||||
[local, alice],
|
||||
undefined,
|
||||
mediaDevices,
|
||||
args.callViewModelOptions,
|
||||
);
|
||||
|
||||
const inCallView = (
|
||||
<InCallView
|
||||
@@ -165,6 +176,7 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
|
||||
return {
|
||||
...renderResult,
|
||||
vm,
|
||||
lowBandwidthMode,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -176,6 +188,25 @@ describe("InCallView", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the camera shortcut in low bandwidth mode", () => {
|
||||
it("says why the camera stays off, as the camera button does", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container, lowBandwidthMode } = createInCallView();
|
||||
act(() => lowBandwidthMode.setEnabled(true));
|
||||
|
||||
await user.keyboard("v");
|
||||
|
||||
const explanation =
|
||||
"You can't turn on your camera while Low bandwidth mode is on. Turn it off in Developer options.";
|
||||
const regions = [
|
||||
...container.querySelectorAll('[aria-live="polite"]'),
|
||||
].map((region) => region.textContent);
|
||||
expect(regions).toContain(explanation);
|
||||
// Said by the call, not by a tooltip that focus is not on
|
||||
expect(document.querySelector('[role="tooltip"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("audioOutputSwitcher", () => {
|
||||
it("is visible and can be clicked", async () => {
|
||||
const user = userEvent.setup();
|
||||
@@ -242,6 +273,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
|
||||
sentCallNotification$={NEVER}
|
||||
matrixRoom={matrixRoom}
|
||||
muteStates={mockMuteStates()}
|
||||
lowBandwidthMode={createLowBandwidthMode(testScope())}
|
||||
matrixInfo={matrixInfo}
|
||||
onShareClick={null}
|
||||
e2eeSystem={{ kind: E2eeType.NONE }}
|
||||
@@ -311,6 +343,7 @@ describe("ActiveCall", () => {
|
||||
sentCallNotification$={NEVER}
|
||||
matrixRoom={matrixRoom}
|
||||
muteStates={mockMuteStates()}
|
||||
lowBandwidthMode={createLowBandwidthMode(testScope())}
|
||||
matrixInfo={matrixInfo}
|
||||
onShareClick={null}
|
||||
e2eeSystem={{ kind: E2eeType.NONE }}
|
||||
|
||||
+23
-2
@@ -26,6 +26,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Header, LeftNav, RightNav, RoomHeaderInfo } from "../Header";
|
||||
import { HeaderStyle, useUrlParams } from "../UrlParams";
|
||||
import { useCallViewKeyboardShortcuts } from "../useCallViewKeyboardShortcuts";
|
||||
import { useAnnouncement } from "../useAnnouncement";
|
||||
import { useHostBridge } from "../HostBridge.ts";
|
||||
import { useRootElement } from "../RootElementContext";
|
||||
import { observeElementSize$ } from "../utils/elementSize";
|
||||
@@ -41,6 +42,7 @@ import { RageshakeRequestModal } from "./RageshakeRequestModal";
|
||||
import { useWakeLock } from "../useWakeLock";
|
||||
import { useMergedRefs } from "../useMergedRefs";
|
||||
import { type MuteStates } from "../state/MuteStates";
|
||||
import { type LowBandwidthMode } from "../state/LowBandwidthMode";
|
||||
import { type MatrixInfo } from "./VideoPreview";
|
||||
import { InviteButton } from "../button/InviteButton";
|
||||
import {
|
||||
@@ -194,6 +196,7 @@ export interface ActiveCallProps extends Omit<
|
||||
e2eeSystem: EncryptionSystem;
|
||||
/** The tracks the lobby opened, for the join to publish. */
|
||||
media: LocalMedia;
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
// TODO refactor those reasons into an enum
|
||||
onLeft: (
|
||||
reason: "user" | "timeout" | "decline" | "allOthersLeft" | "error",
|
||||
@@ -230,6 +233,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
const capture = captureSettings();
|
||||
const rtcParticipation = props.slot.join({
|
||||
...rtcParticipationOptions(urlParams),
|
||||
receiveVideo: !props.lowBandwidthMode.enabled$.value,
|
||||
// Without a lobby nothing was captured and the join captures itself
|
||||
publish:
|
||||
props.media.requests.length > 0
|
||||
@@ -250,6 +254,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
client: props.client,
|
||||
mediaDevices,
|
||||
muteStates: props.muteStates,
|
||||
lowBandwidthMode: props.lowBandwidthMode,
|
||||
encryptionSystem: props.e2eeSystem,
|
||||
viewSize$: scope.behavior(observeElementSize$(rootElement)),
|
||||
handsRaisedSubject$: reactionsReader.raisedHands$,
|
||||
@@ -282,6 +287,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
props.sentCallNotification$,
|
||||
props.matrixRoom,
|
||||
props.muteStates,
|
||||
props.lowBandwidthMode,
|
||||
props.e2eeSystem,
|
||||
props.onLeft,
|
||||
urlParams,
|
||||
@@ -301,13 +307,16 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
scope,
|
||||
vm,
|
||||
props.muteStates,
|
||||
props.lowBandwidthMode.enabled$,
|
||||
mediaDevices,
|
||||
backgroundEffectsState$,
|
||||
`${props.client.getUserId()}:${props.client.getDeviceId()}`,
|
||||
{ showControls: urlParams.showControls, header: urlParams.header },
|
||||
);
|
||||
setFooterVm(footerVm);
|
||||
setDeveloperSettingsVm(createDeveloperSettingsTabViewModel(scope, vm));
|
||||
setDeveloperSettingsVm(
|
||||
createDeveloperSettingsTabViewModel(scope, vm, props.lowBandwidthMode),
|
||||
);
|
||||
|
||||
return (): void => {
|
||||
scope.end();
|
||||
@@ -315,6 +324,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
}, [
|
||||
props.matrixRoom,
|
||||
props.muteStates,
|
||||
props.lowBandwidthMode,
|
||||
props.e2eeSystem,
|
||||
props.onLeft,
|
||||
urlParams,
|
||||
@@ -397,10 +407,20 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
const toggleAudio = useBehavior(muteStates.audio.toggle$);
|
||||
const toggleVideo = useBehavior(muteStates.video.toggle$);
|
||||
const setAudioEnabled = useBehavior(muteStates.audio.setEnabled$);
|
||||
const cameraMenuVm = useBehavior(footerVm.cameraMenuVm$);
|
||||
const cameraUnavailable = useBehavior(cameraMenuVm.unavailableReason$);
|
||||
const [cameraUnavailableLiveRegion, announce] = useAnnouncement();
|
||||
// The shortcut does what the camera button does: says why, and nothing else
|
||||
const explainCameraUnavailable = useCallback(
|
||||
() => announce(t("low_bandwidth_mode.camera_unavailable")),
|
||||
[announce, t],
|
||||
);
|
||||
|
||||
useCallViewKeyboardShortcuts(
|
||||
toggleAudio,
|
||||
toggleVideo,
|
||||
cameraUnavailable === "lowBandwidthMode"
|
||||
? explainCameraUnavailable
|
||||
: toggleVideo,
|
||||
setAudioEnabled,
|
||||
(reaction) => void sendReaction(reaction),
|
||||
() => void toggleRaisedHand(),
|
||||
@@ -785,6 +805,7 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
<CallEventAudioRenderer vm={vm} muted={muteAllAudio} />
|
||||
<ReactionsAudioRenderer vm={vm} muted={muteAllAudio} />
|
||||
<RingingAudioRenderer vm={ringingVm} muted={muteAllAudio} />
|
||||
{cameraUnavailableLiveRegion}
|
||||
{reconnectingToast}
|
||||
{screenShareToast}
|
||||
{earpieceOverlay}
|
||||
|
||||
@@ -112,6 +112,10 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
>
|
||||
<div />
|
||||
</div>
|
||||
<span
|
||||
aria-live="polite"
|
||||
style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"
|
||||
/>
|
||||
<div
|
||||
class="_bg_2f5303 _animate_2f5303"
|
||||
data-state="closed"
|
||||
@@ -360,7 +364,7 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_q_"
|
||||
aria-labelledby="_r_r_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -385,7 +389,7 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
aria-disabled="false"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
aria-labelledby="_r_v_"
|
||||
aria-labelledby="_r_10_"
|
||||
class="_button_1nw83_8 _raiseHand_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="secondary"
|
||||
data-size="lg"
|
||||
@@ -408,7 +412,7 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
aria-labelledby="_r_17_"
|
||||
aria-labelledby="_r_18_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -436,8 +440,8 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
data-size="lg"
|
||||
>
|
||||
<input
|
||||
aria-labelledby="_r_1d_"
|
||||
name="_r_1c_"
|
||||
aria-labelledby="_r_1e_"
|
||||
name="_r_1d_"
|
||||
type="radio"
|
||||
value="spotlight"
|
||||
/>
|
||||
@@ -456,9 +460,9 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
/>
|
||||
</svg>
|
||||
<input
|
||||
aria-labelledby="_r_1i_"
|
||||
aria-labelledby="_r_1j_"
|
||||
checked=""
|
||||
name="_r_1c_"
|
||||
name="_r_1d_"
|
||||
type="radio"
|
||||
value="grid"
|
||||
/>
|
||||
|
||||
@@ -7,7 +7,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
>
|
||||
<header>
|
||||
<button
|
||||
aria-labelledby="_r_36_"
|
||||
aria-labelledby="_r_39_"
|
||||
class="_icon-button_1215g_8 _primaryButton_221541"
|
||||
data-kind="primary"
|
||||
role="button"
|
||||
@@ -102,7 +102,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
class="_settingsLogoContainer_20b7b4"
|
||||
>
|
||||
<button
|
||||
aria-labelledby="_r_3c_"
|
||||
aria-labelledby="_r_3f_"
|
||||
class="_icon-button_1215g_8 _settingsOnlyShowWide_20b7b4"
|
||||
data-kind="secondary"
|
||||
data-testid="settings-bottom-left"
|
||||
@@ -133,7 +133,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
class="_buttons_20b7b4"
|
||||
>
|
||||
<button
|
||||
aria-labelledby="_r_3h_"
|
||||
aria-labelledby="_r_3k_"
|
||||
class="_button_1nw83_8 _settingsOnlyShowNarrow_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="secondary"
|
||||
data-size="lg"
|
||||
@@ -158,7 +158,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_3m_"
|
||||
aria-labelledby="_r_3p_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -183,7 +183,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_3r_"
|
||||
aria-labelledby="_r_3v_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -205,7 +205,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
aria-labelledby="_r_40_"
|
||||
aria-labelledby="_r_44_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -239,7 +239,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
>
|
||||
<header>
|
||||
<button
|
||||
aria-labelledby="_r_4a_"
|
||||
aria-labelledby="_r_4e_"
|
||||
class="_icon-button_1215g_8 _primaryButton_221541"
|
||||
data-kind="primary"
|
||||
role="button"
|
||||
@@ -334,7 +334,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
class="_settingsLogoContainer_20b7b4"
|
||||
>
|
||||
<button
|
||||
aria-labelledby="_r_4g_"
|
||||
aria-labelledby="_r_4k_"
|
||||
class="_icon-button_1215g_8 _settingsOnlyShowWide_20b7b4"
|
||||
data-kind="secondary"
|
||||
data-testid="settings-bottom-left"
|
||||
@@ -365,7 +365,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
class="_buttons_20b7b4"
|
||||
>
|
||||
<button
|
||||
aria-labelledby="_r_4l_"
|
||||
aria-labelledby="_r_4p_"
|
||||
class="_button_1nw83_8 _settingsOnlyShowNarrow_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="secondary"
|
||||
data-size="lg"
|
||||
@@ -390,7 +390,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_4q_"
|
||||
aria-labelledby="_r_4u_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -415,7 +415,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_4v_"
|
||||
aria-labelledby="_r_54_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -437,7 +437,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
aria-labelledby="_r_54_"
|
||||
aria-labelledby="_r_59_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -797,7 +797,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
|
||||
aria-busy="false"
|
||||
aria-checked="false"
|
||||
aria-disabled="true"
|
||||
aria-labelledby="_r_l_"
|
||||
aria-labelledby="_r_m_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
@@ -819,7 +819,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
aria-labelledby="_r_q_"
|
||||
aria-labelledby="_r_r_"
|
||||
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
|
||||
data-kind="primary"
|
||||
data-size="lg"
|
||||
|
||||
@@ -429,6 +429,7 @@ describe("DeveloperSettingsTab", () => {
|
||||
const client = createMockMatrixClient();
|
||||
const vm = createStaticViewModel<DeveloperSettingsSnapshot>({
|
||||
keyRotation: { suppressed: false, participantCount: 5 },
|
||||
lowBandwidthMode: null,
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -452,6 +453,7 @@ describe("DeveloperSettingsTab", () => {
|
||||
const client = createMockMatrixClient();
|
||||
const vm = createStaticViewModel<DeveloperSettingsSnapshot>({
|
||||
keyRotation: { suppressed: true, participantCount: 50 },
|
||||
lowBandwidthMode: null,
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -493,4 +495,48 @@ describe("DeveloperSettingsTab", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Low bandwidth mode", () => {
|
||||
it("is a switch for the call, while in one", async () => {
|
||||
const user = userEvent.setup();
|
||||
const setEnabled = vi.fn();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<DeveloperSettingsTab
|
||||
client={createMockMatrixClient()}
|
||||
env={{} as unknown as ImportMetaEnv}
|
||||
vm={createStaticViewModel<DeveloperSettingsSnapshot>({
|
||||
keyRotation: null,
|
||||
lowBandwidthMode: { enabled: false, setEnabled },
|
||||
})}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
|
||||
const toggle = screen.getByRole("checkbox", {
|
||||
name: "Low bandwidth mode",
|
||||
});
|
||||
expect(toggle).not.toBeChecked();
|
||||
expect(toggle).toHaveAccessibleDescription(
|
||||
"Stop all video for this call, so that audio keeps flowing on a slow network. Lasts until the call ends.",
|
||||
);
|
||||
await user.click(toggle);
|
||||
expect(setEnabled).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("is not offered outside a call", () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<DeveloperSettingsTab
|
||||
client={createMockMatrixClient()}
|
||||
env={{} as unknown as ImportMetaEnv}
|
||||
vm={outOfCallDeveloperSettingsTabViewModel}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("checkbox", { name: "Low bandwidth mode" }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,6 +97,11 @@ export interface KeyRotationInfo {
|
||||
export interface DeveloperSettingsSnapshot {
|
||||
/** The media key rotation state, or `null` when we are not in a call. */
|
||||
keyRotation: KeyRotationInfo | null;
|
||||
/** The call's low bandwidth mode, or `null` when we are not in a call. */
|
||||
lowBandwidthMode: {
|
||||
enabled: boolean;
|
||||
setEnabled: (enabled: boolean) => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,6 +146,7 @@ export const DeveloperSettingsTab: FC<Props> = ({
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const keyRotation = useBehavior(vm.keyRotation$);
|
||||
const lowBandwidthMode = useBehavior(vm.lowBandwidthMode$);
|
||||
const [duplicateTiles, setDuplicateTiles] = useSetting(duplicateTilesSetting);
|
||||
const [debugTileLayout, setDebugTileLayout] = useSetting(
|
||||
debugTileLayoutSetting,
|
||||
@@ -410,6 +416,21 @@ export const DeveloperSettingsTab: FC<Props> = ({
|
||||
</p>
|
||||
{keyRotation !== null && <KeyRotationStatus info={keyRotation} />}
|
||||
<Separator />
|
||||
{/* Null outside a call (the lobby, the user menu): the mode belongs to a call */}
|
||||
{lowBandwidthMode !== null && (
|
||||
<FieldRow>
|
||||
<InputField
|
||||
id="lowBandwidthMode"
|
||||
type="checkbox"
|
||||
label={t("low_bandwidth_mode.switch_label")}
|
||||
description={t("low_bandwidth_mode.switch_description")}
|
||||
checked={lowBandwidthMode.enabled}
|
||||
onChange={(event: ChangeEvent<HTMLInputElement>): void =>
|
||||
lowBandwidthMode.setEnabled(event.target.checked)
|
||||
}
|
||||
/>
|
||||
</FieldRow>
|
||||
)}
|
||||
<FieldRow>
|
||||
<InputField
|
||||
id="duplicateTiles"
|
||||
|
||||
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
|
||||
import { testScope } from "../utils/test";
|
||||
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
|
||||
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
|
||||
import {
|
||||
createDeveloperSettingsTabViewModel,
|
||||
@@ -19,10 +20,11 @@ describe("createDeveloperSettingsTabViewModel", () => {
|
||||
it("projects the key rotation state of the call", () => {
|
||||
const keyRotationSuppressed$ = new BehaviorSubject(false);
|
||||
const participantCount$ = new BehaviorSubject(5);
|
||||
const vm = createDeveloperSettingsTabViewModel(testScope(), {
|
||||
keyRotationSuppressed$,
|
||||
participantCount$,
|
||||
} as unknown as CallViewModel);
|
||||
const vm = createDeveloperSettingsTabViewModel(
|
||||
testScope(),
|
||||
{ keyRotationSuppressed$, participantCount$ } as unknown as CallViewModel,
|
||||
createLowBandwidthMode(testScope()),
|
||||
);
|
||||
|
||||
expect(vm.keyRotation$.value).toEqual({
|
||||
suppressed: false,
|
||||
@@ -37,9 +39,35 @@ describe("createDeveloperSettingsTabViewModel", () => {
|
||||
participantCount: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("has a switch reflecting the call's low bandwidth mode", () => {
|
||||
const mode = createLowBandwidthMode(testScope());
|
||||
const vm = createDeveloperSettingsTabViewModel(
|
||||
testScope(),
|
||||
{
|
||||
keyRotationSuppressed$: new BehaviorSubject(false),
|
||||
participantCount$: new BehaviorSubject(1),
|
||||
} as unknown as CallViewModel,
|
||||
mode,
|
||||
);
|
||||
expect(vm.lowBandwidthMode$.value?.enabled).toBe(false);
|
||||
|
||||
vm.lowBandwidthMode$.value!.setEnabled(true);
|
||||
expect(mode.enabled$.value).toBe(true);
|
||||
expect(vm.lowBandwidthMode$.value?.enabled).toBe(true);
|
||||
|
||||
mode.setEnabled(false);
|
||||
expect(vm.lowBandwidthMode$.value?.enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("outOfCallDeveloperSettingsTabViewModel", () => {
|
||||
it("has no low bandwidth mode switch", () => {
|
||||
expect(outOfCallDeveloperSettingsTabViewModel.lowBandwidthMode$.value).toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
it("has no key rotation state", () => {
|
||||
expect(outOfCallDeveloperSettingsTabViewModel.keyRotation$.value).toBe(
|
||||
null,
|
||||
|
||||
@@ -5,9 +5,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { combineLatest } from "rxjs";
|
||||
import { combineLatest, map } from "rxjs";
|
||||
|
||||
import { type CallViewModel } from "../state/CallViewModel/CallViewModel.ts";
|
||||
import { type LowBandwidthMode } from "../state/LowBandwidthMode.ts";
|
||||
import { type ObservableScope } from "../state/ObservableScope.ts";
|
||||
import { createStaticViewModel, type ViewModel } from "../state/ViewModel.ts";
|
||||
import { type DeveloperSettingsSnapshot } from "./DeveloperSettingsTab.tsx";
|
||||
@@ -20,12 +21,22 @@ import { type DeveloperSettingsSnapshot } from "./DeveloperSettingsTab.tsx";
|
||||
*
|
||||
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
|
||||
* @param callModel - The root CallViewModel; provides the key rotation state.
|
||||
* @param lowBandwidthMode - The call's low bandwidth mode, for its switch.
|
||||
*/
|
||||
export function createDeveloperSettingsTabViewModel(
|
||||
scope: ObservableScope,
|
||||
callModel: CallViewModel,
|
||||
lowBandwidthMode: LowBandwidthMode,
|
||||
): ViewModel<DeveloperSettingsSnapshot> {
|
||||
return {
|
||||
lowBandwidthMode$: scope.behavior(
|
||||
lowBandwidthMode.enabled$.pipe(
|
||||
map((enabled) => ({
|
||||
enabled,
|
||||
setEnabled: lowBandwidthMode.setEnabled,
|
||||
})),
|
||||
),
|
||||
),
|
||||
keyRotation$: scope.behavior(
|
||||
combineLatest(
|
||||
[callModel.keyRotationSuppressed$, callModel.participantCount$],
|
||||
@@ -40,4 +51,7 @@ export function createDeveloperSettingsTabViewModel(
|
||||
* menu), where no call state exists. All call specific fields are `null`.
|
||||
*/
|
||||
export const outOfCallDeveloperSettingsTabViewModel: ViewModel<DeveloperSettingsSnapshot> =
|
||||
createStaticViewModel<DeveloperSettingsSnapshot>({ keyRotation: null });
|
||||
createStaticViewModel<DeveloperSettingsSnapshot>({
|
||||
keyRotation: null,
|
||||
lowBandwidthMode: null,
|
||||
});
|
||||
|
||||
@@ -75,6 +75,10 @@ import {
|
||||
type VideoProcessor,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
import { type BackgroundEffectsState } from "../BackgroundEffects";
|
||||
import { createLowBandwidthMode } from "../LowBandwidthMode.ts";
|
||||
import { type MediaViewModel } from "../media/MediaViewModel.ts";
|
||||
import { type RemoteScreenShareViewModel } from "../media/RemoteScreenShareViewModel.ts";
|
||||
import { type UserMediaViewModel } from "../media/UserMediaViewModel.ts";
|
||||
|
||||
initializeWidget();
|
||||
|
||||
@@ -1897,3 +1901,201 @@ describe("a camera with a video processor", () => {
|
||||
expect(participation!.publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("low bandwidth mode", () => {
|
||||
const withCallViewModel = withCallViewModelInMode(MatrixRTCMode.Matrix_2_0);
|
||||
const onOff = { y: true, n: false };
|
||||
|
||||
test("stops and resumes receiving video as the mode is turned on and off", () => {
|
||||
const lowBandwidthMode = createLowBandwidthMode(testScope());
|
||||
withCallViewModel(
|
||||
{ lowBandwidthMode },
|
||||
(_vm, _session, { rtcParticipation }) => {
|
||||
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
|
||||
lowBandwidthMode.setEnabled(true);
|
||||
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(
|
||||
false,
|
||||
);
|
||||
lowBandwidthMode.setEnabled(false);
|
||||
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("shows a camera that is still sending as off while on", () => {
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
const lowBandwidthMode = createLowBandwidthMode(testScope());
|
||||
withCallViewModel(
|
||||
{
|
||||
lowBandwidthMode,
|
||||
// Three, for the grid
|
||||
remoteParticipants$: constant([aliceParticipant, bobParticipant]),
|
||||
rtcMembers$: constant([localRtcMember, aliceRtcMember, bobRtcMember]),
|
||||
videoEnabled: new Map([[aliceParticipant, constant(true)]]),
|
||||
},
|
||||
(vm) => {
|
||||
schedule("-yn", {
|
||||
y: () => lowBandwidthMode.setEnabled(true),
|
||||
n: () => lowBandwidthMode.setEnabled(false),
|
||||
});
|
||||
expectObservable(
|
||||
gridMedia$(vm.layout$, `${aliceId}:0`).pipe(
|
||||
switchMap((media) => media?.videoEnabled$ ?? NEVER),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
).toBe("yny", onOff);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps a remote screen share on the stage, without its picture, while on", () => {
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
const lowBandwidthMode = createLowBandwidthMode(testScope());
|
||||
withCallViewModel(
|
||||
{
|
||||
lowBandwidthMode,
|
||||
remoteParticipants$: constant([aliceParticipant]),
|
||||
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
|
||||
sharingScreen: new Map([[aliceParticipant, constant(true)]]),
|
||||
},
|
||||
(vm) => {
|
||||
schedule("-yn", {
|
||||
y: () => lowBandwidthMode.setEnabled(true),
|
||||
n: () => lowBandwidthMode.setEnabled(false),
|
||||
});
|
||||
const share$ = spotlightMedia$(
|
||||
vm.layout$,
|
||||
`${aliceId}:0:screen-share`,
|
||||
);
|
||||
expectObservable(
|
||||
share$.pipe(
|
||||
map((share) => share !== undefined),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
).toBe("y", onOff);
|
||||
expectObservable(
|
||||
share$.pipe(
|
||||
switchMap(
|
||||
(share) =>
|
||||
(share as RemoteScreenShareViewModel | undefined)
|
||||
?.videoEnabled$ ?? NEVER,
|
||||
),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
).toBe("yny", onOff);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("leaves a blank share out of the picture-in-picture window while on", () => {
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
const lowBandwidthMode = createLowBandwidthMode(testScope());
|
||||
withCallViewModel(
|
||||
{
|
||||
lowBandwidthMode,
|
||||
remoteParticipants$: constant([aliceParticipant]),
|
||||
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
|
||||
sharingScreen: new Map([[aliceParticipant, constant(true)]]),
|
||||
},
|
||||
(vm) => {
|
||||
schedule("-pyn", {
|
||||
p: () => window.controls.enablePip(),
|
||||
y: () => lowBandwidthMode.setEnabled(true),
|
||||
n: () => lowBandwidthMode.setEnabled(false),
|
||||
});
|
||||
onTestFinished(() => window.controls.disablePip());
|
||||
expectObservable(summarizeLayout$(vm.layout$)).toBe("abcb", {
|
||||
a: {
|
||||
type: "spotlight-landscape",
|
||||
spotlight: [`${aliceId}:0:screen-share`],
|
||||
grid: [`${localId}:0`, `${aliceId}:0`],
|
||||
},
|
||||
b: { type: "pip", spotlight: [`${aliceId}:0:screen-share`] },
|
||||
c: { type: "pip", spotlight: [`${aliceId}:0`] },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("stops our screen share when turned on, and starts none while on", () => {
|
||||
const getDisplayMedia = stubGetDisplayMedia();
|
||||
const lowBandwidthMode = createLowBandwidthMode(testScope());
|
||||
const sharing$ = new BehaviorSubject(true);
|
||||
withCallViewModel(
|
||||
{
|
||||
lowBandwidthMode,
|
||||
sharingScreen: new Map([[localParticipant, sharing$]]),
|
||||
},
|
||||
(vm, _session, { rtcParticipation }) => {
|
||||
expect(vm.sharingScreen$.value).toBe(true);
|
||||
lowBandwidthMode.setEnabled(true);
|
||||
expect(rtcParticipation.unpublish).toHaveBeenCalledExactlyOnceWith(
|
||||
"screenShare",
|
||||
);
|
||||
sharing$.next(false);
|
||||
|
||||
vm.toggleScreenSharing!();
|
||||
expect(rtcParticipation.publish).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ source: "screenShare" }),
|
||||
);
|
||||
|
||||
// Not restarted when the mode is turned off
|
||||
lowBandwidthMode.setEnabled(false);
|
||||
expect(rtcParticipation.publish).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ source: "screenShare" }),
|
||||
);
|
||||
expect(getDisplayMedia).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/** Lets the view model offer screen sharing, as a desktop browser does. */
|
||||
function stubGetDisplayMedia(): ReturnType<typeof vi.fn> {
|
||||
const getDisplayMedia = vi.fn();
|
||||
const original = Object.getOwnPropertyDescriptor(navigator, "mediaDevices");
|
||||
Object.defineProperty(navigator, "mediaDevices", {
|
||||
configurable: true,
|
||||
value: { ...navigator.mediaDevices, getDisplayMedia },
|
||||
});
|
||||
onTestFinished(() => {
|
||||
if (original) Object.defineProperty(navigator, "mediaDevices", original);
|
||||
else Reflect.deleteProperty(navigator, "mediaDevices");
|
||||
});
|
||||
return getDisplayMedia;
|
||||
}
|
||||
|
||||
function gridMedia$(
|
||||
layout$: Observable<Layout>,
|
||||
id: string,
|
||||
): Observable<UserMediaViewModel | undefined> {
|
||||
return layout$.pipe(
|
||||
switchMap((layout) =>
|
||||
"grid" in layout && layout.grid.length > 0
|
||||
? combineLatest(layout.grid.map((tile) => tile.media$))
|
||||
: NEVER,
|
||||
),
|
||||
map((media) =>
|
||||
media.find(
|
||||
(m): m is UserMediaViewModel => m.id === id && m.type === "user",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function spotlightMedia$(
|
||||
layout$: Observable<Layout>,
|
||||
id: string,
|
||||
): Observable<MediaViewModel | undefined> {
|
||||
return layout$.pipe(
|
||||
switchMap((layout) =>
|
||||
layout.type === "spotlight-landscape"
|
||||
? layout.spotlight.vm.media$
|
||||
: NEVER,
|
||||
),
|
||||
map((media) => media.find((m) => m.id === id)),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -82,6 +82,7 @@ import {
|
||||
import { type BackgroundEffectsState } from "../BackgroundEffects";
|
||||
import { shallowEquals as arrayShallowEquals } from "../../utils/array";
|
||||
import { type MediaDevices } from "../MediaDevices";
|
||||
import { type LowBandwidthMode } from "../LowBandwidthMode";
|
||||
import { type MuteStates } from "../MuteStates";
|
||||
import {
|
||||
followDevice,
|
||||
@@ -207,6 +208,8 @@ export interface CallViewModelProps {
|
||||
client: Pick<MatrixClient, "getUserId" | "getDeviceId">;
|
||||
mediaDevices: MediaDevices;
|
||||
muteStates: MuteStates;
|
||||
/** The call's low bandwidth mode, which outlives this view model. */
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
encryptionSystem: EncryptionSystem;
|
||||
/**
|
||||
* The size of the space the call is drawn in: the page when Element Call
|
||||
@@ -506,6 +509,7 @@ export function createCallViewModel$(
|
||||
client,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
lowBandwidthMode,
|
||||
encryptionSystem,
|
||||
viewSize$,
|
||||
handsRaisedSubject$,
|
||||
@@ -653,6 +657,10 @@ export function createCallViewModel$(
|
||||
});
|
||||
});
|
||||
|
||||
lowBandwidthMode.enabled$
|
||||
.pipe(scope.bind())
|
||||
.subscribe((enabled) => rtcParticipation.setReceiveVideo(!enabled));
|
||||
|
||||
const members$ = scope.behavior<(LocalRTCMember | RemoteRTCMember)[]>(
|
||||
combineLatest(
|
||||
[rtcParticipation.localMember$, rtcParticipation.remoteMembers$],
|
||||
@@ -750,6 +758,7 @@ export function createCallViewModel$(
|
||||
),
|
||||
mediaDevices,
|
||||
pretendToBeDisconnected$: reconnecting$,
|
||||
videoPaused$: lowBandwidthMode.enabled$,
|
||||
displayName$: member.displayName$,
|
||||
mxcAvatarUrl$: member.avatarUrl$,
|
||||
handRaised$: scope.behavior(
|
||||
@@ -925,34 +934,6 @@ export function createCallViewModel$(
|
||||
),
|
||||
);
|
||||
|
||||
const spotlightAndPip$ = scope.behavior(
|
||||
combineLatest(
|
||||
[ringingMedia$, screenShares$, spotlightSpeaker$, localUserMediaForPip$],
|
||||
(ringing, screenShares, speaker, localPip) =>
|
||||
computeSpotlight({ ringing, screenShares, speaker, localPip }),
|
||||
).pipe(
|
||||
distinctUntilChanged(
|
||||
(a, b) =>
|
||||
arrayShallowEquals(a.spotlight, b.spotlight) && a.pip === b.pip,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const spotlight$ = scope.behavior<MediaViewModel[]>(
|
||||
spotlightAndPip$.pipe(
|
||||
map(({ spotlight }) => spotlight),
|
||||
distinctUntilChanged<MediaViewModel[]>(arrayShallowEquals),
|
||||
),
|
||||
);
|
||||
|
||||
const hasRemoteScreenShares$ = scope.behavior<boolean>(
|
||||
spotlight$.pipe(
|
||||
map((spotlight) =>
|
||||
spotlight.some((vm) => vm.type === "screen share" && !vm.local),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pipEnabled$ = scope.behavior(setPipEnabled$, false);
|
||||
|
||||
// A guess at what the window's mode should be based on the size and shape of
|
||||
@@ -980,6 +961,49 @@ export function createCallViewModel$(
|
||||
),
|
||||
);
|
||||
|
||||
// A share received without its picture is a blank tile: one is no use
|
||||
// in a window this small
|
||||
const spotlightScreenShares$ = scope.behavior(
|
||||
combineLatest(
|
||||
[screenShares$, lowBandwidthMode.enabled$, windowMode$],
|
||||
(screenShares, lowBandwidth, windowMode) =>
|
||||
lowBandwidth && windowMode === "pip" ? [] : screenShares,
|
||||
),
|
||||
);
|
||||
|
||||
const spotlightAndPip$ = scope.behavior(
|
||||
combineLatest(
|
||||
[
|
||||
ringingMedia$,
|
||||
spotlightScreenShares$,
|
||||
spotlightSpeaker$,
|
||||
localUserMediaForPip$,
|
||||
],
|
||||
(ringing, screenShares, speaker, localPip) =>
|
||||
computeSpotlight({ ringing, screenShares, speaker, localPip }),
|
||||
).pipe(
|
||||
distinctUntilChanged(
|
||||
(a, b) =>
|
||||
arrayShallowEquals(a.spotlight, b.spotlight) && a.pip === b.pip,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const spotlight$ = scope.behavior<MediaViewModel[]>(
|
||||
spotlightAndPip$.pipe(
|
||||
map(({ spotlight }) => spotlight),
|
||||
distinctUntilChanged<MediaViewModel[]>(arrayShallowEquals),
|
||||
),
|
||||
);
|
||||
|
||||
const hasRemoteScreenShares$ = scope.behavior<boolean>(
|
||||
spotlight$.pipe(
|
||||
map((spotlight) =>
|
||||
spotlight.some((vm) => vm.type === "screen share" && !vm.local),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const spotlightExpandedToggle$ = new Subject<void>();
|
||||
const spotlightExpanded$ = createToggle$(
|
||||
scope,
|
||||
@@ -1540,6 +1564,19 @@ export function createCallViewModel$(
|
||||
);
|
||||
|
||||
const screenShareError$ = new BehaviorSubject<Error | null>(null);
|
||||
// Stopped when the mode comes on, and not restarted when it goes: a new
|
||||
// share needs the user to pick a screen again
|
||||
lowBandwidthMode.enabled$
|
||||
.pipe(
|
||||
filter((enabled) => enabled && sharingScreen$.value),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe(() => {
|
||||
rtcParticipation.unpublish("screenShare").catch((e: unknown) => {
|
||||
logger.error("Failed to stop the screen share", e);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Callback to toggle screen sharing. If null, screen sharing is not possible:
|
||||
* the platform cannot capture a screen, or the host hides the button.
|
||||
@@ -1549,6 +1586,7 @@ export function createCallViewModel$(
|
||||
? null
|
||||
: (): void => {
|
||||
const track = screenShare$.value;
|
||||
if (track === undefined && lowBandwidthMode.enabled$.value) return;
|
||||
(track === undefined
|
||||
? rtcParticipation.publish({
|
||||
source: "screenShare",
|
||||
|
||||
@@ -6,6 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLowBandwidthMode,
|
||||
type LowBandwidthMode,
|
||||
} from "../LowBandwidthMode";
|
||||
import {
|
||||
type Behavior,
|
||||
constant,
|
||||
@@ -95,6 +99,7 @@ export interface CallViewModelInputs {
|
||||
mediaDevices: MediaDevices;
|
||||
initialSyncState: SyncState;
|
||||
viewSize$: Behavior<{ width: number; height: number }>;
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
}
|
||||
|
||||
export const localParticipant: Participant = { identity: "" };
|
||||
@@ -121,6 +126,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
|
||||
mediaDevices = mockMediaDevices({}),
|
||||
initialSyncState = SyncState.Syncing,
|
||||
viewSize$ = constant({ width: 1000, height: 800 }),
|
||||
lowBandwidthMode = createLowBandwidthMode(testScope()),
|
||||
}: Partial<CallViewModelInputs> = {},
|
||||
continuation: (
|
||||
vm: CallViewModel,
|
||||
@@ -290,6 +296,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
|
||||
client: room.client,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
lowBandwidthMode,
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
viewSize$,
|
||||
handsRaisedSubject$: raisedHands$,
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { BehaviorSubject, Subject } from "rxjs";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
type DeviceMuteRequest,
|
||||
type DeviceMuteState,
|
||||
type HostRequest,
|
||||
nullHostBridge,
|
||||
} from "../HostBridge";
|
||||
import {
|
||||
deviceStub,
|
||||
flushPromises,
|
||||
mockMediaDevices,
|
||||
testScope,
|
||||
withTestScheduler,
|
||||
} from "../utils/test";
|
||||
import { constant } from "./Behavior";
|
||||
import { createLowBandwidthMode } from "./LowBandwidthMode";
|
||||
import {
|
||||
type AudioOutputDeviceLabel,
|
||||
type DeviceLabel,
|
||||
type SelectedAudioOutputDevice,
|
||||
} from "./MediaDevices";
|
||||
import { MuteStates } from "./MuteStates";
|
||||
|
||||
describe("LowBandwidthMode", () => {
|
||||
test("starts off, and is turned on and off and reset without developer mode", () => {
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
const mode = createLowBandwidthMode(testScope());
|
||||
schedule("-ab-ar", {
|
||||
a: () => mode.setEnabled(true),
|
||||
b: () => mode.setEnabled(false),
|
||||
r: () => mode.reset(),
|
||||
});
|
||||
expectObservable(mode.enabled$).toBe("nyn-yn", { y: true, n: false });
|
||||
});
|
||||
});
|
||||
|
||||
test("holds the camera off while on, and restores a camera chosen on", async () => {
|
||||
const { mode, muteStates, handler } = await callWithCamera(true);
|
||||
|
||||
mode.setEnabled(true);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
expect(muteStates.video.setEnabled$.value).toBeNull();
|
||||
expect(handler).toHaveBeenLastCalledWith(false);
|
||||
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.enabled$.value).toBe(true);
|
||||
expect(handler).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
test("leaves a camera chosen off off", async () => {
|
||||
const { mode, muteStates, handler } = await callWithCamera(false);
|
||||
|
||||
mode.setEnabled(true);
|
||||
await flushPromises();
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
expect(handler).not.toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
test("saves a camera the earpiece had forced off as the user's choice", async () => {
|
||||
const { mode, muteStates, audioOutput } = await callWithCamera(true);
|
||||
audioOutput.next(earpiece);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
|
||||
mode.setEnabled(true);
|
||||
audioOutput.next(speaker);
|
||||
await flushPromises();
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(muteStates.video.enabled$.value).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps the camera off after the mode where the host turned it off during it", async () => {
|
||||
const { mode, muteStates, deviceMute$ } = await callWithCamera(true);
|
||||
mode.setEnabled(true);
|
||||
await flushPromises();
|
||||
|
||||
deviceMute$.next({ data: { video_enabled: false }, reply: vi.fn() });
|
||||
await flushPromises();
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
});
|
||||
|
||||
test("ignores the host asking for the camera during the mode", async () => {
|
||||
const { mode, muteStates, deviceMute$ } = await callWithCamera(false);
|
||||
mode.setEnabled(true);
|
||||
await flushPromises();
|
||||
|
||||
const reply = vi.fn();
|
||||
deviceMute$.next({ data: { video_enabled: true }, reply });
|
||||
await flushPromises();
|
||||
expect(reply).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ video_enabled: false }),
|
||||
);
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves the camera off where it cannot come back when the mode ends", async () => {
|
||||
const { mode, muteStates, audioOutput } = await callWithCamera(true);
|
||||
mode.setEnabled(true);
|
||||
audioOutput.next(earpiece);
|
||||
await flushPromises();
|
||||
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
expect(muteStates.video.setEnabled$.value).toBeNull();
|
||||
});
|
||||
|
||||
test("forgets the camera to restore on reset, for a new call", async () => {
|
||||
const { mode, muteStates } = await callWithCamera(true);
|
||||
mode.setEnabled(true);
|
||||
await flushPromises();
|
||||
|
||||
mode.reset();
|
||||
await flushPromises();
|
||||
expect(mode.enabled$.value).toBe(false);
|
||||
expect(muteStates.video.setEnabled$.value).not.toBeNull();
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
|
||||
mode.setEnabled(true);
|
||||
mode.setEnabled(false);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
});
|
||||
|
||||
test("holds rebuilt mute states off at once while on", async () => {
|
||||
const { mode } = await callWithCamera(true);
|
||||
mode.setEnabled(true);
|
||||
|
||||
const { muteStates: rebuilt } = muteStatesWithCamera(true);
|
||||
mode.bind(rebuilt);
|
||||
await flushPromises();
|
||||
|
||||
expect(rebuilt.video.enabled$.value).toBe(false);
|
||||
expect(rebuilt.video.setEnabled$.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
const speaker: SelectedAudioOutputDevice = {
|
||||
id: "speaker",
|
||||
virtualEarpiece: false,
|
||||
};
|
||||
const earpiece: SelectedAudioOutputDevice = {
|
||||
id: "earpiece",
|
||||
virtualEarpiece: false,
|
||||
};
|
||||
|
||||
/** A joined call with a camera, the user's choice, and a host. */
|
||||
async function callWithCamera(cameraOn: boolean): Promise<
|
||||
ReturnType<typeof muteStatesWithCamera> & {
|
||||
mode: ReturnType<typeof createLowBandwidthMode>;
|
||||
}
|
||||
> {
|
||||
const call = muteStatesWithCamera(cameraOn);
|
||||
const mode = createLowBandwidthMode(testScope());
|
||||
mode.bind(call.muteStates);
|
||||
await flushPromises();
|
||||
expect(call.muteStates.video.enabled$.value).toBe(cameraOn);
|
||||
return { ...call, mode };
|
||||
}
|
||||
|
||||
function muteStatesWithCamera(cameraOn: boolean): {
|
||||
muteStates: MuteStates;
|
||||
handler: ReturnType<typeof vi.fn<(desired: boolean) => Promise<boolean>>>;
|
||||
deviceMute$: Subject<HostRequest<DeviceMuteRequest, DeviceMuteState>>;
|
||||
audioOutput: BehaviorSubject<SelectedAudioOutputDevice>;
|
||||
} {
|
||||
const deviceMute$ = new Subject<
|
||||
HostRequest<DeviceMuteRequest, DeviceMuteState>
|
||||
>();
|
||||
const audioOutput = new BehaviorSubject(speaker);
|
||||
const muteStates = new MuteStates(
|
||||
testScope(),
|
||||
mockMediaDevices({
|
||||
videoInput: {
|
||||
...deviceStub,
|
||||
selected$: constant(undefined),
|
||||
available$: constant(
|
||||
new Map<string, DeviceLabel>([
|
||||
["camera", { type: "name", name: "Camera" }],
|
||||
]),
|
||||
),
|
||||
},
|
||||
audioOutput: {
|
||||
...deviceStub,
|
||||
available$: constant(
|
||||
new Map<string, AudioOutputDeviceLabel>([
|
||||
["speaker", { type: "speaker" }],
|
||||
["earpiece", { type: "earpiece" }],
|
||||
]),
|
||||
),
|
||||
selected$: audioOutput,
|
||||
},
|
||||
}),
|
||||
{ audioEnabled: false, videoEnabled: cameraOn },
|
||||
{ ...nullHostBridge, deviceMute$ },
|
||||
);
|
||||
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
|
||||
muteStates.video.setHandler(handler);
|
||||
return { muteStates, handler, deviceMute$, audioOutput };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { BehaviorSubject, filter, NEVER, switchMap } from "rxjs";
|
||||
|
||||
import { type Behavior } from "./Behavior";
|
||||
import { type MuteStates } from "./MuteStates";
|
||||
import { type ObservableScope } from "./ObservableScope";
|
||||
|
||||
/**
|
||||
* Whether the call has given up video to keep audio flowing on a slow
|
||||
* network. Lasts for one call: never stored.
|
||||
*/
|
||||
export interface LowBandwidthMode {
|
||||
enabled$: Behavior<boolean>;
|
||||
/** The one way in and out. Not gated on developer mode: only the switch is. */
|
||||
setEnabled(enabled: boolean): void;
|
||||
/** Back to off, forgetting the camera to restore, for a new call. */
|
||||
reset(): void;
|
||||
/** The current mute states, which can be rebuilt. */
|
||||
bind(muteStates: MuteStates): void;
|
||||
}
|
||||
|
||||
export function createLowBandwidthMode(
|
||||
scope: ObservableScope,
|
||||
): LowBandwidthMode {
|
||||
const enabled$ = new BehaviorSubject(false);
|
||||
const muteStates$ = new BehaviorSubject<MuteStates | null>(null);
|
||||
let cameraToRestore = false;
|
||||
|
||||
muteStates$
|
||||
.pipe(
|
||||
switchMap((muteStates) => muteStates?.hostVideoOff$ ?? NEVER),
|
||||
filter(() => enabled$.value),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe(() => (cameraToRestore = false));
|
||||
|
||||
return {
|
||||
enabled$,
|
||||
setEnabled(enabled): void {
|
||||
if (enabled === enabled$.value) return;
|
||||
const muteStates = muteStates$.value;
|
||||
if (enabled) {
|
||||
cameraToRestore = muteStates?.video.chosen$.value ?? false;
|
||||
enabled$.next(true);
|
||||
muteStates?.holdVideoOff(true);
|
||||
} else {
|
||||
enabled$.next(false);
|
||||
muteStates?.holdVideoOff(false);
|
||||
if (cameraToRestore) muteStates?.video.setEnabled$.value?.(true);
|
||||
}
|
||||
},
|
||||
reset(): void {
|
||||
cameraToRestore = false;
|
||||
enabled$.next(false);
|
||||
muteStates$.value?.holdVideoOff(false);
|
||||
},
|
||||
bind(muteStates): void {
|
||||
muteStates$.next(muteStates);
|
||||
muteStates.holdVideoOff(enabled$.value);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -461,4 +461,128 @@ describe("MuteStates", () => {
|
||||
await flushPromises();
|
||||
expect(lastVideoEnabled).toBe(true);
|
||||
});
|
||||
|
||||
describe("holding the camera off", () => {
|
||||
test("turns it off and closes every way of turning it on", async () => {
|
||||
const { muteStates, handler, deviceMute$ } = videoOnInCall();
|
||||
await flushPromises();
|
||||
expect(muteStates.video.enabled$.value).toBe(true);
|
||||
|
||||
muteStates.holdVideoOff(true);
|
||||
await flushPromises();
|
||||
|
||||
expect(handler).toHaveBeenLastCalledWith(false);
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
expect(muteStates.video.setEnabled$.value).toBeNull();
|
||||
expect(muteStates.video.toggle$.value).toBeNull();
|
||||
|
||||
const reply = vi.fn();
|
||||
deviceMute$.next({ data: { video_enabled: true }, reply });
|
||||
await flushPromises();
|
||||
expect(reply).toHaveBeenCalledExactlyOnceWith({
|
||||
audio_enabled: false,
|
||||
video_enabled: false,
|
||||
});
|
||||
expect(handler).not.toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
test("reports the host turning the camera off, and only while held", async () => {
|
||||
const { muteStates, deviceMute$ } = videoOnInCall();
|
||||
const hostVideoOff = vi.fn();
|
||||
muteStates.hostVideoOff$.subscribe(hostVideoOff);
|
||||
await flushPromises();
|
||||
|
||||
deviceMute$.next({ data: { video_enabled: false }, reply: vi.fn() });
|
||||
await flushPromises();
|
||||
expect(hostVideoOff).not.toHaveBeenCalled();
|
||||
|
||||
muteStates.holdVideoOff(true);
|
||||
await flushPromises();
|
||||
const reply = vi.fn();
|
||||
deviceMute$.next({ data: { video_enabled: false }, reply });
|
||||
await flushPromises();
|
||||
expect(hostVideoOff).toHaveBeenCalledOnce();
|
||||
expect(reply).toHaveBeenCalledWith({
|
||||
audio_enabled: false,
|
||||
video_enabled: false,
|
||||
});
|
||||
|
||||
deviceMute$.next({ data: { video_enabled: true }, reply: vi.fn() });
|
||||
await flushPromises();
|
||||
expect(hostVideoOff).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("is released only once both it and earpiece mode have let go", async () => {
|
||||
const { muteStates, audioOutput } = videoOnInCall();
|
||||
await flushPromises();
|
||||
|
||||
muteStates.holdVideoOff(true);
|
||||
audioOutput.select("1111");
|
||||
await flushPromises();
|
||||
muteStates.holdVideoOff(false);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.setEnabled$.value).toBeNull();
|
||||
|
||||
audioOutput.select("0000");
|
||||
await flushPromises();
|
||||
expect(muteStates.video.setEnabled$.value).not.toBeNull();
|
||||
// Released, the camera comes back off
|
||||
expect(muteStates.video.enabled$.value).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps the user's choice through a forced mute", async () => {
|
||||
const { muteStates, audioOutput } = videoOnInCall();
|
||||
await flushPromises();
|
||||
expect(muteStates.video.chosen$.value).toBe(true);
|
||||
|
||||
audioOutput.select("1111");
|
||||
muteStates.holdVideoOff(true);
|
||||
await flushPromises();
|
||||
expect(muteStates.video.chosen$.value).toBe(true);
|
||||
|
||||
audioOutput.select("0000");
|
||||
muteStates.holdVideoOff(false);
|
||||
await flushPromises();
|
||||
// Back, but off: that is now the choice
|
||||
expect(muteStates.video.chosen$.value).toBe(false);
|
||||
});
|
||||
|
||||
test("takes the user's request as the choice while the handler is still applying it", () => {
|
||||
const { muteStates, handler } = videoOnInCall();
|
||||
handler.mockImplementation(async () => new Promise(() => {}));
|
||||
muteStates.video.setEnabled$.value!(false);
|
||||
expect(muteStates.video.chosen$.value).toBe(false);
|
||||
});
|
||||
|
||||
/** A call with the camera on, a handler attached and a host to talk to. */
|
||||
function videoOnInCall(): {
|
||||
muteStates: MuteStates;
|
||||
handler: ReturnType<typeof vi.fn<(desired: boolean) => Promise<boolean>>>;
|
||||
deviceMute$: Subject<HostRequest<DeviceMuteRequest, DeviceMuteState>>;
|
||||
audioOutput: MediaDevice<
|
||||
AudioOutputDeviceLabel,
|
||||
SelectedAudioOutputDevice
|
||||
>;
|
||||
} {
|
||||
const deviceMute$ = new Subject<
|
||||
HostRequest<DeviceMuteRequest, DeviceMuteState>
|
||||
>();
|
||||
const audioOutput = aAudioOutputDevices();
|
||||
const muteStates = new MuteStates(
|
||||
testScope,
|
||||
mockMediaDevices({
|
||||
audioInput: aAudioInput(),
|
||||
audioOutput,
|
||||
videoInput: aVideoInput(),
|
||||
}),
|
||||
{ audioEnabled: false, videoEnabled: true },
|
||||
{ ...nullHostBridge, deviceMute$ },
|
||||
);
|
||||
const handler = vi.fn(async (desired: boolean) =>
|
||||
Promise.resolve(desired),
|
||||
);
|
||||
muteStates.video.setHandler(handler);
|
||||
return { muteStates, handler, deviceMute$, audioOutput };
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+35
-2
@@ -18,6 +18,7 @@ import {
|
||||
of,
|
||||
Subject,
|
||||
switchMap,
|
||||
tap,
|
||||
withLatestFrom,
|
||||
} from "rxjs";
|
||||
|
||||
@@ -55,6 +56,14 @@ export class MuteState<Label, Selected> {
|
||||
|
||||
private devicesConnectedBefore = false;
|
||||
|
||||
private readonly chosen = new BehaviorSubject(this.enabledByDefault);
|
||||
/**
|
||||
* The user's last request, kept while the device is forced off or the
|
||||
* handler is still applying it. A device that comes back after being
|
||||
* forced off comes back off, which is then the choice.
|
||||
*/
|
||||
public readonly chosen$: Behavior<boolean> = this.chosen;
|
||||
|
||||
private readonly canControlDevices$ = combineLatest([
|
||||
this.device.available$,
|
||||
this.forceMute$,
|
||||
@@ -94,6 +103,7 @@ export class MuteState<Label, Selected> {
|
||||
handlerAttached && this.devicesConnectedBefore;
|
||||
// Set the flag. A marker, that we reached this code before.
|
||||
this.devicesConnectedBefore = true;
|
||||
if (deviceCameBackInCall) this.chosen.next(false);
|
||||
const initialWanted = deviceCameBackInCall
|
||||
? false
|
||||
: this.enabledByDefault;
|
||||
@@ -104,7 +114,9 @@ export class MuteState<Label, Selected> {
|
||||
const set$ = new Subject<boolean>();
|
||||
const toggle$ = new Subject<void>();
|
||||
const syncing$ = new BehaviorSubject(false);
|
||||
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled)));
|
||||
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled))).pipe(
|
||||
tap((desired) => this.chosen.next(desired)),
|
||||
);
|
||||
const enabled$ = new Observable<boolean>((subscriber) => {
|
||||
subscriber.next(enabled);
|
||||
let latestDesired = initialWanted;
|
||||
@@ -210,6 +222,11 @@ export class MuteStates {
|
||||
}),
|
||||
);
|
||||
|
||||
private readonly videoHeld$ = new BehaviorSubject(false);
|
||||
private readonly hostVideoOff = new Subject<void>();
|
||||
/** The host turned the camera off while it was held off. */
|
||||
public readonly hostVideoOff$: Observable<void> = this.hostVideoOff;
|
||||
|
||||
public readonly audio = new MuteState(
|
||||
this.scope,
|
||||
this.mediaDevices.audioInput,
|
||||
@@ -220,9 +237,20 @@ export class MuteStates {
|
||||
this.scope,
|
||||
this.mediaDevices.videoInput,
|
||||
this.initialMuteState.videoEnabled,
|
||||
this.isEarpiece$,
|
||||
combineLatest(
|
||||
[this.isEarpiece$, this.videoHeld$],
|
||||
(earpiece, held) => earpiece || held,
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Keeps the camera off, and every way of turning it on closed, until
|
||||
* released. Released, the camera comes back off.
|
||||
*/
|
||||
public holdVideoOff(held: boolean): void {
|
||||
this.videoHeld$.next(held);
|
||||
}
|
||||
|
||||
public constructor(
|
||||
private readonly scope: ObservableScope,
|
||||
private readonly mediaDevices: MediaDevices,
|
||||
@@ -273,6 +301,11 @@ export class MuteStates {
|
||||
) {
|
||||
newState.video_enabled = request.data.video_enabled;
|
||||
setVideoEnabled(newState.video_enabled);
|
||||
} else if (
|
||||
request.data.video_enabled === false &&
|
||||
this.videoHeld$.value
|
||||
) {
|
||||
this.hostVideoOff.next();
|
||||
}
|
||||
request.reply(newState);
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type ObservableScope,
|
||||
trackBySource$,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
import { map } from "rxjs";
|
||||
import { combineLatest, map } from "rxjs";
|
||||
|
||||
import {
|
||||
type BaseScreenShareInputs,
|
||||
@@ -27,6 +27,11 @@ export interface RemoteScreenShareViewModel
|
||||
* Whether this screen share's video should be displayed.
|
||||
*/
|
||||
videoEnabled$: Behavior<boolean>;
|
||||
/**
|
||||
* Whether the call has stopped receiving video: the share is shown
|
||||
* without its picture, and nothing in its place.
|
||||
*/
|
||||
videoPaused$: Behavior<boolean>;
|
||||
/**
|
||||
* Whether this screen share should be considered to have an audio track.
|
||||
*/
|
||||
@@ -35,11 +40,16 @@ export interface RemoteScreenShareViewModel
|
||||
|
||||
export interface RemoteScreenShareInputs extends BaseScreenShareInputs {
|
||||
pretendToBeDisconnected$: Behavior<boolean>;
|
||||
videoPaused$: Behavior<boolean>;
|
||||
}
|
||||
|
||||
export function createRemoteScreenShare(
|
||||
scope: ObservableScope,
|
||||
{ pretendToBeDisconnected$, ...inputs }: RemoteScreenShareInputs,
|
||||
{
|
||||
pretendToBeDisconnected$,
|
||||
videoPaused$,
|
||||
...inputs
|
||||
}: RemoteScreenShareInputs,
|
||||
): RemoteScreenShareViewModel {
|
||||
const audio$ = trackBySource$(
|
||||
scope,
|
||||
@@ -58,8 +68,12 @@ export function createRemoteScreenShare(
|
||||
}),
|
||||
local: false,
|
||||
videoEnabled$: scope.behavior(
|
||||
pretendToBeDisconnected$.pipe(map((disconnected) => !disconnected)),
|
||||
combineLatest(
|
||||
[pretendToBeDisconnected$, videoPaused$],
|
||||
(disconnected, paused) => !disconnected && !paused,
|
||||
),
|
||||
),
|
||||
videoPaused$,
|
||||
audioEnabled$: scope.behavior(
|
||||
audio$.pipe(map((track) => track !== undefined)),
|
||||
),
|
||||
|
||||
@@ -33,11 +33,13 @@ export interface RemoteUserMediaViewModel
|
||||
|
||||
export interface RemoteUserMediaInputs extends BaseUserMediaInputs {
|
||||
pretendToBeDisconnected$: Behavior<boolean>;
|
||||
/** Whether the call has stopped receiving video, while the sender may still be sending it. */
|
||||
videoPaused$: Behavior<boolean>;
|
||||
}
|
||||
|
||||
export function createRemoteUserMedia(
|
||||
scope: ObservableScope,
|
||||
{ pretendToBeDisconnected$, ...inputs }: RemoteUserMediaInputs,
|
||||
{ pretendToBeDisconnected$, videoPaused$, ...inputs }: RemoteUserMediaInputs,
|
||||
): RemoteUserMediaViewModel {
|
||||
const baseUserMedia = createBaseUserMedia(scope, inputs);
|
||||
|
||||
@@ -73,9 +75,9 @@ export function createRemoteUserMedia(
|
||||
),
|
||||
),
|
||||
videoEnabled$: scope.behavior(
|
||||
pretendToBeDisconnected$.pipe(
|
||||
switchMap((disconnected) =>
|
||||
disconnected ? of(false) : baseUserMedia.videoEnabled$,
|
||||
combineLatest([pretendToBeDisconnected$, videoPaused$]).pipe(
|
||||
switchMap(([disconnected, paused]) =>
|
||||
disconnected || paused ? of(false) : baseUserMedia.videoEnabled$,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -90,6 +90,7 @@ export function createWrappedUserMedia(
|
||||
member,
|
||||
mediaDevices,
|
||||
pretendToBeDisconnected$,
|
||||
videoPaused$,
|
||||
...inputs
|
||||
}: WrappedUserMediaInputs,
|
||||
): WrappedUserMediaViewModel {
|
||||
@@ -98,6 +99,7 @@ export function createWrappedUserMedia(
|
||||
: createRemoteUserMedia(scope, {
|
||||
member,
|
||||
pretendToBeDisconnected$,
|
||||
videoPaused$,
|
||||
...inputs,
|
||||
});
|
||||
|
||||
@@ -122,6 +124,7 @@ export function createWrappedUserMedia(
|
||||
id,
|
||||
member,
|
||||
pretendToBeDisconnected$,
|
||||
videoPaused$,
|
||||
});
|
||||
},
|
||||
),
|
||||
|
||||
@@ -46,6 +46,27 @@ describe("MediaView", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("with no placeholder", () => {
|
||||
it("draws nothing in place of a video that is off", () => {
|
||||
render(
|
||||
<MediaView
|
||||
{...baseProps}
|
||||
video={mockVideoTrack({ source: "screenShare" })}
|
||||
videoEnabled={false}
|
||||
placeholder="none"
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("img", { name: "@alice:example.com" }),
|
||||
).toBeNull();
|
||||
expect(screen.getByTestId("videoTile")).toHaveAttribute(
|
||||
"data-video-enabled",
|
||||
"false",
|
||||
);
|
||||
expect(screen.getByTestId("name_tag")).toHaveTextContent("some name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("with video", () => {
|
||||
it("labels the video element with the track source", () => {
|
||||
render(
|
||||
|
||||
+14
-9
@@ -58,6 +58,8 @@ interface Props extends ComponentProps<typeof animated.div> {
|
||||
displayName: string;
|
||||
mxcAvatarUrl: string | undefined;
|
||||
avatarStyle?: "solid" | "translucent";
|
||||
/** What is drawn while there is no video: the avatar, or nothing. */
|
||||
placeholder?: "avatar" | "none";
|
||||
background?: "solid" | "transparent";
|
||||
focusable: boolean;
|
||||
primaryButton?: ReactNode;
|
||||
@@ -97,6 +99,7 @@ export const MediaView: FC<Props> = ({
|
||||
displayName,
|
||||
mxcAvatarUrl,
|
||||
avatarStyle = "solid",
|
||||
placeholder = "avatar",
|
||||
background = "solid",
|
||||
focusable,
|
||||
primaryButton,
|
||||
@@ -188,15 +191,17 @@ export const MediaView: FC<Props> = ({
|
||||
<div className={styles.speakingBorder} />
|
||||
</div>
|
||||
)}
|
||||
<Avatar
|
||||
id={userId}
|
||||
name={displayName}
|
||||
size={avatarSize}
|
||||
src={mxcAvatarUrl}
|
||||
data-style={avatarStyle}
|
||||
className={styles.avatar}
|
||||
style={{ display: video && videoEnabled ? "none" : "initial" }}
|
||||
/>
|
||||
{placeholder === "avatar" && (
|
||||
<Avatar
|
||||
id={userId}
|
||||
name={displayName}
|
||||
size={avatarSize}
|
||||
src={mxcAvatarUrl}
|
||||
data-style={avatarStyle}
|
||||
className={styles.avatar}
|
||||
style={{ display: video && videoEnabled ? "none" : "initial" }}
|
||||
/>
|
||||
)}
|
||||
{video !== undefined && (
|
||||
// A live camera has no captions to offer
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
|
||||
@@ -146,6 +146,7 @@ SpotlightUserMediaItem.displayName = "SpotlightUserMediaItem";
|
||||
interface SpotlightScreenShareItemProps extends SpotlightMemberMediaItemBaseProps {
|
||||
vm: ScreenShareViewModel;
|
||||
videoEnabled: boolean;
|
||||
placeholder?: "avatar" | "none";
|
||||
}
|
||||
|
||||
const SpotlightScreenShareItem: FC<SpotlightScreenShareItemProps> = ({
|
||||
@@ -163,8 +164,14 @@ const SpotlightRemoteScreenShareItem: FC<
|
||||
SpotlightRemoteScreenShareItemProps
|
||||
> = ({ vm, ...props }) => {
|
||||
const videoEnabled = useBehavior(vm.videoEnabled$);
|
||||
const videoPaused = useBehavior(vm.videoPaused$);
|
||||
return (
|
||||
<SpotlightScreenShareItem vm={vm} videoEnabled={videoEnabled} {...props} />
|
||||
<SpotlightScreenShareItem
|
||||
vm={vm}
|
||||
videoEnabled={videoEnabled}
|
||||
placeholder={videoPaused ? "none" : "avatar"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type ReactNode, useCallback, useState } from "react";
|
||||
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
|
||||
|
||||
/**
|
||||
* A polite live region, and the function that has a screen reader read a
|
||||
* text out through it.
|
||||
*/
|
||||
export function useAnnouncement(): [ReactNode, (text: string) => void] {
|
||||
const [text, setText] = useState("");
|
||||
const announce = useCallback(
|
||||
(next: string) =>
|
||||
// A changed text is read out again, the same text is not
|
||||
setText((previous) => (previous === next ? `${next} ` : next)),
|
||||
[],
|
||||
);
|
||||
return [<VisuallyHidden aria-live="polite">{text}</VisuallyHidden>, announce];
|
||||
}
|
||||
@@ -5,6 +5,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLowBandwidthMode,
|
||||
type LowBandwidthMode,
|
||||
} from "../state/LowBandwidthMode";
|
||||
import { type CallMembership } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
import { vitest } from "vitest";
|
||||
@@ -171,6 +175,7 @@ export function getBasicCallViewModelEnvironment(
|
||||
vm: CallViewModel;
|
||||
footerVm: ViewModel<FooterSnapshot>;
|
||||
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
|
||||
lowBandwidthMode: LowBandwidthMode;
|
||||
rtcMemberships$: BehaviorSubject<CallMembership[]>;
|
||||
rtcSession: MockRTCSession;
|
||||
matrixRoom: Room;
|
||||
@@ -221,6 +226,7 @@ export function getBasicCallViewModelEnvironment(
|
||||
),
|
||||
),
|
||||
});
|
||||
const lowBandwidthMode = createLowBandwidthMode(scope);
|
||||
const vm = createCallViewModel$(
|
||||
scope,
|
||||
{
|
||||
@@ -229,6 +235,7 @@ export function getBasicCallViewModelEnvironment(
|
||||
client,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
lowBandwidthMode,
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
viewSize$: constant({ width: 1000, height: 800 }),
|
||||
handsRaisedSubject$: handRaisedSubject$,
|
||||
@@ -246,6 +253,7 @@ export function getBasicCallViewModelEnvironment(
|
||||
testScope(),
|
||||
vm,
|
||||
muteStates,
|
||||
lowBandwidthMode.enabled$,
|
||||
mediaDevices,
|
||||
constant({ supported: false, processor: undefined }),
|
||||
"reactionId",
|
||||
@@ -254,7 +262,12 @@ export function getBasicCallViewModelEnvironment(
|
||||
return {
|
||||
vm,
|
||||
footerVm,
|
||||
developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm),
|
||||
developerSettingsVm: createDeveloperSettingsTabViewModel(
|
||||
testScope(),
|
||||
vm,
|
||||
lowBandwidthMode,
|
||||
),
|
||||
lowBandwidthMode,
|
||||
rtcMemberships$,
|
||||
rtcSession,
|
||||
matrixRoom,
|
||||
|
||||
+10
-1
@@ -406,7 +406,12 @@ export function mockRemoteMedia(
|
||||
roomMember: Partial<RoomMember>,
|
||||
/** The tracks, or a behavior of them for a test that has them arrive. */
|
||||
tracks: MockTracks | Behavior<MockTracks>,
|
||||
{ transport }: { transport?: Transport } = { transport: exampleTransport },
|
||||
{
|
||||
transport,
|
||||
videoPaused$ = constant(false),
|
||||
}: { transport?: Transport; videoPaused$?: Behavior<boolean> } = {
|
||||
transport: exampleTransport,
|
||||
},
|
||||
): RemoteUserMediaViewModel {
|
||||
const member = mockMatrixRoomMember(rtcMember, roomMember);
|
||||
return createRemoteUserMedia(testScope(), {
|
||||
@@ -422,6 +427,7 @@ export function mockRemoteMedia(
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
transport$: constant(transport),
|
||||
pretendToBeDisconnected$: constant(false),
|
||||
videoPaused$,
|
||||
displayName$: constant(member.rawDisplayName ?? "nodisplayname"),
|
||||
mxcAvatarUrl$: constant(member.getMxcAvatarUrl()),
|
||||
handRaised$: constant(null),
|
||||
@@ -433,6 +439,7 @@ export function mockRemoteScreenShare(
|
||||
rtcMember: CallMembership,
|
||||
roomMember: Partial<RoomMember>,
|
||||
tracks: MockTracks,
|
||||
videoPaused$: Behavior<boolean> = constant(false),
|
||||
): RemoteScreenShareViewModel {
|
||||
const member = mockMatrixRoomMember(rtcMember, roomMember);
|
||||
return createRemoteScreenShare(testScope(), {
|
||||
@@ -446,6 +453,7 @@ export function mockRemoteScreenShare(
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
transport$: constant(exampleTransport),
|
||||
pretendToBeDisconnected$: constant(false),
|
||||
videoPaused$,
|
||||
displayName$: constant(member.rawDisplayName ?? "nodisplayname"),
|
||||
mxcAvatarUrl$: constant(member.getMxcAvatarUrl()),
|
||||
});
|
||||
@@ -574,6 +582,7 @@ function mockSlotWithParticipation(
|
||||
keyRotationSuppressed$,
|
||||
connectedTransports$,
|
||||
setAudioOutputDeviceId: vi.fn(async () => Promise.resolve()),
|
||||
setReceiveVideo: vi.fn(),
|
||||
sendData: vi.fn(async () => Promise.resolve()),
|
||||
data$: NEVER,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user