Compare commits

..
Author SHA1 Message Date
Timo K. 597812fbeb remaining client and SuppliadClient seperation
SuppliedClient is the subset (Pick) of a client which we need as the
CallView backend.
2026-11-30 17:42:22 +01:00
Timo K. a217e9b461 merge cleanup 2026-11-30 15:49:24 +01:00
Timo K. 3bce06b81e Merge branch 'main' into toger5/refactor-clientSession 2026-11-30 15:16:47 +01:00
Timo K. 805f64aec5 refactor disconnectedBanner to use a custom context + app view model
logic.
2026-11-23 15:59:44 +01:00
Timo K. 74ff32e818 rename factory methods that return behaviors 2026-11-23 15:43:23 +01:00
Timo K. 9301043ef5 make clientState an implicit behavior (not a subject that can race) 2026-11-23 15:32:39 +01:00
Timo K. 23a8d559e9 Add warn log to logout no case. 2026-11-23 14:08:00 +01:00
Timo K. c096332c8f convert StandaloneClientSession into factor fn instead of class. 2026-11-23 13:53:10 +01:00
TimoandRobin 121137dd29 Update src/ClientContext.tsx
Co-authored-by: Robin <robin@robin.town>
2026-11-23 13:47:14 +01:00
Timo K. 0cf3c459e6 Pass the client manager as a prop instead of through context 2026-11-23 13:45:24 +01:00
Timo K. 1c82da2693 review: useClient return MatrixClient | undefined (instead of obj) 2026-11-23 13:35:06 +01:00
Timo K. cbbe450acf review comments 2026-11-23 13:34:43 +01:00
Timo K. 80ca4d7e0f Add basic tests for refactored files 2026-11-12 17:47:27 +01:00
Timo K. a2e3a2c13f review 2026-11-12 13:25:45 +01:00
Timo K. 8d5d482771 Remove the derived hooks from ClientContext
Those were hooks just used in one place. We move them directly into
their component.
This is acceptable because the disconnect banner needs a new appraoch
when not having a syncing clinet but just a matrixBackend.
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 87f2726dd8 Hand the client provider a session
ClientProvider had a `client` prop and a `loadClient` prop and ran the
session in an effect: restoring, exposing setClient, changePassword and
logout, and holding the "load" broadcast. It takes one `ClientSession`
now and only renders what the session says, so the context carries the
session itself rather than a parallel `ClientState` shape.

- main.tsx builds a `StandaloneClientSession` for the SPA and a
  `pendingHostClientSession` for the widget; App.tsx no longer waits for
  the widget client itself. The component wraps the host's client in a
  `hostClientSession`.
- The login and registration pages call `session.login` and
  `session.register`, and sign a registration in with `setSignedIn` once
  they are done with the account, in place of `setClient`. The two
  wrapper hooks and `utils/spa` go; their logic lives in the holder.
- `useClient` and `useClientLegacy` keep their shapes minus `setClient`;
  `useClientSession` and `useClientSessionState` are the new way in.
  Logging out leaves for home and resets analytics from `useClientLegacy`,
  as before, around the session's own logout.
- `useClientDisconnected` reads the session state directly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 5fb9d6a81e Add a client session holder for the standalone app
Where the client comes from, and what may be done with the session
behind it, is state that outlives any React tree: main.tsx, the widget
and the component each need to construct a different one and hand it
down. `ClientSession` names that: a Behavior of the session state plus
the actions a session offers, which are absent when the session is not
Element Call's to manage. `hostClientSession` wraps a client a host
already has, `pendingHostClientSession` one still arriving over the
widget API.

`StandaloneClientSession` is the one for the SPA. Nothing in it is new
logic: `restore` is `initSPA` from `utils/spa`; `login`, `register` and
`createClient` are the tails of `useInteractiveLogin` and
`useInteractiveRegistration` after the auth split; `changePassword`,
`logout` and the "load" broadcast that shuts other instances down are
lifted out of `ClientProvider`. Registering and signing in are separate
steps, as a caller may have more to do with the account before the
session changes hands. `StoredSession` is `Session` from the context,
which goes once the provider takes a session.

Nothing consumes the holder yet; the next commit switches the provider
over. Both are tested through every state here, while the code they
replace is still around to compare against.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 ba6bcdc4eb Separate interactive auth from client creation
The login and registration hooks each did three things: talk the
user-interactive auth flow through with the homeserver, start a client
on the credentials it handed out, and, for registration, fetch the terms
and recaptcha key. Only the first is auth.

`interactiveAuth.ts` keeps that part as two plain functions, with the UIA
bodies moved verbatim, so they can be unit tested without React or a
client store: `loginWithPassword` and `registerWithPassword` resolve to
the credentials the homeserver issued and nothing else. Fetching the
terms is `useRegistrationTerms` now. The two hooks are left as thin
wrappers that compose the pieces, with the same signatures, so their
callers do not change in this commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 56d73d1dfc Track the client's connection in a hook of its own
Whether the client is disconnected is a fact about the client's sync, not
about the session, yet the provider owned the sync listener and put the
flag on the context state, so the banner had to reach through the whole
`ClientState` to read it. `useClientDisconnected` listens on whichever
client is signed in, tagging its verdict with that client so a swapped
client does not inherit the old one's before its first sync.

The avatar, which only needs the client, takes it from `useClient` in the
same spirit: consumers read the narrowest hook that answers them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 89ad1ec936 Read reaction support from the host bridge
The client context copied `hostBridge.supportsReactions` into a
`supportedFeatures` field, and the one consumer, the reactions sender,
read it from there. It reads the host bridge itself now, which is where
the fact comes from; the context carries one thing less that has nothing
to do with the client.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 b9a3cc6678 Reword the store worker comments
Shorter notes on why `initClient` has a module of its own and why
`utils/matrix` must not import a client store; the reasoning is the same.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
129 changed files with 4299 additions and 3392 deletions
+10 -2
View File
@@ -1,14 +1,22 @@
name: Prevent blocked
on:
pull_request:
# zizmor: ignore[dangerous-triggers]
# Reason: This workflow does not checkout code or use secrets.
# It only reads labels to set a failure status on the PR.
pull_request_target:
types: [opened, labeled, unlabeled, synchronize]
permissions: {}
permissions:
pull-requests: read
# Required to fail the check on the PR
statuses: write
jobs:
prevent-blocked:
name: Prevent blocked
runs-on: ubuntu-24.04
permissions:
pull-requests: read
steps:
- name: Add notice
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
+7 -2
View File
@@ -1,10 +1,15 @@
name: PR changelog label
on:
pull_request:
# zizmor: ignore[dangerous-triggers]
# This is safe because we do not use actions/checkout or execute untrusted code.
# Using pull_request_target is necessary to allow status writes for PRs from forks.
pull_request_target:
types: [labeled, unlabeled, opened, synchronize]
permissions: {}
permissions:
pull-requests: read
statuses: write
jobs:
pr-changelog-label:
+1 -4
View File
@@ -14,8 +14,6 @@ jobs:
# Only run on labelling and skip forks.
if: github.event.label.name == 'Claude-Review' && github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-24.04
# The turn limit below is generous, so bound the job by time instead.
timeout-minutes: 30
steps:
- name: Checkout code
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
@@ -100,8 +98,7 @@ jobs:
Use Markdown links for anything that can be navigated to on GitHub such
as files, commits, issues, pull requests, workflow runs, etc.
# Set a generous turn limit. It's bounded by timeout-minutes above.
claude_args: |
--model claude-fable-5-1
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(git log:*),Bash(git diff:*),Bash(git show:*)"
--max-turns 150
--max-turns 50
@@ -156,9 +156,7 @@ jobs:
publish_android:
needs: [build_element_call, versioning]
# Release candidates are not published to Maven Central: the organisation's Central account
# has a monthly release quota, and Element X Android (the only consumer) ships final releases.
if: always() && needs.versioning.outputs.TAG != 'rc'
if: always()
name: Publish Android AAR
runs-on: ubuntu-24.04
outputs:
@@ -190,6 +188,8 @@ jobs:
run: |
if [[ "${NEEDS_VERSIONING_OUTPUTS_TAG}" == "latest" ]]; then
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}" >> "$GITHUB_ENV"
elif [[ "${NEEDS_VERSIONING_OUTPUTS_TAG}" == "rc" ]]; then
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}" >> "$GITHUB_ENV"
else
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}-SNAPSHOT" >> "$GITHUB_ENV"
fi
@@ -338,7 +338,11 @@ jobs:
### Android AAR
${{ needs.publish_android.outputs.ARTIFACT_VERSION && format('`implementation ''io.element.android:element-call-embedded:{0}''`', needs.publish_android.outputs.ARTIFACT_VERSION) || 'Not published: release candidates do not go to Maven Central.' }}
```
dependencies {
implementation 'io.element.android:element-call-embedded:${{ needs.publish_android.outputs.ARTIFACT_VERSION }}'
}
```
### SwiftPM
+1 -1
View File
@@ -1 +1 @@
26
24
Binary file not shown.
+5
View File
@@ -26,6 +26,10 @@ vi.mock("../src/state/AppViewModel", () => ({
AppViewModel: class {
public mediaDevices = {};
public backgroundEffects = {};
public clientSession: unknown;
public constructor(_scope: unknown, _options: unknown, session: unknown) {
this.clientSession = session;
}
},
}));
@@ -43,6 +47,7 @@ beforeEach(() => {
_unstable_getStickyEvents: vi.fn(),
getMxcAvatarUrl: vi.fn(),
getJoinRule: vi.fn(),
hasEncryptionStateEvent: vi.fn(),
});
});
+2 -1
View File
@@ -30,7 +30,7 @@ import type { Room } from "matrix-js-sdk";
import type { UrlProperties } from "../src/UrlParams";
import type { ElementCallHandle, ElementCallHostBridge } from "./host";
import type { HostClientPart } from "./componentLocalJsClient";
import type { SuppliedClient } from "../src/ClientContext";
import type { SuppliedClient } from "../src/state/ClientSession";
import {
BackgroundStyle,
configurationForIntent,
@@ -91,6 +91,7 @@ type HostRoomPart = Pick<
| "getMxcAvatarUrl"
| "getJoinRule"
| "relations"
| "hasEncryptionStateEvent"
>;
export interface ElementCallProps {
-41
View File
@@ -1,41 +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.
*/
/**
* The js-sdk for the component: the package's own entry points
* (`lib/index.js`, `lib/browser-index.js`) throw when the host's copy has
* already loaded one, and `browser-index` also writes the host's globals.
* `lib/matrix` is the same API without either. The client this exports
* refuses the few calls that would collide with the host's js-sdk: a sync
* loop, crypto, and the IndexedDB stores both would open by the same name.
*/
import { IndexedDBStore, MatrixClient } from "matrix-js-sdk/lib/matrix";
function refuse<C extends { prototype: object }>(
cls: C,
name: string,
methods: (keyof C["prototype"] & string)[],
): void {
for (const method of methods)
Object.defineProperty(cls.prototype, method, {
value() {
throw new Error(
`${name}.${method} is not available in the Element Call component: the host's client does this`,
);
},
});
}
refuse(MatrixClient, "MatrixClient", [
"startClient",
"initRustCrypto",
"clearStores",
]);
refuse(IndexedDBStore, "IndexedDBStore", ["startup"]);
export * from "matrix-js-sdk/lib/matrix";
+14 -8
View File
@@ -73,6 +73,7 @@ import {
} from "../src/UrlParams";
import { MediaDevicesContext } from "../src/MediaDevicesContext";
import { AppViewModel } from "../src/state/AppViewModel";
import { hostClientSession } from "../src/state/ClientSession";
import { ObservableScope } from "../src/state/ObservableScope";
import { BackgroundEffectsProvider } from "../src/tracks/BackgroundEffectsContext";
import { Config } from "../src/config/Config";
@@ -192,20 +193,25 @@ export const ElementCall: FC<ElementCallProps> = ({
[roomId, intent, stableConfig],
);
// Created in an effect so that the scope it lives in ends when the component
// is unmounted (or these options change), rather than keeping its device
// observers running for the rest of the page's life. Null until then, which
// is one render.
const { controlledAudioDevices, callIntent } = params;
const [vm, setVm] = useState<AppViewModel | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setVm(new AppViewModel(scope, { controlledAudioDevices, callIntent }));
setVm(
new AppViewModel(
scope,
{ controlledAudioDevices, callIntent },
// The host owns the client. We create a clientSession wrapping the host client.
hostClientSession(client),
// The host owns the session too, so there is nothing to manage here
null,
),
);
return (): void => {
setVm(null);
scope.end();
};
}, [controlledAudioDevices, callIntent]);
}, [controlledAudioDevices, callIntent, client]);
const backend = useMemo(
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
@@ -247,11 +253,11 @@ export const ElementCall: FC<ElementCallProps> = ({
>
<Decoration>
<TooltipProvider>
{/* The host's own client: what reads it through
{/* The client session: what reads it through
the context (avatars, the encryption system,
rageshakes, the disconnected banner) uses only its
stable methods. */}
<ClientProvider client={client}>
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider
effects={vm.backgroundEffects}
+2 -3
View File
@@ -34,15 +34,14 @@
"./style.css": "./dist/element-call.css"
},
"sideEffects": [
"*.css",
"./guestJsSdk.ts"
"*.css"
],
"scripts": {
"prepare": "cd .. && pnpm install --frozen-lockfile && pnpm build:component"
},
"peerDependencies": {
"@vector-im/compound-design-tokens": "^11.0.0",
"@vector-im/compound-web": "^10.5.0",
"@vector-im/compound-web": "^10.3.1",
"react": "^19",
"react-dom": "^19"
}
+2 -2
View File
@@ -19,10 +19,10 @@ services:
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
element-web:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:a9fba6e7ea9a32f62bc1459fcdad790662476ff1b2bcebc62fe47e5cf51e3932
image: ghcr.io/element-hq/element-web:develop@sha256:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:a9fba6e7ea9a32f62bc1459fcdad790662476ff1b2bcebc62fe47e5cf51e3932
image: ghcr.io/element-hq/element-web:develop@sha256:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
+25 -25
View File
@@ -46,31 +46,31 @@ possible to support encryption.
These parameters are relevant to both [widget](./embedded_standalone.md) and [standalone](./embedded_standalone.md) modes:
| Name | Values | Required for widget | Required for SPA | Description |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intent` | `start_call`, `join_existing`, `start_call_voice`, `join_existing_voice`, `start_call_dm`, `join_existing_dm`, `start_call_dm_voice`, `join_existing_dm_voice`, or `video_room`. | No, defaults to `start_call` | No, defaults to `start_call` | The intent is a special url parameter that defines the defaults for all the other parameters. In most cases it should be enough to only set the intent to setup element-call. |
| `allowIceFallback` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Allows use of fallback STUN servers for ICE if the user's homeserver doesn’t provide any. |
| `posthogUserId` | Posthog analytics ID | No | No | Available only with user's consent for sharing telemetry in Element Web. |
| `confineToRoom` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Keeps the user confined to the current call/room. |
| `displayName` | | No | No | Display name used for auto-registration. |
| `enableE2EE` (deprecated) | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Legacy flag to enable end-to-end encryption, not used in the `livekit` branch. |
| `fontScale` | A decimal number such as `0.9` | No, defaults to `1.0` | No, defaults to `1.0` | Factor by which to scale the interface's font size. |
| `fonts` | | No | No | Defines the font(s) used by the interface. Multiple font parameters can be specified: `?font=font-one&font=font-two...`. |
| `header` | `none`, `standard` or `app_bar` | No, defaults to `standard` | No, defaults to `standard` | The style of headers to show. `standard` is the default arrangement, `none` hides the header entirely, and `app_bar` produces a header with a back button like you might see in mobile apps. The callback for the back button is `window.controls.onBackButtonPressed`. |
| `hideScreensharing` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Hides the screen-sharing button. |
| `homeserver` | | Not applicable | No | Homeserver for registering a new (guest) user, configures non-default guest user server when creating a spa link. |
| `lang` | [BCP 47](https://www.rfc-editor.org/info/bcp47) code | No | No | The language the app should use. |
| `password` | | No | No | E2EE password when using a shared secret. (For individual sender keys in embedded mode this is not required.) |
| `controlledAudioDevices` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the [global JS controls for audio devices](./controls.md#audio-devices) should be enabled, allowing the list of audio devices to be controlled by the app hosting Element Call. |
| `roomId` | [Matrix Room ID](https://spec.matrix.org/v1.12/appendices/#room-ids) | Yes | No | Anything about what room we're pointed to should be from useRoomIdentifier which parses the path and resolves alias with respect to the default server name, however roomId is an exception as we need the room ID in embedded widget mode, and not the room alias (or even the via params because we are not trying to join it). This is also not validated, where it is in `useRoomIdentifier()`. |
| `showControls` | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Displays controls like mute, screen-share, invite, and hangup buttons during a call. |
| `skipLobby` (deprecated: use `intent` instead) | `true` or `false` | No. If `intent` is explicitly `start_call` then defaults to `true`. Otherwise defaults to `false` | No, defaults to `false` | Skips the lobby to join a call directly, can be combined with preload in widget. When `true` the audio and video inputs will be muted by default. (This means there currently is no way to start without muted video if one wants to skip the lobby. Also not in widget mode.) |
| `theme` | One of: `light`, `dark`, `light-high-contrast`, `dark-high-contrast` | No, defaults to `dark` | No, defaults to `dark` | UI theme to use. |
| `background` | One of: `solid`, `gradient` | No, defaults to `gradient` | No, defaults to `gradient` | Visual style of the page background. |
| `viaServers` | Comma separated list of [Matrix Server Names](https://spec.matrix.org/v1.12/appendices/#server-name) | Not applicable | No | Homeserver for joining a room, non-empty value required for rooms not on the user’s default homeserver. |
| `sendNotificationType` | `ring` or `notification` | No | No | Will send a "ring" or "notification" `m.rtc.notification` event if the user is the first one in the call. |
| `autoLeave` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the app should automatically leave the call when there is no one left in the call. |
| `waitForCallPickup` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | When sending a notification, show UI that the app is awaiting an answer, play a dial tone, and (in widget mode) auto-close the widget once the notification expires. |
| Name | Values | Required for widget | Required for SPA | Description |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intent` | `start_call`, `join_existing`, `start_call_voice`, `join_existing_voice`, `start_call_dm`, `join_existing_dm`, `start_call_dm_voice`, or `join_existing_dm_voice`. | No, defaults to `start_call` | No, defaults to `start_call` | The intent is a special url parameter that defines the defaults for all the other parameters. In most cases it should be enough to only set the intent to setup element-call. |
| `allowIceFallback` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Allows use of fallback STUN servers for ICE if the user's homeserver doesn’t provide any. |
| `posthogUserId` | Posthog analytics ID | No | No | Available only with user's consent for sharing telemetry in Element Web. |
| `confineToRoom` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Keeps the user confined to the current call/room. |
| `displayName` | | No | No | Display name used for auto-registration. |
| `enableE2EE` (deprecated) | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Legacy flag to enable end-to-end encryption, not used in the `livekit` branch. |
| `fontScale` | A decimal number such as `0.9` | No, defaults to `1.0` | No, defaults to `1.0` | Factor by which to scale the interface's font size. |
| `fonts` | | No | No | Defines the font(s) used by the interface. Multiple font parameters can be specified: `?font=font-one&font=font-two...`. |
| `header` | `none`, `standard` or `app_bar` | No, defaults to `standard` | No, defaults to `standard` | The style of headers to show. `standard` is the default arrangement, `none` hides the header entirely, and `app_bar` produces a header with a back button like you might see in mobile apps. The callback for the back button is `window.controls.onBackButtonPressed`. |
| `hideScreensharing` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Hides the screen-sharing button. |
| `homeserver` | | Not applicable | No | Homeserver for registering a new (guest) user, configures non-default guest user server when creating a spa link. |
| `lang` | [BCP 47](https://www.rfc-editor.org/info/bcp47) code | No | No | The language the app should use. |
| `password` | | No | No | E2EE password when using a shared secret. (For individual sender keys in embedded mode this is not required.) |
| `controlledAudioDevices` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the [global JS controls for audio devices](./controls.md#audio-devices) should be enabled, allowing the list of audio devices to be controlled by the app hosting Element Call. |
| `roomId` | [Matrix Room ID](https://spec.matrix.org/v1.12/appendices/#room-ids) | Yes | No | Anything about what room we're pointed to should be from useRoomIdentifier which parses the path and resolves alias with respect to the default server name, however roomId is an exception as we need the room ID in embedded widget mode, and not the room alias (or even the via params because we are not trying to join it). This is also not validated, where it is in `useRoomIdentifier()`. |
| `showControls` | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Displays controls like mute, screen-share, invite, and hangup buttons during a call. |
| `skipLobby` (deprecated: use `intent` instead) | `true` or `false` | No. If `intent` is explicitly `start_call` then defaults to `true`. Otherwise defaults to `false` | No, defaults to `false` | Skips the lobby to join a call directly, can be combined with preload in widget. When `true` the audio and video inputs will be muted by default. (This means there currently is no way to start without muted video if one wants to skip the lobby. Also not in widget mode.) |
| `theme` | One of: `light`, `dark`, `light-high-contrast`, `dark-high-contrast` | No, defaults to `dark` | No, defaults to `dark` | UI theme to use. |
| `background` | One of: `solid`, `gradient` | No, defaults to `gradient` | No, defaults to `gradient` | Visual style of the page background. |
| `viaServers` | Comma separated list of [Matrix Server Names](https://spec.matrix.org/v1.12/appendices/#server-name) | Not applicable | No | Homeserver for joining a room, non-empty value required for rooms not on the user’s default homeserver. |
| `sendNotificationType` | `ring` or `notification` | No | No | Will send a "ring" or "notification" `m.rtc.notification` event if the user is the first one in the call. |
| `autoLeave` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the app should automatically leave the call when there is no one left in the call. |
| `waitForCallPickup` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | When sending a notification, show UI that the app is awaiting an answer, play a dial tone, and (in widget mode) auto-close the widget once the notification expires. |
### Widget-only parameters
+1 -1
View File
@@ -4,7 +4,6 @@
},
"action": {
"add_background_image": "Add image",
"adjust_view": "Adjust view",
"close": "Close",
"copy_link": "Copy link",
"edit": "Edit",
@@ -159,6 +158,7 @@
},
"layout_grid_label": "Grid",
"layout_spotlight_label": "Spotlight",
"layout_switch_label": "Layout",
"lobby": {
"ask_to_join": "Request to join call",
"join_as_guest": "Join as guest",
+7 -8
View File
@@ -39,8 +39,8 @@
"lint:knip": "knip",
"lint:externals": "node scripts/check-component-externals.mjs",
"lint:types": "tsc",
"i18n": "i18next-cli extract",
"i18n:check": "i18next-cli extract --ci",
"i18n": "npx i18next-cli extract",
"i18n:check": "npx i18next-cli extract --ci",
"test": "vitest",
"test:storybook": "vitest --project=storybook",
"test:unit": "vitest --project=unit",
@@ -55,7 +55,6 @@
"build-storybook": "storybook build"
},
"devDependencies": {
"@base-ui/react": "^1.9.0",
"@codecov/vite-plugin": "^2.0.0",
"@fontsource/inconsolata": "^5.1.0",
"@fontsource/inter": "^5.1.0",
@@ -83,7 +82,7 @@
"@types/grecaptcha": "^3.0.9",
"@types/jsdom": "^21.1.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^26.6.11",
"@types/node": "^24.0.0",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
@@ -91,7 +90,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.8.0",
"@vector-im/compound-web": "^10.5.0",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/browser-playwright": "^4.1.5",
"@vitest/coverage-v8": "^4.0.18",
@@ -106,16 +105,16 @@
"i18next": "^26.0.0",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-cli": "^1.61.0",
"jsdom": "^31.0.0",
"jsdom": "^26.0.0",
"knip": "^5.86.0",
"livekit-client": "^2.18.1",
"lodash-es": "^4.17.21",
"loglevel": "^1.9.1",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#aa1a8db0689465a8549546aea4c6cf1e696d6e44",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb",
"matrix-widget-api": "^1.18.0",
"node-stdlib-browser": "^1.3.1",
"normalize.css": "^8.0.1",
"oxfmt": "^0.80.0",
"oxfmt": "^0.79.0",
"oxlint": "^1.70.0",
"oxlint-tsgolint": "^0.25.0",
"pako": "^3.0.3",
+3 -10
View File
@@ -27,17 +27,10 @@ process.env.NODE_EXTRA_CA_CERTS = join(
"backend/dev_tls_local-ca.crt",
);
const commonDeviceOptions = {
// Disabling motion-based animations helps Playwright position the cursor
// correctly when clicking on menus etc.
reducedMotion: "reduce" as const,
ignoreHTTPSErrors: true,
};
const desktopChrome = {
...devices["Desktop Chrome"],
...commonDeviceOptions,
permissions: ["clipboard-write", "clipboard-read", "microphone", "camera"],
ignoreHTTPSErrors: true,
launchOptions: {
args: [
"--use-fake-ui-for-media-stream",
@@ -123,7 +116,7 @@ export default defineConfig({
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
use: {
...devices["Desktop Firefox"],
...commonDeviceOptions,
ignoreHTTPSErrors: true,
launchOptions: {
firefoxUserPrefs: {
"permissions.default.microphone": 1,
@@ -147,7 +140,7 @@ export default defineConfig({
testMatch: "**/mobile/**",
use: {
...devices["Pixel 7"],
...commonDeviceOptions,
ignoreHTTPSErrors: true,
permissions: [
"clipboard-write",
"clipboard-read",
+6 -4
View File
@@ -62,7 +62,8 @@ test("Sign up a new account, then login, then logout", async ({ browser }) => {
test("As a guest, create a call, share link and other join", async ({
browser,
}) => {
const creatorContext = await browser.newContext();
// Use reduce motion to disable animations that are making the tests a bit flaky
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
@@ -75,8 +76,7 @@ test("As a guest, create a call, share link and other join", async ({
// join
await creatorPage.getByTestId("lobby_joinCall").click();
// Spotlight mode to make checking the test visually clearer
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await creatorPage.getByRole("radio", { name: "Spotlight" }).check();
// Get the invite link
const inviteLink = await SpaHelpers.getCallInviteLink(creatorPage);
@@ -84,7 +84,9 @@ test("As a guest, create a call, share link and other join", async ({
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink);
+4 -4
View File
@@ -50,13 +50,13 @@ test.describe("the quick audio menu", () => {
}) => {
// Two browsers and a real call.
test.slow();
const hostContext = await browser.newContext();
const hostContext = await browser.newContext({ reducedMotion: "reduce" });
const host = await hostContext.newPage();
await installFakeDevices(host, { microphones: 3, speakers: 3 });
await joinACall(host, "Host", "Device switch");
const inviteLink = await SpaHelpers.getCallInviteLink(host);
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guest = await guestContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guest, inviteLink, "Guest");
await SpaHelpers.expectVideoTilesCount(guest, 2);
@@ -85,13 +85,13 @@ test.describe("the quick audio menu", () => {
}) => {
// Two browsers and a real call.
test.slow();
const hostContext = await browser.newContext();
const hostContext = await browser.newContext({ reducedMotion: "reduce" });
const host = await hostContext.newPage();
await installFakeDevices(host);
await joinACall(host, "Muted host", "Muted meter");
const inviteLink = await SpaHelpers.getCallInviteLink(host);
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guest = await guestContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guest, inviteLink, "Listener");
await SpaHelpers.expectVideoTilesCount(guest, 2);
+11 -3
View File
@@ -30,6 +30,15 @@ import { SpaHelpers } from "../spa-helpers.ts";
// are sized for that, so the tests have to be too
test.describe.configure({ timeout: 180_000 });
/** The settings button, whichever of the two the footer is currently showing. */
function settingsButton(pane: Locator): Locator {
return pane
.getByTestId("settings-bottom-left")
.or(pane.getByTestId("settings-bottom-center"))
.filter({ visible: true })
.first();
}
test("holds a call between two components on one page", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("twocomponents");
const panes = await startHarness(page, username, roomId);
@@ -72,7 +81,7 @@ test("keeps its modals inside the container it was given", async ({ page }) => {
// rather than the container until it was made a containing block. The
// settings dialog spilled over the host's interface; the reaction picker sat
// at 82vh, which put it below the container entirely and so out of sight.
await pane.getByTestId("settings-bottom").click();
await settingsButton(pane).click();
await expectWithin(pane.getByRole("dialog"), container);
await pane.getByTestId("modal_close").click();
@@ -103,8 +112,7 @@ test("keeps the call inside the container, wherever the host put it", async ({
// the container below a header of its own, so a grid offset measured from
// the top of the page instead of from the root would land the tile on top of
// the footer and out of the bottom of the container.
await pane.getByRole("button", { name: "Adjust view" }).click();
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
await pane.getByRole("radio", { name: "Spotlight" }).check();
const tile = pane.getByTestId("videoTile").first();
await expect(tile).toBeVisible({ timeout: 60_000 });
await expectWithin(tile, container);
+1 -1
View File
@@ -30,7 +30,7 @@ export const mobileTest = test.extend<MobileCreateFixtures>({
async function createCallAndInvite(
browser: Browser,
): Promise<{ page: Page; inviteLink: string }> {
const creatorContext = await browser.newContext();
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
+3 -1
View File
@@ -58,7 +58,9 @@ mobileTest(
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await guestPage.goto(inviteLink + "&controlledAudioDevices=true");
+11 -9
View File
@@ -12,7 +12,8 @@ test("When creator left, avoid reconnect to the same SFU", async ({
browserName,
}) => {
test.skip(browserName === "firefox", "Browser independent");
const creatorContext = await browser.newContext();
// Use reduce motion to disable animations that are making the tests a bit flaky
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
@@ -30,8 +31,7 @@ test("When creator left, avoid reconnect to the same SFU", async ({
// join
await creatorPage.getByTestId("lobby_joinCall").click();
// Spotlight mode to make checking the test visually clearer
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await creatorPage.getByRole("radio", { name: "Spotlight" }).check();
// Get the invite link
await creatorPage.getByRole("button", { name: "Invite" }).click();
@@ -51,7 +51,9 @@ test("When creator left, avoid reconnect to the same SFU", async ({
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestB = await browser.newContext();
const guestB = await browser.newContext({
reducedMotion: "reduce",
});
const guestBPage = await guestB.newPage();
await guestBPage.goto(inviteLink);
@@ -59,13 +61,14 @@ test("When creator left, avoid reconnect to the same SFU", async ({
await expect(guestBPage.getByTestId("joincall_joincall")).toBeVisible();
await guestBPage.getByTestId("joincall_joincall").click();
await guestBPage.getByTestId("lobby_joinCall").click();
await guestBPage.getByRole("button", { name: "Adjust view" }).click();
await guestBPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await guestBPage.getByRole("radio", { name: "Spotlight" }).check();
// ========
// ACT: add a third user to the call to reproduce the bug
// ========
const guestC = await browser.newContext();
const guestC = await browser.newContext({
reducedMotion: "reduce",
});
const guestCPage = await guestC.newPage();
// Track WebSocket connections
let wsConnectionCount = 0;
@@ -82,8 +85,7 @@ test("When creator left, avoid reconnect to the same SFU", async ({
await expect(guestCPage.getByTestId("joincall_joincall")).toBeVisible();
await guestCPage.getByTestId("joincall_joincall").click();
await guestCPage.getByTestId("lobby_joinCall").click();
await guestCPage.getByRole("button", { name: "Adjust view" }).click();
await guestCPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await guestCPage.getByRole("radio", { name: "Spotlight" }).check();
await guestCPage.waitForTimeout(1000);
if (wsConnectionCount === 2) {
+5 -3
View File
@@ -33,7 +33,7 @@ async function setupTwoUserSpaCall(
await interceptEventSend(
page,
// This room is not encrypted, so the event is sent in clear
"m.rtc.member",
"org.matrix.msc4143.rtc.member",
(req) => {
androlHasSentStickyEvent =
androlHasSentStickyEvent || isStickySend(req.url());
@@ -46,7 +46,9 @@ async function setupTwoUserSpaCall(
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// Other
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await guestPage.goto("/");
@@ -60,7 +62,7 @@ async function setupTwoUserSpaCall(
await interceptEventSend(
guestPage,
// This room is not encrypted, so the event is sent in clear
"m.rtc.member",
"org.matrix.msc4143.rtc.member",
(req) => {
pevaraHasSentStickyEvent =
pevaraHasSentStickyEvent || isStickySend(req.url());
+1 -2
View File
@@ -88,8 +88,7 @@ async function joinCallFromInviteLink(
}
await page.getByTestId("lobby_joinCall").click();
await page.getByRole("button", { name: "Adjust view" }).click();
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
await page.getByRole("radio", { name: "Spotlight" }).check();
}
async function setRtcModeFromSettings(
+6 -6
View File
@@ -105,7 +105,7 @@ for (const { hostShape, guestShape, mode, hostFlows, guestFlows } of cases) {
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes[guestShape]);
const guestRequests = recordAuthRequests(guestPage);
@@ -178,7 +178,7 @@ test("Falls back to the JWT service for a url+legacy transport when the homeserv
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins, and its C-S requests fail as well.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes["url+legacy"]);
await rejectCsApiTokens(guestPage);
@@ -224,13 +224,13 @@ test("Group call with all possible transport shapes at once", async ({
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest with a legacy transport joins.
const bobContext = await browser.newContext();
const bobContext = await browser.newContext({ reducedMotion: "reduce" });
const bobPage = await bobContext.newPage();
await advertiseTransport(bobPage, shapes.legacy);
await SpaHelpers.joinCallFromInviteLink(bobPage, inviteLink, "Bob");
// The guest with a url+legacy transport joins.
const carolContext = await browser.newContext();
const carolContext = await browser.newContext({ reducedMotion: "reduce" });
const carolPage = await carolContext.newPage();
await advertiseTransport(carolPage, shapes["url+legacy"]);
await SpaHelpers.joinCallFromInviteLink(carolPage, inviteLink, "Carol");
@@ -265,7 +265,7 @@ for (const { shape, via } of delegationCases) {
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes[shape]);
const delayedLeave = recordDelayedLeave(guestPage);
@@ -327,7 +327,7 @@ test("Subscribers get tokens for a remote homeserver's SFU over federation", asy
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest lives on the default homeserver and joins over federation.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes.url);
const guestRequests = recordAuthRequests(guestPage);
+2 -10
View File
@@ -86,11 +86,7 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
const frame = alice.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await frame.getByRole("button", { name: "Adjust view" }).click();
await expect(
frame.getByRole("menuitemradio", { name: "Grid" }),
).toBeChecked();
await frame.getByRole("menu").press("Escape");
await expect(frame.getByRole("radio", { name: "Grid" })).toBeChecked();
}
// Others should have switched to spotlight
@@ -99,11 +95,7 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
.locator('iframe[title="Element Call"]')
.contentFrame();
await frame.getByRole("button", { name: "Adjust view" }).click();
await expect(
frame.getByRole("menuitemradio", { name: "Spotlight" }),
).toBeChecked();
await frame.getByRole("menu").press("Escape");
await expect(frame.getByRole("radio", { name: "Spotlight" })).toBeChecked();
}
// await alice.page.pause();
// await bob.page.pause();
+3 -1
View File
@@ -123,7 +123,9 @@ export class TestHelpers {
);
// STEP 2: Open browser and login
const userContext = await browser.newContext();
const userContext = await browser.newContext({
reducedMotion: "reduce",
});
const page = await userContext.newPage();
await page.goto(host);
+1095 -1046
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -28,8 +28,8 @@ overrides:
# - https://github.com/advisories/GHSA-7r86-cg39-jmmj
# - https://github.com/advisories/GHSA-23c5-xmqv-rm74
"minimatch": "^11.0.0"
# The v8 line is deprecated.
"eslint": "^9.0.0"
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
"glob": "^10.5.0"
# Security fix: https://github.com/advisories/GHSA-6pq8-jhm2-2vcw
"qs": ">=6.16.1"
# Security fix: https://github.com/advisories/GHSA-2883-xcg3-v3hh
+2 -4
View File
@@ -28,14 +28,12 @@
{
"groupName": "matrix-widget-api",
"matchDepNames": ["matrix-widget-api"],
"extends": ["schedule:weekly"],
"minimumReleaseAge": null
"extends": ["schedule:weekly"]
},
{
"groupName": "Compound",
"matchPackageNames": ["@vector-im/compound-{/,}**"],
"extends": ["schedule:weekly"],
"minimumReleaseAge": null
"extends": ["schedule:weekly"]
},
{
"groupName": "LiveKit client",
+11 -11
View File
@@ -6,18 +6,18 @@ Please see LICENSE in the repository root for full details.
*/
/**
* Checks the component build's output for things we do not want to end up in the
* component target.
* Checks the component build's output for what a host must not be handed.
*
* A library build inlines every asset it needs as a data URL unless the import
* says otherwise: if one adds an import without `no-inline` the
* module grows by the asset (due to encoding a third larger than the original file)
* that every host then downloads and parses before the first call.
* MediaPipe's runtime alone is 11 MB, so it should not be inlined.
* The standalone app's client store worker, which carries a copy of the Matrix SDK
* and its crypto, is also not needed in a package whose host supplies the client:
* the bundler packages if it is imported, even if not used (see src/utils/initClient.ts).
* The script makes sure, the build fails on each of those issues.
* A library build inlines every asset it meets as a data URL unless the import
* says otherwise, and does so silently: one import without `no-inline` and the
* module grows by the asset, encoded a third larger, that every host then
* downloads and parses before the first call. MediaPipe's runtime alone is
* 11 MB. A reference to a file by an absolute path is just as silent and
* breaks at runtime instead, since a host serves the module from wherever it
* likes. And the standalone app's client store worker, which carries a copy of
* the Matrix SDK and its crypto, has no business in a package whose host
* supplies the client: the bundler emits it on loading its import, used or
* not (see src/utils/initClient.ts). This fails the build on each of those.
*/
import { existsSync } from "node:fs";
+15 -13
View File
@@ -7,31 +7,33 @@ Please see LICENSE in the repository root for full details.
import { afterEach, expect, test, vi } from "vitest";
const initSPA = vi.hoisted(() => vi.fn());
vi.mock("./utils/spa", () => ({ initSPA }));
import { testScope } from "./utils/test";
const createStandaloneClientSession$ = vi.hoisted(() => vi.fn());
vi.mock("./state/StandaloneClientSession", () => ({
createStandaloneClientSession$,
}));
afterEach(() => {
vi.unstubAllEnvs();
vi.resetModules();
initSPA.mockReset();
createStandaloneClientSession$.mockReset();
});
test("the app restores its own session", async () => {
vi.stubEnv("VITE_PACKAGE", "full");
const { loadStandaloneClient } = await import("./App");
const loadSession = vi.fn();
const clearSession = vi.fn();
initSPA.mockResolvedValue(null);
const { loadStandaloneClientSession } = await import("./App");
const scope = testScope();
const session = {};
createStandaloneClientSession$.mockReturnValue(session);
await expect(loadStandaloneClient!(loadSession, clearSession)).resolves.toBe(
null,
);
expect(initSPA).toHaveBeenCalledWith(loadSession, clearSession);
await expect(loadStandaloneClientSession!(scope)).resolves.toBe(session);
expect(createStandaloneClientSession$).toHaveBeenCalledWith(scope);
});
test("the embedded package has no session of its own", async () => {
vi.stubEnv("VITE_PACKAGE", "embedded");
const { loadStandaloneClient } = await import("./App");
const { loadStandaloneClientSession } = await import("./App");
expect(loadStandaloneClient).toBeUndefined();
expect(loadStandaloneClientSession).toBeUndefined();
});
+43 -33
View File
@@ -23,14 +23,13 @@ import {
import * as Sentry from "@sentry/react";
import { TooltipProvider } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixClient } from "matrix-js-sdk";
import { I18nextProvider } from "react-i18next";
import { HomePage } from "./home/HomePage";
import { LoginPage } from "./auth/LoginPage";
import { RegisterPage } from "./auth/RegisterPage";
import { RoomPage } from "./room/RoomPage";
import { type ClientLoader, ClientProvider } from "./ClientContext";
import { ClientProvider } from "./ClientContext";
import { ErrorPage, LoadingPage } from "./FullScreenView";
import { Initializer } from "./initializer";
import { type WidgetHelpers } from "./widget";
@@ -54,22 +53,26 @@ import {
} from "./HostBridge";
import { useInitial } from "./useInitial";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import { DisconnectedProvider } from "./DisconnectedContext";
import { type ClientManager, type ClientSession } from "./state/ClientSession";
import { type ObservableScope } from "./state/ObservableScope";
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
// Element Call's own session, for when no host supplies a client.
// - Passed in here, not imported by ClientProvider: this module is only in the
// app builds, so the client setup and the store worker behind it stay out of
// the component package (see the `loadClient` prop).
// - Imported on demand, as it was before, so that a widget, which gets its
// client from the host, never downloads it.
// - Module-level, so that the provider's effect sees one stable loader.
// - Imported on demand, so that a widget, which gets its client from the host,
// never downloads it.
// - None in the embedded package, which only runs as a widget: the constant
// condition lets its build drop the client setup and the store worker.
export const loadStandaloneClient: ClientLoader | undefined =
export const loadStandaloneClientSession:
| ((scope: ObservableScope) => Promise<ClientSession & ClientManager>)
| undefined =
import.meta.env.VITE_PACKAGE === "embedded"
? undefined
: async (...args) => (await import("./utils/spa")).initSPA(...args);
: async (scope) =>
(
await import("./state/StandaloneClientSession")
).createStandaloneClientSession$(scope);
interface SimpleProviderProps {
children: JSX.Element;
@@ -145,40 +148,47 @@ export const App: FC<Props> = ({ vm, widget }) => {
.catch(logger.error);
});
// As a widget, the client comes from the host over the widget API. Standalone,
// Element Call finds one itself, so there is nothing to wait for here.
const [widgetClient, setWidgetClient] = useState<MatrixClient | undefined>(
undefined,
);
useEffect(() => {
if (widget === null) return;
widget.client
.then(setWidgetClient)
.catch((e) => logger.error("Failed to obtain the host's client", e));
}, [widget]);
const clientReady = widget === null || widgetClient !== undefined;
const content =
loaded && clientReady ? (
<ClientProvider client={widgetClient} loadClient={loadStandaloneClient}>
const content = loaded ? (
<DisconnectedProvider value={vm.disconnected$}>
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute path="/" element={<HomePage />} />
<SentryRoute path="/login" element={<LoginPage />} />
<SentryRoute path="/register" element={<RegisterPage />} />
<SentryRoute path="*" element={<RoomPage />} />
<SentryRoute
path="/"
element={<HomePage clientManager={vm.clientManager} />}
/>
{/* A host's session is signed in to by the host, never here */}
{vm.clientManager !== null && (
<>
<SentryRoute
path="/login"
element={<LoginPage clientManager={vm.clientManager} />}
/>
<SentryRoute
path="/register"
element={
<RegisterPage clientManager={vm.clientManager} />
}
/>
</>
)}
<SentryRoute
path="*"
element={<RoomPage clientManager={vm.clientManager} />}
/>
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientProvider>
) : (
<LoadingPage />
);
</DisconnectedProvider>
) : (
<LoadingPage />
);
return (
<I18nextProvider i18n={i18n}>
+2 -16
View File
@@ -12,6 +12,7 @@ import { type FC, type PropsWithChildren } from "react";
import { ClientContextProvider } from "./ClientContext";
import { Avatar } from "./Avatar";
import { hostClientSession } from "./state/ClientSession";
import { mockMatrixRoomMember, mockRtcMembership } from "./utils/test";
import {
type HostBridge,
@@ -26,22 +27,7 @@ const TestComponent: FC<
}>
> = ({ client, hostBridge = nullHostBridge, children }) => {
return (
<ClientContextProvider
value={{
state: "valid",
disconnected: false,
supportedFeatures: {
reactions: true,
},
setClient: vi.fn(),
authenticated: {
client,
isPasswordlessUser: true,
changePassword: vi.fn(),
logout: vi.fn(),
},
}}
>
<ClientContextProvider value={hostClientSession(client)}>
<HostBridgeProvider value={hostBridge}>{children}</HostBridgeProvider>
</ClientContextProvider>
);
+8 -12
View File
@@ -15,7 +15,7 @@ import {
import { Avatar as CompoundAvatar } from "@vector-im/compound-web";
import { type MatrixClient } from "matrix-js-sdk";
import { useClientState } from "./ClientContext";
import { useClient } from "./ClientContext";
import { useHostBridge } from "./HostBridge";
export enum Size {
@@ -44,7 +44,7 @@ export interface Props {
}
export function getAvatarUrl(
client: MatrixClient,
client: Pick<MatrixClient, "mxcUrlToHttp">,
mxcUrl: string | null,
avatarSize = 96,
): string | null {
@@ -74,7 +74,7 @@ export const Avatar: FC<Props> = ({
style,
...props
}) => {
const clientState = useClientState();
const client = useClient();
const hostBridge = useHostBridge();
const sizePx = useMemo(
@@ -87,7 +87,7 @@ export const Avatar: FC<Props> = ({
const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
// In theory, a change in `clientState` or `sizePx` could run extra media
// In theory, a change in `client` or `sizePx` could run extra media
// downloads, but in practice they should be stable long before this code runs.
useEffect(() => {
if (!src) {
@@ -99,12 +99,8 @@ export const Avatar: FC<Props> = ({
if (hostBridge.downloadMedia) {
blob = hostBridge.downloadMedia(src);
} else if (
clientState?.state === "valid" &&
clientState.authenticated?.client &&
sizePx
) {
blob = getAvatarFromServer(clientState.authenticated.client, src, sizePx);
} else if (client && sizePx) {
blob = getAvatarFromServer(client, src, sizePx);
} else {
setAvatarUrl(undefined);
return;
@@ -133,7 +129,7 @@ export const Avatar: FC<Props> = ({
URL.revokeObjectURL(objectUrl);
}
};
}, [clientState, hostBridge, src, sizePx]);
}, [client, hostBridge, src, sizePx]);
return (
<CompoundAvatar
@@ -149,7 +145,7 @@ export const Avatar: FC<Props> = ({
};
async function getAvatarFromServer(
client: MatrixClient,
client: Pick<MatrixClient, "mxcUrlToHttp" | "getAccessToken">,
src: string,
sizePx: number,
): Promise<Blob> {
+3
View File
@@ -38,6 +38,8 @@ type CallRoomPart = Pick<
| "getJoinRule"
// Raised hands already in the room
| "relations"
// The encryption system, where no shared key is in use
| "hasEncryptionStateEvent"
>;
/**
@@ -73,5 +75,6 @@ export function createCallMatrixBackend(
get relations() {
return room.relations;
},
hasEncryptionStateEvent: room.hasEncryptionStateEvent.bind(room),
};
}
+81 -74
View File
@@ -6,16 +6,23 @@ Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import { act, render, renderHook } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { type FC } from "react";
import { BehaviorSubject } from "rxjs";
import {
type ClientLoader,
ClientProvider,
useClientState,
useClientSessionState,
useLoggedInSpaClient,
} from "./ClientContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
({
@@ -28,67 +35,47 @@ const mockClient = (userId = "@alice:example.org"): MatrixClient =>
/** Reports what the context says, so a test can assert on it. */
const ShowClientState: FC = () => {
const state = useClientState();
if (state === undefined) return <span>loading</span>;
if (state.state === "error") return <span>error</span>;
return (
<span>{state.authenticated?.client.getUserId() ?? "unauthenticated"}</span>
);
const state = useClientSessionState();
switch (state.state) {
case "signedIn":
return <span>{state.client.getUserId()}</span>;
case "signedOut":
return <span>unauthenticated</span>;
default:
return <span>{state.state}</span>;
}
};
test("uses a client supplied by the host without waiting", () => {
const client = mockClient();
const { container } = render(
const renderProvider = (
session: ClientSession,
children = <ShowClientState />,
): ReturnType<typeof render> =>
render(
<BrowserRouter>
<ClientProvider client={client}>
<ShowClientState />
</ClientProvider>
<ClientProvider session={session}>{children}</ClientProvider>
</BrowserRouter>,
);
test("uses a client supplied by the host without waiting", () => {
const { container } = renderProvider(hostClientSession(mockClient()));
// Available on the very first render: a supplied client needs no session
// restoring, so there is no loading state to pass through.
expect(container.textContent).toBe("@alice:example.org");
});
test("does not claim exclusive use of storage when given a client", () => {
// The channel is created when the module loads, so spy on the prototype
// rather than trying to replace the global.
const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage");
render(
<BrowserRouter>
<ClientProvider client={mockClient()}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
// The broadcast shuts down other instances to protect Element Call's own
// stores. A host's client brings its own, so there is nothing to protect.
expect(postMessage).not.toHaveBeenCalled();
postMessage.mockRestore();
});
test("follows the client when the host swaps it", () => {
const first = mockClient();
const second = mockClient("@bob:example.org");
const { container, rerender } = render(
<BrowserRouter>
<ClientProvider client={first}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
const { container, rerender } = renderProvider(
hostClientSession(mockClient()),
);
expect(container.textContent).toBe("@alice:example.org");
// A host that re-authenticates hands us a new client on a mounted component
rerender(
<BrowserRouter>
<ClientProvider client={second}>
<ClientProvider
session={hostClientSession(mockClient("@bob:example.org"))}
>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
@@ -97,38 +84,58 @@ test("follows the client when the host swaps it", () => {
expect(container.textContent).toBe("@bob:example.org");
});
test("finds a client of its own when the host supplies none", async () => {
const client = mockClient();
const loadClient = vi
.fn<ClientLoader>()
.mockResolvedValue({ client, passwordlessUser: true });
const { container } = render(
<BrowserRouter>
<ClientProvider loadClient={loadClient}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
test("follows a session of its own as it is restored", () => {
const state$ = new BehaviorSubject<ClientSessionState>({ state: "loading" });
const { container } = renderProvider({ state$ });
// Nothing to show until a session has been restored or created
expect(container.textContent).toBe("loading");
await waitFor(() => expect(container.textContent).toBe("@alice:example.org"));
// Given the session store to restore from and to clear on a stale session
expect(loadClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
act(() =>
state$.next({
state: "signedIn",
client: mockClient(),
passwordlessUser: true,
}),
);
expect(container.textContent).toBe("@alice:example.org");
});
test("has no one signed in when given neither a client nor a way to load one", async () => {
const { container } = render(
<BrowserRouter>
<ClientProvider>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
await waitFor(() => expect(container.textContent).toBe("unauthenticated"));
test("has no one signed in when the session says so", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({ state: "signedOut" }),
});
expect(container.textContent).toBe("unauthenticated");
});
test("shows the session's error in place of its children", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({
state: "error",
error: new Error("Opened elsewhere"),
}),
});
// The error page, not the children
expect(container.textContent).not.toContain("error");
expect(container.textContent).toContain("Something went wrong");
});
test("has no SPA client where the session is a host's", () => {
const { result } = renderHook(() => useLoggedInSpaClient(null));
expect(result.current).toBeUndefined();
});
test("gives the SPA's pages its client manager's client, whole", () => {
const client = mockClient();
const client$ = new BehaviorSubject<MatrixClient | undefined>(undefined);
const manager: ClientManager = {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$,
};
const { result } = renderHook(() => useLoggedInSpaClient(manager));
expect(result.current).toBeUndefined();
act(() => client$.next(client));
expect(result.current).toBe(client);
});
+42 -416
View File
@@ -5,450 +5,76 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
type FC,
useCallback,
useEffect,
useState,
createContext,
use,
useRef,
useMemo,
type JSX,
} from "react";
import { logger } from "matrix-js-sdk/lib/logger";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { type FC, useEffect, createContext, use, type JSX } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { ErrorPage } from "./FullScreenView";
import { useHostBridge } from "./HostBridge";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { PosthogAnalytics } from "./analytics/PosthogAnalytics";
import { useBehavior } from "./useBehavior";
import { constant } from "./state/Behavior";
import {
PosthogAnalytics,
RegistrationType,
} from "./analytics/PosthogAnalytics";
import { useEventTarget } from "./useEvents";
import { OpenElsewhereError } from "./RichError";
type ClientManager,
type ClientSession,
type ClientSessionState,
signedOutClientSession,
type SuppliedClient,
} from "./state/ClientSession";
declare global {
interface Window {
matrixclient: MatrixClient;
matrixclient: SuppliedClient;
passwordlessUser: boolean;
}
}
export type ClientState = ValidClientState | ErrorState;
export type ValidClientState = {
state: "valid";
authenticated?: AuthenticatedClient;
// 'Disconnected' rather than 'connected' because it tracks specifically
// whether the client is supposed to be connected but is not
disconnected: boolean;
supportedFeatures: {
reactions: boolean;
};
setClient: (client: MatrixClient, session: Session) => void;
};
export type AuthenticatedClient = {
client: MatrixClient;
isPasswordlessUser: boolean;
changePassword: (password: string) => Promise<void>;
logout: () => void;
};
export type ErrorState = {
state: "error";
error: Error;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
// Without a provider, no one is signed in
const ClientContext = createContext<ClientSession>(signedOutClientSession);
export const ClientContextProvider = ClientContext.Provider;
export const useClientState = (): ClientState | undefined => use(ClientContext);
export const useClientSessionState = (): ClientSessionState =>
useBehavior(use(ClientContext).state$);
export function useClient(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
export function useClient(): SuppliedClient | undefined {
const state = useClientSessionState();
return state.state === "signedIn" ? state.client : undefined;
}
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
passwordlessUser: boolean;
loading: boolean;
authenticated: boolean;
logout?: () => void;
error?: Error;
} {
const clientState = useClientState();
const noClient$ = constant(undefined);
let client;
let setClient;
let passwordlessUser = false;
let loading = true;
let error;
let authenticated = false;
let logout;
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false;
loading = false;
authenticated = client !== undefined;
logout = clientState.authenticated?.logout;
} else if (clientState?.state === "error") {
error = clientState.error;
loading = false;
}
return {
client,
setClient,
passwordlessUser,
loading,
authenticated,
logout,
error,
};
/**
* The SPA's whole client, for its own pages outside the call view. Undefined
* while no one is signed in, and wherever the session is a host's (no client
* manager).
*/
export function useLoggedInSpaClient(
clientManager: ClientManager | null,
): MatrixClient | undefined {
return useBehavior(clientManager?.client$ ?? noClient$);
}
const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
interface Props {
children: JSX.Element;
/**
* The client Element Call should use.
*
* An application hosting Element Call as a component already has a client,
* and owns the user's session; supplying it here means Element Call neither
* authenticates anyone nor manages their session. Left out, Element Call finds a client
* itself — from the widget API, or by restoring or creating a session of its
* own.
*/
client?: SuppliedClient;
/**
* How Element Call finds a client when none is supplied: the standalone app
* restores or creates a session of its own. Stable, as a hook dependency.
* Left out along with the client, no one is signed in.
*
* A prop, rather than this module importing `utils/spa` itself, because:
* - This module is in the component build, and so is everything it imports,
* dynamically or not: a dynamic import becomes a chunk in the package,
* not a module left out of it.
* - Behind `utils/spa` sits `utils/initClient` and the client store worker,
* which the bundler emits as soon as it loads the import (see there).
* - `App.tsx`, which the component never imports, is where the standalone
* app passes the loader in; the component passes nothing, having the
* host's client.
*/
loadClient?: ClientLoader;
/** A session from Element Call SPA, a widget, or the host (EW). */
session: ClientSession;
}
/**
* What is read of a supplied client under a call, and by this provider and
* analytics. Stable methods only, so a host's client, from the host's own copy
* of matrix-js-sdk, will do.
*/
export type SuppliedClient = Pick<
MatrixClient,
// The disconnected banner, and stopping a client opened elsewhere
| "on"
| "off"
| "stopClient"
// Analytics, through `window.matrixclient`
| "getCrypto"
| "isGuest"
| "getAccountDataFromServer"
| "setAccountData"
// The room's encryption system
| "getRoom"
// Avatars
| "mxcUrlToHttp"
| "getAccessToken"
// Rageshakes: who sends them, their crypto state, and asking others for theirs
| "getUserId"
| "getUser"
| "credentials"
| "deviceId"
| "secretStorage"
| "isKeyBackupKeyStored"
| "sendEvent"
>;
/**
* Restores or creates a session of Element Call's own, kept where the given
* functions keep it. Resolves to null when no one is signed in.
*/
export type ClientLoader = (
loadSession: () => Session | undefined,
clearSession: () => void,
) => Promise<InitResult | null>;
export const ClientProvider: FC<Props> = ({
children,
client: suppliedClient,
loadClient,
}) => {
// STOP GAP: held as a whole client, as the standalone and widget pages need
// one. A component host's client is only read through `SuppliedClient`.
const client = suppliedClient as MatrixClient | undefined;
const leaveToHome = useLeaveToHome();
const hostBridge = useHostBridge();
// null = signed out, undefined = loading
const [initClientState, setInitClientState] = useState<
InitResult | null | undefined
>(
client === undefined
? undefined
: // A supplied client belongs to the host, so there is no session of ours
// to restore and nothing to wait for.
{ client, passwordlessUser: false },
);
const initializing = useRef(false);
useEffect(() => {
if (client !== undefined) {
// Nothing to load, but a host may hand us a different client later — on
// re-authenticating, say — so follow whichever one it has given us.
setInitClientState((current) =>
current?.client === client
? current
: { client, passwordlessUser: false },
);
// Analytics still need to follow the user's choices.
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
return;
}
// In case the component is mounted, unmounted, and remounted quickly (as
// React does in strict mode), we need to make sure not to doubly initialize
// the client.
if (initializing.current) return;
if (loadClient === undefined) {
setInitClientState(null);
return;
}
initializing.current = true;
loadClient(loadSession, clearSession)
.then((initResult) => {
setInitClientState(initResult);
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
})
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
}, [client, loadClient]);
const changePassword = useCallback(
async (password: string) => {
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
await initClientState.client.setPassword(
{
type: "m.login.password",
identifier: {
type: "m.id.user",
user: session.user_id,
},
user: session.user_id,
password: session.tempPassword,
},
password,
);
saveSession({ ...session, passwordlessUser: false });
setInitClientState({
...initClientState,
passwordlessUser: false,
});
},
[initClientState],
);
const setClient = useCallback(
(client: MatrixClient, session: Session) => {
const oldClient = initClientState?.client;
if (oldClient && oldClient !== client) {
oldClient.stopClient();
}
saveSession(session);
setInitClientState({
client,
passwordlessUser: session.passwordlessUser,
});
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
},
[initClientState?.client],
);
const logout = useCallback(async () => {
const client = initClientState?.client;
if (!client) {
return;
}
await client.logout(true);
await client.clearStores();
clearSession();
setInitClientState(null);
leaveToHome?.();
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [leaveToHome, initClientState?.client]);
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. Element Call only has storage of its own to
// protect when it created the session itself; given a client — by a host, or
// over the widget API — it is mostly stateless.
const ownsSession = client === undefined;
useEffect(() => {
if (ownsSession) loadChannel?.postMessage({});
}, [ownsSession]);
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
undefined,
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
initClientState?.client.stopClient();
setAlreadyOpenedErr(new OpenElsewhereError());
}, [initClientState?.client, setAlreadyOpenedErr]),
);
const [isDisconnected, setIsDisconnected] = useState(false);
const [supportsReactions, setSupportsReactions] = useState(false);
const state: ClientState | undefined = useMemo(() => {
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
}
if (initClientState === undefined) return undefined;
const authenticated =
initClientState === null
? undefined
: {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
return {
state: "valid",
authenticated,
setClient,
disconnected: isDisconnected,
supportedFeatures: {
reactions: supportsReactions,
},
};
}, [
alreadyOpenedErr,
changePassword,
initClientState,
logout,
setClient,
isDisconnected,
supportsReactions,
]);
const onSync = useCallback(
(state: SyncState, _old: SyncState | null, data?: ISyncStateData) => {
setIsDisconnected(clientIsDisconnected(state, data));
},
[],
);
export const ClientProvider: FC<Props> = ({ children, session }) => {
const state = useBehavior(session.state$);
useEffect(() => {
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
if (state.state !== "signedIn") return;
window.matrixclient = state.client;
window.passwordlessUser = state.passwordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
// Analytics follow the user's choices whoever the client belongs to
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
}, [state]);
if (initClientState.client) {
initClientState.client.on(ClientEvent.Sync, onSync);
}
if (state.state === "error") return <ErrorPage error={state.error} />;
if (!hostBridge.supportsReactions)
logger.warn("The host does not permit reactions");
setSupportsReactions(hostBridge.supportsReactions);
return (): void => {
if (initClientState.client) {
initClientState.client.off(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync, hostBridge]);
if (alreadyOpenedErr) {
return <ErrorPage error={alreadyOpenedErr} />;
}
return <ClientContext value={state}>{children}</ClientContext>;
return <ClientContext value={session}>{children}</ClientContext>;
};
export type InitResult = {
client: MatrixClient;
passwordlessUser: boolean;
};
export interface Session {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
tempPassword?: string;
}
const clearSession = (): void => localStorage.removeItem("matrix-auth-store");
const saveSession = (s: Session): void =>
localStorage.setItem("matrix-auth-store", JSON.stringify(s));
const loadSession = (): Session | undefined => {
const data = localStorage.getItem("matrix-auth-store");
if (!data) {
return undefined;
}
return JSON.parse(data);
};
const clientIsDisconnected = (
syncState: SyncState,
syncData?: ISyncStateData,
): boolean =>
syncState === "ERROR" && syncData?.error?.name === "ConnectionError";
+33
View File
@@ -0,0 +1,33 @@
/*
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 "vitest";
import { act, render } from "@testing-library/react";
import { BehaviorSubject } from "rxjs";
import { DisconnectedBanner } from "./DisconnectedBanner";
import { DisconnectedProvider } from "./DisconnectedContext";
test("shows while the client is disconnected", () => {
const disconnected$ = new BehaviorSubject(false);
const { container } = render(
<DisconnectedProvider value={disconnected$}>
<DisconnectedBanner />
</DisconnectedProvider>,
);
expect(container.textContent).toBe("");
act(() => disconnected$.next(true));
expect(container.textContent).not.toBe("");
act(() => disconnected$.next(false));
expect(container.textContent).toBe("");
});
test("stays hidden without a provider", () => {
const { container } = render(<DisconnectedBanner />);
expect(container.textContent).toBe("");
});
+6 -9
View File
@@ -10,30 +10,27 @@ import { type FC, type HTMLAttributes, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import styles from "./DisconnectedBanner.module.css";
import { type ValidClientState, useClientState } from "./ClientContext";
import { useDisconnected } from "./DisconnectedContext";
interface Props extends HTMLAttributes<HTMLElement> {
children?: ReactNode;
className?: string;
}
/**
* Shown while the signed-in client is supposed to be connected but is not.
*/
export const DisconnectedBanner: FC<Props> = ({
children,
className,
...rest
}) => {
const { t } = useTranslation();
const clientState = useClientState();
let shouldShowBanner = false;
if (clientState?.state === "valid") {
const validClientState = clientState as ValidClientState;
shouldShowBanner = validClientState.disconnected;
}
const disconnected = useDisconnected();
return (
<>
{shouldShowBanner && (
{disconnected && (
<div className={classNames(styles.banner, className)} {...rest}>
{children}
{t("disconnected_banner")}
+20
View File
@@ -0,0 +1,20 @@
/*
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 { createContext, use } from "react";
import { type Behavior, constant } from "./state/Behavior";
import { useBehavior } from "./useBehavior";
// Without a provider there is no client whose connection could fail
const DisconnectedContext = createContext<Behavior<boolean>>(constant(false));
export const DisconnectedProvider = DisconnectedContext.Provider;
/** Whether the signed-in client is failing to reach its homeserver. */
export const useDisconnected = (): boolean =>
useBehavior(use(DisconnectedContext));
-68
View File
@@ -1,68 +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.
*/
.popover {
position: relative;
border-radius: var(--cpd-space-3x);
background: var(--cpd-color-bg-canvas-default);
box-shadow: var(--big-drop-shadow);
padding: var(--cpd-space-5x);
box-sizing: border-box;
inline-size: 310px;
max-inline-size: 90vw;
/* Draw an internal border */
&::after {
content: "";
position: absolute;
inset: 0;
border: var(--cpd-border-width-1) solid
var(--cpd-color-border-interactive-secondary);
border-radius: inherit;
pointer-events: none;
}
transition:
opacity 180ms,
transform 180ms;
&[data-starting-style] {
opacity: 0;
@media (prefers-reduced-motion: no-preference) {
transform: translate(0, var(--cpd-space-3x));
}
}
&[data-ending-style] {
transition-duration: 110ms;
opacity: 0;
@media (prefers-reduced-motion: no-preference) {
transform: translate(0, var(--cpd-space-2x));
}
}
p {
font: var(--cpd-font-body-sm-regular);
color: var(--cpd-color-text-secondary);
margin-block-end: var(--cpd-space-4x);
}
}
.title {
width: 100%;
display: flex;
> h3 {
margin-block-end: var(--cpd-space-2x);
flex-grow: 1;
}
> button {
margin-block-start: calc(-1 * var(--cpd-space-1x));
margin-inline-end: calc(-1 * var(--cpd-space-1x));
}
}
-41
View File
@@ -1,41 +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 { Meta, StoryObj } from "@storybook/react-vite";
import { Popover } from "./Popover";
import { Button } from "@vector-im/compound-web";
import { VideoCallOffSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import { useState } from "react";
const meta = {
component: Popover,
} satisfies Meta<typeof Popover>;
export default meta;
export const Default: StoryObj = {
render: () => {
const [open, setOpen] = useState(true);
return (
<Popover
title="Poor connection"
trigger={<Button>Open popover</Button>}
open={open}
onOpenChange={setOpen}
>
<p>Turn off all videos to improve call performance.</p>
<Button
size="md"
Icon={VideoCallOffSolidIcon}
style={{ width: "100%", marginBlockStart: 24 }}
>
Turn off all videos
</Button>
</Popover>
);
},
};
-30
View File
@@ -1,30 +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 "vitest";
import { axe } from "vitest-axe";
import { render, screen } from "@testing-library/react";
import { Popover } from "./Popover";
test("Popover renders", async () => {
render(
<Popover
title="Example"
trigger={<button>Open popover</button>}
open
onOpenChange={() => {}}
>
<p>This is an example of a popover.</p>
</Popover>,
);
const button = screen.getByRole("button", { name: "Open popover" });
const popover = screen.getByRole("dialog", { name: "Example" });
expect(button).toMatchSnapshot("button");
expect(popover).toMatchSnapshot("popover");
expect(await axe(document.body)).toHaveNoViolations();
});
-104
View File
@@ -1,104 +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 FC, type ReactElement, type ReactNode } from "react";
import { Popover as BUIPopover } from "@base-ui/react/popover";
import styles from "./Popover.module.css";
import { Heading, IconButton } from "@vector-im/compound-web";
import { CloseIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import classNames from "classnames";
import { useRootElement } from "./RootElementContext";
import { useTranslation } from "react-i18next";
export interface PopoverProps {
/**
* The popover title.
*/
title: string;
/**
* The button that opens the popover. This must be a component that accepts a
* ref and spreads props.
*
* https://base-ui.com/react/handbook/composition
*/
trigger: ReactElement;
/**
* Whether the popover is open.
*/
open: boolean;
/**
* Event handler called when the user tries to open or close the popover.
*/
onOpenChange: (open: boolean) => void;
/**
* The popover contents.
*/
children: ReactNode;
className?: string;
/**
* The side of the trigger on which to place the popover. Note that the menu
* may still end up on a different side than the one you request if there
* isn't enough space.
* @default bottom
*/
side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start";
/**
* The edge along which the popover and trigger will be aligned.
* @default center
*/
align?: "start" | "center" | "end";
}
/**
* A popover opened by pressing a button.
*/
export const Popover: FC<PopoverProps> = ({
title,
trigger,
open,
onOpenChange,
children,
className,
side,
align,
}) => {
const { t } = useTranslation();
const rootElement = useRootElement();
return (
<BUIPopover.Root open={open} onOpenChange={onOpenChange}>
<BUIPopover.Trigger render={trigger} />
<BUIPopover.Portal container={rootElement}>
<BUIPopover.Positioner sideOffset={8} side={side} align={align}>
<BUIPopover.Popup className={classNames(styles.popover, className)}>
<div className={styles.title}>
<BUIPopover.Title
render={
<Heading as="h3" type="body" weight="semibold" size="lg">
{title}
</Heading>
}
/>
<BUIPopover.Close
render={
<IconButton
kind="secondary"
size="28px"
aria-label={t("action.close")}
>
<CloseIcon />
</IconButton>
}
/>
</div>
{children}
</BUIPopover.Popup>
</BUIPopover.Positioner>
</BUIPopover.Portal>
</BUIPopover.Root>
);
};
-21
View File
@@ -41,7 +41,6 @@ export enum UserIntent {
StartNewCallDMVoice = "start_call_dm_voice",
JoinExistingCallDM = "join_existing_dm",
JoinExistingCallDMVoice = "join_existing_dm_voice",
VideoRoom = "video_room",
Unknown = "unknown",
}
@@ -144,18 +143,6 @@ export interface UrlConfiguration {
* Defaults to true.
*/
noiseSuppression?: boolean;
/**
* Whether the user may start with the microphone on, whether or not the
* lobby is shown. Set by the intent, not a URL parameter.
* Defaults to true.
*/
initialAudioEnabled?: boolean;
/**
* Whether the user may start with the camera on, whether or not the lobby is
* shown. Set by the intent, not a URL parameter.
* Defaults to true.
*/
initialVideoEnabled?: boolean;
callIntent?: RTCCallIntent;
}
@@ -235,14 +222,6 @@ export function configurationForIntent(intent: UserIntent): UrlConfiguration {
preset.autoLeaveWhenOthersLeft = true;
preset.callIntent = preset.callIntent ?? RTC_CALL_INTENT_VIDEO;
break;
case UserIntent.VideoRoom:
preset.skipLobby = false;
preset.returnToLobby = true;
preset.callIntent = RTC_CALL_INTENT_VIDEO;
// Opening the room should not turn on the user's microphone or camera.
preset.initialAudioEnabled = false;
preset.initialVideoEnabled = false;
break;
// Non widget usecase defaults
default:
preset = {
-27
View File
@@ -318,20 +318,6 @@ describe("UrlParams", () => {
).toMatchObject(joinExistingCallDefaults("desktop"));
});
it("accepts video_room", () => {
expect(
computeUrlParams(
"?intent=video_room&widgetId=1234&parentUrl=parent.org",
),
).toMatchObject({
...joinExistingCallDefaults("desktop"),
returnToLobby: true,
callIntent: RTC_CALL_INTENT_VIDEO,
initialAudioEnabled: false,
initialVideoEnabled: false,
});
});
it("accepts start_call_voice", () => {
expect(
computeUrlParams(
@@ -422,19 +408,6 @@ describe("UrlParams", () => {
});
});
describe.each(["initialAudioEnabled", "initialVideoEnabled"] as const)(
"%s",
(name) => {
it("is not read from the URL", () => {
expect(
computeUrlParams(
`?${name}=false&intent=join_existing&widgetId=1234&parentUrl=parent.org`,
)[name],
).toBeUndefined();
});
},
);
describe("noiseSuppression", () => {
it("defaults to true", () => {
expect(computeUrlParams().noiseSuppression).toBe(true);
+101
View File
@@ -0,0 +1,101 @@
/*
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, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { TooltipProvider } from "@vector-im/compound-web";
import { BehaviorSubject } from "rxjs";
import { ClientProvider } from "./ClientContext";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
import { constant } from "./state/Behavior";
import { UserMenuContainer } from "./UserMenuContainer";
import { flushPromises } from "./utils/test";
vi.mock("./settings/SettingsModal", () => ({
defaultSettingsTab: "audio",
SettingsModal: (): null => null,
}));
const mockClient = (): MatrixClient =>
({
on: vi.fn(),
removeListener: vi.fn(),
getUserId: () => "@alice:example.org",
getUserIdLocalpart: () => "alice",
getDeviceId: () => "AAAA",
getUser: () => null,
stopClient: vi.fn(),
}) as Partial<MatrixClient> as MatrixClient;
test("leaves for home after logging out of the session", async () => {
const logout = vi.fn().mockResolvedValue(undefined);
const leaveToHome = vi.fn();
const client = mockClient();
renderMenu(
{
state$: new BehaviorSubject<ClientSessionState>({
state: "signedIn",
client,
passwordlessUser: false,
}),
},
{
login: vi.fn(),
register: vi.fn(),
logout,
client$: constant(client),
},
leaveToHome,
);
await selectSignOut();
expect(logout).toHaveBeenCalled();
expect(leaveToHome).toHaveBeenCalled();
});
test("cannot end a session that is not ours", async () => {
const leaveToHome = vi.fn();
renderMenu(hostClientSession(mockClient()), null, leaveToHome);
await selectSignOut();
expect(leaveToHome).not.toHaveBeenCalled();
});
async function selectSignOut(): Promise<void> {
const user = userEvent.setup();
await user.click(screen.getByTestId("usermenu_open"));
await user.click(await screen.findByTestId("usermenu_logout"));
await flushPromises();
}
function renderMenu(
session: ClientSession,
manager: ClientManager | null,
leaveToHome: (() => void) | null = null,
): void {
render(
<BrowserRouter>
<TooltipProvider>
<LeaveToHomeProvider value={leaveToHome}>
<ClientProvider session={session}>
<UserMenuContainer clientManager={manager} />
</ClientProvider>
</LeaveToHomeProvider>
</TooltipProvider>
</BrowserRouter>,
);
}
+28 -7
View File
@@ -9,19 +9,38 @@ import { type FC, useCallback, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { logger } from "matrix-js-sdk/lib/logger";
import { useClientLegacy } from "./ClientContext";
import {
useClient,
useClientSessionState,
useLoggedInSpaClient,
} from "./ClientContext";
import { type ClientManager } from "./state/ClientSession";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { useProfile } from "./profile/useProfile";
import { defaultSettingsTab, SettingsModal } from "./settings/SettingsModal";
import { UserMenu } from "./UserMenu";
interface Props {
preventNavigation?: boolean;
/** Null when the session is a host's, which Element Call cannot end. */
clientManager: ClientManager | null;
}
export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
export const UserMenuContainer: FC<Props> = ({
preventNavigation = false,
clientManager,
}) => {
const location = useLocation();
const navigate = useNavigate();
const { client, logout, authenticated, passwordlessUser } = useClientLegacy();
// Who is signed in is the session's; the profile and settings need the
// SPA's whole client
const suppliedClient = useClient();
const client = useLoggedInSpaClient(clientManager);
const logout = clientManager?.logout;
const session = useClientSessionState();
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const leaveToHome = useLeaveToHome();
const { displayName, avatarUrl } = useProfile(client);
const [settingsModalOpen, setSettingsModalOpen] = useState(false);
const onDismissSettingsModal = useCallback(
@@ -43,7 +62,9 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
setSettingsModalOpen(true);
break;
case "logout":
logout?.();
logout?.()
.then(() => leaveToHome?.())
.catch((e) => logger.error("Failed to log out", e));
break;
case "login":
navigate("/login", { state: { from: location } })?.catch((error) =>
@@ -52,7 +73,7 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
break;
}
},
[navigate, location, logout, setSettingsModalOpen],
[navigate, location, logout, leaveToHome, setSettingsModalOpen],
);
const userName = client?.getUserIdLocalpart() ?? "";
@@ -60,11 +81,11 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
<>
<UserMenu
preventNavigation={preventNavigation}
isAuthenticated={authenticated}
isAuthenticated={suppliedClient !== undefined}
isPasswordlessUser={passwordlessUser}
avatarUrl={avatarUrl}
onAction={onAction}
userId={client?.getUserId() ?? ""}
userId={suppliedClient?.getUserId() ?? ""}
displayName={displayName || (userName ? userName.replace("@", "") : "")}
/>
{client && (
+1 -1
View File
@@ -61,7 +61,7 @@ exports[`the modal renders as a drawer in mobile viewports 1`] = `
/>
<h2
id="radix-_r_a_"
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;"
style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"
>
My modal
</h2>
-71
View File
@@ -1,71 +0,0 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Popover renders > button 1`] = `
<button
aria-controls="_r_0_"
aria-expanded="true"
aria-haspopup="dialog"
data-base-ui-click-trigger=""
data-popup-open=""
id="base-ui-_r_1_"
tabindex="0"
type="button"
>
Open popover
</button>
`;
exports[`Popover renders > popover 1`] = `
<div
aria-labelledby="base-ui-_r_4_"
class="_popover_8e8188"
data-align="center"
data-base-ui-focusable=""
data-open=""
data-side="bottom"
id="_r_0_"
role="dialog"
tabindex="-1"
>
<div
class="_title_8e8188"
>
<h3
class="_typography_6v6n8_153 _font-body-lg-semibold_6v6n8_74"
id="base-ui-_r_4_"
>
Example
</h3>
<button
aria-disabled="false"
aria-label="Close"
class="_icon-button_1215g_8"
data-kind="secondary"
role="button"
style="--cpd-icon-button-size: 28px;"
tabindex="0"
type="button"
>
<div
class="_indicator-icon_j097f_17"
style="--cpd-icon-button-size: 100%;"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.293 6.293a1 1 0 0 1 1.414 0L12 10.586l4.293-4.293a1 1 0 1 1 1.414 1.414L13.414 12l4.293 4.293a1 1 0 0 1-1.414 1.414L12 13.414l-4.293 4.293a1 1 0 0 1-1.414-1.414L10.586 12 6.293 7.707a1 1 0 0 1 0-1.414"
/>
</svg>
</div>
</button>
</div>
<p>
This is an example of a popover.
</p>
</div>
`;
+1 -2
View File
@@ -12,7 +12,6 @@ import posthog, {
type Properties,
} from "posthog-js";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixClient } from "matrix-js-sdk";
import { type Subscription } from "rxjs";
import {
@@ -343,7 +342,7 @@ export class PosthogAnalytics {
}
private async getAnalyticsId(): Promise<string | null> {
const client: MatrixClient = window.matrixclient;
const client = window.matrixclient;
if (this.config.matrixBackend === "embedded") {
return this.config.hostAnalyticsId ?? null;
} else {
+81
View File
@@ -0,0 +1,81 @@
/*
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 { afterEach, beforeEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { LoginPage } from "./LoginPage";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { Config } from "../config/Config";
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("signs in with the session's manager and goes home", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockResolvedValue({} as MatrixClient);
renderLogin(manager);
await submit("alice", "hunter2");
expect(manager.login).toHaveBeenCalledWith(
"https://hs.example.org",
"alice",
"hunter2",
);
expect(await screen.findByText("at /")).toBeVisible();
});
test("shows why signing in failed", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockRejectedValue(new Error("Wrong password"));
renderLogin(manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Wrong password")).toBeVisible();
expect(screen.getByText("at /login")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("login_username"), username);
await user.type(screen.getByTestId("login_password"), password);
await user.click(screen.getByTestId("login_login"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderLogin(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/login"]}>
<LoginPage clientManager={manager} />
<WhereAmI />
</MemoryRouter>,
);
}
+9 -14
View File
@@ -11,21 +11,23 @@ import { Trans, useTranslation } from "react-i18next";
import { Button } from "@vector-im/compound-web";
import Logo from "../icons/LogoLarge.svg?react";
import { useClient } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import styles from "./LoginPage.module.css";
import { useInteractiveLogin } from "./useInteractiveLogin";
import { usePageTitle } from "../usePageTitle";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { Link } from "../button/Link";
export const LoginPage: FC = () => {
interface Props {
clientManager: ClientManager;
}
export const LoginPage: FC<Props> = ({ clientManager }) => {
const { t } = useTranslation();
usePageTitle(t("login_title"));
const { client, setClient } = useClient();
const login = useInteractiveLogin(client);
const { login } = clientManager;
const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
@@ -46,15 +48,8 @@ export const LoginPage: FC = () => {
setLoading(false);
return;
}
login(homeserver, usernameRef.current.value, passwordRef.current.value)
.then(async ([client, session]) => {
if (!setClient) {
return;
}
setClient(client, session);
.then(async () => {
const locationState = location.state;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@@ -72,7 +67,7 @@ export const LoginPage: FC = () => {
setLoading(false);
});
},
[login, location, navigate, homeserver, setClient],
[login, location, navigate, homeserver],
);
// we need to limit the length of the homserver name to not cover the whole loginview input with the string.
let shortendHomeserverName = Config.defaultServerName()?.slice(0, 25);
+137
View File
@@ -0,0 +1,137 @@
/*
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 { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RegisterPage } from "./RegisterPage";
import { ClientContextProvider } from "../ClientContext";
import {
type ClientManager,
type ClientSessionState,
} from "../state/ClientSession";
import { constant } from "../state/Behavior";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRegister({ state: "loading" }, mockManager());
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("registers an account, signs in and goes home", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
false,
);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /")).toBeVisible();
});
test("upgrades a passwordless user to a full account", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn: vi.fn(),
});
renderRegister(
{
state: "signedIn",
client: { getUserId: () => "@guest:example.org" } as MatrixClient,
passwordlessUser: true,
},
manager,
);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
true,
);
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Name taken"));
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Name taken")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(screen.getByText("at /register")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("register_username"), username);
await user.type(screen.getByTestId("register_password"), password);
await user.type(screen.getByTestId("register_confirm_password"), password);
await user.click(screen.getByTestId("register_register"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderRegister(
state: ClientSessionState,
manager: ClientManager,
): void {
render(
<MemoryRouter initialEntries={["/register"]}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<RegisterPage clientManager={manager} />
<WhereAmI />
</ClientContextProvider>
</MemoryRouter>,
);
}
+19 -18
View File
@@ -22,8 +22,9 @@ import { logger } from "matrix-js-sdk/lib/logger";
import { Button, Text } from "@vector-im/compound-web";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { useClientLegacy } from "../ClientContext";
import { useInteractiveRegistration } from "./useInteractiveRegistration";
import { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { useRegistrationTerms } from "./useRegistrationTerms";
import styles from "./LoginPage.module.css";
import Logo from "../icons/LogoLarge.svg?react";
import { LoadingPage } from "../FullScreenView";
@@ -33,12 +34,21 @@ import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { ExternalLink, Link } from "../button/Link";
export const RegisterPage: FC = () => {
interface Props {
clientManager: ClientManager;
}
export const RegisterPage: FC<Props> = ({ clientManager }) => {
const { t } = useTranslation();
usePageTitle(t("action.register"));
const { loading, authenticated, passwordlessUser, client, setClient } =
useClientLegacy();
const session = useClientSessionState();
const loading = session.state === "loading";
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const client = useLoggedInSpaClient(clientManager);
const authenticated = client !== undefined;
const { register } = clientManager;
const confirmPasswordRef = useRef<HTMLInputElement>(null);
const navigate = useNavigate();
@@ -47,7 +57,7 @@ export const RegisterPage: FC = () => {
const [error, setError] = useState<Error>();
const [password, setPassword] = useState("");
const [passwordConfirmation, setPasswordConfirmation] = useState("");
const { recaptchaKey, register } = useInteractiveRegistration(client);
const { recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const onSubmitRegisterForm = useCallback(
@@ -64,7 +74,7 @@ export const RegisterPage: FC = () => {
setRegistering(true);
const recaptchaResponse = await execute();
const [newClient, session] = await register(
const { client: newClient, setSignedIn } = await register(
userName,
password,
userName,
@@ -95,7 +105,7 @@ export const RegisterPage: FC = () => {
}
}
setClient?.(newClient, session);
setSignedIn();
PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date());
};
@@ -117,16 +127,7 @@ export const RegisterPage: FC = () => {
reset();
});
},
[
register,
location,
navigate,
passwordlessUser,
reset,
execute,
client,
setClient,
],
[register, location, navigate, passwordlessUser, reset, execute, client],
);
useEffect(() => {
+104
View File
@@ -0,0 +1,104 @@
/*
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 { afterEach, expect, test, vi } from "vitest";
import { createClient, type MatrixClient, MatrixError } from "matrix-js-sdk";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { loginWithPassword, registerWithPassword } from "./interactiveAuth";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const credentials = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
};
// What interactive auth asks of the client besides the request itself
const authClient = { generateClientSecret: () => "client-secret" };
afterEach(() => {
vi.clearAllMocks();
});
test("logs in with a password", async () => {
const login = vi.fn().mockResolvedValue({ ...credentials, extra: "ignored" });
vi.mocked(createClient).mockReturnValue({
...authClient,
login,
} as Partial<MatrixClient> as MatrixClient);
await expect(
loginWithPassword("https://hs.example.org", "alice", "hunter2"),
).resolves.toEqual(credentials);
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
expect(login).toHaveBeenCalledWith("m.login.password", {
identifier: { type: "m.id.user", user: "alice" },
password: "hunter2",
});
});
test("registers, agreeing to the terms and answering the recaptcha", async () => {
// The homeserver turns the first request away with the stages to complete
// No error in it: that is the shape of a challenge rather than a refusal
const challenge = new MatrixError(
{
session: "session",
flows: [{ stages: ["m.login.terms", "m.login.recaptcha"] }],
params: {},
completed: [],
},
401,
);
const registerRequest = vi
.fn()
.mockImplementation(({ auth }: { auth?: { type: string } }) => {
if (auth === undefined) throw challenge;
challenge.data.completed = [
...(challenge.data.completed as string[]),
auth.type,
];
if (challenge.data.completed.length < 2) throw challenge;
return credentials;
});
vi.mocked(createClient).mockReturnValue({
...authClient,
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
await expect(
registerWithPassword(
"https://hs.example.org",
"alice",
"hunter2",
"captcha",
),
).resolves.toEqual(credentials);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
username: "alice",
password: "hunter2",
auth: expect.objectContaining({ type: "m.login.terms" }),
}),
);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
auth: expect.objectContaining({
type: "m.login.recaptcha",
response: "captcha",
}),
}),
);
});
+106
View File
@@ -0,0 +1,106 @@
/*
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 {
createClient,
InteractiveAuth,
type LoginResponse,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { type StoredSession } from "../state/ClientSession";
/** What the homeserver hands out for a new session. */
export type Credentials = Pick<
StoredSession,
"user_id" | "device_id" | "access_token"
>;
/**
* Logs in to the given homeserver with a password.
*/
export async function loginWithPassword(
homeserver: string,
username: string,
password: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
/**
* Registers an account on the given homeserver, accepting its terms and
* answering its recaptcha challenge.
*/
export async function registerWithPassword(
homeserver: string,
username: string,
password: string,
recaptchaResponse: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
// XXX: attemptAuth claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
function credentials(authData: unknown): Credentials {
/* eslint-disable camelcase */
const { user_id, access_token, device_id } = authData as Credentials;
return { user_id, access_token, device_id };
/* eslint-enable camelcase */
}
-84
View File
@@ -1,84 +0,0 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useCallback } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type LoginResponse,
type MatrixClient,
} from "matrix-js-sdk";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
/**
* This provides the login method to login using user credentials.
* @param oldClient If there is an already authenticated client it should be passed to this hook
* this allows the interactive login to sign out the client before logging in.
* @returns A async method that can be called/awaited to log in with the provided credentials.
*/
export function useInteractiveLogin(
oldClient?: MatrixClient,
): (
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]> {
return useCallback<
(
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]>
>(
async (homeserver: string, username: string, password: string) => {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
const session = {
user_id,
access_token,
device_id,
passwordlessUser: false,
};
// To not confuse the rust crypto sessions we need to logout the old client before initializing the new one.
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: homeserver,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
/* eslint-enable camelcase */
return [client, session];
},
[oldClient],
);
}
-145
View File
@@ -1,145 +0,0 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useState, useEffect, useCallback, useRef } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type MatrixClient,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
export const useInteractiveRegistration = (
oldClient?: MatrixClient,
): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<[MatrixClient, Session]>;
} => {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
const authClient = useRef<MatrixClient | undefined>(undefined);
if (!authClient.current) {
authClient.current = createClient({
baseUrl: Config.defaultHomeserverUrl()!,
});
}
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
authClient.current!.registerRequest({}).catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
const register = useCallback(
async (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
): Promise<[MatrixClient, Session]> => {
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient.current!,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.current!.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
await client.setDisplayName(displayName);
const session: Session = {
user_id,
device_id,
access_token,
passwordlessUser,
};
/* eslint-enable camelcase */
if (passwordlessUser) {
session.tempPassword = password;
}
const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName);
user.setDisplayName(displayName);
return [client, session];
},
[oldClient],
);
return { privacyPolicyUrl, recaptchaKey, register };
};
@@ -0,0 +1,116 @@
/*
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 { afterEach, expect, test, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import { type FC, type PropsWithChildren } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { useRegisterPasswordlessUser } from "./useRegisterPasswordlessUser";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
}));
vi.mock("./generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("registers a user under a random name and signs them in", async () => {
const setSignedIn = vi.fn();
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(false),
});
await result.current.registerPasswordlessUser("Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(setSignedIn).toHaveBeenCalled();
expect(result.current.privacyPolicyUrl).toBe(
"https://hs.example.org/privacy",
);
expect(result.current.recaptchaId).toBe("recaptcha");
});
test("resets the captcha when registration fails", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Nope"));
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("Nope");
expect(reset).toHaveBeenCalled();
});
test("cannot register on a session that is not ours", async () => {
const { result } = renderHook(() => useRegisterPasswordlessUser(null), {
wrapper: wrapper(false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("This session cannot register");
});
test("never registers as a widget", async () => {
const manager = mockManager();
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(true),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow(/embedded mode/);
expect(manager.register).not.toHaveBeenCalled();
});
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
function wrapper(isWidget: boolean): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>{children}</UrlParamsProvider>
);
}
+15 -11
View File
@@ -8,8 +8,8 @@ Please see LICENSE in the repository root for full details.
import { useCallback } from "react";
import { secureRandomString } from "matrix-js-sdk/lib/randomstring";
import { useClient } from "../ClientContext";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { type ClientManager } from "../state/ClientSession";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { generateRandomName } from "../auth/generateRandomName";
import { useRecaptcha } from "../auth/useRecaptcha";
import { useUrlParams } from "../UrlParams";
@@ -20,17 +20,21 @@ interface UseRegisterPasswordlessUserType {
recaptchaId?: string;
}
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
const { setClient } = useClient();
/**
* @param clientManager Null in the widget, which never registers anyone.
*/
export function useRegisterPasswordlessUser(
clientManager: ClientManager | null,
): UseRegisterPasswordlessUserType {
const register = clientManager?.register;
const { isWidget } = useUrlParams();
const { privacyPolicyUrl, recaptchaKey, register } =
useInteractiveRegistration();
const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const registerPasswordlessUser = useCallback(
async (displayName: string) => {
if (!setClient) {
throw new Error("No client context");
if (!register) {
throw new Error("This session cannot register");
}
if (isWidget) {
throw new Error(
@@ -41,20 +45,20 @@ export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
try {
const recaptchaResponse = await execute();
const userName = generateRandomName();
const [client, session] = await register(
const { setSignedIn } = await register(
userName,
secureRandomString(16),
displayName,
recaptchaResponse,
true,
);
setClient(client, session);
setSignedIn();
} catch (e) {
reset();
throw e;
}
},
[execute, reset, register, setClient, isWidget],
[execute, reset, register, isWidget],
);
return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId };
+98
View File
@@ -0,0 +1,98 @@
/*
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 { afterEach, beforeEach, expect, test, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { createClient, type MatrixClient } from "matrix-js-sdk";
import { type FC, type PropsWithChildren } from "react";
import { useRegistrationTerms } from "./useRegistrationTerms";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { Config } from "../config/Config";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const registerRequest = vi.fn();
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
vi.mocked(createClient).mockReturnValue({
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("reads the terms the homeserver asks for from a registration attempt", async () => {
registerRequest.mockRejectedValue({
data: {
params: {
"m.login.terms": {
policies: {
privacy_policy: { en: { url: "https://hs.example.org/privacy" } },
},
},
"m.login.recaptcha": { public_key: "site-key" },
},
},
});
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
await waitFor(() =>
expect(result.current).toEqual({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
);
});
test("has nothing to agree to where the homeserver asks for nothing", async () => {
registerRequest.mockRejectedValue({ data: { params: {} } });
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
await waitFor(() => expect(registerRequest).toHaveBeenCalled());
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
test("asks the homeserver nothing as a widget", () => {
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(true),
});
expect(createClient).not.toHaveBeenCalled();
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
function wrapper(isWidget: boolean): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>{children}</UrlParamsProvider>
);
}
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright 2022-2024 New Vector Ltd.
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 { useEffect, useState } from "react";
import { createClient } from "matrix-js-sdk";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
/**
* What the homeserver asks of a registration: its privacy policy to agree to
* and the recaptcha key to answer a challenge with.
*/
export function useRegistrationTerms(): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
} {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
createClient({ baseUrl: Config.defaultHomeserverUrl()! })
.registerRequest({})
.catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en
?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
return { privacyPolicyUrl, recaptchaKey };
}
+32 -31
View File
@@ -25,14 +25,11 @@ import {
OverflowVerticalIcon,
VolumeOnSolidIcon,
VolumeOffSolidIcon,
SettingsSolidIcon,
GridIcon,
SpotlightViewIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import styles from "./Button.module.css";
import callFooterStyles from "../components/CallFooter.module.css";
import { platform } from "../Platform";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
interface MicButtonProps extends ComponentPropsWithoutRef<"button"> {
enabled: boolean;
@@ -152,7 +149,6 @@ interface LoudspeakerButtonProps extends ComponentPropsWithoutRef<"button"> {
size?: "md" | "lg";
loudspeakerModeEnabled: boolean;
}
export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
loudspeakerModeEnabled,
...props
@@ -175,37 +171,36 @@ export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
);
};
interface LayoutSwitchButtonProps extends ComponentPropsWithoutRef<"button"> {
layout: LayoutMode;
function classNamesForScreenWidth(
className?: string,
forScreenWidth?: "wide" | "narrow",
): string {
return classNames(className, {
[callFooterStyles.settingsOnlyShowWide]: forScreenWidth === "wide",
[callFooterStyles.settingsOnlyShowNarrow]: forScreenWidth === "narrow",
});
}
export const LayoutSwitchButton: FC<LayoutSwitchButtonProps> = ({
layout,
interface SettingsIconButtonProps extends ComponentPropsWithoutRef<"button"> {
/** If this buttons should be setup to be used in the app bar */
showForScreenWidth?: "wide" | "narrow";
kind?: "secondary" | "primary";
}
export const SettingsIconButton: FC<SettingsIconButtonProps> = ({
showForScreenWidth,
className,
...props
}) => {
const { t } = useTranslation();
return (
<Tooltip label={t("action.adjust_view")}>
<CpdButton
iconOnly
Icon={layout === "grid" ? GridIcon : SpotlightViewIcon}
kind="secondary"
{...props}
/>
</Tooltip>
);
};
interface SettingsIconButtonProps extends ComponentPropsWithoutRef<"button"> {
kind?: "secondary" | "primary";
}
export const SettingsIconButton: FC<SettingsIconButtonProps> = (props) => {
const { t } = useTranslation();
const Icon =
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon;
return (
<Tooltip label={t("common.settings")}>
<IconButton {...props}>
<SettingsSolidIcon aria-hidden />
<IconButton
className={classNamesForScreenWidth(className, showForScreenWidth)}
{...props}
>
<Icon aria-hidden />
</IconButton>
</Tooltip>
);
@@ -213,13 +208,19 @@ export const SettingsIconButton: FC<SettingsIconButtonProps> = (props) => {
interface SettingsButtonProps extends ComponentPropsWithoutRef<"button"> {
size?: "md" | "lg";
/** If this buttons should be setup to be used in the app bar */
showForScreenWidth?: "wide" | "narrow";
}
export const SettingsButton: FC<SettingsButtonProps> = (props) => {
export const SettingsButton: FC<SettingsButtonProps> = ({
showForScreenWidth,
className,
...props
}) => {
const { t } = useTranslation();
return (
<Tooltip label={t("common.settings")}>
<CpdButton
className={classNamesForScreenWidth(className, showForScreenWidth)}
iconOnly
Icon={
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon
+2
View File
@@ -112,6 +112,7 @@ 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.
@@ -159,6 +160,7 @@ export const BackgroundEffectGrid: FC<Props> = ({
onAdd === undefined ? null : (
<MenuItem
label={null}
hideChevron
className={styles.tile}
onSelect={(e) => {
e.preventDefault();
+1 -1
View File
@@ -24,7 +24,7 @@ import * as CallFooterStories from "./CallFooter.stories";
<Title> Call Footer </Title>
The footer component contains all main interactions needed for a call.
The footer compoentn contains all main interactions needed for a call.
<Subtitle> Mobile layouts </Subtitle>
+33 -93
View File
@@ -9,10 +9,9 @@ Please see LICENSE in the repository root for full details.
position: sticky;
inset-block-end: 0;
z-index: var(--call-view-header-footer-layer);
pointer-events: none;
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-template-areas: ". buttons .";
grid-template-areas: ". buttons layout";
align-items: center;
gap: var(--cpd-space-3x);
/* Ensure that footer lies within the safe area */
@@ -20,10 +19,6 @@ Please see LICENSE in the repository root for full details.
padding-right: calc(env(safe-area-inset-right) + var(--cpd-space-6x));
padding-block: var(--cpd-space-10x)
calc(env(safe-area-inset-bottom) + var(--cpd-space-10x));
> * {
pointer-events: auto;
}
}
.footer.hidden {
@@ -31,57 +26,21 @@ Please see LICENSE in the repository root for full details.
}
.footer.overlay {
transition: opacity 0.18s;
opacity: 0;
> .buttons {
transition: transform 0.18s;
@media (prefers-reduced-motion: no-preference) {
transform: translateY(var(--slide-distance));
}
}
> * {
animation: none;
}
}
@keyframes enable-pointer-events {
0% {
pointer-events: none;
}
100% {
pointer-events: auto;
}
}
.footer.overlay:not(.hidden) {
/* Note that the footer is still position: sticky in this case so that certain
tiles can move up out of the way of the footer when visible. */
opacity: 1;
> .buttons {
transform: none;
}
> * {
/* Enable pointer events after a short timeout, so that tapping to reveal the
footer won't immediately cause any of the buttons to be pressed. */
animation: enable-pointer-events 1ms;
}
transition: opacity 0.15s;
}
.footer.overlay.hidden {
display: grid;
opacity: 0;
pointer-events: none;
/* Switch to position: absolute so the footer takes up no space in the layout
when hidden. */
position: absolute;
inset-block-end: 0;
inset-inline: 0;
> * {
pointer-events: none;
}
}
/* Keep the footer while it is in use: focus inside it, or a menu opened from
@@ -89,17 +48,10 @@ Please see LICENSE in the repository root for full details.
.footer.overlay:has(:focus-visible),
.footer.overlay:has([aria-expanded="true"]) {
opacity: 1;
> .buttons {
transform: none;
}
> * {
pointer-events: auto;
}
pointer-events: initial;
}
.logoContainer {
.settingsLogoContainer {
display: flex;
align-items: center;
gap: var(--cpd-space-4x);
@@ -118,45 +70,13 @@ Please see LICENSE in the repository root for full details.
.buttons {
grid-area: buttons;
justify-self: center;
background: var(--cpd-color-bg-canvas-default);
border-radius: var(--cpd-radius-pill-effect);
box-shadow: var(--big-drop-shadow);
display: flex;
flex-wrap: nowrap;
gap: var(--cpd-space-3x);
}
:global(.cpd-theme-light),
:global(.cpd-theme-light-hc) {
.buttons {
background: var(--cpd-color-bg-canvas-default);
}
}
/* Dark theme uses a different background color, since the drop shadow doesn't
provide enough contrast */
:global(.cpd-theme-dark),
:global(.cpd-theme-dark-hc) {
.buttons {
background: var(--cpd-color-bg-subtle-primary);
}
}
@media (prefers-color-scheme: dark) {
.buttons {
background: var(--cpd-color-bg-subtle-primary);
}
}
.footer[data-button-size="md"] > .buttons {
padding: var(--cpd-space-3x);
gap: var(--cpd-space-2x);
--slide-distance: var(--cpd-space-2x);
}
.footer[data-button-size="lg"] > .buttons {
padding: var(--cpd-space-4x);
gap: var(--cpd-space-4x);
--slide-distance: var(--cpd-space-4x);
.layout {
grid-area: layout;
justify-self: end;
}
/*First hide the logo*/
@@ -166,16 +86,30 @@ provide enough contrast */
}
}
.settingsOnlyShowNarrow {
display: none;
}
.settingsOnlyShowWide {
display: inherit;
}
/*
With the logo hidden >500px is enough space to show logo and buttons.
Once we exceed 500 we hide the logo.
With the logo hidden >500px is enough space to show overflow, buttons, layout.
Once we exceed 500 we hide everything except the buttons.
*/
@container element-call (max-width: 500px) {
.footer {
grid-template-areas: "buttons buttons buttons";
}
.logoContainer {
.settingsOnlyShowNarrow {
display: inherit;
}
.settingsOnlyShowWide {
display: none;
}
.settingsLogoContainer {
display: none;
}
@@ -222,3 +156,9 @@ Once we exceed 500 we hide the logo.
display: none;
}
}
@container element-call (min-width: 800px) {
.buttons {
gap: var(--cpd-space-4x);
}
}
+8 -13
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 { expect, fn, userEvent, waitFor, within } from "storybook/test";
import { expect, fn, userEvent, within } from "storybook/test";
import { BehaviorSubject } from "rxjs";
import { type JSX, type ReactNode } from "react";
import { Link } from "@vector-im/compound-web";
@@ -172,7 +172,7 @@ export const Default: Story = {
openSettings: fn(),
toggleScreenSharing: fn(),
hangup: fn(),
buttonSize: "md",
buttonSize: "lg",
showFooter: true,
hideControls: false,
asOverlay: false,
@@ -202,11 +202,8 @@ export const StaysWhileAMenuIsOpen: Story = {
const footer = canvasElement.querySelector<HTMLElement>(
'[data-testid="footer-container"]',
)!;
// Open microphone menu once footer becomes interactive
await waitFor(async () =>
userEvent.click(
within(canvasElement).getByRole("button", { name: "Microphone" }),
),
await userEvent.click(
within(canvasElement).getByRole("button", { name: "Microphone" }),
);
await expect(document.body.querySelector('[role="menu"]')).not.toBeNull();
@@ -235,9 +232,8 @@ export const SpotlightMode: Story = {
layout: "spotlight",
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement.parentElement!);
await userEvent.click(canvas.getByRole("button", { name: "Adjust view" }));
await userEvent.click(canvas.getByRole("menuitemradio", { name: "Grid" }));
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("radio", { name: "Grid" }));
await expect(args.setLayout).toHaveBeenCalledWith("grid");
await userEvent.click(canvas.getByRole("switch", { name: "Share screen" }));
await expect(args.toggleScreenSharing).toHaveBeenCalled();
@@ -273,11 +269,12 @@ export const Pip: Story = {
...Default,
args: {
...Default.args,
buttonSize: "md",
layout: null,
},
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByRole("button", { name: "Adjust view" }),
within(canvasElement).queryByRole("radio", { name: "Spotlight" }),
).not.toBeInTheDocument();
},
};
@@ -304,7 +301,6 @@ export const MobileLayout: Story = {
args: {
...Default.args,
showLogo: false,
buttonSize: "lg",
audioOutputSwitcher: { targetOutput: "speaker", switch: fn() },
},
@@ -336,7 +332,6 @@ export const LobbyRecentButtonMobile: Story = {
...Default.args,
children: <Link>Back To Recents</Link>,
showLogo: false,
buttonSize: "lg",
layout: null,
toggleScreenSharing: undefined,
},
+28 -24
View File
@@ -16,6 +16,7 @@ import {
SettingsButton,
ReactionToggleButton,
LoudspeakerButton,
SettingsIconButton,
type ReactionData,
} from "../button";
import styles from "./CallFooter.module.css";
@@ -119,6 +120,20 @@ export const CallFooter: FC<FooterProps> = ({
const buttons: JSX.Element[] = [];
if (openSettings !== undefined) {
// Add the settings button to the center group so it's visible on small
// screens. On larger screens the SettingsIconButton with
// showForScreenWidth="wide" in the settingsLogoContainer is used instead.
buttons.push(
<SettingsButton
key="settings"
showForScreenWidth="narrow"
onClick={openSettings}
data-testid="settings-bottom-center"
/>,
);
}
buttons.push(
<MediaMenuButton
key="audio"
@@ -174,28 +189,6 @@ export const CallFooter: FC<FooterProps> = ({
if (audioOutputButton) buttons.push(audioOutputButton);
if (layoutSwitchVm !== null) {
buttons.push(
<LayoutSwitch
key="layout"
vm={layoutSwitchVm}
className={styles.layout}
size={buttonSize}
/>,
);
}
if (openSettings !== undefined) {
buttons.push(
<SettingsButton
size={buttonSize}
key="settings"
onClick={openSettings}
data-testid="settings-bottom"
/>,
);
}
if (hangup)
buttons.push(
<EndCallButton
@@ -228,17 +221,28 @@ export const CallFooter: FC<FooterProps> = ({
<div
ref={ref}
data-testid="footer-container"
data-button-size={buttonSize}
className={classNames(className, styles.footer, {
[styles.overlay]: asOverlay,
[styles.hidden]: !showFooter,
})}
>
<div className={styles.logoContainer}>
<div className={styles.settingsLogoContainer}>
{openSettings !== undefined && (
<SettingsIconButton
key="settings"
kind="secondary"
showForScreenWidth="wide"
onClick={openSettings}
data-testid="settings-bottom-left"
/>
)}
{children}
{(showLogo || debugTileLayout) && logoDebugContainer}
</div>
{!hideControls && <div className={styles.buttons}>{buttons}</div>}
{!hideControls && layoutSwitchVm && (
<LayoutSwitch vm={layoutSwitchVm} className={styles.layout} />
)}
</div>
);
};
+4 -2
View File
@@ -80,7 +80,9 @@ export function createCallFooterViewModel(
hideControls$: constant(!showControls),
showModals$: callModel.showModals$,
asOverlay$: callModel.edgeToEdge$,
buttonSize$: constant(platform === "desktop" ? "md" : "lg"),
buttonSize$: scope.behavior(
isPip$.pipe(map<boolean, "md" | "lg">((pip) => (pip ? "md" : "lg"))),
),
openSettings$: scope.behavior(
combineLatest([
@@ -160,7 +162,7 @@ export function createLobbyFooterViewModel(
hideControls: false,
asOverlay: false,
showModals: true,
buttonSize: platform === "desktop" ? "md" : "lg",
buttonSize: "lg",
openSettings,
hangup,
debugTileLayout: false,
+1 -1
View File
@@ -26,7 +26,7 @@ function MediaMenuButtonStoryWrapper({
...snapshot
}: MediaMenuSnapshot & { kind: "audio" | "video" }): ReactNode {
const vm = useStaticViewModel(snapshot);
return <MediaMenuButton kind={kind} vm={vm} size="md" />;
return <MediaMenuButton kind={kind} vm={vm} size="lg" />;
}
const meta = {
-2
View File
@@ -88,7 +88,6 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
return kind === "audio" ? (
<MediaMuteAndSwitchButton
size={size}
iconsAndLabels="audio"
enabled={enabled}
busy={busy}
@@ -103,7 +102,6 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
/>
) : (
<MediaMuteAndSwitchButton
size={size}
iconsAndLabels="video"
enabled={enabled}
busy={busy}
@@ -16,25 +16,13 @@ Please see LICENSE in the repository root for full details.
.containerOpen {
background-color: var(--cpd-color-bg-action-primary-pressed);
}
.menuButton {
background-color: transparent !important;
&[data-size="md"] {
width: var(--cpd-space-8x);
}
&[data-size="lg"] {
width: var(--cpd-space-10x);
}
> svg {
color: var(--cpd-color-icon-secondary);
/* Nudge the icon toward the toggle button to perceptually center it */
margin-inline-start: calc(-1 * var(--cpd-space-1x));
}
}
.menuButton.chevronIconOpen > svg {
.chevronIconOpen > svg {
color: var(--cpd-color-icon-on-solid-primary);
}
.menuButton {
width: 40px;
background-color: transparent !important;
}
.itemIcon {
color: var(--cpd-color-text-secondary);
}
@@ -537,9 +537,7 @@ export const RemovingWithLiveSelection: Story = {
const cross = tile.parentElement!.querySelector<HTMLElement>(
"[aria-hidden]:last-child",
)!;
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
await waitFor(async () => expect(cross).toBeVisible());
await expect(cross).toBeVisible();
await userEvent.click(cross);
await waitFor(async () =>
@@ -909,10 +907,7 @@ export const SelectionSettling: Story = {
await menu.findByRole("menuitemradio", { name: "Microphone 2" }),
);
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
const spinner = await menu.findByLabelText("Activating…");
await waitFor(async () => expect(spinner).toBeVisible());
await expect(await menu.findByLabelText("Activating…")).toBeVisible();
for (const item of menu.getAllByRole("menuitemradio"))
await expect(item).toHaveAttribute("aria-disabled", "true");
},
@@ -291,7 +291,7 @@ describe("MediaMuteAndSwitchButton", () => {
// After clicking, plannedSelection="mic2" but selectedOption is still "mic1",
// so mic2 should be in an activating state
screen.getByRole("menuitemradio", {
name: /^Microphone 2\s*Activating…$/,
name: "Microphone 2 Activating…",
checked: false,
});
+2 -4
View File
@@ -57,7 +57,6 @@ export interface MenuOptions {
}
export interface MediaMuteAndSwitchButtonProps {
size?: "md" | "lg";
/** If the Mute button is enabled */
enabled?: boolean;
/** Callback if the mute button is clicked */
@@ -121,7 +120,6 @@ const MENU_MARGIN = 16;
const PREVIEW_GAP = 12;
export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
size,
enabled,
busy,
onMuteClick,
@@ -278,7 +276,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
const MuteButton = audioMeter ? MicButton : VideoButton;
const button = (
<MuteButton
size={size}
enabled={enabled ?? false}
busy={isBusy}
onClick={(e) => {
@@ -368,6 +365,7 @@ 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={
@@ -449,7 +447,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
})}
Icon={menuOpen ? ChevronUpIcon : ChevronDownIcon}
kind={"tertiary"}
size={size}
size="lg"
aria-label={optionsButtonLabel}
/>
}
+14 -10
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 { afterEach, describe, expect, test, vi } from "vitest";
import { afterEach, describe, expect, test } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { E2eeType } from "@element-hq/matrixrtc-sdk";
@@ -15,14 +15,9 @@ import {
useRoomEncryptionSystem,
} from "./sharedKeyManagement";
vi.mock("../ClientContext", () => {
const room = { hasEncryptionStateEvent: (): boolean => false };
const client = { getRoom: (): typeof room => room };
return { useClient: (): { client: typeof client } => ({ client }) };
});
const roomId = "!room:example.org";
const otherRoomId = "!other:example.org";
const room = { roomId, hasEncryptionStateEvent: (): boolean => false };
describe("getKeyForRoom", () => {
afterEach(() => {
@@ -67,8 +62,17 @@ describe("useRoomEncryptionSystem", () => {
localStorage.clear();
});
test("encrypts per participant in an encrypted room without a key", () => {
const encryptedRoom = {
roomId,
hasEncryptionStateEvent: (): boolean => true,
};
const { result } = renderHook(() => useRoomEncryptionSystem(encryptedRoom));
expect(result.current).toEqual({ kind: E2eeType.PER_PARTICIPANT });
});
test("picks up a key saved for the room after it rendered", () => {
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
const { result } = renderHook(() => useRoomEncryptionSystem(room));
expect(result.current).toEqual({ kind: E2eeType.NONE });
act(() => saveKeyForRoom(roomId, "stored"));
@@ -82,7 +86,7 @@ describe("useRoomEncryptionSystem", () => {
test("stores a key from the parameters under the room's key only", () => {
window.location.hash = `#?roomId=${encodeURIComponent(roomId)}&password=from-the-link`;
renderHook(() => useRoomEncryptionSystem(roomId));
renderHook(() => useRoomEncryptionSystem(room));
expect(Object.keys(localStorage)).toEqual([`room-shared-key-${roomId}`]);
expect(getKeyForRoom(roomId)).toBe("from-the-link");
@@ -92,7 +96,7 @@ describe("useRoomEncryptionSystem", () => {
saveKeyForRoom(roomId, "stored");
window.location.hash = `#?roomId=${encodeURIComponent(otherRoomId)}&password=other-room`;
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
const { result } = renderHook(() => useRoomEncryptionSystem(room));
expect(result.current).toEqual({
kind: E2eeType.SHARED_KEY,
+6 -7
View File
@@ -6,6 +6,7 @@ Please see LICENSE in the repository root for full details.
*/
import { useEffect, useMemo } from "react";
import { type Room } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import {
@@ -14,7 +15,6 @@ import {
} from "../useLocalStorage";
import { getUrlParams, useUrlParams } from "../UrlParams";
import { E2eeType, type EncryptionSystem } from "@element-hq/matrixrtc-sdk";
import { useClient } from "../ClientContext";
/**
* This setter will update the state for all `useRoomSharedKey` hooks
@@ -89,18 +89,17 @@ export function getKeyForRoom(roomId: string): string | null {
export { type EncryptionSystem } from "@element-hq/matrixrtc-sdk";
export function useRoomEncryptionSystem(roomId: string): EncryptionSystem {
const { client } = useClient();
export function useRoomEncryptionSystem(
room: Pick<Room, "roomId" | "hasEncryptionStateEvent">,
): EncryptionSystem {
const { roomId: paramsRoomId, password } = useUrlParams();
const [storedPassword] = useRoomSharedKey(
roomId,
keyForRoom(roomId, paramsRoomId, password) ?? undefined,
room.roomId,
keyForRoom(room.roomId, paramsRoomId, password) ?? undefined,
);
const room = client?.getRoom(roomId);
const e2eeSystem = useMemo<EncryptionSystem>(() => {
if (!room) return { kind: E2eeType.NONE };
if (storedPassword)
return {
kind: E2eeType.SHARED_KEY,
+1
View File
@@ -29,6 +29,7 @@ describe("CallList", () => {
roomAlias: "#room-name:server.org",
room: {
roomId: "!roomId",
hasEncryptionStateEvent: () => false,
},
},
] as GroupCallRoom[];
+1 -1
View File
@@ -58,7 +58,7 @@ interface CallTileProps {
const CallTile: FC<CallTileProps> = ({ name, avatarUrl, room, client }) => {
const { t } = useTranslation();
const roomEncryptionSystem = useRoomEncryptionSystem(room.roomId);
const roomEncryptionSystem = useRoomEncryptionSystem(room);
const [isLeaving, setIsLeaving] = useState(false);
const onRemove = useCallback(
+96
View File
@@ -0,0 +1,96 @@
/*
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, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { HomePage } from "./HomePage";
import { ClientContextProvider } from "../ClientContext";
import { constant } from "../state/Behavior";
import {
type ClientManager,
type ClientSessionState,
} from "../state/ClientSession";
vi.mock("./RegisteredView", () => ({
RegisteredView: ({ client }: { client: MatrixClient }) => (
<span>registered as {client.getUserId()}</span>
),
}));
vi.mock("./UnauthenticatedView", () => ({
UnauthenticatedView: () => <span>unauthenticated</span>,
}));
test("waits for the session to be restored", () => {
renderHome({ state: "loading" });
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("shows the session's error", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
renderHome({ state: "error", error: new Error("Opened elsewhere") });
expect(screen.getByText("Something went wrong")).toBeVisible();
});
test("welcomes a signed-in user", () => {
renderHome({
state: "signedIn",
client: { getUserId: () => "@alice:example.org" } as MatrixClient,
passwordlessUser: false,
});
expect(screen.getByText("registered as @alice:example.org")).toBeVisible();
});
test("welcomes a widget's user, who has no client manager", () => {
renderHome(
{
state: "signedIn",
client: { getUserId: () => "@bob:example.org" } as MatrixClient,
passwordlessUser: false,
},
null,
);
expect(screen.getByText("registered as @bob:example.org")).toBeVisible();
});
test("invites a signed-out user to start a call", () => {
renderHome({ state: "signedOut" });
expect(screen.getByText("unauthenticated")).toBeVisible();
});
test("cannot sign in to a host's session that is signed out", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
renderHome({ state: "signedOut" }, null);
expect(screen.getByText("Something went wrong")).toBeVisible();
expect(screen.queryByText("unauthenticated")).toBeNull();
});
function renderHome(
state: ClientSessionState,
manager: ClientManager | null = {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
// The manager's client is the session's, whole
client$: constant(
state.state === "signedIn" ? (state.client as MatrixClient) : undefined,
),
},
): void {
render(
<BrowserRouter>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<HomePage clientManager={manager} />
</ClientContextProvider>
</BrowserRouter>,
);
}
+36 -13
View File
@@ -7,28 +7,51 @@ Please see LICENSE in the repository root for full details.
import { useTranslation } from "react-i18next";
import { type FC } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { useClientState } from "../ClientContext";
import { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
import { ErrorPage, LoadingPage } from "../FullScreenView";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { RegisteredView } from "./RegisteredView";
import { type ClientManager } from "../state/ClientSession";
import { usePageTitle } from "../usePageTitle";
export const HomePage: FC = () => {
interface Props {
/** Null where the session is a host's and not ours to manage. */
clientManager: ClientManager | null;
}
export const HomePage: FC<Props> = ({ clientManager }) => {
const { t } = useTranslation();
usePageTitle(t("common.home"));
const clientState = useClientState();
const session = useClientSessionState();
const spaClient = useLoggedInSpaClient(clientManager);
if (!clientState) {
return <LoadingPage />;
} else if (clientState.state === "error") {
return <ErrorPage error={clientState.error} />;
} else {
return clientState.authenticated ? (
<RegisteredView client={clientState.authenticated.client} />
) : (
<UnauthenticatedView />
);
switch (session.state) {
case "loading":
return <LoadingPage />;
case "error":
return <ErrorPage error={session.error} />;
case "signedIn": {
// STOP GAP: a widget has no client manager, but its client is a whole
// one from our own js-sdk.
const client =
clientManager !== null
? spaClient
: (session.client as MatrixClient | undefined);
return client ? (
<RegisteredView client={client} clientManager={clientManager} />
) : (
<LoadingPage />
);
}
case "signedOut":
// A host's session cannot be signed in to from here
return clientManager === null ? (
<ErrorPage error={new Error("Signed out of the host's session")} />
) : (
<UnauthenticatedView clientManager={clientManager} />
);
}
};
+4 -2
View File
@@ -38,12 +38,14 @@ import { AnalyticsNotice } from "../analytics/AnalyticsNotice";
import { E2eeType } from "../e2ee/e2eeType";
import { useOptInAnalytics } from "../settings/settings";
import { useUrlParams } from "../UrlParams";
import { type ClientManager } from "../state/ClientSession";
interface Props {
client: MatrixClient;
clientManager: ClientManager | null;
}
export const RegisteredView: FC<Props> = ({ client }) => {
export const RegisteredView: FC<Props> = ({ client, clientManager }) => {
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
@@ -122,7 +124,7 @@ export const RegisteredView: FC<Props> = ({ client }) => {
<HeaderLogo />
</LeftNav>
<RightNav>
<UserMenuContainer />
<UserMenuContainer clientManager={clientManager} />
</RightNav>
</Header>
)}
+139
View File
@@ -0,0 +1,139 @@
/*
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 { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import type * as matrixUtils from "../utils/matrix";
import { createRoom, getRelativeRoomUrl } from "../utils/matrix";
import { E2eeType } from "../e2ee/e2eeType";
vi.mock("../auth/useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("../auth/useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
vi.mock("../auth/generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
vi.mock("../utils/matrix", async (importOriginal) => ({
...(await importOriginal<typeof matrixUtils>()),
createRoom: vi.fn(),
}));
vi.mock("../UserMenuContainer", () => ({ UserMenuContainer: () => null }));
const reset = vi.fn();
const client = {} as MatrixClient;
afterEach(() => vi.clearAllMocks());
test("registers a guest, creates their call and signs them in", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockResolvedValue({
roomId: "!call:example.org",
alias: "#my-call:example.org",
password: "secret",
});
renderView(manager);
await submit("My Call", "Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(createRoom).toHaveBeenCalledWith(
client,
"My Call",
E2eeType.SHARED_KEY,
);
expect(setSignedIn).toHaveBeenCalled();
const url = getRelativeRoomUrl(
"!call:example.org",
{ kind: E2eeType.SHARED_KEY, secret: "secret" },
"My Call",
);
expect(await screen.findByText(`at ${url}`)).toBeVisible();
});
test("signs in only once the user chooses to join a call that exists", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockRejectedValue({ errcode: "M_ROOM_IN_USE" });
renderView(manager);
await submit("My Call", "Alice");
const join = await screen.findByRole("button", { name: "Yes, join call" });
expect(setSignedIn).not.toHaveBeenCalled();
await userEvent.click(join);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /my-call")).toBeVisible();
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Rate limited"));
renderView(manager);
await submit("My Call", "Alice");
expect(await screen.findByText("Rate limited")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(createRoom).not.toHaveBeenCalled();
});
async function submit(callName: string, displayName: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("home_callName"), callName);
await user.type(screen.getByTestId("home_displayName"), displayName);
await user.click(screen.getByTestId("home_go"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => {
const { pathname, search, hash } = useLocation();
return <span>{`at ${pathname}${search}${hash}`}</span>;
};
function renderView(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/"]}>
<UrlParamsProvider value={computeUrlParams()}>
<UnauthenticatedView clientManager={manager} />
<WhereAmI />
</UrlParamsProvider>
</MemoryRouter>,
);
}
+18 -26
View File
@@ -12,7 +12,7 @@ import { Button, Heading, Text } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { useNavigate } from "react-router-dom";
import { useClient } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
import { UserMenuContainer } from "../UserMenuContainer";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
@@ -22,7 +22,7 @@ import {
roomAliasLocalpartFromRoomName,
sanitiseRoomNameInput,
} from "../utils/matrix";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { JoinExistingCallModal } from "./JoinExistingCallModal";
import { useRecaptcha } from "../auth/useRecaptcha";
import { Form } from "../form/Form";
@@ -36,13 +36,17 @@ import { useOptInAnalytics } from "../settings/settings";
import { ExternalLink, Link } from "../button/Link";
import { useUrlParams } from "../UrlParams";
export const UnauthenticatedView: FC = () => {
const { setClient } = useClient();
interface Props {
clientManager: ClientManager;
}
export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
const { register } = clientManager;
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const [optInAnalytics] = useOptInAnalytics();
const { recaptchaKey, register } = useInteractiveRegistration();
const { recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const [joinExistingCallModalOpen, setJoinExistingCallModalOpen] =
@@ -67,7 +71,9 @@ export const UnauthenticatedView: FC = () => {
setLoading(true);
const recaptchaResponse = await execute();
const userName = generateRandomName();
const [client, session] = await register(
// Signed in only once the call exists too: this view is replaced the
// moment the session has a user, and the call is what they came for
const { client, setSignedIn } = await register(
userName,
secureRandomString(16),
displayName,
@@ -83,15 +89,12 @@ export const UnauthenticatedView: FC = () => {
E2eeType.SHARED_KEY,
);
} catch (error) {
if (!setClient) {
throw error;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (error.errcode === "M_ROOM_IN_USE") {
setOnFinished(() => {
setClient(client, session);
// Wrapped once more, as a bare function would be taken for an updater
setOnFinished(() => () => {
setSignedIn();
const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName);
navigate(`/${aliasLocalpart}`)?.catch((error) => {
logger.error("Failed to navigate to alias localpart", error);
@@ -106,14 +109,10 @@ export const UnauthenticatedView: FC = () => {
}
}
// Only consider the registration successful if we managed to create the room, too
if (!setClient) {
throw new Error("setClient is undefined");
}
if (!createRoomResult.password)
throw new Error("Failed to create room with shared secret");
setClient(client, session);
setSignedIn();
await navigate(
getRelativeRoomUrl(
createRoomResult.roomId,
@@ -130,14 +129,7 @@ export const UnauthenticatedView: FC = () => {
reset();
});
},
[
register,
reset,
execute,
navigate,
setJoinExistingCallModalOpen,
setClient,
],
[register, reset, execute, navigate, setJoinExistingCallModalOpen],
);
return (
@@ -149,7 +141,7 @@ export const UnauthenticatedView: FC = () => {
<HeaderLogo />
</LeftNav>
<RightNav hideMobile>
<UserMenuContainer />
<UserMenuContainer clientManager={clientManager} />
</RightNav>
</Header>
)}
+14 -24
View File
@@ -25,25 +25,19 @@ describe("useGroupCallRooms", () => {
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test.each([EventType.RTCMembershipStable, EventType.RTCMembership])(
"lists a joined room with a sticky %s membership",
(type) => {
const room = mockCallRoom({
stickyEvents: [new MatrixEvent({ type })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
},
);
test("lists a joined room with a sticky RTC membership", () => {
const room = mockCallRoom({
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test.each([EventType.RTCMembershipStable, EventType.RTCMembership])(
"lists a joined room with a %s membership in its timeline",
(type) => {
const room = mockCallRoom({
timelineEvents: [new MatrixEvent({ type })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
},
);
test("lists a joined room with an RTC membership in its timeline", () => {
const room = mockCallRoom({
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test("lists a knocked room without any call events", () => {
const room = mockCallRoom({
@@ -67,12 +61,8 @@ describe("useGroupCallRooms", () => {
const room = mockCallRoom({
membership,
legacyMemberState: true,
stickyEvents: [
new MatrixEvent({ type: EventType.RTCMembershipStable }),
],
timelineEvents: [
new MatrixEvent({ type: EventType.RTCMembershipStable }),
],
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([]);
},
+4 -11
View File
@@ -7,7 +7,6 @@ Please see LICENSE in the repository root for full details.
import {
type MatrixClient,
type MatrixEvent,
type RoomMember,
type Room,
RoomEvent,
@@ -144,25 +143,19 @@ const roomHasCallMembershipEvents = (room: Room): boolean => {
// Check for recent calls using sticky events.
for (const sticky of room._unstable_getStickyEvents()) {
if (isRtcMembershipEvent(sticky)) {
if (sticky.getType() === EventType.RTCMembership) {
return true;
}
}
// Otherwise, check recent event history to see if anyone had
// sent a call membership in here.
return timeline.getEvents().some(isRtcMembershipEvent);
return timeline
.getEvents()
.some((e) => e.getType() === EventType.RTCMembership);
// Otherwise, it's *unlikely* this room was ever a call.
};
// Memberships sent before the event type was stabilised still mark a call room.
function isRtcMembershipEvent(event: MatrixEvent): boolean {
const type = event.getType();
return (
type === EventType.RTCMembershipStable || type === EventType.RTCMembership
);
}
export function useGroupCallRooms(client: MatrixClient): GroupCallRoom[] {
const [rooms, setRooms] = useState<GroupCallRoom[]>([]);
+26 -11
View File
@@ -16,10 +16,14 @@ import { createRoot } from "react-dom/client";
import "./index.css";
import { logger } from "matrix-js-sdk/lib/logger";
import { App } from "./App";
import { App, loadStandaloneClientSession } from "./App";
import { init as initRageshake } from "./settings/rageshake";
import { Initializer } from "./initializer";
import { AppViewModel } from "./state/AppViewModel";
import {
pendingHostClientSession,
signedOutClientSession,
} from "./state/ClientSession";
import { globalScope } from "./state/ObservableScope";
import { getUrlParams } from "./UrlParams";
@@ -49,19 +53,30 @@ if (fatalError !== null) {
}
Initializer.initBeforeReact()
.then((widget) => {
.then(async (widget) => {
const { controlledAudioDevices, callIntent } = getUrlParams();
// As a widget, the client comes from the host over the widget API, and
// the session is the host's. Standalone, Element Call restores or creates
// a session of its own, which it also manages.
const options = { controlledAudioDevices, callIntent };
let vm: AppViewModel;
if (widget !== null) {
vm = new AppViewModel(
globalScope,
options,
pendingHostClientSession(globalScope, widget.client),
null,
);
} else if (loadStandaloneClientSession !== undefined) {
const session = await loadStandaloneClientSession(globalScope);
vm = new AppViewModel(globalScope, options, session, session);
} else {
// The embedded package opened outside a widget: no one can sign in
vm = new AppViewModel(globalScope, options, signedOutClientSession, null);
}
root.render(
<StrictMode>
<App
vm={
new AppViewModel(globalScope, {
controlledAudioDevices,
callIntent,
})
}
widget={widget}
/>
<App vm={vm} widget={widget} />
</StrictMode>,
);
})
+2 -4
View File
@@ -21,7 +21,7 @@ import {
} from "react";
import { logger } from "matrix-js-sdk/lib/logger";
import { useClientState } from "../ClientContext";
import { useHostBridge } from "../HostBridge";
import { ElementCallReactionEventType, type ReactionOption } from ".";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { useBehavior } from "../useBehavior";
@@ -72,9 +72,7 @@ export const ReactionsSenderProvider = ({
/** Our own membership, which the reactions relate to, and the current reactions. */
vm: CallViewModel;
}): JSX.Element => {
const clientState = useClientState();
const supportsReactions =
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
const { supportsReactions } = useHostBridge();
const myMembershipIdentifier = `${client.getUserId()}:${client.getDeviceId()}`;
const localMember = useBehavior(vm.localMember$);
+14 -16
View File
@@ -59,7 +59,7 @@ import {
} from "../utils/errors";
import {
BackgroundEffectsProvider,
createAppBackgroundEffects,
createAppBackgroundEffects$,
} from "../tracks/BackgroundEffectsContext";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { constant } from "../state/Behavior";
@@ -137,24 +137,23 @@ beforeEach(() => {
);
});
async function createCallView(
function createCallView(
hostBridge: HostBridge,
joined = true,
options: {
/** Wait for the host to say when to join, rather than joining at once. */
preload?: boolean;
} = {},
): Promise<{
): {
rtcSession: MatrixRTCSession;
getByText: ReturnType<typeof render>["getByText"];
}> {
} {
const client = {
...mockEmitter(),
getUser: () => null,
getUserId: () => localRtcMember.userId,
getDeviceId: () => localRtcMember.deviceId,
getRoom: (rId) => (rId === roomId ? room : null),
doesServerSupportUnstableFeature: vi.fn().mockResolvedValue(true),
} as Partial<MatrixClient> as MatrixClient;
const room = mockMatrixRoom({
relations: {
@@ -169,6 +168,7 @@ async function createCallView(
getMembersWithMembership: () => [carol],
getMxcAvatarUrl: () => null,
getJoinRule: () => JoinRule.Invite,
hasEncryptionStateEvent: () => false,
});
const rtcSession = new MockRTCSession(room, []).withMemberships(
constant([localRtcMember]),
@@ -180,7 +180,7 @@ async function createCallView(
<TooltipProvider>
<MediaDevicesContext value={mockMediaDevices({})}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects(testScope())}
effects={createAppBackgroundEffects$(testScope())}
>
<CallView
backend={
@@ -204,8 +204,6 @@ async function createCallView(
</HostBridgeProvider>
</BrowserRouter>,
);
// Let the homeserver capability check resolve, which the call waits for
await act(flushPromises);
return {
getByText,
rtcSession: rtcSession.asMockedSession(),
@@ -214,7 +212,7 @@ async function createCallView(
test.skip("CallView plays a leave sound asynchronously in SPA mode", async () => {
const user = userEvent.setup();
const { getByText, rtcSession } = await createCallView(nullHostBridge);
const { getByText, rtcSession } = createCallView(nullHostBridge);
const leaveButton = getByText("Leave");
await user.click(leaveButton);
expect(playSound).toHaveBeenCalledWith("left");
@@ -244,7 +242,7 @@ test.skip("CallView plays a leave sound synchronously in widget mode", async ()
soundDuration: {},
});
const { getByText, rtcSession } = await createCallView(hostBridge);
const { getByText, rtcSession } = createCallView(hostBridge);
const leaveButton = getByText("Leave");
await user.click(leaveButton);
await flushPromises();
@@ -277,7 +275,7 @@ test("Should ask the host to close when all other left and play a sound", async
soundDuration: {},
});
const { getByText } = await createCallView(hostBridge);
const { getByText } = createCallView(hostBridge);
const leaveButton = getByText("SimulateOtherLeft");
await user.click(leaveButton);
await flushPromises();
@@ -294,7 +292,7 @@ test("Waits for the host to say when to join, when preloaded", async () => {
const join$ = new Subject<HostRequest<JoinCallData>>();
const hostBridge: HostBridge = { ...nullHostBridge, join$ };
await createCallView(hostBridge, false, { preload: true });
createCallView(hostBridge, false, { preload: true });
await flushPromises();
// Past the lobby, but not in the call: the host has not asked yet
expect(screen.queryByText("Leave")).toBeNull();
@@ -319,7 +317,7 @@ test("Should not ask the host to close when auto leave due to error", async () =
close,
};
const { getByText } = await createCallView(hostBridge);
const { getByText } = createCallView(hostBridge);
const leaveButton = getByText("SimulateErrorLeft");
await user.click(leaveButton);
await flushPromises();
@@ -342,7 +340,7 @@ test.skip("CallView leaves the session when an error occurs", async () => {
);
});
const user = userEvent.setup();
const { rtcSession } = await createCallView(nullHostBridge);
const { rtcSession } = createCallView(nullHostBridge);
await user.click(screen.getByRole("button", { name: "Panic!" }));
screen.getByText("Something went wrong");
expect(leaveRTCSession).toHaveBeenCalledWith(
@@ -359,7 +357,7 @@ test.skip("CallView shows errors that occur during joining", async () => {
onTestFinished(() => {
enterRTCSession.mockReset();
});
await createCallView(nullHostBridge, false);
createCallView(nullHostBridge, false);
await user.click(screen.getByRole("button", { name: "Join call" }));
screen.getByText("Call is not supported");
});
@@ -381,7 +379,7 @@ test("user can reconnect after losing the connection", async () => {
},
);
const user = userEvent.setup();
await createCallView(nullHostBridge, true);
createCallView(nullHostBridge, true);
await user.click(screen.getByRole("button", { name: "LoseConnection" }));
await screen.findByText("Connection lost");
// Never joined, so there was no call to leave
+5 -41
View File
@@ -13,12 +13,7 @@ import {
useMemo,
useState,
} from "react";
import {
type MatrixClient,
JoinRule,
type Room,
UNSTABLE_MSC4354_STICKY_EVENTS,
} from "matrix-js-sdk";
import { type MatrixClient, JoinRule, type Room } from "matrix-js-sdk";
import {
Room as LivekitRoom,
isE2EESupported as isE2EESupportedBrowser,
@@ -151,7 +146,7 @@ export const CallView: FC<Props> = ({
// rebuilt.
const [joined, setJoined] = useState(false);
const muteStates = useMuteStates();
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
const e2eeSystem = useRoomEncryptionSystem(backend);
// One slot for every join of this call: leaving and joining again, to
// reconnect or from the lobby, happens on the same one
@@ -171,35 +166,7 @@ export const CallView: FC<Props> = ({
return (): void => scope.end();
}, [backend, e2eeSystem, externalRtcSession]);
// Known before the call renders, so a join without a lobby picks the right
// Matrix RTC mode
const [stickyEventsSupported, setStickyEventsSupported] = useState<
boolean | null
>(null);
useEffect(() => {
let cancelled = false;
void backend
.doesServerSupportUnstableFeature(UNSTABLE_MSC4354_STICKY_EVENTS)
.catch((e) => {
// This will also fail in embedded mode if the HS does not
// set `Access-Control-Allow-Origin: *`:
// The page is loaded from a file url (origin=null) + widget api does not handle this
// -> a raw http request will be used -> CORS errors due to origin=null
// The conclusion is: matrix 2.0 mode will always fall back in widget mode on mobile.
// This is acceptable as we plan to not extend the widget api for full 2.0 mode support.
logger.warn("Failed to check if sticky events are supported", e);
return false;
})
.then((supported) => {
if (!cancelled) setStickyEventsSupported(supported);
});
return (): void => {
cancelled = true;
};
}, [backend]);
if (muteStates === null || slot === null || stickyEventsSupported === null)
return null;
if (muteStates === null || slot === null) return null;
return (
<LoadedCallView
@@ -213,7 +180,6 @@ export const CallView: FC<Props> = ({
joined={joined}
setJoined={setJoined}
muteStates={muteStates}
stickyEventsSupported={stickyEventsSupported}
/>
);
};
@@ -259,6 +225,8 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
| "_unstable_getStickyEvents"
| "getLiveTimeline"
| "relations"
// The invite link's encryption system
| "hasEncryptionStateEvent"
// `on`/`off`, to listen for:
// - `RoomEvent.Name` (room name)
// - `RoomStateEvent.Update` and `RoomEvent.CurrentStateUpdated` (avatar
@@ -283,8 +251,6 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
joined: boolean;
setJoined: (value: boolean) => void;
muteStates: MuteStates;
/** Whether the homeserver supports sticky events (MSC4354), which Matrix 2.0 needs. */
stickyEventsSupported: boolean;
}
/**
@@ -317,7 +283,6 @@ const LoadedCallView: FC<LoadedProps> = ({
joined,
setJoined,
muteStates,
stickyEventsSupported,
}) => {
// Used to thread through any errors that occur outside the error boundary
const [externalError, setExternalError] = useState<ElementCallError | null>(
@@ -656,7 +621,6 @@ const LoadedCallView: FC<LoadedProps> = ({
media={media}
muteStates={muteStates}
e2eeSystem={e2eeSystem}
stickyEventsSupported={stickyEventsSupported}
//otelGroupCallMembership={otelGroupCallMembership}
onShareClick={onShareClick}
/>
+17
View File
@@ -14,6 +14,23 @@ Please see LICENSE in the repository root for full details.
overflow-y: auto;
}
/* Normally the footer uses a transparent background to allow our expressive
page gradients to shine through. However, we sometimes need to visually separate
it from the content underneath. If the call layout is overflowing, or if the
spotlight tile is maximised and displaying video, apply a gradient background. */
.overflowing > .footer,
.fixedGrid:has(
> .tile[data-maximised="true"]
.spotlightItem[data-background="transparent"][data-video-enabled="true"][aria-hidden="false"]
)
~ .footer {
background: linear-gradient(
180deg,
rgba(0, 0, 0, 0) 0%,
var(--cpd-color-bg-canvas-default) 100%
);
}
.header {
position: sticky;
flex-shrink: 0;
+5 -40
View File
@@ -7,7 +7,6 @@ Please see LICENSE in the repository root for full details.
*/
import {
afterEach,
beforeEach,
describe,
expect,
@@ -21,10 +20,8 @@ import { BrowserRouter } from "react-router-dom";
import { TooltipProvider } from "@vector-im/compound-web";
import userEvent from "@testing-library/user-event";
import { ActiveCall, InCallView, rtcParticipationOptions } from "./InCallView";
import { getUrlParams } from "../UrlParams";
import { ActiveCall, InCallView } from "./InCallView";
import {
mockConfig,
mockMediaDevices,
mockMuteStates,
mockRtcMembership,
@@ -46,18 +43,14 @@ import { ReactionsSenderProvider } from "../reactions/useReactionsSender";
import { useRoomEncryptionSystem } from "../e2ee/sharedKeyManagement";
import { MemberAudioRenderer } from "../tracks/MemberAudioRenderer";
import type * as MatrixRTCSdk from "@element-hq/matrixrtc-sdk";
import {
constant,
MatrixRTCMode,
type RTCSlot,
} from "@element-hq/matrixrtc-sdk";
import { constant, type RTCSlot } from "@element-hq/matrixrtc-sdk";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { type MediaDevices as ECMediaDevices } from "../state/MediaDevices";
import { AppBar } from "../AppBar";
import { type MatrixInfo } from "./VideoPreview";
import {
BackgroundEffectsProvider,
createAppBackgroundEffects,
createAppBackgroundEffects$,
} from "../tracks/BackgroundEffectsContext";
import { initializeWidget } from "../widget";
import { RootElementProvider } from "../RootElementContext";
@@ -240,7 +233,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
<BrowserRouter>
<MediaDevicesContext value={mockMediaDevices({})}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects(testScope())}
effects={createAppBackgroundEffects$(testScope())}
>
<TooltipProvider>
<ActiveCall
@@ -253,7 +246,6 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
media={fakeLocalMedia()}
stickyEventsSupported
onLeft={(): void => {}}
/>
</TooltipProvider>
@@ -263,32 +255,6 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
);
}
describe("rtcParticipationOptions", () => {
const urlParams = getUrlParams("", "");
afterEach(() => vi.restoreAllMocks());
it("joins in Matrix 2.0 mode when the homeserver supports sticky events", () => {
mockConfig({ matrix_rtc_mode: MatrixRTCMode.Matrix_2_0 });
expect(rtcParticipationOptions(urlParams, true).matrixRTCMode).toBe(
MatrixRTCMode.Matrix_2_0,
);
});
it("falls back to compatibility mode when the homeserver lacks sticky events", () => {
mockConfig({ matrix_rtc_mode: MatrixRTCMode.Matrix_2_0 });
expect(rtcParticipationOptions(urlParams, false).matrixRTCMode).toBe(
MatrixRTCMode.Compatibility,
);
});
it("keeps compatibility mode when the homeserver lacks sticky events", () => {
mockConfig({ matrix_rtc_mode: MatrixRTCMode.Compatibility });
expect(rtcParticipationOptions(urlParams, false).matrixRTCMode).toBe(
MatrixRTCMode.Compatibility,
);
});
});
describe("ActiveCall", () => {
it("creates the view models and renders the call", async () => {
const { findByTestId } = renderActiveCall(mockSlot());
@@ -336,7 +302,7 @@ describe("ActiveCall", () => {
<RootElementProvider value={root}>
<MediaDevicesContext value={mediaDevices}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects(testScope())}
effects={createAppBackgroundEffects$(testScope())}
>
<TooltipProvider>
<ActiveCall
@@ -349,7 +315,6 @@ describe("ActiveCall", () => {
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
media={fakeLocalMedia()}
stickyEventsSupported
onLeft={(): void => {}}
/>
</TooltipProvider>
+19 -21
View File
@@ -55,7 +55,7 @@ import { SpotlightTile } from "../tile/SpotlightTile";
import {
type EncryptionSystem,
type LocalMedia,
MatrixRTCMode,
type MatrixRTCMode,
} from "@element-hq/matrixrtc-sdk";
import { E2eeType } from "../e2ee/e2eeType";
import { makeGridLayout } from "../grid/GridLayout";
@@ -194,8 +194,6 @@ export interface ActiveCallProps extends Omit<
e2eeSystem: EncryptionSystem;
/** The tracks the lobby opened, for the join to publish. */
media: LocalMedia;
/** Whether the homeserver supports sticky events (MSC4354), which Matrix 2.0 needs. */
stickyEventsSupported: boolean;
// TODO refactor those reasons into an enum
onLeft: (
reason: "user" | "timeout" | "decline" | "allOthersLeft" | "error",
@@ -231,7 +229,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const capture = captureSettings();
const rtcParticipation = props.slot.join({
...rtcParticipationOptions(urlParams, props.stickyEventsSupported),
...rtcParticipationOptions(urlParams),
// Without a lobby nothing was captured and the join captures itself
publish:
props.media.requests.length > 0
@@ -292,7 +290,6 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
backgroundEffectsState$,
props.client,
props.media,
props.stickyEventsSupported,
rootElement,
]);
@@ -416,6 +413,7 @@ export const InCallView: FC<InCallViewProps> = ({
const screenShareError = useBehavior(vm.screenShareError$);
const layout = useBehavior(vm.layout$);
const edgeToEdge = useBehavior(vm.edgeToEdge$);
const overflowing = useBehavior(vm.overflowing$);
const showNameTags = useBehavior(vm.showNameTags$);
const showHeader = useBehavior(vm.showHeader$);
const showModals = useBehavior(vm.showModals$);
@@ -638,6 +636,7 @@ export const InCallView: FC<InCallViewProps> = ({
showRingingStatus={showRingingStatus}
focusable={!contentObscured}
className={classNames(className, styles.tile)}
itemClassName={styles.spotlightItem}
style={style}
/>
);
@@ -663,6 +662,7 @@ export const InCallView: FC<InCallViewProps> = ({
return (
<SpotlightTile
className={styles.tile}
itemClassName={styles.spotlightItem}
data-maximised
vm={layout.spotlight}
expanded
@@ -753,6 +753,10 @@ export const InCallView: FC<InCallViewProps> = ({
/>,
);
// Only hide the settings button if we have an AppBar header and we are showing the header
const footer = footerVm !== null && (
<CallFooter className={styles.footer} ref={footerRef} vm={footerVm} />
);
const connectedTransports = useBehavior(vm.connectedTransports$);
const localMember = useBehavior(vm.localMember$);
const localTransport = useBehavior(
@@ -764,7 +768,9 @@ export const InCallView: FC<InCallViewProps> = ({
// and the footer is also viewable by moving focus into it, so this is fine.
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className={styles.inRoom}
className={classNames(styles.inRoom, {
[styles.overflowing]: overflowing,
})}
ref={containerRef}
// Which layout the call has settled on, for tests and for anyone
// wondering why the call looks the way it does at the size it was given
@@ -783,7 +789,7 @@ export const InCallView: FC<InCallViewProps> = ({
{screenShareToast}
{earpieceOverlay}
<ReactionsOverlay vm={vm} />
<CallFooter ref={footerRef} vm={footerVm} />
{footer}
{showModals && (
<>
<RageshakeRequestModal {...rageshakeRequestModalProps} />
@@ -861,24 +867,16 @@ export function captureSettings(): CaptureSettings {
*/
export function rtcParticipationOptions(
urlParams: ReturnType<typeof useUrlParams>,
stickyEventsSupported: boolean,
): Omit<RTCParticipationOptions, "publish"> {
const config = Config.get();
const session = config.matrix_rtc_session;
// matrix_rtc_mode in config.json overrides the user's Developer Settings
// choice. We merely sample the current mode here, so the user would need
// to manually rejoin to switch to a different one.
let matrixRTCMode =
(config.matrix_rtc_mode as MatrixRTCMode | undefined) ??
matrixRTCModeSetting.value$.value;
if (matrixRTCMode === MatrixRTCMode.Matrix_2_0 && !stickyEventsSupported) {
rootLogger.warn(
"Homeserver does not support sticky events (MSC4354), falling back from Matrix 2.0 to compatibility mode",
);
matrixRTCMode = MatrixRTCMode.Compatibility;
}
return {
matrixRTCMode,
// matrix_rtc_mode in config.json overrides the user's Developer Settings
// choice. We merely sample the current mode here, so the user would need
// to manually rejoin to switch to a different one.
matrixRTCMode:
(config.matrix_rtc_mode as MatrixRTCMode | undefined) ??
matrixRTCModeSetting.value$.value,
sendNotificationType: urlParams.sendNotificationType,
callIntent: urlParams.callIntent,
timings: {
+1
View File
@@ -22,6 +22,7 @@ test("InviteModal is accessible", async () => {
const room = {
roomId: "!a:example.org",
name: "Mission Control",
hasEncryptionStateEvent: () => false,
} as unknown as Room;
const onDismiss = vi.fn();
const { container } = render(
+2 -2
View File
@@ -29,14 +29,14 @@ import { useRoomEncryptionSystem } from "../e2ee/sharedKeyManagement";
import { QrCode } from "../QrCode";
interface Props {
room: Pick<Room, "roomId" | "name">;
room: Pick<Room, "roomId" | "name" | "hasEncryptionStateEvent">;
open: boolean;
onDismiss: () => void;
}
export const InviteModal: FC<Props> = ({ room, open, onDismiss }) => {
const { t } = useTranslation();
const e2eeSystem = useRoomEncryptionSystem(room.roomId);
const e2eeSystem = useRoomEncryptionSystem(room);
const url = useMemo(
() => getAbsoluteRoomUrl(room.roomId, e2eeSystem, room.name),
+21 -41
View File
@@ -5,60 +5,40 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useId, 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,
GridIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import {
type LayoutMode,
type LayoutSwitchViewModel,
} from "../state/LayoutSwitchViewModel";
import { type LayoutSwitchViewModel } from "../state/LayoutSwitchViewModel";
import { useBehavior } from "../useBehavior";
import { LayoutSwitchButton } from "../button";
import { useTranslation } from "react-i18next";
import { Switch } from "@vector-im/compound-web";
interface LayoutSwitchProps {
interface Props {
vm: LayoutSwitchViewModel;
className?: string;
size?: "md" | "lg";
}
export const LayoutSwitch: FC<LayoutSwitchProps> = ({ vm, ...props }) => {
export const LayoutSwitch: FC<Props> = ({ vm, className }) => {
const { t } = useTranslation();
const layout = useBehavior(vm.layout$);
const [open, setOpen] = useState(false);
const menuItem = (
value: LayoutMode,
label: string,
Icon: ComponentType<SVGAttributes<SVGElement>>,
): ReactNode => (
<OptionMenuItem
label={label}
Icon={Icon}
checked={layout === value}
onSelect={() => vm.setLayout(value)}
/>
);
const name = useId();
return (
<Menu
title={t("action.adjust_view")}
open={open}
onOpenChange={setOpen}
trigger={<LayoutSwitchButton layout={layout} {...props} />}
>
{menuItem("grid", t("layout_grid_label"), GridIcon)}
{menuItem("spotlight", t("layout_spotlight_label"), SpotlightViewIcon)}
</Menu>
<Switch<"spotlight", "grid">
name={name}
aria-label={t("layout_switch_label")}
leftLabel={t("layout_spotlight_label")}
leftValue="spotlight"
leftIcon={SpotlightViewIcon}
rightLabel={t("layout_grid_label")}
rightValue="grid"
rightIcon={GridIcon}
className={className}
value={layout}
onChange={vm.setLayout}
/>
);
};
+12 -3
View File
@@ -17,17 +17,23 @@ import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { Form } from "../form/Form";
import { UserMenuContainer } from "../UserMenuContainer";
import { useRegisterPasswordlessUser } from "../auth/useRegisterPasswordlessUser";
import { type ClientManager } from "../state/ClientSession";
import { Config } from "../config/Config";
import { ExternalLink, Link } from "../button/Link";
import { useUrlParams } from "../UrlParams";
export const RoomAuthView: FC = () => {
interface Props {
/** Null where the session is a host's and not ours to manage. */
clientManager: ClientManager | null;
}
export const RoomAuthView: FC<Props> = ({ clientManager }) => {
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const { registerPasswordlessUser, recaptchaId } =
useRegisterPasswordlessUser();
useRegisterPasswordlessUser(clientManager);
const onSubmit = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -61,7 +67,10 @@ export const RoomAuthView: FC = () => {
<HeaderLogo />
</LeftNav>
<RightNav>
<UserMenuContainer preventNavigation />
<UserMenuContainer
preventNavigation
clientManager={clientManager}
/>
</RightNav>
</Header>
)}
+109
View File
@@ -0,0 +1,109 @@
/*
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 { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RoomPage } from "./RoomPage";
import { ClientContextProvider } from "../ClientContext";
import { type ClientSessionState } from "../state/ClientSession";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { useLoadGroupCall } from "./useLoadGroupCall";
vi.mock("./useLoadGroupCall", () => ({
useLoadGroupCall: vi.fn(() => ({ kind: "loading" })),
CallTerminatedMessage: class extends Error {},
}));
vi.mock("./useRoomName", () => ({ useRoomName: () => null }));
vi.mock("../profile/useProfile", () => ({ useProfile: () => ({}) }));
vi.mock("../auth/useRegisterPasswordlessUser", () => ({
useRegisterPasswordlessUser: () => ({ registerPasswordlessUser }),
}));
vi.mock("./RoomAuthView", () => ({
RoomAuthView: () => <span>room auth view</span>,
}));
vi.mock("../home/HomePage", () => ({
HomePage: () => <span>home page</span>,
}));
vi.mock("./CallView", () => ({
CallView: ({ isPasswordlessUser }: { isPasswordlessUser: boolean }) => (
<span>call view, passwordless: {String(isPasswordlessUser)}</span>
),
}));
vi.mock("./KnockLobbyView", () => ({ KnockLobbyView: () => null }));
vi.mock("../CallMatrixBackend", () => ({
createCallMatrixBackend: () => ({}),
}));
const registerPasswordlessUser = vi.fn().mockResolvedValue(undefined);
const room = { roomId: "!room:example.org" };
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRoom({ state: "loading" }, "/call");
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("asks a signed-out user to join as a guest", () => {
renderRoom({ state: "signedOut" }, "/call");
expect(screen.getByText("room auth view")).toBeVisible();
expect(registerPasswordlessUser).not.toHaveBeenCalled();
});
test("registers a passwordless user when the URL names one", () => {
renderRoom({ state: "signedOut" }, "/call", "Alice");
expect(registerPasswordlessUser).toHaveBeenCalledWith("Alice");
});
test("falls back to the home page without a room", () => {
renderRoom(signedIn(false), "/");
expect(screen.getByText("home page")).toBeVisible();
});
test("tells the call whether its user is passwordless", () => {
vi.mocked(useLoadGroupCall).mockReturnValue({
kind: "loaded",
room,
rtcSession: {},
} as unknown as ReturnType<typeof useLoadGroupCall>);
renderRoom(signedIn(true), "/call");
expect(screen.getByText("call view, passwordless: true")).toBeVisible();
});
function signedIn(passwordlessUser: boolean): ClientSessionState {
return {
state: "signedIn",
client: {
getUserId: () => "@alice:example.org",
getRoom: () => room,
} as unknown as MatrixClient,
passwordlessUser,
};
}
function renderRoom(
state: ClientSessionState,
path: string,
displayName: string | null = null,
): void {
render(
<MemoryRouter initialEntries={[path]}>
<UrlParamsProvider value={{ ...computeUrlParams(), displayName }}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<RoomPage clientManager={null} />
</ClientContextProvider>
</UrlParamsProvider>
</MemoryRouter>,
);
}

Some files were not shown because too many files have changed in this diff Show More