Compare commits

..
Author SHA1 Message Date
Robin 4362f7ea89 Update design of layout switch options 2026-12-03 10:29:53 -05:00
Robin 38e9696d22 Stop using deprecated hideChevron prop 2026-12-03 10:27:29 -05:00
Robin 2cf05335af Update Compound Web to 10.8.0 2026-12-03 10:26:57 -05:00
87 changed files with 249 additions and 3554 deletions
+2 -12
View File
@@ -7,7 +7,7 @@ on:
type: string
package:
type: string # This would ideally be a `choice` type, but that isn't supported yet
description: The package type to be built. Must be one of 'full', 'embedded', 'widget-rtc-sdk' or 'component'
description: The package type to be built. Must be one of 'full', 'embedded', or 'widget-rtc-sdk'
required: true
build_mode:
type: string # This would ideally be a `choice` type, but that isn't supported yet
@@ -59,21 +59,11 @@ jobs:
NODE_OPTIONS: "--max-old-space-size=4096"
PACKAGE: ${{ inputs.package }}
BUILD_MODE: ${{ inputs.build_mode }}
- name: Pack component
# A tarball a host installs like the npm release. Stripped as in
# publish-component.yaml, so the install does not run `prepare` and
# rebuild it.
if: inputs.package == 'component'
working-directory: component
run: |
jq 'del(.devEngines, .scripts)' package.json > package.json.tmp && mv package.json.tmp package.json
mkdir -p ../component-pack
npm pack --pack-destination ../component-pack
- name: Upload Artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: build-output-${{ inputs.package }}
path: ${{ inputs.package == 'component' && 'component-pack' || 'dist' }}
path: dist
if-no-files-found: error
# We'll only use this in a triggered job, then we're done with it
retention-days: 1
-113
View File
@@ -1,113 +0,0 @@
# Element Web develop with this commit's component in place of the npm release
# it pins, and the component embedding forced on. Deployed to
# element-web--element-call.netlify.app by deploy_element_web_with_ec_component
# for main, and to pr<N>-element-web--element-call.netlify.app by pr-deploy.yaml.
#
# A workflow of its own rather than part of Build: pr-deploy.yaml runs once per
# finished workflow, so the Element Call previews do not wait for this slower
# build, and a broken Element Web develop does not hold them back.
name: Build Element Web
on:
pull_request:
types:
- synchronize
- opened
- labeled
push:
branches: [main]
permissions: {}
# A newer push to a PR cancels its running build. A label event that builds
# nothing gets a group of its own: concurrency applies before the jobs' `if`,
# so in the PR's group it would cancel a real build and then skip.
concurrency:
group: ${{ github.workflow }}-${{ (github.event.action == 'labeled' && github.event.label.name != 'development build') && github.run_id || github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build_component_element_call:
# The React component package, as a tarball for build_element_web_with_ec_component
# Of the labels only `development build` changes the build
if: github.event.action != 'labeled' || github.event.label.name == 'development build'
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
with:
package: component
vite_app_version: ${{ github.sha }}
build_mode: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'development build') && 'development' || 'production' }}
secrets:
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_URL: ${{ secrets.SENTRY_URL }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
build_element_web_with_ec_component:
# The steps follow the prepare job of Element Web's build-and-test.yaml.
name: Build Element Web with the Element Call component
needs: build_component_element_call
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout Element Web
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
repository: element-hq/element-web
ref: develop
persist-credentials: false
# Also installs the Node of Element Web's .node-version
- uses: pnpm/setup@731dfb6463bbd11c11fd0ee11fe00ed0e36d48a1 # v3.2.0
with:
cache: true
save-cache: false
install: false
- name: Fetch layered build
id: layered
run: |
./scripts/layered.sh
VERSION=$(scripts/get-version-from-git.sh)
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Download the component
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: build-output-component
path: ec-component
- name: Install the component
# The same tarball install Element Web's layered.sh does for matrix-js-sdk
run: pnpm -C apps/web install "$PWD"/ec-component/*.tgz
- name: Write config
# The setting prefers the config's value, so this forces it on
working-directory: apps/web
run: jq '.features.feature_element_call_react = true' element.io/develop/config.json > config.json
- name: Build
env:
CI_PACKAGE: true
VERSION: ${{ steps.layered.outputs.version }}
working-directory: apps/web
run: pnpm run build
- name: Upload Artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: build-output-element-web-with-ec-component
path: apps/web/webapp
if-no-files-found: error
# We'll only use this in a deploy job, then we're done with it
retention-days: 1
deploy_element_web_with_ec_component:
# PRs are deployed by pr-deploy.yaml, which keeps the secrets away from PR code
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: build_element_web_with_ec_component
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
with:
package: element-web-with-ec-component
deployment_ref: ${{ github.sha }}
secrets:
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
+8 -14
View File
@@ -2,17 +2,14 @@ name: Deploy to Netlify
on:
workflow_call:
inputs:
# Optional so that main can deploy element-web-with-ec-component,
# which then uses the alias `element-web`. Every other package needs
# pr_number (for its alias) and full needs pr_head_* (for its config).
pr_number:
required: false
required: true
type: string
pr_head_full_name:
required: false
required: true
type: string
pr_head_ref:
required: false
required: true
type: string
deployment_ref:
required: true
@@ -20,7 +17,7 @@ on:
package:
required: true
type: string
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', 'storybook' or 'element-web-with-ec-component'
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', or 'storybook'
artifact_run_id:
required: false
type: string
@@ -62,9 +59,8 @@ jobs:
- name: Add redirects file
# We fetch from github directly as we don't bother checking out the repo
# Not needed for storybook deployments, nor for Element Web, which
# routes with the URL fragment
if: inputs.package != 'storybook' && inputs.package != 'element-web-with-ec-component'
# Not needed for storybook deployments
if: inputs.package != 'storybook'
run: curl -s https://raw.githubusercontent.com/element-hq/element-call/main/config/netlify_redirects > webapp/_redirects
- name: Add config file
@@ -88,13 +84,11 @@ jobs:
with:
publish-dir: webapp
deploy-message: "Deploy from GitHub Actions"
# Element Web with the component deploys for main too, without a PR number
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || inputs.package == 'element-web-with-ec-component' && (inputs.pr_number && format('pr{0}-element-web', inputs.pr_number) || 'element-web') || format('pr{0}', inputs.pr_number) }}
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
# Element Web has many times the files of Element Call to upload
timeout-minutes: ${{ inputs.package == 'element-web-with-ec-component' && 10 || 1 }}
timeout-minutes: 1
- name: 🚦 Update deployment status
uses: bobheadxi/deployments@648679e8e4915b27893bd7dbc35cb504dc915bc8 # v1
+4 -47
View File
@@ -2,10 +2,8 @@ name: Deploy previews for PRs
on:
# zizmor: ignore[dangerous-triggers]
# Reason: This is now restricted to internal PRs only using the 'if' condition below.
# Runs once per finished workflow, and deploys only what that workflow built,
# so each preview goes up as soon as its own build is done
workflow_run:
workflows: ["Build", "Build Element Web"]
workflows: ["Build"]
types:
- completed
@@ -14,7 +12,7 @@ permissions: {}
jobs:
prdetails:
# Logic:
# 1. The build workflow must be successful
# 1. Build must be successful
# 2. Event must be a pull_request
# 3. Head repository must be the SAME as the base repository (No Forks!)
if: >
@@ -36,7 +34,6 @@ jobs:
branch: ${{ github.event.workflow_run.head_branch }}
netlify-full:
if: github.event.workflow_run.name == 'Build'
needs: prdetails
permissions:
deployments: write
@@ -54,7 +51,6 @@ jobs:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
netlify-widget-rtc-sdk:
if: github.event.workflow_run.name == 'Build'
needs: prdetails
permissions:
deployments: write
@@ -71,48 +67,9 @@ jobs:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
element-web-built:
# A Build Element Web run started by a label it ignores skips every job
# and uploads nothing to deploy
if: github.event.workflow_run.name == 'Build Element Web'
needs: prdetails
runs-on: ubuntu-24.04
permissions:
actions: read
outputs:
built: ${{ steps.check.outputs.built }}
steps:
- id: check
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
count=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID/artifacts?name=build-output-element-web-with-ec-component" --jq '.total_count')
if [ "$count" -gt 0 ]; then built=true; else built=false; fi
echo "built=$built" >> "$GITHUB_OUTPUT"
netlify-element-web-with-ec-component:
# Element Web with this PR's component
if: needs.element-web-built.outputs.built == 'true'
needs: [prdetails, element-web-built]
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
pr_number: ${{ needs.prdetails.outputs.pr_number }}
pr_head_full_name: ${{ github.event.workflow_run.head_repository.full_name }}
pr_head_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.ref }}
deployment_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.sha || github.ref || github.head_ref }}
package: element-web-with-ec-component
secrets:
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
netlify-storybook:
needs: prdetails
if: ${{ github.event.workflow_run.name == 'Build' && needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
@@ -129,7 +86,7 @@ jobs:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
docker:
if: ${{ github.event.workflow_run.name == 'Build' && needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'docker build') }}
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'docker build') }}
needs: prdetails
permissions:
contents: write
+11 -61
View File
@@ -22,21 +22,13 @@ const LabelledButton = (): ReactNode => (
</TooltipProvider>
);
/** The container of Element Call's own that the button's tooltip floated into. */
const labelPortal = (): Element | null => {
const button = screen.getByRole("button", { name: "Microphone" });
return document
.getElementById(button.getAttribute("aria-labelledby")!)!
.closest("[data-element-call-portal]");
};
test("floats into the host document with no root", () => {
render(
<CallPortalRoot root={undefined}>
<LabelledButton />
</CallPortalRoot>,
);
expect(labelPortal()?.parentElement).toBe(document.body);
expect(screen.getByRole("button", { name: "Microphone" })).toBeTruthy();
});
test("floats into the root it is given", () => {
@@ -47,61 +39,19 @@ test("floats into the root it is given", () => {
<LabelledButton />
</CallPortalRoot>,
);
// Into a container of Element Call's own, for its stylesheets to find
expect(labelPortal()?.parentElement).toBe(root);
const button = screen.getByRole("button", { name: "Microphone" });
const label = document.getElementById(
button.getAttribute("aria-labelledby")!,
);
expect(root.contains(label)).toBe(true);
root.remove();
});
test("moves what floated along when the root changes", () => {
const first = document.createElement("div");
const second = document.createElement("div");
document.body.append(first, second);
const { rerender, unmount } = render(
<CallPortalRoot root={first}>
<LabelledButton />
</CallPortalRoot>,
);
rerender(
<CallPortalRoot root={second}>
<LabelledButton />
</CallPortalRoot>,
);
expect(first.querySelector("[data-element-call-portal]")).toBeNull();
expect(labelPortal()?.parentElement).toBe(second);
unmount();
expect(second.querySelector("[data-element-call-portal]")).toBeNull();
first.remove();
second.remove();
});
test("waits for a root that is not available yet", () => {
// Floated content mounted off the page would not show up in the document,
// so record every mount of the tooltip's content, wherever it happens
const mounted: HTMLElement[] = [];
const probe = (
<span
ref={(node) => {
if (node) mounted.push(node);
}}
/>
render(
<CallPortalRoot root={null}>
<LabelledButton />
</CallPortalRoot>,
);
const button = (
<TooltipProvider>
<Tooltip label="Microphone" caption={probe}>
<button>🎤</button>
</Tooltip>
</TooltipProvider>
);
const { rerender } = render(
<CallPortalRoot root={null}>{button}</CallPortalRoot>,
);
expect(mounted).toEqual([]);
expect(document.querySelector("[data-element-call-portal]")).toBeNull();
const root = document.createElement("div");
document.body.appendChild(root);
rerender(<CallPortalRoot root={root}>{button}</CallPortalRoot>);
expect(mounted.at(-1)?.isConnected).toBe(true);
expect(labelPortal()?.parentElement).toBe(root);
root.remove();
expect(screen.queryByRole("button", { name: "Microphone" })).toBeNull();
});
+9 -37
View File
@@ -5,50 +5,22 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, type ReactNode, useLayoutEffect, useState } from "react";
import { type FC, type ReactNode } from "react";
import { PortalRoot } from "@vector-im/compound-web";
import { PortalElementProvider } from "../src/RootElementContext";
interface Props {
root: HTMLElement | null | undefined;
children: ReactNode;
}
/**
* Where Compound floats the call's menus and tooltips: a container of Element
* Call's own inside `root`, or inside the host document's body with no `root`.
* With `null`, the root is not available yet: Compound gets `null` too and
* floats nothing until it is.
*
* The container is marked `data-element-call-portal` and carries the call's
* theme and platform (see `useTheme`), so that Element Call's stylesheets reach
* what floats out of its root just as they reach what stays inside.
* Where Compound floats the call's menus and tooltips. With no `root` the call
* is not wrapped at all and they go into the host document's body; `null` is
* Compound's "not available yet", and the floating parts wait for it.
*/
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode => {
// One container for the call's lifetime, moved to wherever the root is.
// What Compound has floated into it moves along, even into another
// document such as a Picture-in-Picture window's; Compound itself leaves
// what it floated where it was when its root changes.
const [container] = useState(() => {
const element = document.createElement("div");
element.setAttribute("data-element-call-portal", "");
return element;
});
useLayoutEffect(() => {
const parent = root === undefined ? document.body : root;
// Left out of the document until the root is available
if (parent === null) return;
parent.append(container);
return (): void => container.remove();
}, [root, container]);
return (
<PortalRoot root={root === null ? null : container}>
<PortalElementProvider value={container}>
{children}
</PortalElementProvider>
</PortalRoot>
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode =>
root === undefined ? (
children
) : (
<PortalRoot root={root}>{children}</PortalRoot>
);
};
+2 -2
View File
@@ -40,8 +40,8 @@ and overlays stay below the modals and toasts, which are portalled into the
root and carry no layer of their own.
What Compound floats — tooltips, menus — is not in here at all: it goes into
Element Call's portal container in the host's `portalRoot` (see
CallPortalRoot), where Element Call's scoped stylesheets still reach it. */
the host's body, as it would for any other component on the host's page, and is
styled and layered by the host's copy of Compound. */
.content {
display: flex;
flex-direction: column;
+2 -6
View File
@@ -156,12 +156,8 @@ export interface ElementCallProps {
/**
* Where the parts of Element Call that float above it — its menus and
* tooltips, which Compound portals out of the call — are rendered. Left out,
* the host document's body.
*
* Element Call does not render them into this element directly: each mounted
* call adds its own `div[data-element-call-portal]` here and floats into
* that. The container carries the call's theme class, and Element Call's
* scoped stylesheets reach it just as they reach the call's root.
* they go into the host document's body, as they do for any other component
* on the host's page.
*
* A host that moves Element Call's DOM into another document, such as a
* Document Picture-in-Picture window, passes that document's body here so
+6 -24
View File
@@ -8,15 +8,10 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import {
PORTAL_SELECTOR,
ROOT_SELECTOR,
scopeStylesToRoot,
} from "./scopeStylesToRoot";
import { ROOT_SELECTOR, scopeStylesToRoot } from "./scopeStylesToRoot";
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
const isRoot = `:where(${ROOT_SELECTOR})`;
const isRootOrPortal = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
async function scope(css: string, file = "base.css"): Promise<string> {
const result = await postcss([scopeStylesToRoot()]).process(css, {
@@ -31,10 +26,7 @@ describe("scopeStylesToRoot", () => {
`${isRoot} { line-height: 1.15 }`,
);
expect(await scope("body { margin: 0 }")).toBe(`${isRoot} { margin: 0 }`);
// The custom properties are needed by what floats out of the root too
expect(await scope(":root { --a: 1 }")).toBe(
`${isRootOrPortal} { --a: 1 }`,
);
expect(await scope(":root { --a: 1 }")).toBe(`${isRoot} { --a: 1 }`);
expect(await scope("body.no-scroll-body { position: fixed }")).toBe(
`${isRoot}.no-scroll-body { position: fixed }`,
);
@@ -74,11 +66,9 @@ describe("scopeStylesToRoot", () => {
);
});
it("leaves alone what already names the root or the portal", async () => {
it("leaves alone what already names the root", async () => {
const css = `${ROOT_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(css)).toBe(css);
const portal = `${PORTAL_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(portal)).toBe(portal);
});
it("reaches into layers and media queries", async () => {
@@ -109,8 +99,8 @@ describe("scopeStylesToRoot", () => {
expect(await scope("pre { font-size: 1px }", file)).toBe(
`pre${inRoot} { font-size: 1px }`,
);
expect(await scope("[data-x] pre { font-size: 1px }", file)).toBe(
`[data-x] pre${inRoot} { font-size: 1px }`,
expect(await scope(".modal pre { font-size: 1px }", file)).toBe(
`.modal pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".box_abc12 { border: 0 }", file)).toBe(
".box_abc12 { border: 0 }",
@@ -118,14 +108,6 @@ describe("scopeStylesToRoot", () => {
expect(await scope(".a .b_abc12:hover { border: 0 }", file)).toBe(
".a .b_abc12:hover { border: 0 }",
);
// Confined by the class on an ancestor: these must still match in a menu
// that Compound portals out of the root
expect(await scope(".preview_abc12>video { inset: 0 }", file)).toBe(
".preview_abc12>video { inset: 0 }",
);
expect(
await scope(".menu_abc12 [role^=menuitem]:focus { outline: 0 }", file),
).toBe(".menu_abc12 [role^=menuitem]:focus { outline: 0 }");
});
it("leaves an excluded stylesheet as it is", async () => {
+14 -37
View File
@@ -24,27 +24,16 @@ import selectorParser, {
*/
export const ROOT_SELECTOR = "[data-element-call-root]";
/**
* How the stylesheets find the container that Element Call's menus and
* tooltips float into, outside the root. `CallPortalRoot` creates it in the
* host's document; it counts as Element Call's own, the way the root does.
*/
export const PORTAL_SELECTOR = "[data-element-call-portal]";
// Both are `:where()`, which has no specificity of its own, so the rules keep
// exactly the weight they had before being scoped and nothing in Element Call's
// cascade changes — only where it applies.
//
// The root or the portal container, or anything inside either. Appended to the
// element a rule is about, rather than prepended to the whole selector, so that
// a rule about the root itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
// The root itself, standing in for the document's `html` and `body`. The page's
// own furniture (its height, margin and background) is not the portal's.
// The root, or anything inside it. Appended to the element a rule is about,
// rather than prepended to the whole selector, so that a rule about the root
// itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
// The root itself, standing in for the document.
const IS_ROOT = `:where(${ROOT_SELECTOR})`;
// The root and the portal container, standing in for `:root`: the custom
// properties declared there are needed by whatever floats out of the root too.
const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
/**
* Confines a stylesheet to Element Call's root element, for the build of
@@ -56,22 +45,15 @@ const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
* the host's document too. This rewrites every selector so that it matches only
* the root or its descendants:
*
* - `html` and `body` become the root element, which is what stands in for the
* document inside a host. `:root` becomes the root and the portal container
* (see `PORTAL_SELECTOR`), so that its custom properties reach both.
* - `html`, `body` and `:root` become the root element, which is what stands in
* for the document inside a host.
* - Everything else keeps its selector and gains `:where([data-element-call-root],
* [data-element-call-root] *, [data-element-call-portal],
* [data-element-call-portal] *)` on the element it styles, so that it applies
* to the menus and tooltips Compound floats out of the root as well.
* - Selectors that already name the root or the portal container are left
* alone, as are keyframe selectors and rules nested inside another rule,
* which are relative to it.
* [data-element-call-root] *)` on the element it styles.
* - Selectors that already name the root are left alone, as are keyframe
* selectors and rules nested inside another rule, which are relative to it.
*
* CSS modules are scoped by their class names already, so only their selectors
* without a class anywhere — `pre`, but neither `.pre` nor `.modal pre` — are
* touched. A module class on an ancestor confines a rule as well as one on the
* element it styles, and scoping such a rule would break it wherever Compound
* portals that part of Element Call out of the root, as it does menus.
* that would match by element alone — `pre` rather than `.pre` — are touched.
*
* The root's custom properties are still inherited by everything inside it,
* the way they were from `:root`. Compound's own stylesheet — the design
@@ -135,8 +117,7 @@ const scopeAll = processor(false);
const scopeBare = processor(true);
function scopeSelector(selector: Selector, isModule: boolean): void {
const text = String(selector);
if (text.includes(ROOT_SELECTOR) || text.includes(PORTAL_SELECTOR)) return;
if (String(selector).includes(ROOT_SELECTOR)) return;
const compounds = splitCompounds(selector);
if (compounds.length === 0) return;
@@ -144,16 +125,12 @@ function scopeSelector(selector: Selector, isModule: boolean): void {
// Something said of the document is said of the root instead
const document = compounds[0].find(isDocumentSelector);
if (document !== undefined) {
document.replaceWith(
pseudo(document.value === ":root" ? IS_ROOT_OR_PORTAL : IS_ROOT),
);
document.replaceWith(pseudo(IS_ROOT));
return;
}
if (isModule && compounds.some((c) => c.some((n) => n.type === "class")))
return;
const subject = compounds.at(-1)!;
if (isModule && subject.some((node) => node.type === "class")) return;
// Pseudo-elements have to come last in a compound selector
const pseudoElement = subject.find(isPseudoElement);
+4 -5
View File
@@ -25,11 +25,10 @@ Please see LICENSE in the repository root for full details.
//
// Compound is not in here. The component uses the host's copy of it (a peer
// dependency, left external by the build), and the host loads Compound's
// stylesheet, design tokens and fonts along with it. Element Call's root takes
// the tokens and fonts of the theme class it carries, as any element on the
// host's page would. What Compound floats out of the root — tooltips, menus —
// goes into Element Call's portal container (see CallPortalRoot), which carries
// the same theme class and is reached by the same scoped stylesheets.
// stylesheet, design tokens and fonts along with it: what Compound floats into
// the host's body — tooltips, menus — is then styled by the same stylesheet as
// everything else there, and Element Call's root takes the tokens and fonts of
// the theme class it carries, as any element on the host's page would.
//
// Where these land relative to the component stylesheets is the bundler's
// choice — the standalone app puts them first, this build puts them in the
-1
View File
@@ -4,7 +4,6 @@ This folder contains documentation for setup, usage, and development of Element
- [Embedded vs standalone mode](./embedded_standalone.md)
- [Element Call as a React component (experimental)](../README.md#element-call-as-a-component-experimental)
- [Component CSS in a host page](./component_css_host_setup.md)
- [Url format and parameters](./url_params.md)
- [Global JS controls](./controls.md)
- [MatrixRTC modes](./matrix_rtc_modes.md)
-69
View File
@@ -1,69 +0,0 @@
# Component CSS in a host page
As a widget or standalone app, Element Call owns its document and loads
`src/index.css` unchanged. As a [React component](../README.md#element-call-as-a-component)
it shares the host's document and the host's copy of Compound, so its
stylesheet must not touch the host, and the host's must not break Element Call.
![Element Call component CSS in Element Web](component_css_host_setup.svg)
## How it works
- **Build.** The component ships `src/base.css` (not `index.css`) plus the CSS
modules as one `style.css`. `component/build/scopeStylesToRoot.ts` rewrites
every selector:
- `html` and `body` become `[data-element-call-root]`.
- `:root` becomes the root or `[data-element-call-portal]`.
- Everything else gets `:where(root, root *, portal, portal *)`.
`:where()` adds no specificity. In CSS modules only selectors without any
class are scoped, since a module class already confines a rule.
- **Runtime.** `useTheme` sets `data-element-call-root`, `data-platform` and the
`cpd-theme-*` class on the root element (`src/RootElementContext.ts`). The
theme and platform also go on the portal container.
- **Portal container.** `component/CallPortalRoot.tsx` creates
`div[data-element-call-portal]` in the host's `portalRoot`. Compound floats
tooltips and menus into it, so they get Element Call's styles too. Modals
portal into the root itself.
- **Containment.** `component/ElementCall.module.css` gives the root
`isolation: isolate` and `contain: layout paint`, so `position: fixed` modals
centre on the call, not the host window.
## What the host does
1. Provides Compound's design tokens, component styles and fonts, since the
component does not bundle them.
2. Declares Element Call's layers below Compound's, then imports
`@element-hq/element-call-component/style.css` **unlayered**. In Element Web:
```css
@layer normalize, compound-legacy, compound-tokens, compound-web, shared-components, app-web;
```
For example, a Compound `<Button>` inside the call, such as the lobby's join
button, meets two rules of equal specificity:
| Rule | From | Layer |
| ---------------------------------------------------------- | --------------------- | -------------- |
| `[type="button"]:where(…) { -webkit-appearance: button }` | normalize.css, scoped | `normalize` |
| `._button_… { appearance: none; font: var(--cpd-font-…) }` | Compound | `compound-web` |
Without layers they tie, so the one loaded last wins: Element Call's
stylesheet, loaded after the host's, and the button looks native (no styling). With
them, `compound-web` beats `normalize` whatever the load order, and a rule
in one of Element Call's CSS modules, being unlayered, would beat both.
3. Passes `portalRoot`: the page body, or the Picture-in-Picture window's body
while the call is shown there, or `null` while that window is not ready.
## Rules for Element Call code
- Style `[data-element-call-root]`, never `body` or `:root` directly; see
[code style](./agents/code-style.md#css).
- Use container queries (`@container element-call`) and `cqw`/`cqh`, not
`@media` or `vw`/`vh`.
- Nothing in `base.css` may depend on its order relative to the CSS modules:
the app and the component build put it in different places.
- `pnpm dev:component` applies the same scoping, so the test host shows what a
real host gets.
-172
View File
@@ -1,172 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1260" height="960" viewBox="0 0 1260 960" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif" font-size="12" fill="#1f2328">
<defs>
<style>
.mono { font-family: ui-monospace, Menlo, Consolas, monospace; }
.b { font-weight: 600; }
.tag { fill: #57606a; font-size: 11px; }
.ok { fill: #2e7d32; font-weight: 700; font-size: 14px; }
.no { fill: #c62828; font-weight: 700; font-size: 14px; }
.lead { stroke: #8250df; stroke-width: 1.5; stroke-dasharray: 5 3; fill: none; }
.dot { fill: #8250df; }
.reach { stroke: #e36209; stroke-width: 1.5; stroke-dasharray: 6 4; fill: none; }
</style>
<marker id="arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0 0 L8 4 L0 8 z" fill="#8250df"/>
</marker>
</defs>
<rect width="1260" height="960" fill="#ffffff"/>
<text x="30" y="34" font-size="17" class="b">Element Call as a component inside Element Web: the live DOM</text>
<!-- ================= DOM tree ================= -->
<!-- body -->
<rect x="30" y="52" width="620" height="680" rx="6" fill="#fafafa" stroke="#8c959f"/>
<text x="44" y="74" class="mono b">&lt;body&gt;</text>
<text x="100" y="74" class="tag">Element Web's document</text>
<!-- EW app UI -->
<rect x="50" y="86" width="580" height="400" rx="5" fill="#eceff1" stroke="#90a4ae"/>
<text x="64" y="106" class="b">EW app UI</text>
<!-- EW h3 -->
<rect x="70" y="118" width="260" height="30" rx="4" fill="#ffffff" stroke="#90a4ae"/>
<text x="82" y="138" class="mono">&lt;h3&gt;</text>
<text x="122" y="138">in EW's own UI</text>
<text x="310" y="139" class="no">✗</text>
<!-- call tile -->
<rect x="70" y="160" width="540" height="314" rx="5" fill="#f6f8fa" stroke="#b0bec5"/>
<text x="84" y="180">call tile → <tspan class="mono">WrappedElementCallComponent</tspan> <tspan class="tag">(EW)</tspan></text>
<!-- EC root -->
<rect x="88" y="192" width="504" height="270" rx="5" fill="#e8f5e9" stroke="#2e7d32" stroke-width="2"/>
<text x="102" y="214" class="mono b">div.root</text>
<text x="102" y="232" class="mono">[data-element-call-root] [data-platform] [data-background]</text>
<text x="102" y="248" class="mono">.cpd-theme-dark</text>
<text x="102" y="268" class="tag">class: component/ElementCall.module.css (isolation, contain: layout paint)</text>
<text x="102" y="284" class="tag">attributes, theme: src/useTheme.ts, Decoration in component/index.tsx</text>
<!-- div.content -->
<rect x="106" y="296" width="470" height="70" rx="4" fill="#ffffff" stroke="#66bb6a"/>
<text x="120" y="316"><tspan class="mono">div.content</tspan> → CallView …</text>
<rect x="124" y="326" width="200" height="28" rx="4" fill="#f1f8e9" stroke="#66bb6a"/>
<text x="136" y="345" class="mono">&lt;h3&gt;</text>
<text x="176" y="345">in the call view</text>
<text x="306" y="346" class="ok">✓</text>
<!-- Modal -->
<rect x="106" y="378" width="470" height="72" rx="4" fill="#ffffff" stroke="#66bb6a"/>
<text x="120" y="398">Modal / Drawer <tspan class="tag">src/Modal.tsx: Drawer.Portal container = root element</tspan></text>
<rect x="124" y="410" width="200" height="28" rx="4" fill="#f1f8e9" stroke="#66bb6a"/>
<text x="136" y="429" class="mono">&lt;h3&gt;</text>
<text x="176" y="429">modal title</text>
<text x="306" y="430" class="ok">✓</text>
<!-- EC portal container -->
<rect x="50" y="502" width="580" height="160" rx="5" fill="#e3f2fd" stroke="#1565c0" stroke-width="2"/>
<text x="64" y="524" class="mono b">div[data-element-call-portal][data-platform].cpd-theme-dark</text>
<text x="64" y="544" class="tag">created by component/CallPortalRoot.tsx, appended to EW's portalRoot:</text>
<text x="64" y="558" class="tag">this body, or the PiP window's body while the call is in Picture-in-Picture</text>
<text x="64" y="574" class="tag">theme + platform: src/useTheme.ts via usePortalElement (src/RootElementContext.ts)</text>
<rect x="70" y="586" width="540" height="64" rx="4" fill="#ffffff" stroke="#64b5f6"/>
<text x="84" y="606">Compound tooltip / menu <tspan class="tag">floated here by Compound's PortalRoot</tspan></text>
<rect x="88" y="614" width="220" height="28" rx="4" fill="#e8f4fd" stroke="#64b5f6"/>
<text x="100" y="633" class="mono">&lt;h3&gt;</text>
<text x="140" y="633">in a floated menu</text>
<text x="290" y="634" class="ok">✓</text>
<!-- EW's own floated UI -->
<rect x="50" y="676" width="580" height="42" rx="5" fill="#eceff1" stroke="#90a4ae"/>
<text x="64" y="702">EW's own Compound tooltips / menus <tspan class="tag">not inside EC's root or portal container</tspan></text>
<text x="604" y="703" class="no">✗</text>
<!-- reach of EC's scoped selectors -->
<rect x="82" y="186" width="516" height="282" rx="8" class="reach"/>
<rect x="44" y="496" width="592" height="172" rx="8" class="reach"/>
<!-- ================= h3 notes ================= -->
<!-- 1 -->
<rect x="750" y="52" width="490" height="174" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="72" r="11" fill="#8250df"/>
<text x="770" y="76" fill="#fff" text-anchor="middle" class="b">1</text>
<text x="790" y="77" class="b">Source: Element Call's own stylesheets</text>
<text x="790" y="100" class="tag"><tspan class="mono">src/base.css</tspan>, in <tspan class="mono">@layer compound-legacy</tspan></text>
<text x="790" y="120" class="mono">h3 {</text>
<text x="806" y="136" class="mono">font-weight: 600;</text>
<text x="806" y="152" class="mono">font-size: var(--font-size-subtitle);</text>
<text x="790" y="168" class="mono">}</text>
<text x="790" y="192" class="tag"><tspan class="mono">src/room/InviteModal.module.css</tspan>, the modal's copy-link button</text>
<text x="790" y="212" class="mono">.button { width: 100%; }</text>
<!-- 2 -->
<rect x="750" y="238" width="490" height="308" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="258" r="11" fill="#8250df"/>
<text x="770" y="262" fill="#fff" text-anchor="middle" class="b">2</text>
<text x="790" y="263" class="b">Component build: <tspan class="mono">component/build/scopeStylesToRoot.ts</tspan></text>
<text x="790" y="286" class="mono">h3:where(</text>
<text x="806" y="302" class="mono">[data-element-call-root],</text>
<text x="806" y="318" class="mono">[data-element-call-root] *,</text>
<text x="806" y="334" class="mono">[data-element-call-portal],</text>
<text x="806" y="350" class="mono">[data-element-call-portal] *</text>
<text x="790" y="366" class="mono">)</text>
<text x="790" y="388"><tspan class="mono">:where()</tspan> adds no specificity: same weight as a plain <tspan class="mono">h3</tspan>.</text>
<text x="790" y="412" class="mono">._button_1ibuh_15 { width: 100%; }</text>
<text x="790" y="432">Not rewritten: the module class already confines it.</text>
<line x1="764" y1="446" x2="1226" y2="446" stroke="#e1d4f5"/>
<text x="764" y="464" class="b">Rules that get <tspan class="mono">:where()</tspan>, all from Element Call's own files:</text>
<text x="764" y="482"><tspan class="mono">src/base.css</tspan> <tspan class="tag">root tokens, theme classes, typography</tspan></text>
<text x="764" y="499"><tspan class="mono">normalize.css</tspan> <tspan class="tag">imported by base.css into @layer normalize</tspan></text>
<text x="764" y="516"><tspan class="mono">*.module.css</tspan> <tspan class="tag">none: every selector there has a class</tspan></text>
<text x="764" y="533" class="tag">Compound's and Element Web's stylesheets never go through it.</text>
<!-- 3 -->
<rect x="750" y="558" width="490" height="126" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="578" r="11" fill="#8250df"/>
<text x="770" y="582" fill="#fff" text-anchor="middle" class="b">3</text>
<text x="790" y="583" class="b">What it matches</text>
<text x="764" y="610"><tspan class="no">✗</tspan> EW's own h3: it is in neither container</text>
<text x="764" y="640"><tspan class="ok">✓</tspan> the h3 in the call view and in the modal (inside the root)</text>
<text x="764" y="670"><tspan class="ok">✓</tspan> an h3 floated into the portal container</text>
<!-- 4 -->
<rect x="750" y="696" width="490" height="120" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="716" r="11" fill="#8250df"/>
<text x="770" y="720" fill="#fff" text-anchor="middle" class="b">4</text>
<text x="790" y="721" class="b">Cascade layer</text>
<text x="790" y="742">Stays in <tspan class="mono">compound-legacy</tspan>. EW's <tspan class="mono">res/css/_index.pcss</tspan> orders:</text>
<text x="790" y="762" class="mono">normalize, compound-legacy, compound-tokens,</text>
<text x="790" y="778" class="mono">compound-web, shared-components, app-web</text>
<text x="790" y="802">so Compound's styles win where both set the same property.</text>
<!-- leaders from the h3 nodes to note 3: one lane each, no crossings -->
<!-- EW's own h3 → ✗ row -->
<path class="lead" d="M330 133 H725 V610 H750" marker-end="url(#arrow)"/>
<!-- call view + modal h3 → first ✓ row -->
<path class="lead" d="M324 340 H700 V640 H750" marker-end="url(#arrow)"/>
<path class="lead" d="M324 424 H700"/>
<!-- floated menu h3 → second ✓ row -->
<path class="lead" d="M308 628 H675 V670 H750" marker-end="url(#arrow)"/>
<circle class="dot" cx="330" cy="133" r="3"/>
<circle class="dot" cx="324" cy="340" r="3"/>
<circle class="dot" cx="324" cy="424" r="3"/>
<circle class="dot" cx="308" cy="628" r="3"/>
<circle class="dot" cx="700" cy="424" r="2.5"/>
<!-- ================= legend ================= -->
<rect x="750" y="830" width="490" height="112" rx="6" fill="#ffffff" stroke="#d0d7de"/>
<text x="766" y="852" class="b">Legend</text>
<rect x="766" y="864" width="18" height="12" fill="#eceff1" stroke="#90a4ae"/>
<text x="792" y="875">Element Web</text>
<rect x="896" y="864" width="18" height="12" fill="#e8f5e9" stroke="#2e7d32"/>
<text x="922" y="875">EC root (the call)</text>
<rect x="1056" y="864" width="18" height="12" fill="#e3f2fd" stroke="#1565c0"/>
<text x="1082" y="875">EC portal container</text>
<rect x="766" y="890" width="30" height="12" rx="3" class="reach"/>
<text x="804" y="901">what EC's scoped selectors can reach</text>
<path class="lead" d="M766 922 L796 922" marker-end="url(#arrow)"/>
<text x="804" y="926">which h3 the rule in note 3 does or does not match</text>
</svg>

Before

Width:  |  Height:  |  Size: 10 KiB

-10
View File
@@ -172,16 +172,6 @@
"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. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"indicator": "Low bandwidth mode",
"indicator_cancel": "Cancel",
"indicator_cancel_label": "Cancel Low bandwidth mode",
"screen_share_unavailable": "You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"switch_description": "Turn off cameras and lower screen-share quality to save data. Lasts until the call ends.",
"switch_label": "Low bandwidth mode",
"turned_on": "Low bandwidth mode on"
},
"microphone_level": {
"label": "Microphone level",
"no_device": "No microphone found. Connect one, then try again.",
+1 -1
View File
@@ -91,7 +91,7 @@
"@typescript-eslint/utils": "^8.61.0",
"@use-gesture/react": "^10.2.11",
"@vector-im/compound-design-tokens": "^11.0.0",
"@vector-im/compound-web": "^10.5.0",
"@vector-im/compound-web": "^10.8.0",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/browser-playwright": "^4.1.5",
"@vitest/coverage-v8": "^4.0.18",
+2 -6
View File
@@ -107,6 +107,8 @@ test("tracks the focus source of its own call, not the page", async ({
await openDeviceList(page, pane);
const menu = page.getByRole("menu");
// Asserted on the attribute: the component build's scoped stylesheet doesn't
// reach the portalled menu, so its ring can't be read here.
await expect(menu).toHaveAttribute("data-focus-source", "pointer");
// A key pressed in the other call says nothing about this menu.
@@ -119,12 +121,6 @@ test("tracks the focus source of its own call, not the page", async ({
await page.keyboard.press("ArrowDown");
await expect(menu).toHaveAttribute("data-focus-source", "keyboard");
// Asserted on the painted ring too: the rule is confined by the menu's module
// class on an ancestor, and has to reach the menu where Compound portals it,
// outside the call's root.
const focused = menu.locator('[role^="menuitem"]:focus');
await expect(focused).toHaveCSS("outline-style", "solid");
});
/** Opens a component's microphone menu and returns its device list. */
@@ -141,51 +141,6 @@ test("leaves the host's own page unstyled", async ({ page }) => {
await expect(root).toHaveCSS("font-feature-settings", /"kern"/);
});
test("styles its tooltips as its own, outside the container", async ({
page,
}) => {
const { username, roomId } = await createUserAndRoom("portalstyles");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
await expect(pane.getByTestId("lobby_joinCall")).toBeVisible({
timeout: 60_000,
});
const button = pane.getByTestId("settings-bottom");
await button.hover();
const labelId = await button.getAttribute("aria-labelledby");
const label = page.locator(`[id="${labelId}"]`);
await expect(label).toHaveText("Settings");
// The harness passes no portal root, so the tooltip floats out of the call's
// root into a container of Element Call's own in the page's body. Each of the
// harness's two calls has one, so pick the one holding this tooltip.
const portal = page
.locator("body > [data-element-call-portal]")
.filter({ has: page.locator(`[id="${labelId}"]`) });
await expect(portal).toHaveCount(1);
await expect(portal.locator(`[id="${labelId}"]`)).toBeVisible();
await expect(pane.locator(`[id="${labelId}"]`)).toHaveCount(0);
// That container carries the call's theme and platform, as the root does
await expect(portal).toHaveClass(/\bcpd-theme-dark\b/);
await expect(portal).toHaveAttribute("data-platform", "desktop");
// And Element Call's stylesheets reach it: `--font-scale` is declared on
// `:root` in base.css, which the component build turns into the root and
// this container. The host's page itself still has none of it.
expect(
await label.evaluate((element) =>
getComputedStyle(element).getPropertyValue("--font-scale").trim(),
),
).toBe("1");
expect(
await page.evaluate(() =>
getComputedStyle(document.body).getPropertyValue("--font-scale"),
),
).toBe("");
});
test("tells its host what it is doing", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("hostbridge");
const panes = await startHarness(page, username, roomId);
-151
View File
@@ -1,151 +0,0 @@
/*
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 {
cancelButton,
expectInboundVideo,
expectNoInboundVideo,
inboundVideoWidths,
openVideoSettings,
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("has no switch in the lobby's settings", async ({ page }) => {
await page.goto("/");
await SpaHelpers.createCall(page, "Alice", "Low bandwidth");
await openVideoSettings(page);
await expect(
page.getByRole("checkbox", { name: "Blur the background of the video" }),
).toBeVisible();
await expect(
page.getByRole("checkbox", { name: "Low bandwidth mode" }),
).toHaveCount(0);
});
test("receives no cameras and sends no video, and Cancel gives the camera back", async ({
browser,
}) => {
const { alice, bob } = await twoInACall(browser);
await expectInboundVideo(alice);
await expect(cancelButton(alice)).toHaveCount(0);
await setLowBandwidthMode(alice, true);
await expect(cancelButton(alice)).toBeVisible();
// 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 is shown to Alice as usual, at its lowest layer
await bob.getByRole("switch", { name: "Share screen" }).click();
await expect(alice.getByRole("radio", { name: "Spotlight" })).toBeChecked();
await expect(
alice.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(alice);
const widths = await inboundVideoWidths(alice);
test.info().annotations.push({
type: "screen share width received in the mode",
description: widths.join(", "),
});
expect(widths.length).toBeGreaterThan(0);
for (const width of widths) expect(width).toBeLessThanOrEqual(960);
await bob.getByRole("switch", { name: "Share screen" }).click();
// From the keyboard, to check where focus lands once the indicator goes
await cancelButton(alice).focus();
await alice.keyboard.press("Enter");
await expect(cancelButton(alice)).toHaveCount(0);
await expect(alice.getByTestId("incall_videomute")).toBeFocused();
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();
}
@@ -1,36 +0,0 @@
/*
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 {
cancelButton,
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. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
);
await expect(camera).toHaveAttribute("aria-checked", "false");
await cancelButton(page).tap();
await expect(camera).not.toHaveAttribute("aria-disabled", "true");
});
-137
View File
@@ -1,137 +0,0 @@
/*
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);
}
/** The widths of the videos arriving now, over every peer connection on the page. */
export async function inboundVideoWidths(
target: Page | FrameLocator,
): Promise<number[]> {
const read = async (): Promise<number[]> => {
const widths: number[] = [];
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")
if (stat.frameWidth) widths.push(stat.frameWidth);
});
}
return widths;
};
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;
}
/** Opens the settings on their Video tab. */
export async function openVideoSettings(
target: Page | FrameLocator,
): Promise<void> {
await target
.getByRole("button", { name: "Settings" })
.filter({ visible: true })
.first()
.click();
await target.getByRole("tab", { name: "Video" }).click();
}
/** Turns Low bandwidth mode on or off from the call's Video settings. */
export async function setLowBandwidthMode(
target: Page | FrameLocator,
on: boolean,
): Promise<void> {
await openVideoSettings(target);
// 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();
}
/** The indicator's way out of Low bandwidth mode. */
export function cancelButton(
target: Page | FrameLocator,
): ReturnType<Page["getByRole"]> {
return target.getByRole("button", { name: "Cancel Low bandwidth mode" });
}
@@ -1,89 +0,0 @@
/*
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 {
cancelButton,
expectInboundVideo,
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 Video settings of the call's own footer
await setLowBandwidthMode(valereCall, true);
await expect(cancelButton(valereCall)).toBeVisible();
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 receives the share and sees it as usual
await timoCall.getByRole("switch", { name: "Share screen" }).click();
await expect(
valereCall.getByRole("radio", { name: "Spotlight" }),
).toBeChecked({ timeout: 10000 });
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(valereCall);
// Element Web's PiP has no room for the indicator, and still shows the share
await TestHelpers.expandRoomList(valere.page);
await TestHelpers.switchToRoomNamed(valere.page, "Elsewhere");
await expect(valere.page.getByTestId("widget-pip-container")).toBeVisible();
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expect(cancelButton(valereCall)).toHaveCount(0);
},
);
+5 -5
View File
@@ -133,8 +133,8 @@ importers:
specifier: ^11.0.0
version: 11.3.1(@types/react@19.3.3)(react@19.3.1)
'@vector-im/compound-web':
specifier: ^10.5.0
version: 10.7.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.3)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
specifier: ^10.8.0
version: 10.8.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.3)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@vitejs/plugin-react':
specifier: ^6.0.2
version: 6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.16(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
@@ -3273,8 +3273,8 @@ packages:
react:
optional: true
'@vector-im/compound-web@10.7.0':
resolution: {integrity: sha512-WP6/TcfxD2tuD8bw9FVAWIIGUti1WHKdojnble3MJmkC6fGRuEtl0p4Cz8ctmHY4XNkNKGGp5Nlax/Csry86IQ==}
'@vector-im/compound-web@10.8.0':
resolution: {integrity: sha512-DSrAiTVAtrg0+3IwY5oguhWDdZ1m+96O/bySxF0St7+TNP7L6fvzc80QFNUmJtNUTMSgNFcbvEEPtvksi0w3fQ==}
peerDependencies:
'@fontsource/inconsolata': ^5
'@fontsource/inter': ^5
@@ -8623,7 +8623,7 @@ snapshots:
'@types/react': 19.3.3
react: 19.3.1
'@vector-im/compound-web@10.7.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.3)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
'@vector-im/compound-web@10.8.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.3)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@floating-ui/react': 0.27.20(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@floating-ui/react-dom': 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
-10
View File
@@ -228,8 +228,6 @@ 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. */
@@ -345,14 +343,6 @@ export interface MatrixRTCClient {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every 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;
-18
View File
@@ -105,7 +105,6 @@ 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>;
}
@@ -153,7 +152,6 @@ function setup(
),
data$: new Subject<DataPacket>(),
setPublishing: vi.fn(),
setReceiveVideo: vi.fn(),
delegateDelayedLeave: vi.fn(async () => Promise.resolve()),
mediaFor: vi.fn(() => ({
tracks$: constant(null),
@@ -180,7 +178,6 @@ function setup(
mediaFor: fake.mediaFor,
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: fake.setReceiveVideo,
sendData: vi.fn(),
data$: fake.data$,
};
@@ -378,21 +375,6 @@ 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[] = [];
-2
View File
@@ -151,7 +151,6 @@ 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,
@@ -321,7 +320,6 @@ 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$,
},
-1
View File
@@ -92,7 +92,6 @@ function idleBackend(): MediaBackend {
mediaFor: vi.fn(),
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: vi.fn(),
sendData: vi.fn(),
data$: EMPTY,
};
-13
View File
@@ -127,11 +127,6 @@ 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.
@@ -221,14 +216,6 @@ export interface RTCParticipation {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every 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;
+1 -1
View File
@@ -81,7 +81,7 @@ export interface MediaQuality {
max_bitrate?: number;
/** Max framerate. Default 30. */
max_framerate?: number;
/** Simulcast layers, lowest quality first. Default one layer of 540p at 15 fps and 625 kbps. */
/** Simulcast layers, lowest quality first. Without them LiveKit adds one layer at half resolution. */
simulcast_layers?: Array<{
height: number;
bitrate: number;
-9
View File
@@ -159,15 +159,6 @@ export interface MediaBackend {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote cameras are subscribed. While false, screen shares are
* still subscribed, capped at their lowest layer. 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.
@@ -25,11 +25,9 @@ import {
RoomEvent,
Track,
ConnectionState as LivekitConnectionState,
VideoQuality,
} 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 {
@@ -58,7 +56,6 @@ let testScope: ObservableScope;
let client: MockedObject<ClientGetTokenParts & ClientOpenIDParts>;
let fakeLivekitRoom: MockedObject<LivekitRoom>;
let receiveVideo$: BehaviorSubject<boolean>;
let localParticipantEventEmiter: EventEmitter;
let fakeLocalParticipant: MockedObject<LocalParticipant>;
@@ -86,14 +83,12 @@ 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",
@@ -393,7 +388,6 @@ describe("Start connection states", () => {
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
"wss://sfu",
testJWTToken,
{ autoSubscribe: true },
);
expect(connection.livekitAlias).toBe("!example_room_id");
});
@@ -682,230 +676,6 @@ 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("receives a screen share at its lowest layer while video is not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe: false
const { publications } = remoteParticipantWithTracks(false);
fakeLivekitRoom.emit(RoomEvent.Connected);
expect(publications.screenShare.isDesired).toBe(true);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
expect(publications.camera.setVideoQuality).not.toHaveBeenCalled();
});
it("lifts the cap on screen shares when video is received again", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
receiveVideo$.next(false);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
receiveVideo$.next(true);
expect(publications.screenShare.quality).toBe(VideoQuality.HIGH);
expect(publications.screenShare.setSubscribed).not.toHaveBeenCalled();
});
it("caps the screen shares a full reconnect recreates", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
remoteParticipantWithTracks(undefined);
fakeLivekitRoom.remoteParticipants.clear();
const { publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(RoomEvent.Reconnected);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
});
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: true,
screenShareAudio: true,
};
const VIDEO_ON = {
microphone: true,
camera: true,
screenShare: true,
screenShareAudio: true,
};
type MockPublication = RemoteTrackPublication & {
setSubscribed: ReturnType<typeof vi.fn>;
setVideoQuality: ReturnType<typeof vi.fn>;
quality: VideoQuality | undefined;
};
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,
Track.Source.Microphone,
subscribed,
),
camera: mockPublication(Track.Kind.Video, Track.Source.Camera, subscribed),
screenShare: mockPublication(
Track.Kind.Video,
Track.Source.ScreenShare,
subscribed,
),
screenShareAudio: mockPublication(
Track.Kind.Audio,
Track.Source.ScreenShareAudio,
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,
source: Track.Source,
subscribed: boolean | undefined,
): MockPublication {
const publication = {
kind,
source,
subscribed,
quality: undefined as VideoQuality | undefined,
get isDesired(): boolean {
return this.subscribed !== false;
},
setSubscribed: vi.fn((value: boolean) => {
publication.subscribed = value;
}),
// As LiveKit, which ignores it on a publication not subscribed
setVideoQuality: vi.fn((value: VideoQuality) => {
if (publication.isDesired) publication.quality = 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();
+4 -67
View File
@@ -19,15 +19,13 @@ import {
type RemoteParticipant,
type RemoteTrackPublication,
type Room as LivekitRoom,
type RoomConnectOptions,
RoomEvent,
type SubscriptionError,
Track,
type Track,
type TrackPublication,
VideoQuality,
} from "livekit-client";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject, distinctUntilChanged, skip } from "rxjs";
import { BehaviorSubject } from "rxjs";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
@@ -75,12 +73,6 @@ export interface ConnectionOpts {
slotId: string;
/** The observable scope to use for this connection. */
scope: ObservableScope;
/**
* Whether remote cameras are subscribed and screen shares received at full
* quality. Read at connect and followed for the connection's lifetime;
* audio and screen shares are always subscribed.
*/
receiveVideo$: Behavior<boolean>;
/** Optional factory to create the LiveKit room, mainly for testing purposes. */
livekitRoomFactory: () => LivekitRoom;
@@ -159,7 +151,6 @@ 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.
*
@@ -185,14 +176,12 @@ export class Connection {
this.client = client;
this.flow = opts.flow;
this.onCsApiMissing = opts.onCsApiMissing;
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`);
@@ -200,53 +189,6 @@ export class Connection {
});
}
/**
* Keeps every remote publication subscribed or not, and every screen share
* at the quality, that `receiveVideo$` asks for. 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 receiveVideo = this.receiveVideo$.value;
const isScreenShare = publication.source === Track.Source.ScreenShare;
const wanted =
publication.kind !== Track.Kind.Video || isScreenShare || receiveVideo;
// Every call sends a subscription update, wanted or not
if (publication.isDesired !== wanted) publication.setSubscribed(wanted);
// Ignored by LiveKit until the publication is subscribed
if (isScreenShare)
publication.setVideoQuality(
receiveVideo ? VideoQuality.HIGH : VideoQuality.LOW,
);
};
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
@@ -458,7 +400,7 @@ export class Connection {
private async connectLivekitRoom(url: string, jwt: string): Promise<void> {
try {
await this.livekitRoom.connect(url, jwt, this.connectOptions());
await this.livekitRoom.connect(url, jwt);
} 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.
@@ -469,15 +411,10 @@ 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, this.connectOptions());
await this.livekitRoom.connect(url, jwt);
}
}
/** A connection made while cameras are not received never asks the SFU for them. */
private connectOptions(): RoomConnectOptions {
return { autoSubscribe: this.receiveVideo$.value };
}
protected async getSFUConfig(): Promise<SFUConfig> {
try {
return await getSFUConfig({
@@ -7,19 +7,15 @@ 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 { type Behavior, constant } from "../../reactive/Behavior";
import { constant } from "../../reactive/Behavior";
import { ownMemberMock, testScope } from "../../utils/test";
import { testJWTToken } from "../../utils/test-fixtures";
import {
@@ -55,7 +51,6 @@ function create(
mediaQuality?: MediaQuality,
audioOutputDeviceId?: string,
transport = exampleTransport,
receiveVideo$: Behavior<boolean> = constant(true),
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
@@ -64,7 +59,6 @@ function create(
"m.call#ROOM",
publish,
constant(audioOutputDeviceId),
receiveVideo$,
undefined,
mediaQuality,
);
@@ -81,29 +75,6 @@ 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([]);
@@ -109,7 +109,6 @@ 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,
) {}
@@ -134,7 +133,6 @@ export class LivekitConnectionFactory implements ConnectionFactory {
client: this.client,
onCsApiMissing: this.onCsApiMissing,
scope,
receiveVideo$: this.receiveVideo$,
livekitRoomFactory: () =>
new LivekitRoom(
roomOptions(
@@ -169,10 +169,6 @@ describe("createLivekitBackend", () => {
state$: BehaviorSubject<ConnectionState>;
}[];
let onCsApiMissing: () => void;
/** What the backend built the factory with. */
let factoryArgs: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -181,14 +177,8 @@ 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,
...args: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>
) {
factoryArgs = args;
onCsApiMissing = args[1];
function (this: unknown, _client, onMissing) {
onCsApiMissing = onMissing;
return {
createConnection: (
scope: ObservableScope,
@@ -273,17 +263,6 @@ describe("createLivekitBackend", () => {
},
);
it("hands every connection the factory makes the receive video choice, true until set", () => {
const b = backend();
const receiveVideo$ = factoryArgs[6];
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 () => {
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
@@ -104,7 +104,6 @@ export function createLivekitBackend(
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const receiveVideo$ = new BehaviorSubject(true);
const connectionFactory = new LivekitConnectionFactory(
client,
// The MSC defines no unstable feature flag. If the transport names a
@@ -118,7 +117,6 @@ export function createLivekitBackend(
slotId,
publish,
audioOutputDeviceId$,
receiveVideo$,
keyProvider,
mediaQuality,
);
@@ -302,7 +300,6 @@ export function createLivekitBackend(
mediaFor,
connections$,
setAudioOutputDeviceId: localMedia_.setAudioOutputDeviceId,
setReceiveVideo: (receive) => receiveVideo$.next(receive),
sendData,
data$,
};
@@ -197,24 +197,9 @@ describe("buildLiveKitOptions", () => {
});
});
it("sends one low screen share layer fit for Low bandwidth mode when not configured", () => {
it("does not include screenShareSimulcastLayers when not configured", () => {
const opts = buildLiveKitOptions();
const layers = opts.publishDefaults?.screenShareSimulcastLayers;
expect(layers).toHaveLength(1);
expect(layers?.[0]).toMatchObject({
width: 960,
height: 540,
encoding: { maxBitrate: 625_000, maxFramerate: 15 },
});
});
it("keeps the low screen share layer when only the top encoding is configured", () => {
const opts = buildLiveKitOptions({
screen_share: { max_bitrate: 8_000_000, max_framerate: 60 },
});
expect(opts.publishDefaults?.screenShareSimulcastLayers).toEqual(
buildLiveKitOptions().publishDefaults?.screenShareSimulcastLayers,
);
expect(opts.publishDefaults?.screenShareSimulcastLayers).toBeUndefined();
});
it("backupCodec always uses stock VP8 720p encoding", () => {
@@ -17,13 +17,6 @@ import {
import { defaultMediaQuality, type MediaQuality } from "../../config";
const lowBandwidthScreenShareLayer = new VideoPresetClass(
960,
540,
625_000,
15,
);
/**
* Find the closest matching VideoPreset for a given height.
*/
@@ -78,7 +71,7 @@ function buildPublishOptions(
};
// Screen share simulcast layers
let screenShareSimulcastLayers: VideoPreset[];
let screenShareSimulcastLayers: VideoPreset[] | undefined;
if (screenConf?.simulcast_layers) {
screenShareSimulcastLayers = screenConf.simulcast_layers.map(
(layer) =>
@@ -89,8 +82,6 @@ function buildPublishOptions(
layer.framerate ?? screenConf?.max_framerate ?? 30,
),
);
} else {
screenShareSimulcastLayers = [lowBandwidthScreenShareLayer];
}
return {
@@ -103,7 +94,9 @@ function buildPublishOptions(
simulcast: true,
videoSimulcastLayers: videoSimulcastLayers as VideoPreset[],
screenShareEncoding,
screenShareSimulcastLayers,
...(screenShareSimulcastLayers && {
screenShareSimulcastLayers: screenShareSimulcastLayers as VideoPreset[],
}),
stopMicTrackOnMute: false,
videoCodec: codec,
videoEncoding,
-1
View File
@@ -32,7 +32,6 @@ 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;
-16
View File
@@ -41,19 +41,3 @@ export const RootElementProvider = RootElementContext.Provider;
*/
export const useRootElement = (): HTMLElement =>
use(RootElementContext) ?? document.body;
const PortalElementContext = createContext<HTMLElement | null>(null);
/**
* Supplies the container that Compound floats Element Call's menus and tooltips
* into when that is outside the root: the component build's `CallPortalRoot`.
*/
export const PortalElementProvider = PortalElementContext.Provider;
/**
* The container that Element Call's menus and tooltips float into, if it is
* not the root's own document body. It gets the root's theme and platform, so
* that what floats out of the root looks as it would inside.
*/
export const usePortalElement = (): HTMLElement | null =>
use(PortalElementContext);
+3 -7
View File
@@ -123,16 +123,12 @@ before using one further down the tree. */
/* On Android and iOS, prefer native system fonts. The global.css file of
Compound Web is where these variables ultimately get consumed to set the page's
font-family. Also on the container that menus and tooltips float into, which
is outside the root in the component build. */
:is(
[data-element-call-root],
[data-element-call-portal]
)[data-platform="android"] {
font-family. */
[data-element-call-root][data-platform="android"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
:is([data-element-call-root], [data-element-call-portal])[data-platform="ios"] {
[data-element-call-root][data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
+7 -89
View File
@@ -5,15 +5,7 @@ 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 {
cloneElement,
type ComponentProps,
type ComponentPropsWithoutRef,
type FC,
type ReactElement,
useId,
useState,
} from "react";
import { type ComponentPropsWithoutRef, type FC } from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import {
@@ -41,9 +33,8 @@ import {
import styles from "./Button.module.css";
import { platform } from "../Platform";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
import { useAnnouncement } from "../useAnnouncement";
interface MicButtonProps extends ComponentProps<"button"> {
interface MicButtonProps extends ComponentPropsWithoutRef<"button"> {
enabled: boolean;
busy?: boolean;
size?: "md" | "lg";
@@ -75,25 +66,15 @@ 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 ComponentProps<"button"> {
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();
@@ -107,7 +88,7 @@ export const VideoButton: FC<VideoButtonProps> = ({
: t("start_video_button_label");
return (
<UnavailableTooltip label={label} unavailable={unavailable}>
<Tooltip label={label}>
<CpdButton
iconOnly
Icon={Icon}
@@ -121,19 +102,17 @@ export const VideoButton: FC<VideoButtonProps> = ({
})}
disabled={props.disabled || busy}
/>
</UnavailableTooltip>
</Tooltip>
);
};
interface ShareScreenButtonProps extends ComponentPropsWithoutRef<"button"> {
enabled: boolean;
size: "md" | "lg";
unavailable?: Unavailable;
}
export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
enabled,
unavailable,
...props
}) => {
const { t } = useTranslation();
@@ -142,7 +121,7 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
: t("screenshare_button_label");
return (
<UnavailableTooltip label={label} unavailable={unavailable}>
<Tooltip label={label}>
<CpdButton
iconOnly
Icon={ShareScreenSolidIcon}
@@ -151,68 +130,7 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
aria-checked={enabled}
{...props}
/>
</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}
</>
</Tooltip>
);
};
-71
View File
@@ -1,71 +0,0 @@
/*
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(),
);
}
-2
View File
@@ -112,7 +112,6 @@ export const BackgroundEffectGrid: FC<Props> = ({
disabled={disabled}
data-disabled={disabled ? "" : undefined}
label={null}
hideChevron
className={styles.tile}
// Without a handler it isn't one of the menu's items, so the keyboard
// passes over it.
@@ -160,7 +159,6 @@ export const BackgroundEffectGrid: FC<Props> = ({
onAdd === undefined ? null : (
<MenuItem
label={null}
hideChevron
className={styles.tile}
onSelect={(e) => {
e.preventDefault();
+2 -61
View File
@@ -23,7 +23,6 @@ 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";
@@ -39,15 +38,12 @@ 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: !heldOff,
enabled: true,
busy: false,
toggle: fn(),
unavailableReason: heldOff ? "lowBandwidthMode" : undefined,
options: withDevices
? [
{ id: "1", label: { type: "name", name: `${device} 1` } },
@@ -110,9 +106,7 @@ function CallFooterStoryWrapper({
withDevices: boolean;
}): ReactNode {
const audioMenuVm = useStaticViewModel(menu("audio", withDevices));
const cameraMenuVm = useStaticViewModel(
menu("video", withDevices, vmSnapshot.screenShareUnavailable),
);
const cameraMenuVm = useStaticViewModel(menu("video", withDevices));
const vm = useStaticViewModel({
...vmSnapshot,
layoutSwitchVm: layout && { layout$: constant(layout), setLayout },
@@ -184,7 +178,6 @@ export const Default: Story = {
asOverlay: false,
showModals: true,
sharingScreen: false,
screenShareUnavailable: false,
audioOutputSwitcher: undefined,
reactionIdentifier: undefined,
reactionData: undefined,
@@ -354,55 +347,3 @@ export const LobbyRecentButtonMobile: Story = {
...Default.parameters,
},
};
const screenShareExplanation =
"You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** 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();
},
};
+5 -19
View File
@@ -7,7 +7,6 @@ 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";
@@ -37,13 +36,13 @@ export interface AudioOutputSwitcher {
* The Snapshot combines all fields required to populate the view.
*
* It is a combination of Actions and State.
* All Actions and State will be wrapped in behaviors.
* This has the advantage that actions can mutate.
* (example: a device gets disconnected, the switch action is not possible anymore, the action becomes undefined)
* With it being reactive we can use the existence of the action to update the rendering without
* All Actions and State will be wrappen in behaviors.
* This has the advantage, that actions can mutate.
* (example: a device gets disconnected, the swicht action is not possible anymore, the actions becomes undefined)
* With it being reactive we can use the existance of the action to update the rendering without
* requiring additional state.
*
* Comment: It might not make sense to separate the two interfaces. Hence the separation
* Comment: It might not make sense to seperate the two interfaces. Hence the seperation
* just happens on the syntax level with the `type = ... & ...` notation.
*/
export type FooterSnapshot = FooterActions & FooterState;
@@ -75,8 +74,6 @@ 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;
@@ -92,8 +89,6 @@ export interface FooterState {
export interface FooterProps {
className?: string;
ref?: Ref<HTMLDivElement>;
/** The camera's mute button, for focus to be moved to it. */
cameraButtonRef?: Ref<HTMLButtonElement>;
children?: JSX.Element | JSX.Element[] | false;
vm: ViewModel<FooterSnapshot>;
}
@@ -101,11 +96,9 @@ export interface FooterProps {
export const CallFooter: FC<FooterProps> = ({
className,
ref,
cameraButtonRef,
children,
vm,
}) => {
const { t } = useTranslation();
const asOverlay = useBehavior(vm.asOverlay$);
const showFooter = useBehavior(vm.showFooter$);
const hideControls = useBehavior(vm.hideControls$);
@@ -116,7 +109,6 @@ 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$);
@@ -139,7 +131,6 @@ export const CallFooter: FC<FooterProps> = ({
kind="video"
vm={cameraMenuVm}
size={buttonSize}
buttonRef={cameraButtonRef}
/>,
);
@@ -151,11 +142,6 @@ 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,7 +102,6 @@ describe("createCallFooterViewModel", () => {
testScope(),
buildMinimalCallViewModel(layout),
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
@@ -122,7 +121,6 @@ describe("createCallFooterViewModel", () => {
testScope(),
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
-7
View File
@@ -30,8 +30,6 @@ 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.
@@ -44,7 +42,6 @@ export function createCallFooterViewModel(
scope: ObservableScope,
callModel: CallViewModel,
muteStates: MuteStates,
lowBandwidthMode$: Behavior<boolean>,
mediaDevices: MediaDevices,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
reactionIdentifier: string | undefined,
@@ -76,7 +73,6 @@ export function createCallFooterViewModel(
disableDeviceSwitcher$,
backgroundEffectsState$,
callModel.camera$,
lowBandwidthMode$,
),
),
// candidat to move into the FooterViewModel
@@ -106,7 +102,6 @@ export function createCallFooterViewModel(
sharingScreen$: callModel.sharingScreen$,
toggleScreenSharing$: constant(callModel.toggleScreenSharing ?? undefined),
screenShareUnavailable$: lowBandwidthMode$,
audioOutputSwitcher$: scope.behavior(
callModel.audioOutputSwitcher$.pipe(
@@ -171,7 +166,6 @@ export function createLobbyFooterViewModel(
debugTileLayout: false,
showFooter: true,
toggleScreenSharing: undefined,
screenShareUnavailable: false,
layoutSwitchVm: null,
sharingScreen: false,
audioOutputSwitcher: undefined,
@@ -191,7 +185,6 @@ export function createLobbyFooterViewModel(
constant(false),
backgroundEffectsState$,
camera$,
constant(false),
),
});
}
@@ -1,42 +0,0 @@
/*
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.
*/
.indicator {
position: absolute;
inset-inline: 0;
margin-inline: auto;
/* Where the footer's buttons are, while the footer is hidden */
inset-block-end: calc(env(safe-area-inset-bottom) + var(--cpd-space-10x));
z-index: var(--call-view-header-footer-layer);
box-shadow: 0px 4px 24px 0px rgba(27, 29, 34, 0.1);
}
.indicator.inline {
position: relative;
inset-block-end: auto;
align-self: center;
flex-shrink: 0;
margin-block-start: var(--cpd-space-3x);
max-inline-size: calc(100% - 2 * var(--cpd-space-3x));
}
.cancel {
appearance: none;
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
.cancel:focus-visible {
outline: 2px solid currentcolor;
outline-offset: 2px;
border-radius: var(--cpd-space-1x);
}
@@ -1,184 +0,0 @@
/*
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, fn, userEvent, within } from "storybook/test";
import { type JSX, type ReactNode, useRef } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import {
LowBandwidthIndicator,
type LowBandwidthIndicatorSnapshot,
} from "./LowBandwidthIndicator";
import inCallViewStyles from "../room/InCallView.module.css";
import { useStaticViewModel } from "../state/ViewModel";
import { VideoButton } from "../button";
const footerHeight = 136;
/** The indicator at the bottom of a call, over a footer of the usual height. */
function LowBandwidthIndicatorStoryWrapper({
footerShown,
...snapshot
}: LowBandwidthIndicatorSnapshot & { footerShown: boolean }): ReactNode {
const vm = useStaticViewModel(snapshot);
const cameraButtonRef = useRef<HTMLButtonElement>(null);
if (snapshot.inline) {
// Element Web's picture-in-picture window: the tile, then the indicator,
// then the footer, in the call view's column
return (
<div
className={inCallViewStyles.inRoom}
style={{ inlineSize: 340, blockSize: 400 }}
>
<div data-testid="tile" style={{ flexGrow: 1 }} />
<LowBandwidthIndicator vm={vm} footerHeight={null} />
<div data-testid="footer" style={{ flexShrink: 0, blockSize: 96 }} />
</div>
);
}
return (
<div className={inCallViewStyles.inRoom} style={{ position: "relative" }}>
<LowBandwidthIndicator
vm={vm}
footerHeight={footerShown ? footerHeight : null}
focusAfterCancel={cameraButtonRef}
/>
{footerShown && (
<div
data-testid="footer"
style={{
position: "absolute",
insetBlockEnd: 0,
inlineSize: "100%",
blockSize: footerHeight,
display: "flex",
alignItems: "center",
justifyContent: "center",
outline: "1px dashed var(--cpd-color-border-interactive-primary)",
}}
>
<VideoButton ref={cameraButtonRef} enabled={false} />
</div>
)}
</div>
);
}
const meta = {
component: LowBandwidthIndicatorStoryWrapper,
args: { shown: true, inline: false, cancel: fn(), footerShown: true },
argTypes: {
cancel: {
control: { type: "select" },
options: ["MockedCallback", "undefined"],
mapping: { MockedCallback: fn(), undefined: undefined },
},
},
parameters: { layout: "fullscreen" },
decorators: [
(Story): JSX.Element => (
<div style={{ blockSize: "100vh" }}>
<Story />
</div>
),
],
} satisfies Meta<typeof LowBandwidthIndicatorStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
export const AboveTheFooter: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
await expect(indicator).toHaveTextContent("Low bandwidth mode");
await expect(indicator.getBoundingClientRect().bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await userEvent.click(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
);
await expect(args.cancel).toHaveBeenCalled();
},
};
export const CancelFromTheKeyboard: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }).focus();
await userEvent.keyboard("{Enter}");
await expect(args.cancel).toHaveBeenCalled();
// The indicator goes with the mode; focus waits on the camera button
await expect(
canvas.getByRole("switch", { name: "Start video" }),
).toHaveFocus();
},
};
export const FooterHidden: Story = {
args: { footerShown: false },
play: async ({ canvasElement }) => {
const indicator = within(canvasElement).getByTestId(
"low-bandwidth-indicator",
);
await expect(indicator).toBeVisible();
await expect(
canvasElement.getBoundingClientRect().bottom -
indicator.getBoundingClientRect().bottom,
).toBeLessThan(footerHeight);
},
};
export const Narrow: Story = {
globals: { viewport: { value: "mobile2" } },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).getByRole("button", {
name: "Cancel Low bandwidth mode",
}),
).toBeVisible();
},
};
export const PictureInPicture: Story = {
args: { inline: true },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
const bounds = indicator.getBoundingClientRect();
await expect(bounds.top).toBeGreaterThanOrEqual(
canvas.getByTestId("tile").getBoundingClientRect().bottom,
);
await expect(bounds.bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await expect(indicator.scrollWidth).toBeLessThanOrEqual(
indicator.clientWidth,
);
await expect(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
).toBeVisible();
},
};
export const WithoutControls: Story = {
args: { cancel: undefined },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByTestId("low-bandwidth-indicator")).toBeVisible();
await expect(canvas.queryByRole("button")).toBeNull();
},
};
export const Off: Story = {
args: { shown: false },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByTestId("low-bandwidth-indicator"),
).toBeNull();
},
};
-83
View File
@@ -1,83 +0,0 @@
/*
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, type Ref, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import classNames from "classnames";
import { Toast } from "@vector-im/compound-web";
import { VideoCallOffIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import styles from "./LowBandwidthIndicator.module.css";
import { type ViewModel } from "../state/ViewModel";
import { useBehavior } from "../useBehavior";
export interface LowBandwidthIndicatorSnapshot {
/** Whether the call is in Low bandwidth mode, in a window big enough to say so. */
shown: boolean;
/** Whether it takes a row of its own between the tile and the footer. */
inline: boolean;
/** Turns the mode off; undefined where the host hides the call's controls. */
cancel: (() => void) | undefined;
}
interface Props {
vm: ViewModel<LowBandwidthIndicatorSnapshot>;
/** The height of the footer to sit above, or null while the footer is hidden. */
footerHeight: number | null;
/** Where focus goes once Cancel has removed the indicator, and itself. */
focusAfterCancel?: RefObject<HTMLElement | null>;
className?: string;
ref?: Ref<HTMLDivElement>;
}
/** A pill above the call's footer that says the call is in Low bandwidth mode. */
export function LowBandwidthIndicator({
vm,
footerHeight,
focusAfterCancel,
className,
ref,
}: Props): ReactNode {
const { t } = useTranslation();
const shown = useBehavior(vm.shown$);
const inline = useBehavior(vm.inline$);
const cancel = useBehavior(vm.cancel$);
if (!shown) return null;
return (
<Toast
Icon={VideoCallOffIcon}
ref={ref}
className={classNames(
styles.indicator,
{ [styles.inline]: inline },
className,
)}
style={
inline || footerHeight === null
? undefined
: { insetBlockEnd: footerHeight }
}
data-testid="low-bandwidth-indicator"
>
<span>{t("low_bandwidth_mode.indicator")}</span>
{cancel && (
<button
type="button"
className={styles.cancel}
onClick={(): void => {
cancel();
focusAfterCancel?.current?.focus();
}}
aria-label={t("low_bandwidth_mode.indicator_cancel_label")}
>
{t("low_bandwidth_mode.indicator_cancel")}
</button>
)}
</Toast>
);
}
@@ -1,81 +0,0 @@
/*
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 { describe, expect, test } from "vitest";
import { createLowBandwidthIndicatorViewModel } from "./LowBandwidthIndicatorViewModel";
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import { constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { testScope, withTestScheduler } from "../utils/test";
describe("LowBandwidthIndicatorViewModel", () => {
test("is shown while the mode is on, in the desktop picture-in-picture window too", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "desktop" },
);
schedule("-yn-y", {
y: () => mode.setEnabled(true),
n: () => mode.setEnabled(false),
});
expectObservable(vm.shown$).toBe("nyn-y", { y: true, n: false });
expectObservable(vm.inline$).toBe("n--y-n", { y: true, n: false });
});
});
test("is not shown in the mobile picture-in-picture window, which has no controls", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "ios" },
);
schedule("-y", { y: () => mode.setEnabled(true) });
expectObservable(vm.shown$).toBe("ny-n-y", { y: true, n: false });
});
});
test("turns the mode off with Cancel", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: true, platform: "desktop" },
);
mode.setEnabled(true);
vm.cancel$.value!();
expect(mode.enabled$.value).toBe(false);
expect(vm.shown$.value).toBe(false);
});
test("has no Cancel where the host hides the call's controls", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: false, platform: "desktop" },
);
mode.setEnabled(true);
expect(vm.shown$.value).toBe(true);
expect(vm.cancel$.value).toBeUndefined();
});
});
const grid = { type: "grid" } as Layout;
const pip = { type: "pip" } as Layout;
@@ -1,50 +0,0 @@
/*
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 { combineLatest, map } from "rxjs";
import { type Behavior, constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { type LowBandwidthMode } from "../state/LowBandwidthMode";
import { type ObservableScope } from "../state/ObservableScope";
import type { platform as currentPlatform } from "../Platform";
import { type ViewModel } from "../state/ViewModel";
import { type LowBandwidthIndicatorSnapshot } from "./LowBandwidthIndicator";
/**
* Creates the ViewModel for the Low bandwidth mode indicator.
*
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param lowBandwidthMode - The call's low bandwidth mode, which Cancel turns off.
* @param layout$ - The call's layout.
* @param options - `showControls`: whether the call controls are shown, Cancel
* among them. `platform`: mobile's picture-in-picture window shows no
* controls, so it shows no indicator either.
*/
export function createLowBandwidthIndicatorViewModel(
scope: ObservableScope,
lowBandwidthMode: LowBandwidthMode,
layout$: Behavior<Layout>,
{
showControls,
platform,
}: { showControls: boolean; platform: typeof currentPlatform },
): ViewModel<LowBandwidthIndicatorSnapshot> {
return {
shown$: scope.behavior(
combineLatest(
[lowBandwidthMode.enabled$, layout$],
(enabled, layout) =>
enabled && (layout.type !== "pip" || platform === "desktop"),
),
),
inline$: scope.behavior(layout$.pipe(map((l) => l.type === "pip"))),
cancel$: constant(
showControls ? (): void => lowBandwidthMode.setEnabled(false) : undefined,
),
};
}
@@ -15,7 +15,6 @@ 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,
@@ -45,7 +44,6 @@ export default meta;
type Story = StoryObj<typeof meta>;
const empty = {
unavailableReason: undefined,
outputOptions: [],
selectedOutput: undefined,
selectOutput: undefined,
@@ -116,50 +114,6 @@ export const CameraBusy: Story = {
args: { ...Camera.args, busy: true },
};
const lowBandwidthExplanation =
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** 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(
+2 -14
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, type Ref, useMemo } from "react";
import { type FC, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { MicButton, VideoButton } from "../button";
@@ -18,20 +18,17 @@ interface Props {
vm: MediaMenuViewModel;
kind: "audio" | "video";
size: "md" | "lg";
/** The mute button itself. */
buttonRef?: Ref<HTMLButtonElement>;
}
/**
* The microphone's or the camera's mute button: with a menu to pick the
* device while there are devices to offer, a plain mute button otherwise.
*/
export const MediaMenuButton: FC<Props> = ({ vm, kind, size, buttonRef }) => {
export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
const { t } = useTranslation();
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$);
@@ -75,22 +72,15 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size, buttonRef }) => {
}
}, [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 (
<PlainButton
ref={buttonRef}
size={size}
enabled={enabled}
busy={busy}
onClick={toggle}
disabled={busy || toggle === undefined}
unavailable={unavailable}
data-testid={testId}
/>
);
@@ -115,11 +105,9 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size, buttonRef }) => {
<MediaMuteAndSwitchButton
size={size}
iconsAndLabels="video"
muteButtonRef={buttonRef}
enabled={enabled}
busy={busy}
onMuteClick={toggle}
unavailable={unavailable}
options={options}
selectedOption={selected}
onSelect={select}
+1 -4
View File
@@ -16,7 +16,7 @@ import {
mockMediaDevices,
mockVideoTrack,
} from "../utils/test";
import { type Behavior, constant } from "../state/Behavior";
import { constant } from "../state/Behavior";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import type { DeviceLabel } from "../state/MediaDevices";
import {
@@ -97,13 +97,11 @@ 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(),
@@ -112,7 +110,6 @@ function cameraMenu({
constant(disableSwitcher),
pipeline$,
camera$,
lowBandwidthMode$,
);
}
+1 -17
View File
@@ -57,11 +57,6 @@ 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;
@@ -136,10 +131,7 @@ export function createAudioMenuViewModel(
): MediaMenuViewModel {
const { audio } = muteStates;
return {
...createStaticViewModel({
...noBackgroundEffects,
unavailableReason: undefined,
}),
...createStaticViewModel(noBackgroundEffects),
enabled$: audio.enabled$,
busy$: audio.syncing$,
toggle$: scope.behavior(audio.toggle$.pipe(map((t) => t ?? undefined))),
@@ -172,8 +164,6 @@ 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,
@@ -182,7 +172,6 @@ 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.
@@ -216,11 +205,6 @@ 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,7 +12,6 @@ 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";
@@ -222,31 +221,6 @@ 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. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
},
},
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" },
+1 -11
View File
@@ -15,7 +15,6 @@ import {
useEffect,
type ReactElement,
type ReactNode,
type Ref,
} from "react";
import {
Alert,
@@ -38,7 +37,7 @@ import { useTranslation } from "react-i18next";
import { distinctUntilChanged, map } from "rxjs";
import styles from "./MediaMuteAndSwitchButton.module.css";
import { MicButton, type Unavailable, VideoButton } from "../button";
import { MicButton, VideoButton } from "../button";
import {
type AudioOutputDeviceLabel,
type DeviceLabel,
@@ -63,10 +62,6 @@ export interface MediaMuteAndSwitchButtonProps {
enabled?: boolean;
/** Callback if the mute button is clicked */
onMuteClick?: () => void;
/** The mute button itself. */
muteButtonRef?: Ref<HTMLButtonElement>;
/** 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";
@@ -130,8 +125,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
enabled,
busy,
onMuteClick,
muteButtonRef,
unavailable,
iconsAndLabels,
options,
selectedOption,
@@ -285,7 +278,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
const MuteButton = audioMeter ? MicButton : VideoButton;
const button = (
<MuteButton
ref={muteButtonRef}
size={size}
enabled={enabled ?? false}
busy={isBusy}
@@ -295,7 +287,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
e.stopPropagation();
}}
disabled={isBusy || onMuteClick === undefined}
unavailable={audioMeter ? undefined : unavailable}
data-testid={audioMeter ? "incall_mute" : "incall_videomute"}
/>
);
@@ -377,7 +368,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
<MenuItem
// A radio input may not sit inside a button.
as="div"
hideChevron
disabled={disabled}
label={labelText(label, numbered)}
Icon={
+2 -2
View File
@@ -158,8 +158,8 @@ export interface ConfigOptions {
max_framerate?: number;
/**
* Simulcast layers for screen sharing as an array of {height, bitrate, framerate} objects,
* ordered from lowest to highest quality. If omitted, one layer of 540p at 15 fps and
* 625 kbps.
* ordered from lowest to highest quality. If omitted, LiveKit SDK defaults apply (1 extra
* layer at half resolution).
*/
simulcast_layers?: Array<{
height: number;
+2 -32
View File
@@ -78,10 +78,6 @@ 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";
@@ -155,15 +151,6 @@ 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
@@ -211,12 +198,7 @@ export const CallView: FC<Props> = ({
};
}, [backend]);
if (
muteStates === null ||
slot === null ||
lowBandwidthMode === null ||
stickyEventsSupported === null
)
if (muteStates === null || slot === null || stickyEventsSupported === null)
return null;
return (
@@ -232,7 +214,6 @@ export const CallView: FC<Props> = ({
setJoined={setJoined}
muteStates={muteStates}
stickyEventsSupported={stickyEventsSupported}
lowBandwidthMode={lowBandwidthMode}
/>
);
};
@@ -304,7 +285,6 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
muteStates: MuteStates;
/** Whether the homeserver supports sticky events (MSC4354), which Matrix 2.0 needs. */
stickyEventsSupported: boolean;
lowBandwidthMode: LowBandwidthMode;
}
/**
@@ -338,7 +318,6 @@ const LoadedCallView: FC<LoadedProps> = ({
setJoined,
muteStates,
stickyEventsSupported,
lowBandwidthMode,
}) => {
// Used to thread through any errors that occur outside the error boundary
const [externalError, setExternalError] = useState<ElementCallError | null>(
@@ -368,11 +347,6 @@ 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 => {
@@ -650,10 +624,7 @@ const LoadedCallView: FC<LoadedProps> = ({
matrixInfo={matrixInfo}
media={media}
muteStates={muteStates}
onEnter={() => {
lowBandwidthMode.reset();
setJoined(true);
}}
onEnter={() => setJoined(true)}
confineToRoom={confineToRoom}
hideHeader={header !== HeaderStyle.Standard}
participantCount={participantCount}
@@ -684,7 +655,6 @@ const LoadedCallView: FC<LoadedProps> = ({
onLeft={onLeft}
media={media}
muteStates={muteStates}
lowBandwidthMode={lowBandwidthMode}
e2eeSystem={e2eeSystem}
stickyEventsSupported={stickyEventsSupported}
//otelGroupCallMembership={otelGroupCallMembership}
+8 -65
View File
@@ -15,7 +15,7 @@ import {
type MockedFunction,
vi,
} from "vitest";
import { act, render, type RenderResult, screen } from "@testing-library/react";
import { act, render, type RenderResult } from "@testing-library/react";
import { BehaviorSubject, NEVER } from "rxjs";
import { BrowserRouter } from "react-router-dom";
import { TooltipProvider } from "@vector-im/compound-web";
@@ -23,10 +23,6 @@ import userEvent from "@testing-library/user-event";
import { ActiveCall, InCallView, rtcParticipationOptions } from "./InCallView";
import { getUrlParams } from "../UrlParams";
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../state/LowBandwidthMode";
import {
mockConfig,
mockMediaDevices,
@@ -138,25 +134,16 @@ interface CreateInCallViewArgs {
}
function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
vm: CallViewModel;
lowBandwidthMode: LowBandwidthMode;
} {
const mediaDevices = args.mediaDevices ?? mockMediaDevices({});
const muteState = mockMuteStates();
const {
vm,
footerVm,
developerSettingsVm,
lowBandwidthModeVm,
lowBandwidthIndicatorVm,
lowBandwidthMode,
matrixRoom,
client,
} = getBasicCallViewModelEnvironment(
[local, alice],
undefined,
mediaDevices,
args.callViewModelOptions,
);
const { vm, footerVm, developerSettingsVm, matrixRoom, client } =
getBasicCallViewModelEnvironment(
[local, alice],
undefined,
mediaDevices,
args.callViewModelOptions,
);
const inCallView = (
<InCallView
@@ -165,8 +152,6 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
vm={vm}
footerVm={footerVm}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
lowBandwidthIndicatorVm={lowBandwidthIndicatorVm}
matrixInfo={matrixInfo}
matrixRoom={matrixRoom}
onShareClick={null}
@@ -187,7 +172,6 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
return {
...renderResult,
vm,
lowBandwidthMode,
};
}
@@ -199,45 +183,6 @@ 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. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
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("the Low bandwidth mode indicator", () => {
it("shows while the mode is on, and Cancel turns the mode off", async () => {
const user = userEvent.setup();
const { container, lowBandwidthMode } = createInCallView();
const cancel = (): HTMLElement | null =>
screen.queryByRole("button", { name: "Cancel Low bandwidth mode" });
expect(cancel()).toBeNull();
act(() => lowBandwidthMode.setEnabled(true));
const regions = [
...container.querySelectorAll('[aria-live="polite"]'),
].map((region) => region.textContent);
expect(regions).toContain("Low bandwidth mode on");
await user.click(cancel()!);
expect(lowBandwidthMode.enabled$.value).toBe(false);
expect(cancel()).toBeNull();
});
});
describe("audioOutputSwitcher", () => {
it("is visible and can be clicked", async () => {
const user = userEvent.setup();
@@ -304,7 +249,6 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode(testScope())}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
@@ -401,7 +345,6 @@ describe("ActiveCall", () => {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode(testScope())}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
+5 -87
View File
@@ -18,7 +18,7 @@ import {
type ReactNode,
} from "react";
import useMeasure from "react-use-measure";
import { filter, type Observable, skip } from "rxjs";
import { type Observable } from "rxjs";
import classNames from "classnames";
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { useTranslation } from "react-i18next";
@@ -26,10 +26,8 @@ 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 { platform } from "../Platform";
import { observeElementSize$ } from "../utils/elementSize";
import styles from "./InCallView.module.css";
import { GridTile } from "../tile/GridTile";
@@ -43,11 +41,6 @@ import { RageshakeRequestModal } from "./RageshakeRequestModal";
import { useWakeLock } from "../useWakeLock";
import { useMergedRefs } from "../useMergedRefs";
import { type MuteStates } from "../state/MuteStates";
import {
createLowBandwidthSwitchViewModel,
type LowBandwidthMode,
type LowBandwidthSwitchSnapshot,
} from "../state/LowBandwidthMode";
import { type MatrixInfo } from "./VideoPreview";
import { InviteButton } from "../button/InviteButton";
import {
@@ -129,11 +122,6 @@ import { CallFooter, type FooterSnapshot } from "../components/CallFooter.tsx";
import { SettingsIconButton } from "../button/Button.tsx";
import { createCallFooterViewModel } from "../components/CallFooterViewModel.tsx";
import { createDeveloperSettingsTabViewModel } from "../settings/DeveloperSettingsTabViewModel.ts";
import {
LowBandwidthIndicator,
type LowBandwidthIndicatorSnapshot,
} from "../components/LowBandwidthIndicator.tsx";
import { createLowBandwidthIndicatorViewModel } from "../components/LowBandwidthIndicatorViewModel.ts";
import { type DeveloperSettingsSnapshot } from "../settings/DeveloperSettingsTab.tsx";
import { type ViewModel } from "../state/ViewModel.ts";
import { RingingStatus } from "../tile/RingingStatus.tsx";
@@ -148,11 +136,7 @@ declare module "react" {
export interface ActiveCallProps extends Omit<
InCallViewProps,
| "vm"
| "footerVm"
| "developerSettingsVm"
| "lowBandwidthModeVm"
| "lowBandwidthIndicatorVm"
"vm" | "footerVm" | "developerSettingsVm"
> {
client: Pick<
MatrixClient,
@@ -212,7 +196,6 @@ export interface ActiveCallProps extends Omit<
media: LocalMedia;
/** Whether the homeserver supports sticky events (MSC4354), which Matrix 2.0 needs. */
stickyEventsSupported: boolean;
lowBandwidthMode: LowBandwidthMode;
// TODO refactor those reasons into an enum
onLeft: (
reason: "user" | "timeout" | "decline" | "allOthersLeft" | "error",
@@ -226,8 +209,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
);
const [developerSettingsVm, setDeveloperSettingsVm] =
useState<ViewModel<DeveloperSettingsSnapshot> | null>(null);
const [lowBandwidthIndicatorVm, setLowBandwidthIndicatorVm] =
useState<ViewModel<LowBandwidthIndicatorSnapshot> | null>(null);
const urlParams = useUrlParams();
const hostBridge = useHostBridge();
@@ -251,7 +232,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const capture = captureSettings();
const rtcParticipation = props.slot.join({
...rtcParticipationOptions(urlParams, props.stickyEventsSupported),
receiveVideo: !props.lowBandwidthMode.enabled$.value,
// Without a lobby nothing was captured and the join captures itself
publish:
props.media.requests.length > 0
@@ -272,7 +252,6 @@ 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$,
@@ -305,7 +284,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
props.sentCallNotification$,
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -326,7 +304,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
scope,
vm,
props.muteStates,
props.lowBandwidthMode.enabled$,
mediaDevices,
backgroundEffectsState$,
`${props.client.getUserId()}:${props.client.getDeviceId()}`,
@@ -334,14 +311,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
);
setFooterVm(footerVm);
setDeveloperSettingsVm(createDeveloperSettingsTabViewModel(scope, vm));
setLowBandwidthIndicatorVm(
createLowBandwidthIndicatorViewModel(
scope,
props.lowBandwidthMode,
vm.layout$,
{ showControls: urlParams.showControls, platform },
),
);
return (): void => {
scope.end();
@@ -349,7 +318,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
}, [
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -359,15 +327,9 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
vm,
]);
const lowBandwidthModeVm = useMemo(
() => createLowBandwidthSwitchViewModel(props.lowBandwidthMode),
[props.lowBandwidthMode],
);
if (vm === null) return null;
if (footerVm === null) return null;
if (developerSettingsVm === null) return null;
if (lowBandwidthIndicatorVm === null) return null;
return (
<ReactionsSenderProvider
@@ -380,8 +342,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
vm={vm}
footerVm={footerVm}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
lowBandwidthIndicatorVm={lowBandwidthIndicatorVm}
/>
</ReactionsSenderProvider>
);
@@ -392,8 +352,6 @@ export interface InCallViewProps {
vm: CallViewModel;
footerVm: ViewModel<FooterSnapshot>;
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
lowBandwidthModeVm: ViewModel<LowBandwidthSwitchSnapshot>;
lowBandwidthIndicatorVm: ViewModel<LowBandwidthIndicatorSnapshot>;
matrixInfo: MatrixInfo;
matrixRoom: Pick<MatrixRoom, "roomId">;
muteStates: MuteStates;
@@ -405,8 +363,6 @@ export const InCallView: FC<InCallViewProps> = ({
vm,
footerVm,
developerSettingsVm,
lowBandwidthModeVm,
lowBandwidthIndicatorVm,
matrixInfo,
matrixRoom,
muteStates,
@@ -444,26 +400,10 @@ 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 [liveRegion, 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],
);
useEffect(() => {
const subscription = lowBandwidthModeVm.enabled$
.pipe(skip(1), filter(Boolean))
.subscribe(() => announce(t("low_bandwidth_mode.turned_on")));
return (): void => subscription.unsubscribe();
}, [lowBandwidthModeVm, announce, t]);
useCallViewKeyboardShortcuts(
toggleAudio,
cameraUnavailable === "lowBandwidthMode"
? explainCameraUnavailable
: toggleVideo,
toggleVideo,
setAudioEnabled,
(reaction) => void sendReaction(reaction),
() => void toggleRaisedHand(),
@@ -530,29 +470,19 @@ export const InCallView: FC<InCallViewProps> = ({
const [headerRef, headerBounds] = useMeasure();
const [footerRef, footerBounds] = useMeasure();
const [indicatorRef, indicatorBounds] = useMeasure();
const cameraButtonRef = useRef<HTMLButtonElement>(null);
const indicatorShown = useBehavior(lowBandwidthIndicatorVm.shown$);
const indicatorInline = useBehavior(lowBandwidthIndicatorVm.inline$);
// An inline indicator takes its row from the tile
const indicatorHeight =
indicatorShown && indicatorInline ? indicatorBounds.height : 0;
const gridBounds = useMemo(
() => ({
width: bounds.width,
height:
bounds.height -
(edgeToEdge
? 0
: headerBounds.height + footerBounds.height + indicatorHeight),
(edgeToEdge ? 0 : headerBounds.height + footerBounds.height),
}),
[
bounds.width,
bounds.height,
headerBounds.height,
footerBounds.height,
indicatorHeight,
edgeToEdge,
],
);
@@ -849,22 +779,11 @@ export const InCallView: FC<InCallViewProps> = ({
<CallEventAudioRenderer vm={vm} muted={muteAllAudio} />
<ReactionsAudioRenderer vm={vm} muted={muteAllAudio} />
<RingingAudioRenderer vm={ringingVm} muted={muteAllAudio} />
{liveRegion}
{reconnectingToast}
{screenShareToast}
{earpieceOverlay}
<ReactionsOverlay vm={vm} />
<LowBandwidthIndicator
ref={indicatorRef}
vm={lowBandwidthIndicatorVm}
footerHeight={showFooter ? footerBounds.height : null}
focusAfterCancel={cameraButtonRef}
/>
<CallFooter
ref={footerRef}
cameraButtonRef={cameraButtonRef}
vm={footerVm}
/>
<CallFooter ref={footerRef} vm={footerVm} />
{showModals && (
<>
<RageshakeRequestModal {...rageshakeRequestModalProps} />
@@ -876,7 +795,6 @@ export const InCallView: FC<InCallViewProps> = ({
tab={settingsTab}
onTabChange={setSettingsTab}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
transports={connectedTransports.map((transport) => ({
transport,
local: transport === localTransport,
+22 -7
View File
@@ -5,15 +5,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ReactNode, useState, type FC } from "react";
import {
type ReactNode,
useState,
type FC,
type ComponentType,
type SVGAttributes,
} from "react";
import { useTranslation } from "react-i18next";
import { Menu, OptionMenuItem } from "@vector-im/compound-web";
import {
GridIcon,
SpotlightViewIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import {
type LayoutMode,
type LayoutSwitchViewModel,
} from "../state/LayoutSwitchViewModel";
import { useBehavior } from "../useBehavior";
import { useTranslation } from "react-i18next";
import { Menu, RadioMenuItem } from "@vector-im/compound-web";
import { LayoutSwitchButton } from "../button";
interface LayoutSwitchProps {
@@ -27,9 +37,14 @@ export const LayoutSwitch: FC<LayoutSwitchProps> = ({ vm, ...props }) => {
const layout = useBehavior(vm.layout$);
const [open, setOpen] = useState(false);
const menuItem = (label: string, value: LayoutMode): ReactNode => (
<RadioMenuItem
const menuItem = (
value: LayoutMode,
label: string,
Icon: ComponentType<SVGAttributes<SVGElement>>,
): ReactNode => (
<OptionMenuItem
label={label}
Icon={Icon}
checked={layout === value}
onSelect={() => vm.setLayout(value)}
/>
@@ -42,8 +57,8 @@ export const LayoutSwitch: FC<LayoutSwitchProps> = ({ vm, ...props }) => {
onOpenChange={setOpen}
trigger={<LayoutSwitchButton layout={layout} {...props} />}
>
{menuItem(t("layout_grid_label"), "grid")}
{menuItem(t("layout_spotlight_label"), "spotlight")}
{menuItem("grid", t("layout_grid_label"), GridIcon)}
{menuItem("spotlight", t("layout_spotlight_label"), SpotlightViewIcon)}
</Menu>
);
};
@@ -111,10 +111,6 @@ 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; overflow-wrap: normal;"
/>
<div
class="_bg_2f5303 _animate_2f5303"
data-state="closed"
@@ -315,7 +311,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_h_"
aria-labelledby="_r_g_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="md"
@@ -340,7 +336,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-disabled="false"
aria-expanded="false"
aria-haspopup="true"
aria-labelledby="_r_m_"
aria-labelledby="_r_l_"
class="_button_1nw83_8 _raiseHand_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="md"
@@ -366,12 +362,12 @@ exports[`InCallView > rendering > renders 1`] = `
aria-disabled="false"
aria-expanded="false"
aria-haspopup="menu"
aria-labelledby="_r_10_"
aria-labelledby="_r_v_"
class="_button_1nw83_8 _layout_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="md"
data-state="closed"
id="radix-_r_u_"
id="radix-_r_t_"
role="button"
tabindex="0"
type="button"
@@ -390,7 +386,7 @@ exports[`InCallView > rendering > renders 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_15_"
aria-labelledby="_r_14_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="md"
@@ -412,7 +408,7 @@ exports[`InCallView > rendering > renders 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_1a_"
aria-labelledby="_r_19_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="md"
+13 -13
View File
@@ -7,7 +7,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
>
<header>
<button
aria-labelledby="_r_2n_"
aria-labelledby="_r_2k_"
class="_icon-button_1215g_8 _primaryButton_221541"
data-kind="primary"
role="button"
@@ -109,7 +109,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_2t_"
aria-labelledby="_r_2q_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -134,7 +134,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_33_"
aria-labelledby="_r_2v_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -156,7 +156,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_38_"
aria-labelledby="_r_34_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -178,7 +178,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_3d_"
aria-labelledby="_r_39_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -212,7 +212,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
>
<header>
<button
aria-labelledby="_r_3m_"
aria-labelledby="_r_3i_"
class="_icon-button_1215g_8 _primaryButton_221541"
data-kind="primary"
role="button"
@@ -314,7 +314,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_3s_"
aria-labelledby="_r_3o_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -339,7 +339,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_42_"
aria-labelledby="_r_3t_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -361,7 +361,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_47_"
aria-labelledby="_r_42_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -383,7 +383,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_4c_"
aria-labelledby="_r_47_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -695,7 +695,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_c_"
aria-labelledby="_r_b_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -717,7 +717,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_h_"
aria-labelledby="_r_g_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -739,7 +739,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_m_"
aria-labelledby="_r_l_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
-111
View File
@@ -1,111 +0,0 @@
/*
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, fn, userEvent, within } from "storybook/test";
import { type ReactNode } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { SettingsModal } from "./SettingsModal";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
import { constant } from "../state/Behavior";
import { BackgroundEffectsProvider } from "../tracks/BackgroundEffectsContext";
import { type BackgroundEffects } from "../state/BackgroundEffects";
import { useStaticViewModel } from "../state/ViewModel";
const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
});
const backgroundEffects: BackgroundEffects = {
state$: constant({ supported: true, processor: undefined }),
};
const client = {
getUserId: () => "@user:example.org",
getUser: () => null,
} as unknown as MatrixClient;
/** The Video tab, as a call or the lobby opens the settings. */
function VideoTabStoryWrapper({
inCall,
enabled,
setEnabled,
}: {
/** Whether the settings were opened from a call, rather than the lobby. */
inCall: boolean;
enabled: boolean;
setEnabled: (enabled: boolean) => void;
}): ReactNode {
const lowBandwidthModeVm = useStaticViewModel({ enabled, setEnabled });
return (
<MediaDevicesContext value={mediaDevices}>
<BackgroundEffectsProvider effects={backgroundEffects}>
<SettingsModal
open
onDismiss={fn()}
tab="video"
onTabChange={fn()}
client={client}
lowBandwidthModeVm={inCall ? lowBandwidthModeVm : undefined}
/>
</BackgroundEffectsProvider>
</MediaDevicesContext>
);
}
const meta = {
title: "settings/SettingsModal/Video tab",
component: VideoTabStoryWrapper,
args: { inCall: true, enabled: false, setEnabled: fn() },
parameters: { layout: "fullscreen" },
} satisfies Meta<typeof VideoTabStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
const lowBandwidthSwitch = (canvasElement: HTMLElement): HTMLElement =>
within(canvasElement.ownerDocument.body).getByRole("checkbox", {
name: "Low bandwidth mode",
});
export const InCallLowBandwidthModeOff: Story = {
play: async ({ args, canvasElement }) => {
const toggle = lowBandwidthSwitch(canvasElement);
await expect(toggle).not.toBeChecked();
await userEvent.click(toggle);
await expect(args.setEnabled).toHaveBeenCalledWith(true);
},
};
export const InCallLowBandwidthModeOn: Story = {
args: { enabled: true },
play: async ({ args, canvasElement }) => {
const toggle = lowBandwidthSwitch(canvasElement);
await expect(toggle).toBeChecked();
await userEvent.click(toggle);
await expect(args.setEnabled).toHaveBeenCalledWith(false);
},
};
export const InCallMobile: Story = {
globals: { viewport: { value: "mobile2" } },
play: async ({ canvasElement }) => {
await expect(lowBandwidthSwitch(canvasElement)).toBeInTheDocument();
},
};
export const Lobby: Story = {
args: { inCall: false },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement.ownerDocument.body).queryByRole("checkbox", {
name: "Low bandwidth mode",
}),
).toBeNull();
},
};
+1 -32
View File
@@ -18,8 +18,6 @@ import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import { mockMediaDevices } from "../utils/test";
import { constant } from "../state/Behavior";
import { type MediaDevices } from "../state/MediaDevices";
import { type LowBandwidthSwitchSnapshot } from "../state/LowBandwidthMode";
import { createStaticViewModel, type ViewModel } from "../state/ViewModel";
vi.mock("../tracks/BackgroundEffectsContext", () => ({
useBackgroundEffects: (): BackgroundEffectsState => ({
@@ -35,9 +33,7 @@ const noDevices = {
select: vi.fn(),
};
function renderVideoTab(
lowBandwidthModeVm?: ViewModel<LowBandwidthSwitchSnapshot>,
): void {
function renderVideoTab(): void {
render(
<TooltipProvider>
<MediaDevicesContext
@@ -59,7 +55,6 @@ function renderVideoTab(
getUser: () => null,
} as unknown as MatrixClient
}
lowBandwidthModeVm={lowBandwidthModeVm}
/>
</MediaDevicesContext>
</TooltipProvider>,
@@ -95,30 +90,4 @@ describe("SettingsModal", () => {
await user.click(blurControl());
expect(backgroundEffect.getValue()).toBe("blur");
});
it("has the Low bandwidth mode switch in a call", async () => {
const user = userEvent.setup();
const setEnabled = vi.fn();
renderVideoTab(
createStaticViewModel<LowBandwidthSwitchSnapshot>({
enabled: false,
setEnabled,
}),
);
const toggle = screen.getByRole("checkbox", { name: "Low bandwidth mode" });
expect(toggle).not.toBeChecked();
expect(toggle).toHaveAccessibleDescription(
"Turn off cameras and lower screen-share quality to save data. Lasts until the call ends.",
);
await user.click(toggle);
expect(setEnabled).toHaveBeenCalledWith(true);
});
it("has no Low bandwidth mode switch outside a call", () => {
renderVideoTab();
expect(
screen.queryByRole("checkbox", { name: "Low bandwidth mode" }),
).toBeNull();
});
});
-32
View File
@@ -42,7 +42,6 @@ import { useSubmitRageshake } from "./submit-rageshake";
import { useUrlParams } from "../UrlParams";
import { useBehavior } from "../useBehavior";
import { type ViewModel } from "../state/ViewModel.ts";
import { type LowBandwidthSwitchSnapshot } from "../state/LowBandwidthMode";
import { outOfCallDeveloperSettingsTabViewModel } from "./DeveloperSettingsTabViewModel";
type SettingsTab =
@@ -84,8 +83,6 @@ interface Props {
transports?: TransportInfo[];
/** Only available while in a call. Used by the developer tab. */
developerSettingsVm?: ViewModel<DeveloperSettingsSnapshot>;
/** The call's Low bandwidth mode switch: in a call only, never in the lobby. */
lowBandwidthModeVm?: ViewModel<LowBandwidthSwitchSnapshot>;
}
export const defaultSettingsTab: SettingsTab = "audio";
@@ -99,7 +96,6 @@ export const SettingsModal: FC<Props> = ({
roomId,
transports,
developerSettingsVm,
lowBandwidthModeVm,
}) => {
const { t } = useTranslation();
@@ -228,9 +224,6 @@ export const SettingsModal: FC<Props> = ({
</Form>
<Separator />
<BlurCheckbox />
{lowBandwidthModeVm && (
<LowBandwidthModeSwitch vm={lowBandwidthModeVm} />
)}
</>
),
};
@@ -295,28 +288,3 @@ export const SettingsModal: FC<Props> = ({
</Modal>
);
};
function LowBandwidthModeSwitch({
vm,
}: {
vm: ViewModel<LowBandwidthSwitchSnapshot>;
}): ReactNode {
const { t } = useTranslation();
const enabled = useBehavior(vm.enabled$);
const setEnabled = useBehavior(vm.setEnabled$);
return (
<>
<Separator />
<FieldRow>
<InputField
id="lowBandwidthMode"
type="checkbox"
label={t("low_bandwidth_mode.switch_label")}
description={t("low_bandwidth_mode.switch_description")}
checked={enabled}
onChange={(event): void => setEnabled(event.target.checked)}
/>
</FieldRow>
</>
);
}
@@ -75,10 +75,6 @@ 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();
@@ -1901,160 +1897,3 @@ 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("shows a remote screen share as usual 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),
});
expectObservable(
spotlightMedia$(vm.layout$, `${aliceId}:0:screen-share`).pipe(
switchMap(
(share) =>
(share as RemoteScreenShareViewModel | undefined)
?.videoEnabled$ ?? NEVER,
),
distinctUntilChanged(),
),
).toBe("y", onOff);
},
);
});
});
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)),
);
}
});
-23
View File
@@ -82,7 +82,6 @@ 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,
@@ -208,8 +207,6 @@ 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
@@ -504,7 +501,6 @@ export function createCallViewModel$(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem,
viewSize$,
handsRaisedSubject$,
@@ -652,10 +648,6 @@ export function createCallViewModel$(
});
});
lowBandwidthMode.enabled$
.pipe(scope.bind())
.subscribe((enabled) => rtcParticipation.setReceiveVideo(!enabled));
const members$ = scope.behavior<(LocalRTCMember | RemoteRTCMember)[]>(
combineLatest(
[rtcParticipation.localMember$, rtcParticipation.remoteMembers$],
@@ -753,7 +745,6 @@ export function createCallViewModel$(
),
mediaDevices,
pretendToBeDisconnected$: reconnecting$,
videoPaused$: lowBandwidthMode.enabled$,
displayName$: member.displayName$,
mxcAvatarUrl$: member.avatarUrl$,
handRaised$: scope.behavior(
@@ -1538,19 +1529,6 @@ 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.
@@ -1560,7 +1538,6 @@ export function createCallViewModel$(
? null
: (): void => {
const track = screenShare$.value;
if (track === undefined && lowBandwidthMode.enabled$.value) return;
(track === undefined
? rtcParticipation.publish({
source: "screenShare",
@@ -6,10 +6,6 @@ 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,
@@ -99,7 +95,6 @@ export interface CallViewModelInputs {
mediaDevices: MediaDevices;
initialSyncState: SyncState;
viewSize$: Behavior<{ width: number; height: number }>;
lowBandwidthMode: LowBandwidthMode;
}
export const localParticipant: Participant = { identity: "" };
@@ -126,7 +121,6 @@ export function withCallViewModel(mode: MatrixRTCMode) {
mediaDevices = mockMediaDevices({}),
initialSyncState = SyncState.Syncing,
viewSize$ = constant({ width: 1000, height: 800 }),
lowBandwidthMode = createLowBandwidthMode(testScope()),
}: Partial<CallViewModelInputs> = {},
continuation: (
vm: CallViewModel,
@@ -296,7 +290,6 @@ export function withCallViewModel(mode: MatrixRTCMode) {
client: room.client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$,
handsRaisedSubject$: raisedHands$,
-242
View File
@@ -1,242 +0,0 @@
/*
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,
createLowBandwidthSwitchViewModel,
} 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("restores the camera when turned off through its switch", async () => {
const { mode, muteStates, handler } = await callWithCamera(true);
const vm = createLowBandwidthSwitchViewModel(mode);
vm.setEnabled$.value(true);
await flushPromises();
expect(vm.enabled$.value).toBe(true);
expect(muteStates.video.enabled$.value).toBe(false);
vm.setEnabled$.value(false);
await flushPromises();
expect(vm.enabled$.value).toBe(false);
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 };
}
-84
View File
@@ -1,84 +0,0 @@
/*
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, constant } from "./Behavior";
import { type MuteStates } from "./MuteStates";
import { type ObservableScope } from "./ObservableScope";
import { type ViewModel } from "./ViewModel";
/**
* 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, for the switch and the indicator alike. */
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);
},
};
}
/** The switch in the settings of a call. */
export interface LowBandwidthSwitchSnapshot {
enabled: boolean;
setEnabled: (enabled: boolean) => void;
}
export function createLowBandwidthSwitchViewModel(
lowBandwidthMode: LowBandwidthMode,
): ViewModel<LowBandwidthSwitchSnapshot> {
return {
enabled$: lowBandwidthMode.enabled$,
setEnabled$: constant(lowBandwidthMode.setEnabled),
};
}
-124
View File
@@ -461,128 +461,4 @@ 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 };
}
});
});
+2 -35
View File
@@ -18,7 +18,6 @@ import {
of,
Subject,
switchMap,
tap,
withLatestFrom,
} from "rxjs";
@@ -56,14 +55,6 @@ 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$,
@@ -103,7 +94,6 @@ 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;
@@ -114,9 +104,7 @@ 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))).pipe(
tap((desired) => this.chosen.next(desired)),
);
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled)));
const enabled$ = new Observable<boolean>((subscriber) => {
subscriber.next(enabled);
let latestDesired = initialWanted;
@@ -222,11 +210,6 @@ 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,
@@ -237,20 +220,9 @@ export class MuteStates {
this.scope,
this.mediaDevices.videoInput,
this.initialMuteState.videoEnabled,
combineLatest(
[this.isEarpiece$, this.videoHeld$],
(earpiece, held) => earpiece || held,
),
this.isEarpiece$,
);
/**
* 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,
@@ -301,11 +273,6 @@ 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);
});
+4 -6
View File
@@ -33,13 +33,11 @@ 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$, videoPaused$, ...inputs }: RemoteUserMediaInputs,
{ pretendToBeDisconnected$, ...inputs }: RemoteUserMediaInputs,
): RemoteUserMediaViewModel {
const baseUserMedia = createBaseUserMedia(scope, inputs);
@@ -75,9 +73,9 @@ export function createRemoteUserMedia(
),
),
videoEnabled$: scope.behavior(
combineLatest([pretendToBeDisconnected$, videoPaused$]).pipe(
switchMap(([disconnected, paused]) =>
disconnected || paused ? of(false) : baseUserMedia.videoEnabled$,
pretendToBeDisconnected$.pipe(
switchMap((disconnected) =>
disconnected ? of(false) : baseUserMedia.videoEnabled$,
),
),
),
@@ -90,7 +90,6 @@ export function createWrappedUserMedia(
member,
mediaDevices,
pretendToBeDisconnected$,
videoPaused$,
...inputs
}: WrappedUserMediaInputs,
): WrappedUserMediaViewModel {
@@ -99,7 +98,6 @@ export function createWrappedUserMedia(
: createRemoteUserMedia(scope, {
member,
pretendToBeDisconnected$,
videoPaused$,
...inputs,
});
-1
View File
@@ -359,7 +359,6 @@ const ScreenShareVolumeButton: FC<ScreenShareVolumeButtonProps> = ({ vm }) => {
className={styles.volumeMenuItem}
onSelect={null}
label={null}
hideChevron={true}
>
<button className={styles.menuMuteButton} onClick={onMuteButtonClick}>
<VolumeIcon aria-hidden width={24} height={24} />
-24
View File
@@ -1,24 +0,0 @@
/*
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];
}
-19
View File
@@ -19,7 +19,6 @@ import {
} from "vitest";
import { useTheme } from "./useTheme";
import { PortalElementProvider } from "./RootElementContext";
import { platform } from "./Platform";
import { useUrlParams } from "./UrlParams";
import {
@@ -104,24 +103,6 @@ describe("useTheme", () => {
expect(document.body.getAttribute("data-platform")).toBe(platform);
});
test("gives the portal container the theme and platform too", () => {
const portal = document.createElement("div");
const withPortal: FC<PropsWithChildren> = ({ children }) =>
createElement(
wrapper,
null,
createElement(PortalElementProvider, { value: portal }, children),
);
renderHook(() => useTheme(), { wrapper: withPortal });
expect(portal.classList.contains("cpd-theme-dark")).toBe(true);
expect(portal.getAttribute("data-platform")).toBe(platform);
act(() => themeChange$.next({ data: { name: "light" }, reply: vi.fn() }));
expect(portal.classList.contains("cpd-theme-dark")).toBe(false);
expect(portal.classList.contains("cpd-theme-light")).toBe(true);
});
test("theme changes in response to host requests", () => {
renderHook(() => useTheme(), { wrapper });
+8 -19
View File
@@ -8,13 +8,12 @@ Please see LICENSE in the repository root for full details.
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useUrlParams } from "./UrlParams";
import { usePortalElement, useRootElement } from "./RootElementContext";
import { useRootElement } from "./RootElementContext";
import { platform } from "./Platform";
import { useHostBridge } from "./HostBridge";
export const useTheme = (): void => {
const rootElement = useRootElement();
const portalElement = usePortalElement();
const hostBridge = useHostBridge();
const { theme } = useUrlParams();
const [requestedTheme, setRequestedTheme] = useState(theme);
@@ -38,14 +37,13 @@ export const useTheme = (): void => {
rootElement.setAttribute("data-platform", platform);
}, [rootElement]);
// If no theme has been explicitly requested we default to dark
const lightness = requestedTheme?.includes("light") ? "light" : "dark";
const themeHighContrast = requestedTheme?.includes("high-contrast")
? "-hc"
: "";
const themeString = "cpd-theme-" + lightness + themeHighContrast;
useLayoutEffect(() => {
// If no theme has been explicitly requested we default to dark
const theme = requestedTheme?.includes("light") ? "light" : "dark";
const themeHighContrast = requestedTheme?.includes("high-contrast")
? "-hc"
: "";
const themeString = "cpd-theme-" + theme + themeHighContrast;
if (themeString !== previousTheme.current) {
rootElement.classList.remove(
"cpd-theme-light",
@@ -57,14 +55,5 @@ export const useTheme = (): void => {
previousTheme.current = themeString;
}
rootElement.classList.remove("no-theme");
}, [previousTheme, themeString, rootElement]);
// The menus and tooltips floating outside the root get its theme and
// platform too, so that they look as they would inside it.
useLayoutEffect(() => {
if (portalElement === null) return;
portalElement.setAttribute("data-platform", platform);
portalElement.classList.add(themeString);
return (): void => portalElement.classList.remove(themeString);
}, [portalElement, themeString]);
}, [previousTheme, requestedTheme, rootElement]);
};
-22
View File
@@ -5,12 +5,6 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
createLowBandwidthMode,
createLowBandwidthSwitchViewModel,
type LowBandwidthMode,
type LowBandwidthSwitchSnapshot,
} from "../state/LowBandwidthMode";
import { type CallMembership } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject } from "rxjs";
import { vitest } from "vitest";
@@ -54,8 +48,6 @@ import { HeaderStyle } from "../UrlParams";
import { type FooterSnapshot } from "../components/CallFooter";
import { type ViewModel } from "../state/ViewModel";
import { createDeveloperSettingsTabViewModel } from "../settings/DeveloperSettingsTabViewModel";
import { createLowBandwidthIndicatorViewModel } from "../components/LowBandwidthIndicatorViewModel";
import { type LowBandwidthIndicatorSnapshot } from "../components/LowBandwidthIndicator";
import { type DeveloperSettingsSnapshot } from "../settings/DeveloperSettingsTab";
mockConfig({ livekit: { livekit_service_url: "https://example.com" } });
@@ -179,9 +171,6 @@ export function getBasicCallViewModelEnvironment(
vm: CallViewModel;
footerVm: ViewModel<FooterSnapshot>;
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
lowBandwidthModeVm: ViewModel<LowBandwidthSwitchSnapshot>;
lowBandwidthIndicatorVm: ViewModel<LowBandwidthIndicatorSnapshot>;
lowBandwidthMode: LowBandwidthMode;
rtcMemberships$: BehaviorSubject<CallMembership[]>;
rtcSession: MockRTCSession;
matrixRoom: Room;
@@ -232,7 +221,6 @@ export function getBasicCallViewModelEnvironment(
),
),
});
const lowBandwidthMode = createLowBandwidthMode(scope);
const vm = createCallViewModel$(
scope,
{
@@ -241,7 +229,6 @@ export function getBasicCallViewModelEnvironment(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$: constant({ width: 1000, height: 800 }),
handsRaisedSubject$: handRaisedSubject$,
@@ -259,7 +246,6 @@ export function getBasicCallViewModelEnvironment(
testScope(),
vm,
muteStates,
lowBandwidthMode.enabled$,
mediaDevices,
constant({ supported: false, processor: undefined }),
"reactionId",
@@ -269,14 +255,6 @@ export function getBasicCallViewModelEnvironment(
vm,
footerVm,
developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm),
lowBandwidthModeVm: createLowBandwidthSwitchViewModel(lowBandwidthMode),
lowBandwidthIndicatorVm: createLowBandwidthIndicatorViewModel(
testScope(),
lowBandwidthMode,
vm.layout$,
{ showControls: true, platform: "desktop" },
),
lowBandwidthMode,
rtcMemberships$,
rtcSession,
matrixRoom,
+1 -8
View File
@@ -406,12 +406,7 @@ 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,
videoPaused$ = constant(false),
}: { transport?: Transport; videoPaused$?: Behavior<boolean> } = {
transport: exampleTransport,
},
{ transport }: { transport?: Transport } = { transport: exampleTransport },
): RemoteUserMediaViewModel {
const member = mockMatrixRoomMember(rtcMember, roomMember);
return createRemoteUserMedia(testScope(), {
@@ -427,7 +422,6 @@ 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),
@@ -580,7 +574,6 @@ function mockSlotWithParticipation(
keyRotationSuppressed$,
connectedTransports$,
setAudioOutputDeviceId: vi.fn(async () => Promise.resolve()),
setReceiveVideo: vi.fn(),
sendData: vi.fn(async () => Promise.resolve()),
data$: NEVER,
};
+35 -15
View File
@@ -6,11 +6,16 @@ Please see LICENSE in the repository root for full details.
*/
import { describe, expect, vi, it, beforeEach } from "vitest";
import { createRoomWidgetClient } from "matrix-js-sdk";
import {
createRoomWidgetClient,
EventType,
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
} from "matrix-js-sdk";
import { getUrlParams } from "./UrlParams";
import { initializeWidget } from "./widget";
import { Config } from "./config/Config";
import { ElementCallReactionEventType } from "./reactions";
vi.mock("matrix-js-sdk", { spy: true });
const createRoomWidgetClientSpy = vi.mocked(createRoomWidgetClient);
@@ -54,17 +59,23 @@ describe("widget", () => {
});
expect(widget).toBeDefined();
expect(configInitSpy).toHaveBeenCalled();
const sendEvent = ["org.matrix.msc4075.rtc.notification"];
const receiveEvent = ["org.matrix.msc4310.rtc.decline"];
const sendEvent = [
EventType.CallNotify, // Sent as a deprecated fallback
EventType.RTCNotification,
];
const sendRecvEvent = [
"org.matrix.rageshake_request",
"m.reaction",
"m.room.redaction",
"io.element.call.reaction",
EventType.CallEncryptionKeysPrefix,
EventType.Reaction,
EventType.RoomRedaction,
ElementCallReactionEventType,
EventType.RTCDecline,
EventType.RTCMembership,
"m.rtc.member",
];
const sendState = [
{ eventType: "org.matrix.msc3401.call.member", stateKey: "myYser" }, // Legacy call membership events
{
eventType: "org.matrix.msc3401.call.member",
stateKey: `_myYser_AAAAA_ANYRTCAPP`,
@@ -75,23 +86,32 @@ describe("widget", () => {
}, // The above with no leading underscore, for room versions whose auth rules allow it
];
const receiveState = [
{ eventType: "m.room.create" },
{ eventType: "m.room.name" },
{ eventType: "m.room.member" },
{ eventType: "m.room.encryption" },
{ eventType: "io.element.functional_members" },
{ eventType: "org.matrix.msc3401.call.member" },
{ eventType: "org.matrix.msc4143.rtc.slot" },
{ eventType: EventType.RoomCreate },
{ eventType: EventType.RoomName },
{ eventType: EventType.RoomMember },
{ eventType: EventType.RoomEncryption },
{ eventType: UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name },
{ eventType: EventType.GroupCallMemberPrefix },
];
const sendRecvToDevice = [
"io.element.call.encryption_keys",
EventType.CallInvite,
EventType.CallCandidates,
EventType.CallAnswer,
EventType.CallHangup,
EventType.CallReject,
EventType.CallSelectAnswer,
EventType.CallNegotiate,
EventType.CallSDPStreamMetadataChanged,
EventType.CallSDPStreamMetadataChangedPrefix,
EventType.CallReplaces,
EventType.CallEncryptionKeysPrefix,
"m.rtc.encryption_key",
];
expect(createRoomWidgetClientSpy.mock.calls[0][1]).toStrictEqual({
sendEvent: [...sendEvent, ...sendRecvEvent],
receiveEvent: [...receiveEvent, ...sendRecvEvent],
receiveEvent: sendRecvEvent,
sendState,
receiveState,
sendToDevice: sendRecvToDevice,
+23 -9
View File
@@ -68,7 +68,7 @@ export interface WidgetHelpers {
* @returns A point of access to the widget API, or null if Element Call is not
* running as a widget.
*/
// this needs to be a separate call and cannot be done on import to allow us to spy on methods in here before
// this needs to be a seperate call and cannot be done on import to allow us to spy on methods in here before
// execution.
export const initializeWidget = (
rtcApplication: string = "m.call",
@@ -118,21 +118,26 @@ export const initializeWidget = (
// request, and is responsible for starting the transport (should it be?)
// These are all the event types the app uses
const sendEvent = [EventType.RTCNotification];
const sendEvent = [
EventType.CallNotify, // Sent as a deprecated fallback
EventType.RTCNotification,
];
if (sendRoomEvents) {
sendEvent.push(EventType.RoomMessage);
}
// Declines are sent by the host (the ringing client), we only watch for them
const receiveEvent = [EventType.RTCDecline];
const sendRecvEvent = [
"org.matrix.rageshake_request",
EventType.CallEncryptionKeysPrefix,
EventType.Reaction,
EventType.RoomRedaction,
ElementCallReactionEventType,
EventType.RTCMembershipStable, // Sticky membership events
EventType.RTCDecline,
EventType.RTCMembership,
"m.rtc.member",
];
const sendState = [
userId, // Legacy call membership events
`_${userId}_${deviceId}_${rtcApplication}`, // Session membership events
`${userId}_${deviceId}_${rtcApplication}`, // The above with no leading underscore, for room versions whose auth rules allow it
].map((stateKey) => ({
@@ -146,19 +151,28 @@ export const initializeWidget = (
{ eventType: EventType.RoomEncryption },
{ eventType: UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name },
{ eventType: EventType.GroupCallMemberPrefix },
{ eventType: EventType.RTCSlot }, // Whether the slot is open or closed
];
const sendRecvToDevice = [
EventType.CallEncryptionKeysPrefix, // For members that only understand the legacy key event
EventType.RTCEncryptionKey,
EventType.CallInvite,
EventType.CallCandidates,
EventType.CallAnswer,
EventType.CallHangup,
EventType.CallReject,
EventType.CallSelectAnswer,
EventType.CallNegotiate,
EventType.CallSDPStreamMetadataChanged,
EventType.CallSDPStreamMetadataChangedPrefix,
EventType.CallReplaces,
EventType.CallEncryptionKeysPrefix,
"m.rtc.encryption_key",
];
const client = createRoomWidgetClient(
api,
{
sendEvent: [...sendEvent, ...sendRecvEvent],
receiveEvent: [...receiveEvent, ...sendRecvEvent],
receiveEvent: sendRecvEvent,
sendState,
receiveState,
sendToDevice: sendRecvToDevice,
+11 -12
View File
@@ -114,7 +114,6 @@ async function loadConfig(): Promise<WidgetConfig> {
function connectWidget(
params: URLSearchParams,
application: string,
slotId: string,
): { api: WidgetApi; client: MatrixClient; roomId: string } {
const required = (name: string): string => {
const value = params.get(name);
@@ -132,29 +131,29 @@ function connectWidget(
api.requestCapability(MatrixCapabilities.AlwaysOnScreen);
const sendRecvEvent = [
EventType.RTCMembershipStable, // Sticky membership events
EventType.CallEncryptionKeysPrefix,
EventType.RTCDecline,
EventType.RTCMembership,
"m.rtc.member",
];
const sendRecvToDevice = [
EventType.CallEncryptionKeysPrefix, // For members that only understand the legacy key event
EventType.RTCEncryptionKey,
EventType.CallEncryptionKeysPrefix,
"m.rtc.encryption_key",
];
// The js-sdk drops the slot id from the state key of the default call slot
const stateKeySlot =
application === "m.call" && slotId === "ROOM"
? application
: `${application}${slotId}`;
const client = createRoomWidgetClient(
api,
{
sendEvent: [
...sendRecvEvent,
EventType.CallNotify, // Sent as a deprecated fallback
EventType.RTCNotification,
EventType.RoomMessage, // For sendRoomMessage
],
receiveEvent: sendRecvEvent,
sendState: [
`_${userId}_${deviceId}_${stateKeySlot}`, // Session membership events
`${userId}_${deviceId}_${stateKeySlot}`, // The above with no leading underscore, for room versions whose auth rules allow it
userId, // Legacy call membership events
`_${userId}_${deviceId}_${application}`, // Session membership events
`${userId}_${deviceId}_${application}`, // The above with no leading underscore, for room versions whose auth rules allow it
].map((stateKey) => ({
eventType: EventType.GroupCallMemberPrefix,
stateKey,
@@ -192,7 +191,7 @@ export async function createMatrixRTCSdk(
): Promise<MatrixRTCSdk> {
const logger = rootLogger.getChild("[MatrixRTCSdk]");
const params = widgetParams();
const { api, client, roomId } = connectWidget(params, application, id);
const { api, client, roomId } = connectWidget(params, application);
const config = await loadConfig();
await client.startClient();
const room = client.getRoom(roomId);