mirror of
https://github.com/vector-im/element-call.git
synced 2026-12-04 10:21:10 +08:00
Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4362f7ea89 | ||
|
|
38e9696d22 | ||
|
|
2cf05335af | ||
|
|
f73339199c | ||
|
|
9ba6a31996 | ||
|
|
0691a09dc5 | ||
|
|
090ff55b4a | ||
|
|
e4f816b1fc | ||
|
|
068d968aab | ||
|
|
9f67069451 | ||
|
|
90b48be6b4 | ||
|
|
8e8886b250 | ||
|
|
965e77be36 | ||
|
|
3818c34c3b | ||
|
|
b7374c4906 | ||
|
|
2100b93f5b | ||
|
|
a62d3f4dd9 | ||
|
|
6b9f8cef45 | ||
|
|
48d2639bb9 | ||
|
|
64994af0c8 | ||
|
|
07b6b6ecd6 | ||
|
|
3550e538ab | ||
|
|
86c2d75db4 | ||
|
|
77020cee2a | ||
|
|
464ffb136e | ||
|
|
e6d0e9ffe9 | ||
|
|
50acca9503 | ||
|
|
1b544b0734 | ||
|
|
96700aea6c | ||
|
|
77c7cdd174 | ||
|
|
ab8340e3c2 | ||
|
|
32e35fdfc8 | ||
|
|
6dede3a678 | ||
|
|
8ebf54159a | ||
|
|
60f5c90bb5 | ||
|
|
f2549a0e17 | ||
|
|
3f933c1077 | ||
|
|
2872857be6 | ||
|
|
6888727328 | ||
|
|
474b27d362 | ||
|
|
33ba54e8bd | ||
|
|
c682a9970c | ||
|
|
acd0fd524e | ||
|
|
36b0e41269 | ||
|
|
51e6baea17 | ||
|
|
3a9708020a | ||
|
|
6e6494fe38 | ||
|
|
d506c9828b | ||
|
|
3c81c131a2 | ||
|
|
3c67a5e54a | ||
|
|
4d7e0f9ec9 | ||
|
|
feab263fad | ||
|
|
aaf78518a3 | ||
|
|
6a6e26e049 | ||
|
|
d423d9bdcc | ||
|
|
fe06f6ba27 | ||
|
|
bf2714da2c | ||
|
|
e2a5fd94ce | ||
|
|
0eff661159 |
@@ -1,22 +1,14 @@
|
||||
name: Prevent blocked
|
||||
on:
|
||||
# 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:
|
||||
pull_request:
|
||||
types: [opened, labeled, unlabeled, synchronize]
|
||||
|
||||
permissions:
|
||||
pull-requests: read
|
||||
# Required to fail the check on the PR
|
||||
statuses: write
|
||||
permissions: {}
|
||||
|
||||
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
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
name: PR changelog label
|
||||
|
||||
on:
|
||||
# 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:
|
||||
pull_request:
|
||||
types: [labeled, unlabeled, opened, synchronize]
|
||||
|
||||
permissions:
|
||||
pull-requests: read
|
||||
statuses: write
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
pr-changelog-label:
|
||||
|
||||
@@ -14,6 +14,8 @@ 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
|
||||
@@ -98,7 +100,8 @@ 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 50
|
||||
--max-turns 150
|
||||
|
||||
@@ -156,7 +156,9 @@ jobs:
|
||||
|
||||
publish_android:
|
||||
needs: [build_element_call, versioning]
|
||||
if: always()
|
||||
# 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'
|
||||
name: Publish Android AAR
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
@@ -188,8 +190,6 @@ 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,11 +338,7 @@ jobs:
|
||||
|
||||
### Android AAR
|
||||
|
||||
```
|
||||
dependencies {
|
||||
implementation 'io.element.android:element-call-embedded:${{ needs.publish_android.outputs.ARTIFACT_VERSION }}'
|
||||
}
|
||||
```
|
||||
${{ 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.' }}
|
||||
|
||||
### SwiftPM
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
24
|
||||
26
|
||||
|
||||
Binary file not shown.
@@ -26,10 +26,6 @@ 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;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -47,7 +43,6 @@ beforeEach(() => {
|
||||
_unstable_getStickyEvents: vi.fn(),
|
||||
getMxcAvatarUrl: vi.fn(),
|
||||
getJoinRule: vi.fn(),
|
||||
hasEncryptionStateEvent: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+1
-2
@@ -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/state/ClientSession";
|
||||
import type { SuppliedClient } from "../src/ClientContext";
|
||||
import {
|
||||
BackgroundStyle,
|
||||
configurationForIntent,
|
||||
@@ -91,7 +91,6 @@ type HostRoomPart = Pick<
|
||||
| "getMxcAvatarUrl"
|
||||
| "getJoinRule"
|
||||
| "relations"
|
||||
| "hasEncryptionStateEvent"
|
||||
>;
|
||||
|
||||
export interface ElementCallProps {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
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";
|
||||
+8
-14
@@ -73,7 +73,6 @@ 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";
|
||||
@@ -193,25 +192,20 @@ 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 },
|
||||
// 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,
|
||||
),
|
||||
);
|
||||
setVm(new AppViewModel(scope, { controlledAudioDevices, callIntent }));
|
||||
return (): void => {
|
||||
setVm(null);
|
||||
scope.end();
|
||||
};
|
||||
}, [controlledAudioDevices, callIntent, client]);
|
||||
}, [controlledAudioDevices, callIntent]);
|
||||
|
||||
const backend = useMemo(
|
||||
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
|
||||
@@ -253,11 +247,11 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
>
|
||||
<Decoration>
|
||||
<TooltipProvider>
|
||||
{/* The client session: what reads it through
|
||||
{/* The host's own client: what reads it through
|
||||
the context (avatars, the encryption system,
|
||||
rageshakes, the disconnected banner) uses only its
|
||||
stable methods. */}
|
||||
<ClientProvider session={vm.clientSession}>
|
||||
<ClientProvider client={client}>
|
||||
<MediaDevicesContext value={vm.mediaDevices}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={vm.backgroundEffects}
|
||||
|
||||
@@ -34,14 +34,15 @@
|
||||
"./style.css": "./dist/element-call.css"
|
||||
},
|
||||
"sideEffects": [
|
||||
"*.css"
|
||||
"*.css",
|
||||
"./guestJsSdk.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"prepare": "cd .. && pnpm install --frozen-lockfile && pnpm build:component"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@vector-im/compound-design-tokens": "^11.0.0",
|
||||
"@vector-im/compound-web": "^10.3.1",
|
||||
"@vector-im/compound-web": "^10.5.0",
|
||||
"react": "^19",
|
||||
"react-dom": "^19"
|
||||
}
|
||||
|
||||
@@ -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:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:a9fba6e7ea9a32f62bc1459fcdad790662476ff1b2bcebc62fe47e5cf51e3932
|
||||
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:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:a9fba6e7ea9a32f62bc1459fcdad790662476ff1b2bcebc62fe47e5cf51e3932
|
||||
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
@@ -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`, 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. |
|
||||
| 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. |
|
||||
|
||||
### Widget-only parameters
|
||||
|
||||
|
||||
+1
-1
@@ -4,6 +4,7 @@
|
||||
},
|
||||
"action": {
|
||||
"add_background_image": "Add image",
|
||||
"adjust_view": "Adjust view",
|
||||
"close": "Close",
|
||||
"copy_link": "Copy link",
|
||||
"edit": "Edit",
|
||||
@@ -158,7 +159,6 @@
|
||||
},
|
||||
"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",
|
||||
|
||||
+8
-7
@@ -39,8 +39,8 @@
|
||||
"lint:knip": "knip",
|
||||
"lint:externals": "node scripts/check-component-externals.mjs",
|
||||
"lint:types": "tsc",
|
||||
"i18n": "npx i18next-cli extract",
|
||||
"i18n:check": "npx i18next-cli extract --ci",
|
||||
"i18n": "i18next-cli extract",
|
||||
"i18n:check": "i18next-cli extract --ci",
|
||||
"test": "vitest",
|
||||
"test:storybook": "vitest --project=storybook",
|
||||
"test:unit": "vitest --project=unit",
|
||||
@@ -55,6 +55,7 @@
|
||||
"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",
|
||||
@@ -82,7 +83,7 @@
|
||||
"@types/grecaptcha": "^3.0.9",
|
||||
"@types/jsdom": "^21.1.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
@@ -90,7 +91,7 @@
|
||||
"@typescript-eslint/utils": "^8.61.0",
|
||||
"@use-gesture/react": "^10.2.11",
|
||||
"@vector-im/compound-design-tokens": "^11.0.0",
|
||||
"@vector-im/compound-web": "^10.5.0",
|
||||
"@vector-im/compound-web": "^10.8.0",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/browser-playwright": "^4.1.5",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
@@ -105,16 +106,16 @@
|
||||
"i18next": "^26.0.0",
|
||||
"i18next-browser-languagedetector": "^8.0.0",
|
||||
"i18next-cli": "^1.61.0",
|
||||
"jsdom": "^26.0.0",
|
||||
"jsdom": "^31.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#6c8b1b418189919bc69fd9df5e57354e7b3c39cb",
|
||||
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#aa1a8db0689465a8549546aea4c6cf1e696d6e44",
|
||||
"matrix-widget-api": "^1.18.0",
|
||||
"node-stdlib-browser": "^1.3.1",
|
||||
"normalize.css": "^8.0.1",
|
||||
"oxfmt": "^0.79.0",
|
||||
"oxfmt": "^0.80.0",
|
||||
"oxlint": "^1.70.0",
|
||||
"oxlint-tsgolint": "^0.25.0",
|
||||
"pako": "^3.0.3",
|
||||
|
||||
+10
-3
@@ -27,10 +27,17 @@ 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",
|
||||
@@ -116,7 +123,7 @@ export default defineConfig({
|
||||
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
ignoreHTTPSErrors: true,
|
||||
...commonDeviceOptions,
|
||||
launchOptions: {
|
||||
firefoxUserPrefs: {
|
||||
"permissions.default.microphone": 1,
|
||||
@@ -140,7 +147,7 @@ export default defineConfig({
|
||||
testMatch: "**/mobile/**",
|
||||
use: {
|
||||
...devices["Pixel 7"],
|
||||
ignoreHTTPSErrors: true,
|
||||
...commonDeviceOptions,
|
||||
permissions: [
|
||||
"clipboard-write",
|
||||
"clipboard-read",
|
||||
|
||||
@@ -62,8 +62,7 @@ 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,
|
||||
}) => {
|
||||
// Use reduce motion to disable animations that are making the tests a bit flaky
|
||||
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
|
||||
const creatorContext = await browser.newContext();
|
||||
const creatorPage = await creatorContext.newPage();
|
||||
|
||||
await creatorPage.goto("/");
|
||||
@@ -76,7 +75,8 @@ 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("radio", { name: "Spotlight" }).check();
|
||||
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
|
||||
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
|
||||
// Get the invite link
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(creatorPage);
|
||||
@@ -84,9 +84,7 @@ 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({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const guestInviteeContext = await browser.newContext();
|
||||
const guestPage = await guestInviteeContext.newPage();
|
||||
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink);
|
||||
|
||||
|
||||
@@ -50,13 +50,13 @@ test.describe("the quick audio menu", () => {
|
||||
}) => {
|
||||
// Two browsers and a real call.
|
||||
test.slow();
|
||||
const hostContext = await browser.newContext({ reducedMotion: "reduce" });
|
||||
const hostContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const hostContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
const guest = await guestContext.newPage();
|
||||
await SpaHelpers.joinCallFromInviteLink(guest, inviteLink, "Listener");
|
||||
await SpaHelpers.expectVideoTilesCount(guest, 2);
|
||||
|
||||
@@ -30,15 +30,6 @@ 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);
|
||||
@@ -81,7 +72,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 settingsButton(pane).click();
|
||||
await pane.getByTestId("settings-bottom").click();
|
||||
await expectWithin(pane.getByRole("dialog"), container);
|
||||
await pane.getByTestId("modal_close").click();
|
||||
|
||||
@@ -112,7 +103,8 @@ 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("radio", { name: "Spotlight" }).check();
|
||||
await pane.getByRole("button", { name: "Adjust view" }).click();
|
||||
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
const tile = pane.getByTestId("videoTile").first();
|
||||
await expect(tile).toBeVisible({ timeout: 60_000 });
|
||||
await expectWithin(tile, container);
|
||||
|
||||
@@ -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({ reducedMotion: "reduce" });
|
||||
const creatorContext = await browser.newContext();
|
||||
const creatorPage = await creatorContext.newPage();
|
||||
|
||||
await creatorPage.goto("/");
|
||||
|
||||
@@ -58,9 +58,7 @@ mobileTest(
|
||||
// ========
|
||||
// ACT: The other user use the invite link to join the call as a guest
|
||||
// ========
|
||||
const guestInviteeContext = await browser.newContext({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const guestInviteeContext = await browser.newContext();
|
||||
const guestPage = await guestInviteeContext.newPage();
|
||||
await guestPage.goto(inviteLink + "&controlledAudioDevices=true");
|
||||
|
||||
|
||||
@@ -12,8 +12,7 @@ test("When creator left, avoid reconnect to the same SFU", async ({
|
||||
browserName,
|
||||
}) => {
|
||||
test.skip(browserName === "firefox", "Browser independent");
|
||||
// Use reduce motion to disable animations that are making the tests a bit flaky
|
||||
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
|
||||
const creatorContext = await browser.newContext();
|
||||
const creatorPage = await creatorContext.newPage();
|
||||
|
||||
await creatorPage.goto("/");
|
||||
@@ -31,7 +30,8 @@ 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("radio", { name: "Spotlight" }).check();
|
||||
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
|
||||
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
|
||||
// Get the invite link
|
||||
await creatorPage.getByRole("button", { name: "Invite" }).click();
|
||||
@@ -51,9 +51,7 @@ 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({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const guestB = await browser.newContext();
|
||||
const guestBPage = await guestB.newPage();
|
||||
|
||||
await guestBPage.goto(inviteLink);
|
||||
@@ -61,14 +59,13 @@ 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("radio", { name: "Spotlight" }).check();
|
||||
await guestBPage.getByRole("button", { name: "Adjust view" }).click();
|
||||
await guestBPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
|
||||
// ========
|
||||
// ACT: add a third user to the call to reproduce the bug
|
||||
// ========
|
||||
const guestC = await browser.newContext({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const guestC = await browser.newContext();
|
||||
const guestCPage = await guestC.newPage();
|
||||
// Track WebSocket connections
|
||||
let wsConnectionCount = 0;
|
||||
@@ -85,7 +82,8 @@ 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("radio", { name: "Spotlight" }).check();
|
||||
await guestCPage.getByRole("button", { name: "Adjust view" }).click();
|
||||
await guestCPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
|
||||
await guestCPage.waitForTimeout(1000);
|
||||
if (wsConnectionCount === 2) {
|
||||
|
||||
@@ -33,7 +33,7 @@ async function setupTwoUserSpaCall(
|
||||
await interceptEventSend(
|
||||
page,
|
||||
// This room is not encrypted, so the event is sent in clear
|
||||
"org.matrix.msc4143.rtc.member",
|
||||
"m.rtc.member",
|
||||
(req) => {
|
||||
androlHasSentStickyEvent =
|
||||
androlHasSentStickyEvent || isStickySend(req.url());
|
||||
@@ -46,9 +46,7 @@ async function setupTwoUserSpaCall(
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(page);
|
||||
|
||||
// Other
|
||||
const guestInviteeContext = await browser.newContext({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const guestInviteeContext = await browser.newContext();
|
||||
const guestPage = await guestInviteeContext.newPage();
|
||||
|
||||
await guestPage.goto("/");
|
||||
@@ -62,7 +60,7 @@ async function setupTwoUserSpaCall(
|
||||
await interceptEventSend(
|
||||
guestPage,
|
||||
// This room is not encrypted, so the event is sent in clear
|
||||
"org.matrix.msc4143.rtc.member",
|
||||
"m.rtc.member",
|
||||
(req) => {
|
||||
pevaraHasSentStickyEvent =
|
||||
pevaraHasSentStickyEvent || isStickySend(req.url());
|
||||
|
||||
@@ -88,7 +88,8 @@ async function joinCallFromInviteLink(
|
||||
}
|
||||
|
||||
await page.getByTestId("lobby_joinCall").click();
|
||||
await page.getByRole("radio", { name: "Spotlight" }).check();
|
||||
await page.getByRole("button", { name: "Adjust view" }).click();
|
||||
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
|
||||
}
|
||||
|
||||
async function setRtcModeFromSettings(
|
||||
|
||||
@@ -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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const bobContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const carolContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
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({ reducedMotion: "reduce" });
|
||||
const guestContext = await browser.newContext();
|
||||
const guestPage = await guestContext.newPage();
|
||||
await advertiseTransport(guestPage, shapes.url);
|
||||
const guestRequests = recordAuthRequests(guestPage);
|
||||
|
||||
@@ -86,7 +86,11 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
|
||||
const frame = alice.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await expect(frame.getByRole("radio", { name: "Grid" })).toBeChecked();
|
||||
await frame.getByRole("button", { name: "Adjust view" }).click();
|
||||
await expect(
|
||||
frame.getByRole("menuitemradio", { name: "Grid" }),
|
||||
).toBeChecked();
|
||||
await frame.getByRole("menu").press("Escape");
|
||||
}
|
||||
|
||||
// Others should have switched to spotlight
|
||||
@@ -95,7 +99,11 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
|
||||
await expect(frame.getByRole("radio", { name: "Spotlight" })).toBeChecked();
|
||||
await frame.getByRole("button", { name: "Adjust view" }).click();
|
||||
await expect(
|
||||
frame.getByRole("menuitemradio", { name: "Spotlight" }),
|
||||
).toBeChecked();
|
||||
await frame.getByRole("menu").press("Escape");
|
||||
}
|
||||
// await alice.page.pause();
|
||||
// await bob.page.pause();
|
||||
|
||||
@@ -123,9 +123,7 @@ export class TestHelpers {
|
||||
);
|
||||
|
||||
// STEP 2: Open browser and login
|
||||
const userContext = await browser.newContext({
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const userContext = await browser.newContext();
|
||||
const page = await userContext.newPage();
|
||||
await page.goto(host);
|
||||
|
||||
|
||||
Generated
+1043
-1092
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -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"
|
||||
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
|
||||
"glob": "^10.5.0"
|
||||
# The v8 line is deprecated.
|
||||
"eslint": "^9.0.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
|
||||
|
||||
+4
-2
@@ -28,12 +28,14 @@
|
||||
{
|
||||
"groupName": "matrix-widget-api",
|
||||
"matchDepNames": ["matrix-widget-api"],
|
||||
"extends": ["schedule:weekly"]
|
||||
"extends": ["schedule:weekly"],
|
||||
"minimumReleaseAge": null
|
||||
},
|
||||
{
|
||||
"groupName": "Compound",
|
||||
"matchPackageNames": ["@vector-im/compound-{/,}**"],
|
||||
"extends": ["schedule:weekly"]
|
||||
"extends": ["schedule:weekly"],
|
||||
"minimumReleaseAge": null
|
||||
},
|
||||
{
|
||||
"groupName": "LiveKit client",
|
||||
|
||||
@@ -6,18 +6,18 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks the component build's output for what a host must not be handed.
|
||||
* Checks the component build's output for things we do not want to end up in the
|
||||
* component target.
|
||||
*
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
|
||||
+13
-15
@@ -7,33 +7,31 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { testScope } from "./utils/test";
|
||||
|
||||
const createStandaloneClientSession$ = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./state/StandaloneClientSession", () => ({
|
||||
createStandaloneClientSession$,
|
||||
}));
|
||||
const initSPA = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./utils/spa", () => ({ initSPA }));
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
createStandaloneClientSession$.mockReset();
|
||||
initSPA.mockReset();
|
||||
});
|
||||
|
||||
test("the app restores its own session", async () => {
|
||||
vi.stubEnv("VITE_PACKAGE", "full");
|
||||
const { loadStandaloneClientSession } = await import("./App");
|
||||
const scope = testScope();
|
||||
const session = {};
|
||||
createStandaloneClientSession$.mockReturnValue(session);
|
||||
const { loadStandaloneClient } = await import("./App");
|
||||
const loadSession = vi.fn();
|
||||
const clearSession = vi.fn();
|
||||
initSPA.mockResolvedValue(null);
|
||||
|
||||
await expect(loadStandaloneClientSession!(scope)).resolves.toBe(session);
|
||||
expect(createStandaloneClientSession$).toHaveBeenCalledWith(scope);
|
||||
await expect(loadStandaloneClient!(loadSession, clearSession)).resolves.toBe(
|
||||
null,
|
||||
);
|
||||
expect(initSPA).toHaveBeenCalledWith(loadSession, clearSession);
|
||||
});
|
||||
|
||||
test("the embedded package has no session of its own", async () => {
|
||||
vi.stubEnv("VITE_PACKAGE", "embedded");
|
||||
const { loadStandaloneClientSession } = await import("./App");
|
||||
const { loadStandaloneClient } = await import("./App");
|
||||
|
||||
expect(loadStandaloneClientSession).toBeUndefined();
|
||||
expect(loadStandaloneClient).toBeUndefined();
|
||||
});
|
||||
|
||||
+33
-43
@@ -23,13 +23,14 @@ 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 { ClientProvider } from "./ClientContext";
|
||||
import { type ClientLoader, ClientProvider } from "./ClientContext";
|
||||
import { ErrorPage, LoadingPage } from "./FullScreenView";
|
||||
import { Initializer } from "./initializer";
|
||||
import { type WidgetHelpers } from "./widget";
|
||||
@@ -53,26 +54,22 @@ 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.
|
||||
// - Imported on demand, so that a widget, which gets its client from the host,
|
||||
// never downloads it.
|
||||
// - 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.
|
||||
// - 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 loadStandaloneClientSession:
|
||||
| ((scope: ObservableScope) => Promise<ClientSession & ClientManager>)
|
||||
| undefined =
|
||||
export const loadStandaloneClient: ClientLoader | undefined =
|
||||
import.meta.env.VITE_PACKAGE === "embedded"
|
||||
? undefined
|
||||
: async (scope) =>
|
||||
(
|
||||
await import("./state/StandaloneClientSession")
|
||||
).createStandaloneClientSession$(scope);
|
||||
: async (...args) => (await import("./utils/spa")).initSPA(...args);
|
||||
|
||||
interface SimpleProviderProps {
|
||||
children: JSX.Element;
|
||||
@@ -148,47 +145,40 @@ export const App: FC<Props> = ({ vm, widget }) => {
|
||||
.catch(logger.error);
|
||||
});
|
||||
|
||||
const content = loaded ? (
|
||||
<DisconnectedProvider value={vm.disconnected$}>
|
||||
<ClientProvider session={vm.clientSession}>
|
||||
// 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}>
|
||||
<MediaDevicesContext value={vm.mediaDevices}>
|
||||
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
|
||||
<Sentry.ErrorBoundary
|
||||
fallback={(error) => <ErrorPage error={error} />}
|
||||
>
|
||||
<Routes>
|
||||
<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} />}
|
||||
/>
|
||||
<SentryRoute path="/" element={<HomePage />} />
|
||||
<SentryRoute path="/login" element={<LoginPage />} />
|
||||
<SentryRoute path="/register" element={<RegisterPage />} />
|
||||
<SentryRoute path="*" element={<RoomPage />} />
|
||||
</Routes>
|
||||
</Sentry.ErrorBoundary>
|
||||
</BackgroundEffectsProvider>
|
||||
</MediaDevicesContext>
|
||||
</ClientProvider>
|
||||
</DisconnectedProvider>
|
||||
) : (
|
||||
<LoadingPage />
|
||||
);
|
||||
) : (
|
||||
<LoadingPage />
|
||||
);
|
||||
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
|
||||
+16
-2
@@ -12,7 +12,6 @@ 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,
|
||||
@@ -27,7 +26,22 @@ const TestComponent: FC<
|
||||
}>
|
||||
> = ({ client, hostBridge = nullHostBridge, children }) => {
|
||||
return (
|
||||
<ClientContextProvider value={hostClientSession(client)}>
|
||||
<ClientContextProvider
|
||||
value={{
|
||||
state: "valid",
|
||||
disconnected: false,
|
||||
supportedFeatures: {
|
||||
reactions: true,
|
||||
},
|
||||
setClient: vi.fn(),
|
||||
authenticated: {
|
||||
client,
|
||||
isPasswordlessUser: true,
|
||||
changePassword: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
},
|
||||
}}
|
||||
>
|
||||
<HostBridgeProvider value={hostBridge}>{children}</HostBridgeProvider>
|
||||
</ClientContextProvider>
|
||||
);
|
||||
|
||||
+12
-8
@@ -15,7 +15,7 @@ import {
|
||||
import { Avatar as CompoundAvatar } from "@vector-im/compound-web";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
|
||||
import { useClient } from "./ClientContext";
|
||||
import { useClientState } from "./ClientContext";
|
||||
import { useHostBridge } from "./HostBridge";
|
||||
|
||||
export enum Size {
|
||||
@@ -44,7 +44,7 @@ export interface Props {
|
||||
}
|
||||
|
||||
export function getAvatarUrl(
|
||||
client: Pick<MatrixClient, "mxcUrlToHttp">,
|
||||
client: MatrixClient,
|
||||
mxcUrl: string | null,
|
||||
avatarSize = 96,
|
||||
): string | null {
|
||||
@@ -74,7 +74,7 @@ export const Avatar: FC<Props> = ({
|
||||
style,
|
||||
...props
|
||||
}) => {
|
||||
const client = useClient();
|
||||
const clientState = useClientState();
|
||||
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 `client` or `sizePx` could run extra media
|
||||
// In theory, a change in `clientState` or `sizePx` could run extra media
|
||||
// downloads, but in practice they should be stable long before this code runs.
|
||||
useEffect(() => {
|
||||
if (!src) {
|
||||
@@ -99,8 +99,12 @@ export const Avatar: FC<Props> = ({
|
||||
|
||||
if (hostBridge.downloadMedia) {
|
||||
blob = hostBridge.downloadMedia(src);
|
||||
} else if (client && sizePx) {
|
||||
blob = getAvatarFromServer(client, src, sizePx);
|
||||
} else if (
|
||||
clientState?.state === "valid" &&
|
||||
clientState.authenticated?.client &&
|
||||
sizePx
|
||||
) {
|
||||
blob = getAvatarFromServer(clientState.authenticated.client, src, sizePx);
|
||||
} else {
|
||||
setAvatarUrl(undefined);
|
||||
return;
|
||||
@@ -129,7 +133,7 @@ export const Avatar: FC<Props> = ({
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
}, [client, hostBridge, src, sizePx]);
|
||||
}, [clientState, hostBridge, src, sizePx]);
|
||||
|
||||
return (
|
||||
<CompoundAvatar
|
||||
@@ -145,7 +149,7 @@ export const Avatar: FC<Props> = ({
|
||||
};
|
||||
|
||||
async function getAvatarFromServer(
|
||||
client: Pick<MatrixClient, "mxcUrlToHttp" | "getAccessToken">,
|
||||
client: MatrixClient,
|
||||
src: string,
|
||||
sizePx: number,
|
||||
): Promise<Blob> {
|
||||
|
||||
@@ -38,8 +38,6 @@ type CallRoomPart = Pick<
|
||||
| "getJoinRule"
|
||||
// Raised hands already in the room
|
||||
| "relations"
|
||||
// The encryption system, where no shared key is in use
|
||||
| "hasEncryptionStateEvent"
|
||||
>;
|
||||
|
||||
/**
|
||||
@@ -75,6 +73,5 @@ export function createCallMatrixBackend(
|
||||
get relations() {
|
||||
return room.relations;
|
||||
},
|
||||
hasEncryptionStateEvent: room.hasEncryptionStateEvent.bind(room),
|
||||
};
|
||||
}
|
||||
|
||||
+73
-80
@@ -6,23 +6,16 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { act, render, renderHook } from "@testing-library/react";
|
||||
import { render, waitFor } 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,
|
||||
useClientSessionState,
|
||||
useLoggedInSpaClient,
|
||||
useClientState,
|
||||
} from "./ClientContext";
|
||||
import {
|
||||
type ClientManager,
|
||||
type ClientSession,
|
||||
type ClientSessionState,
|
||||
hostClientSession,
|
||||
} from "./state/ClientSession";
|
||||
|
||||
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
|
||||
({
|
||||
@@ -35,47 +28,67 @@ const mockClient = (userId = "@alice:example.org"): MatrixClient =>
|
||||
|
||||
/** Reports what the context says, so a test can assert on it. */
|
||||
const ShowClientState: FC = () => {
|
||||
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>;
|
||||
}
|
||||
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 renderProvider = (
|
||||
session: ClientSession,
|
||||
children = <ShowClientState />,
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
test("uses a client supplied by the host without waiting", () => {
|
||||
const client = mockClient();
|
||||
|
||||
const { container } = render(
|
||||
<BrowserRouter>
|
||||
<ClientProvider session={session}>{children}</ClientProvider>
|
||||
<ClientProvider client={client}>
|
||||
<ShowClientState />
|
||||
</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 { container, rerender } = renderProvider(
|
||||
hostClientSession(mockClient()),
|
||||
const first = mockClient();
|
||||
const second = mockClient("@bob:example.org");
|
||||
|
||||
const { container, rerender } = render(
|
||||
<BrowserRouter>
|
||||
<ClientProvider client={first}>
|
||||
<ShowClientState />
|
||||
</ClientProvider>
|
||||
</BrowserRouter>,
|
||||
);
|
||||
expect(container.textContent).toBe("@alice:example.org");
|
||||
|
||||
// A host that re-authenticates hands us a new client on a mounted component
|
||||
rerender(
|
||||
<BrowserRouter>
|
||||
<ClientProvider
|
||||
session={hostClientSession(mockClient("@bob:example.org"))}
|
||||
>
|
||||
<ClientProvider client={second}>
|
||||
<ShowClientState />
|
||||
</ClientProvider>
|
||||
</BrowserRouter>,
|
||||
@@ -84,58 +97,38 @@ test("follows the client when the host swaps it", () => {
|
||||
expect(container.textContent).toBe("@bob:example.org");
|
||||
});
|
||||
|
||||
test("follows a session of its own as it is restored", () => {
|
||||
const state$ = new BehaviorSubject<ClientSessionState>({ state: "loading" });
|
||||
const { container } = renderProvider({ state$ });
|
||||
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>,
|
||||
);
|
||||
|
||||
// Nothing to show until a session has been restored or created
|
||||
expect(container.textContent).toBe("loading");
|
||||
act(() =>
|
||||
state$.next({
|
||||
state: "signedIn",
|
||||
client: mockClient(),
|
||||
passwordlessUser: true,
|
||||
}),
|
||||
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),
|
||||
);
|
||||
expect(container.textContent).toBe("@alice:example.org");
|
||||
});
|
||||
|
||||
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("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>,
|
||||
);
|
||||
|
||||
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);
|
||||
await waitFor(() => expect(container.textContent).toBe("unauthenticated"));
|
||||
});
|
||||
|
||||
+416
-42
@@ -5,76 +5,450 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type FC, useEffect, createContext, use, type JSX } from "react";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
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 { ErrorPage } from "./FullScreenView";
|
||||
import { PosthogAnalytics } from "./analytics/PosthogAnalytics";
|
||||
import { useBehavior } from "./useBehavior";
|
||||
import { constant } from "./state/Behavior";
|
||||
import { useHostBridge } from "./HostBridge";
|
||||
import { useLeaveToHome } from "./LeaveToHomeContext";
|
||||
import {
|
||||
type ClientManager,
|
||||
type ClientSession,
|
||||
type ClientSessionState,
|
||||
signedOutClientSession,
|
||||
type SuppliedClient,
|
||||
} from "./state/ClientSession";
|
||||
PosthogAnalytics,
|
||||
RegistrationType,
|
||||
} from "./analytics/PosthogAnalytics";
|
||||
import { useEventTarget } from "./useEvents";
|
||||
import { OpenElsewhereError } from "./RichError";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
matrixclient: SuppliedClient;
|
||||
matrixclient: MatrixClient;
|
||||
passwordlessUser: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
// Without a provider, no one is signed in
|
||||
const ClientContext = createContext<ClientSession>(signedOutClientSession);
|
||||
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);
|
||||
|
||||
export const ClientContextProvider = ClientContext.Provider;
|
||||
|
||||
export const useClientSessionState = (): ClientSessionState =>
|
||||
useBehavior(use(ClientContext).state$);
|
||||
export const useClientState = (): ClientState | undefined => use(ClientContext);
|
||||
|
||||
export function useClient(): SuppliedClient | undefined {
|
||||
const state = useClientSessionState();
|
||||
return state.state === "signedIn" ? state.client : undefined;
|
||||
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 };
|
||||
}
|
||||
|
||||
const noClient$ = constant(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();
|
||||
|
||||
/**
|
||||
* 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$);
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
const loadChannel =
|
||||
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
|
||||
|
||||
interface Props {
|
||||
children: JSX.Element;
|
||||
/** A session from Element Call SPA, a widget, or the host (EW). */
|
||||
session: ClientSession;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export const ClientProvider: FC<Props> = ({ children, session }) => {
|
||||
const state = useBehavior(session.state$);
|
||||
/**
|
||||
* 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));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.state !== "signedIn") return;
|
||||
window.matrixclient = state.client;
|
||||
window.passwordlessUser = state.passwordlessUser;
|
||||
if (!initClientState) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.matrixclient = initClientState.client;
|
||||
window.passwordlessUser = initClientState.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 (state.state === "error") return <ErrorPage error={state.error} />;
|
||||
if (initClientState.client) {
|
||||
initClientState.client.on(ClientEvent.Sync, onSync);
|
||||
}
|
||||
|
||||
return <ClientContext value={session}>{children}</ClientContext>;
|
||||
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>;
|
||||
};
|
||||
|
||||
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";
|
||||
|
||||
@@ -1,33 +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 { 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("");
|
||||
});
|
||||
@@ -10,27 +10,30 @@ import { type FC, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import styles from "./DisconnectedBanner.module.css";
|
||||
import { useDisconnected } from "./DisconnectedContext";
|
||||
import { type ValidClientState, useClientState } from "./ClientContext";
|
||||
|
||||
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 disconnected = useDisconnected();
|
||||
const clientState = useClientState();
|
||||
let shouldShowBanner = false;
|
||||
|
||||
if (clientState?.state === "valid") {
|
||||
const validClientState = clientState as ValidClientState;
|
||||
shouldShowBanner = validClientState.disconnected;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{disconnected && (
|
||||
{shouldShowBanner && (
|
||||
<div className={classNames(styles.banner, className)} {...rest}>
|
||||
{children}
|
||||
{t("disconnected_banner")}
|
||||
|
||||
@@ -1,20 +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 { 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));
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
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>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "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
@@ -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 { 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>
|
||||
);
|
||||
};
|
||||
@@ -41,6 +41,7 @@ export enum UserIntent {
|
||||
StartNewCallDMVoice = "start_call_dm_voice",
|
||||
JoinExistingCallDM = "join_existing_dm",
|
||||
JoinExistingCallDMVoice = "join_existing_dm_voice",
|
||||
VideoRoom = "video_room",
|
||||
Unknown = "unknown",
|
||||
}
|
||||
|
||||
@@ -143,6 +144,18 @@ 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;
|
||||
}
|
||||
@@ -222,6 +235,14 @@ 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 = {
|
||||
|
||||
@@ -318,6 +318,20 @@ 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(
|
||||
@@ -408,6 +422,19 @@ 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);
|
||||
|
||||
@@ -1,101 +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, 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>,
|
||||
);
|
||||
}
|
||||
@@ -9,38 +9,19 @@ import { type FC, useCallback, useState } from "react";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import {
|
||||
useClient,
|
||||
useClientSessionState,
|
||||
useLoggedInSpaClient,
|
||||
} from "./ClientContext";
|
||||
import { type ClientManager } from "./state/ClientSession";
|
||||
import { useLeaveToHome } from "./LeaveToHomeContext";
|
||||
import { useClientLegacy } from "./ClientContext";
|
||||
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,
|
||||
clientManager,
|
||||
}) => {
|
||||
export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
// 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 { client, logout, authenticated, passwordlessUser } = useClientLegacy();
|
||||
const { displayName, avatarUrl } = useProfile(client);
|
||||
const [settingsModalOpen, setSettingsModalOpen] = useState(false);
|
||||
const onDismissSettingsModal = useCallback(
|
||||
@@ -62,9 +43,7 @@ export const UserMenuContainer: FC<Props> = ({
|
||||
setSettingsModalOpen(true);
|
||||
break;
|
||||
case "logout":
|
||||
logout?.()
|
||||
.then(() => leaveToHome?.())
|
||||
.catch((e) => logger.error("Failed to log out", e));
|
||||
logout?.();
|
||||
break;
|
||||
case "login":
|
||||
navigate("/login", { state: { from: location } })?.catch((error) =>
|
||||
@@ -73,7 +52,7 @@ export const UserMenuContainer: FC<Props> = ({
|
||||
break;
|
||||
}
|
||||
},
|
||||
[navigate, location, logout, leaveToHome, setSettingsModalOpen],
|
||||
[navigate, location, logout, setSettingsModalOpen],
|
||||
);
|
||||
|
||||
const userName = client?.getUserIdLocalpart() ?? "";
|
||||
@@ -81,11 +60,11 @@ export const UserMenuContainer: FC<Props> = ({
|
||||
<>
|
||||
<UserMenu
|
||||
preventNavigation={preventNavigation}
|
||||
isAuthenticated={suppliedClient !== undefined}
|
||||
isAuthenticated={authenticated}
|
||||
isPasswordlessUser={passwordlessUser}
|
||||
avatarUrl={avatarUrl}
|
||||
onAction={onAction}
|
||||
userId={suppliedClient?.getUserId() ?? ""}
|
||||
userId={client?.getUserId() ?? ""}
|
||||
displayName={displayName || (userName ? userName.replace("@", "") : "")}
|
||||
/>
|
||||
{client && (
|
||||
|
||||
@@ -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; word-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; overflow-wrap: normal;"
|
||||
>
|
||||
My modal
|
||||
</h2>
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// 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>
|
||||
`;
|
||||
@@ -12,6 +12,7 @@ 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 {
|
||||
@@ -342,7 +343,7 @@ export class PosthogAnalytics {
|
||||
}
|
||||
|
||||
private async getAnalyticsId(): Promise<string | null> {
|
||||
const client = window.matrixclient;
|
||||
const client: MatrixClient = window.matrixclient;
|
||||
if (this.config.matrixBackend === "embedded") {
|
||||
return this.config.hostAnalyticsId ?? null;
|
||||
} else {
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { 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>,
|
||||
);
|
||||
}
|
||||
+14
-9
@@ -11,23 +11,21 @@ import { Trans, useTranslation } from "react-i18next";
|
||||
import { Button } from "@vector-im/compound-web";
|
||||
|
||||
import Logo from "../icons/LogoLarge.svg?react";
|
||||
import { type ClientManager } from "../state/ClientSession";
|
||||
import { useClient } from "../ClientContext";
|
||||
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";
|
||||
|
||||
interface Props {
|
||||
clientManager: ClientManager;
|
||||
}
|
||||
|
||||
export const LoginPage: FC<Props> = ({ clientManager }) => {
|
||||
export const LoginPage: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t("login_title"));
|
||||
|
||||
const { login } = clientManager;
|
||||
const { client, setClient } = useClient();
|
||||
const login = useInteractiveLogin(client);
|
||||
const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable
|
||||
const usernameRef = useRef<HTMLInputElement>(null);
|
||||
const passwordRef = useRef<HTMLInputElement>(null);
|
||||
@@ -48,8 +46,15 @@ export const LoginPage: FC<Props> = ({ clientManager }) => {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
login(homeserver, usernameRef.current.value, passwordRef.current.value)
|
||||
.then(async () => {
|
||||
.then(async ([client, session]) => {
|
||||
if (!setClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
setClient(client, session);
|
||||
|
||||
const locationState = location.state;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
@@ -67,7 +72,7 @@ export const LoginPage: FC<Props> = ({ clientManager }) => {
|
||||
setLoading(false);
|
||||
});
|
||||
},
|
||||
[login, location, navigate, homeserver],
|
||||
[login, location, navigate, homeserver, setClient],
|
||||
);
|
||||
// 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);
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { 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>,
|
||||
);
|
||||
}
|
||||
+18
-19
@@ -22,9 +22,8 @@ import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { Button, Text } from "@vector-im/compound-web";
|
||||
|
||||
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
|
||||
import { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
|
||||
import { type ClientManager } from "../state/ClientSession";
|
||||
import { useRegistrationTerms } from "./useRegistrationTerms";
|
||||
import { useClientLegacy } from "../ClientContext";
|
||||
import { useInteractiveRegistration } from "./useInteractiveRegistration";
|
||||
import styles from "./LoginPage.module.css";
|
||||
import Logo from "../icons/LogoLarge.svg?react";
|
||||
import { LoadingPage } from "../FullScreenView";
|
||||
@@ -34,21 +33,12 @@ import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
|
||||
import { Config } from "../config/Config";
|
||||
import { ExternalLink, Link } from "../button/Link";
|
||||
|
||||
interface Props {
|
||||
clientManager: ClientManager;
|
||||
}
|
||||
|
||||
export const RegisterPage: FC<Props> = ({ clientManager }) => {
|
||||
export const RegisterPage: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t("action.register"));
|
||||
|
||||
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 { loading, authenticated, passwordlessUser, client, setClient } =
|
||||
useClientLegacy();
|
||||
|
||||
const confirmPasswordRef = useRef<HTMLInputElement>(null);
|
||||
const navigate = useNavigate();
|
||||
@@ -57,7 +47,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
|
||||
const [error, setError] = useState<Error>();
|
||||
const [password, setPassword] = useState("");
|
||||
const [passwordConfirmation, setPasswordConfirmation] = useState("");
|
||||
const { recaptchaKey } = useRegistrationTerms();
|
||||
const { recaptchaKey, register } = useInteractiveRegistration(client);
|
||||
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
|
||||
|
||||
const onSubmitRegisterForm = useCallback(
|
||||
@@ -74,7 +64,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
|
||||
setRegistering(true);
|
||||
|
||||
const recaptchaResponse = await execute();
|
||||
const { client: newClient, setSignedIn } = await register(
|
||||
const [newClient, session] = await register(
|
||||
userName,
|
||||
password,
|
||||
userName,
|
||||
@@ -105,7 +95,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
|
||||
}
|
||||
}
|
||||
|
||||
setSignedIn();
|
||||
setClient?.(newClient, session);
|
||||
PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date());
|
||||
};
|
||||
|
||||
@@ -127,7 +117,16 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
|
||||
reset();
|
||||
});
|
||||
},
|
||||
[register, location, navigate, passwordlessUser, reset, execute, client],
|
||||
[
|
||||
register,
|
||||
location,
|
||||
navigate,
|
||||
passwordlessUser,
|
||||
reset,
|
||||
execute,
|
||||
client,
|
||||
setClient,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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 { 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",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,106 +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 {
|
||||
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 */
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
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],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
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 };
|
||||
};
|
||||
@@ -1,116 +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 { 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>
|
||||
);
|
||||
}
|
||||
@@ -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 { type ClientManager } from "../state/ClientSession";
|
||||
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
|
||||
import { useClient } from "../ClientContext";
|
||||
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
|
||||
import { generateRandomName } from "../auth/generateRandomName";
|
||||
import { useRecaptcha } from "../auth/useRecaptcha";
|
||||
import { useUrlParams } from "../UrlParams";
|
||||
@@ -20,21 +20,17 @@ interface UseRegisterPasswordlessUserType {
|
||||
recaptchaId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param clientManager Null in the widget, which never registers anyone.
|
||||
*/
|
||||
export function useRegisterPasswordlessUser(
|
||||
clientManager: ClientManager | null,
|
||||
): UseRegisterPasswordlessUserType {
|
||||
const register = clientManager?.register;
|
||||
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
|
||||
const { setClient } = useClient();
|
||||
const { isWidget } = useUrlParams();
|
||||
const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms();
|
||||
const { privacyPolicyUrl, recaptchaKey, register } =
|
||||
useInteractiveRegistration();
|
||||
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
|
||||
|
||||
const registerPasswordlessUser = useCallback(
|
||||
async (displayName: string) => {
|
||||
if (!register) {
|
||||
throw new Error("This session cannot register");
|
||||
if (!setClient) {
|
||||
throw new Error("No client context");
|
||||
}
|
||||
if (isWidget) {
|
||||
throw new Error(
|
||||
@@ -45,20 +41,20 @@ export function useRegisterPasswordlessUser(
|
||||
try {
|
||||
const recaptchaResponse = await execute();
|
||||
const userName = generateRandomName();
|
||||
const { setSignedIn } = await register(
|
||||
const [client, session] = await register(
|
||||
userName,
|
||||
secureRandomString(16),
|
||||
displayName,
|
||||
recaptchaResponse,
|
||||
true,
|
||||
);
|
||||
setSignedIn();
|
||||
setClient(client, session);
|
||||
} catch (e) {
|
||||
reset();
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
[execute, reset, register, isWidget],
|
||||
[execute, reset, register, setClient, isWidget],
|
||||
);
|
||||
|
||||
return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId };
|
||||
|
||||
@@ -1,98 +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 { 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>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
/*
|
||||
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 };
|
||||
}
|
||||
+31
-32
@@ -25,11 +25,14 @@ 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;
|
||||
@@ -149,6 +152,7 @@ interface LoudspeakerButtonProps extends ComponentPropsWithoutRef<"button"> {
|
||||
size?: "md" | "lg";
|
||||
loudspeakerModeEnabled: boolean;
|
||||
}
|
||||
|
||||
export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
|
||||
loudspeakerModeEnabled,
|
||||
...props
|
||||
@@ -171,36 +175,37 @@ export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
function classNamesForScreenWidth(
|
||||
className?: string,
|
||||
forScreenWidth?: "wide" | "narrow",
|
||||
): string {
|
||||
return classNames(className, {
|
||||
[callFooterStyles.settingsOnlyShowWide]: forScreenWidth === "wide",
|
||||
[callFooterStyles.settingsOnlyShowNarrow]: forScreenWidth === "narrow",
|
||||
});
|
||||
interface LayoutSwitchButtonProps extends ComponentPropsWithoutRef<"button"> {
|
||||
layout: LayoutMode;
|
||||
}
|
||||
|
||||
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,
|
||||
export const LayoutSwitchButton: FC<LayoutSwitchButtonProps> = ({
|
||||
layout,
|
||||
...props
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const Icon =
|
||||
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon;
|
||||
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();
|
||||
return (
|
||||
<Tooltip label={t("common.settings")}>
|
||||
<IconButton
|
||||
className={classNamesForScreenWidth(className, showForScreenWidth)}
|
||||
{...props}
|
||||
>
|
||||
<Icon aria-hidden />
|
||||
<IconButton {...props}>
|
||||
<SettingsSolidIcon aria-hidden />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
);
|
||||
@@ -208,19 +213,13 @@ export const SettingsIconButton: FC<SettingsIconButtonProps> = ({
|
||||
|
||||
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> = ({
|
||||
showForScreenWidth,
|
||||
className,
|
||||
...props
|
||||
}) => {
|
||||
|
||||
export const SettingsButton: FC<SettingsButtonProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Tooltip label={t("common.settings")}>
|
||||
<CpdButton
|
||||
className={classNamesForScreenWidth(className, showForScreenWidth)}
|
||||
iconOnly
|
||||
Icon={
|
||||
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon
|
||||
|
||||
@@ -112,7 +112,6 @@ export const BackgroundEffectGrid: FC<Props> = ({
|
||||
disabled={disabled}
|
||||
data-disabled={disabled ? "" : undefined}
|
||||
label={null}
|
||||
hideChevron
|
||||
className={styles.tile}
|
||||
// Without a handler it isn't one of the menu's items, so the keyboard
|
||||
// passes over it.
|
||||
@@ -160,7 +159,6 @@ export const BackgroundEffectGrid: FC<Props> = ({
|
||||
onAdd === undefined ? null : (
|
||||
<MenuItem
|
||||
label={null}
|
||||
hideChevron
|
||||
className={styles.tile}
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -24,7 +24,7 @@ import * as CallFooterStories from "./CallFooter.stories";
|
||||
|
||||
<Title> Call Footer </Title>
|
||||
|
||||
The footer compoentn contains all main interactions needed for a call.
|
||||
The footer component contains all main interactions needed for a call.
|
||||
|
||||
<Subtitle> Mobile layouts </Subtitle>
|
||||
|
||||
|
||||
@@ -9,9 +9,10 @@ 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 layout";
|
||||
grid-template-areas: ". buttons .";
|
||||
align-items: center;
|
||||
gap: var(--cpd-space-3x);
|
||||
/* Ensure that footer lies within the safe area */
|
||||
@@ -19,6 +20,10 @@ 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 {
|
||||
@@ -26,21 +31,57 @@ 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;
|
||||
transition: opacity 0.15s;
|
||||
|
||||
> .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;
|
||||
}
|
||||
}
|
||||
|
||||
.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
|
||||
@@ -48,10 +89,17 @@ Please see LICENSE in the repository root for full details.
|
||||
.footer.overlay:has(:focus-visible),
|
||||
.footer.overlay:has([aria-expanded="true"]) {
|
||||
opacity: 1;
|
||||
pointer-events: initial;
|
||||
|
||||
> .buttons {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
> * {
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.settingsLogoContainer {
|
||||
.logoContainer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--cpd-space-4x);
|
||||
@@ -70,13 +118,45 @@ 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;
|
||||
gap: var(--cpd-space-3x);
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.layout {
|
||||
grid-area: layout;
|
||||
justify-self: end;
|
||||
: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);
|
||||
}
|
||||
|
||||
/*First hide the logo*/
|
||||
@@ -86,30 +166,16 @@ Please see LICENSE in the repository root for full details.
|
||||
}
|
||||
}
|
||||
|
||||
.settingsOnlyShowNarrow {
|
||||
display: none;
|
||||
}
|
||||
.settingsOnlyShowWide {
|
||||
display: inherit;
|
||||
}
|
||||
|
||||
/*
|
||||
With the logo hidden >500px is enough space to show overflow, buttons, layout.
|
||||
Once we exceed 500 we hide everything except the buttons.
|
||||
With the logo hidden >500px is enough space to show logo and buttons.
|
||||
Once we exceed 500 we hide the logo.
|
||||
*/
|
||||
@container element-call (max-width: 500px) {
|
||||
.footer {
|
||||
grid-template-areas: "buttons buttons buttons";
|
||||
}
|
||||
|
||||
.settingsOnlyShowNarrow {
|
||||
display: inherit;
|
||||
}
|
||||
.settingsOnlyShowWide {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settingsLogoContainer {
|
||||
.logoContainer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -156,9 +222,3 @@ Once we exceed 500 we hide everything except the buttons.
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@container element-call (min-width: 800px) {
|
||||
.buttons {
|
||||
gap: var(--cpd-space-4x);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, within } from "storybook/test";
|
||||
import { expect, fn, userEvent, waitFor, 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: "lg",
|
||||
buttonSize: "md",
|
||||
showFooter: true,
|
||||
hideControls: false,
|
||||
asOverlay: false,
|
||||
@@ -202,8 +202,11 @@ export const StaysWhileAMenuIsOpen: Story = {
|
||||
const footer = canvasElement.querySelector<HTMLElement>(
|
||||
'[data-testid="footer-container"]',
|
||||
)!;
|
||||
await userEvent.click(
|
||||
within(canvasElement).getByRole("button", { name: "Microphone" }),
|
||||
// Open microphone menu once footer becomes interactive
|
||||
await waitFor(async () =>
|
||||
userEvent.click(
|
||||
within(canvasElement).getByRole("button", { name: "Microphone" }),
|
||||
),
|
||||
);
|
||||
await expect(document.body.querySelector('[role="menu"]')).not.toBeNull();
|
||||
|
||||
@@ -232,8 +235,9 @@ export const SpotlightMode: Story = {
|
||||
layout: "spotlight",
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("radio", { name: "Grid" }));
|
||||
const canvas = within(canvasElement.parentElement!);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Adjust view" }));
|
||||
await userEvent.click(canvas.getByRole("menuitemradio", { name: "Grid" }));
|
||||
await expect(args.setLayout).toHaveBeenCalledWith("grid");
|
||||
await userEvent.click(canvas.getByRole("switch", { name: "Share screen" }));
|
||||
await expect(args.toggleScreenSharing).toHaveBeenCalled();
|
||||
@@ -269,12 +273,11 @@ export const Pip: Story = {
|
||||
...Default,
|
||||
args: {
|
||||
...Default.args,
|
||||
buttonSize: "md",
|
||||
layout: null,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await expect(
|
||||
within(canvasElement).queryByRole("radio", { name: "Spotlight" }),
|
||||
within(canvasElement).queryByRole("button", { name: "Adjust view" }),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
@@ -301,6 +304,7 @@ export const MobileLayout: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
showLogo: false,
|
||||
buttonSize: "lg",
|
||||
|
||||
audioOutputSwitcher: { targetOutput: "speaker", switch: fn() },
|
||||
},
|
||||
@@ -332,6 +336,7 @@ export const LobbyRecentButtonMobile: Story = {
|
||||
...Default.args,
|
||||
children: <Link>Back To Recents</Link>,
|
||||
showLogo: false,
|
||||
buttonSize: "lg",
|
||||
layout: null,
|
||||
toggleScreenSharing: undefined,
|
||||
},
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
SettingsButton,
|
||||
ReactionToggleButton,
|
||||
LoudspeakerButton,
|
||||
SettingsIconButton,
|
||||
type ReactionData,
|
||||
} from "../button";
|
||||
import styles from "./CallFooter.module.css";
|
||||
@@ -120,20 +119,6 @@ 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"
|
||||
@@ -189,6 +174,28 @@ 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
|
||||
@@ -221,28 +228,17 @@ 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.settingsLogoContainer}>
|
||||
{openSettings !== undefined && (
|
||||
<SettingsIconButton
|
||||
key="settings"
|
||||
kind="secondary"
|
||||
showForScreenWidth="wide"
|
||||
onClick={openSettings}
|
||||
data-testid="settings-bottom-left"
|
||||
/>
|
||||
)}
|
||||
<div className={styles.logoContainer}>
|
||||
{children}
|
||||
{(showLogo || debugTileLayout) && logoDebugContainer}
|
||||
</div>
|
||||
{!hideControls && <div className={styles.buttons}>{buttons}</div>}
|
||||
{!hideControls && layoutSwitchVm && (
|
||||
<LayoutSwitch vm={layoutSwitchVm} className={styles.layout} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -80,9 +80,7 @@ export function createCallFooterViewModel(
|
||||
hideControls$: constant(!showControls),
|
||||
showModals$: callModel.showModals$,
|
||||
asOverlay$: callModel.edgeToEdge$,
|
||||
buttonSize$: scope.behavior(
|
||||
isPip$.pipe(map<boolean, "md" | "lg">((pip) => (pip ? "md" : "lg"))),
|
||||
),
|
||||
buttonSize$: constant(platform === "desktop" ? "md" : "lg"),
|
||||
|
||||
openSettings$: scope.behavior(
|
||||
combineLatest([
|
||||
@@ -162,7 +160,7 @@ export function createLobbyFooterViewModel(
|
||||
hideControls: false,
|
||||
asOverlay: false,
|
||||
showModals: true,
|
||||
buttonSize: "lg",
|
||||
buttonSize: platform === "desktop" ? "md" : "lg",
|
||||
openSettings,
|
||||
hangup,
|
||||
debugTileLayout: false,
|
||||
|
||||
@@ -26,7 +26,7 @@ function MediaMenuButtonStoryWrapper({
|
||||
...snapshot
|
||||
}: MediaMenuSnapshot & { kind: "audio" | "video" }): ReactNode {
|
||||
const vm = useStaticViewModel(snapshot);
|
||||
return <MediaMenuButton kind={kind} vm={vm} size="lg" />;
|
||||
return <MediaMenuButton kind={kind} vm={vm} size="md" />;
|
||||
}
|
||||
|
||||
const meta = {
|
||||
|
||||
@@ -88,6 +88,7 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
|
||||
return kind === "audio" ? (
|
||||
<MediaMuteAndSwitchButton
|
||||
size={size}
|
||||
iconsAndLabels="audio"
|
||||
enabled={enabled}
|
||||
busy={busy}
|
||||
@@ -102,6 +103,7 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
|
||||
/>
|
||||
) : (
|
||||
<MediaMuteAndSwitchButton
|
||||
size={size}
|
||||
iconsAndLabels="video"
|
||||
enabled={enabled}
|
||||
busy={busy}
|
||||
|
||||
@@ -16,12 +16,24 @@ Please see LICENSE in the repository root for full details.
|
||||
.containerOpen {
|
||||
background-color: var(--cpd-color-bg-action-primary-pressed);
|
||||
}
|
||||
.chevronIconOpen > svg {
|
||||
color: var(--cpd-color-icon-on-solid-primary);
|
||||
}
|
||||
.menuButton {
|
||||
width: 40px;
|
||||
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 {
|
||||
color: var(--cpd-color-icon-on-solid-primary);
|
||||
}
|
||||
.itemIcon {
|
||||
color: var(--cpd-color-text-secondary);
|
||||
|
||||
@@ -537,7 +537,9 @@ export const RemovingWithLiveSelection: Story = {
|
||||
const cross = tile.parentElement!.querySelector<HTMLElement>(
|
||||
"[aria-hidden]:last-child",
|
||||
)!;
|
||||
await expect(cross).toBeVisible();
|
||||
// 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 userEvent.click(cross);
|
||||
|
||||
await waitFor(async () =>
|
||||
@@ -907,7 +909,10 @@ export const SelectionSettling: Story = {
|
||||
await menu.findByRole("menuitemradio", { name: "Microphone 2" }),
|
||||
);
|
||||
|
||||
await expect(await menu.findByLabelText("Activating…")).toBeVisible();
|
||||
// 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());
|
||||
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 Activating…",
|
||||
name: /^Microphone 2\s*Activating…$/,
|
||||
checked: false,
|
||||
});
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ export interface MenuOptions {
|
||||
}
|
||||
|
||||
export interface MediaMuteAndSwitchButtonProps {
|
||||
size?: "md" | "lg";
|
||||
/** If the Mute button is enabled */
|
||||
enabled?: boolean;
|
||||
/** Callback if the mute button is clicked */
|
||||
@@ -120,6 +121,7 @@ const MENU_MARGIN = 16;
|
||||
const PREVIEW_GAP = 12;
|
||||
|
||||
export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
size,
|
||||
enabled,
|
||||
busy,
|
||||
onMuteClick,
|
||||
@@ -276,6 +278,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
const MuteButton = audioMeter ? MicButton : VideoButton;
|
||||
const button = (
|
||||
<MuteButton
|
||||
size={size}
|
||||
enabled={enabled ?? false}
|
||||
busy={isBusy}
|
||||
onClick={(e) => {
|
||||
@@ -365,7 +368,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
<MenuItem
|
||||
// A radio input may not sit inside a button.
|
||||
as="div"
|
||||
hideChevron
|
||||
disabled={disabled}
|
||||
label={labelText(label, numbered)}
|
||||
Icon={
|
||||
@@ -447,7 +449,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
|
||||
})}
|
||||
Icon={menuOpen ? ChevronUpIcon : ChevronDownIcon}
|
||||
kind={"tertiary"}
|
||||
size="lg"
|
||||
size={size}
|
||||
aria-label={optionsButtonLabel}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -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 } from "vitest";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { E2eeType } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
@@ -15,9 +15,14 @@ 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(() => {
|
||||
@@ -62,17 +67,8 @@ 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(room));
|
||||
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
|
||||
expect(result.current).toEqual({ kind: E2eeType.NONE });
|
||||
|
||||
act(() => saveKeyForRoom(roomId, "stored"));
|
||||
@@ -86,7 +82,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(room));
|
||||
renderHook(() => useRoomEncryptionSystem(roomId));
|
||||
|
||||
expect(Object.keys(localStorage)).toEqual([`room-shared-key-${roomId}`]);
|
||||
expect(getKeyForRoom(roomId)).toBe("from-the-link");
|
||||
@@ -96,7 +92,7 @@ describe("useRoomEncryptionSystem", () => {
|
||||
saveKeyForRoom(roomId, "stored");
|
||||
window.location.hash = `#?roomId=${encodeURIComponent(otherRoomId)}&password=other-room`;
|
||||
|
||||
const { result } = renderHook(() => useRoomEncryptionSystem(room));
|
||||
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
|
||||
|
||||
expect(result.current).toEqual({
|
||||
kind: E2eeType.SHARED_KEY,
|
||||
|
||||
@@ -6,7 +6,6 @@ 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 {
|
||||
@@ -15,6 +14,7 @@ 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,17 +89,18 @@ export function getKeyForRoom(roomId: string): string | null {
|
||||
|
||||
export { type EncryptionSystem } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
export function useRoomEncryptionSystem(
|
||||
room: Pick<Room, "roomId" | "hasEncryptionStateEvent">,
|
||||
): EncryptionSystem {
|
||||
export function useRoomEncryptionSystem(roomId: string): EncryptionSystem {
|
||||
const { client } = useClient();
|
||||
const { roomId: paramsRoomId, password } = useUrlParams();
|
||||
|
||||
const [storedPassword] = useRoomSharedKey(
|
||||
room.roomId,
|
||||
keyForRoom(room.roomId, paramsRoomId, password) ?? undefined,
|
||||
roomId,
|
||||
keyForRoom(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,
|
||||
|
||||
@@ -29,7 +29,6 @@ describe("CallList", () => {
|
||||
roomAlias: "#room-name:server.org",
|
||||
room: {
|
||||
roomId: "!roomId",
|
||||
hasEncryptionStateEvent: () => false,
|
||||
},
|
||||
},
|
||||
] as GroupCallRoom[];
|
||||
|
||||
@@ -58,7 +58,7 @@ interface CallTileProps {
|
||||
|
||||
const CallTile: FC<CallTileProps> = ({ name, avatarUrl, room, client }) => {
|
||||
const { t } = useTranslation();
|
||||
const roomEncryptionSystem = useRoomEncryptionSystem(room);
|
||||
const roomEncryptionSystem = useRoomEncryptionSystem(room.roomId);
|
||||
const [isLeaving, setIsLeaving] = useState(false);
|
||||
|
||||
const onRemove = useCallback(
|
||||
|
||||
@@ -1,96 +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, 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>,
|
||||
);
|
||||
}
|
||||
+13
-36
@@ -7,51 +7,28 @@ 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 { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
|
||||
import { useClientState } 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";
|
||||
|
||||
interface Props {
|
||||
/** Null where the session is a host's and not ours to manage. */
|
||||
clientManager: ClientManager | null;
|
||||
}
|
||||
|
||||
export const HomePage: FC<Props> = ({ clientManager }) => {
|
||||
export const HomePage: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t("common.home"));
|
||||
|
||||
const session = useClientSessionState();
|
||||
const spaClient = useLoggedInSpaClient(clientManager);
|
||||
const clientState = useClientState();
|
||||
|
||||
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} />
|
||||
);
|
||||
if (!clientState) {
|
||||
return <LoadingPage />;
|
||||
} else if (clientState.state === "error") {
|
||||
return <ErrorPage error={clientState.error} />;
|
||||
} else {
|
||||
return clientState.authenticated ? (
|
||||
<RegisteredView client={clientState.authenticated.client} />
|
||||
) : (
|
||||
<UnauthenticatedView />
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -38,14 +38,12 @@ 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, clientManager }) => {
|
||||
export const RegisteredView: FC<Props> = ({ client }) => {
|
||||
const { header } = useUrlParams();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error>();
|
||||
@@ -124,7 +122,7 @@ export const RegisteredView: FC<Props> = ({ client, clientManager }) => {
|
||||
<HeaderLogo />
|
||||
</LeftNav>
|
||||
<RightNav>
|
||||
<UserMenuContainer clientManager={clientManager} />
|
||||
<UserMenuContainer />
|
||||
</RightNav>
|
||||
</Header>
|
||||
)}
|
||||
|
||||
@@ -1,139 +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 { 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>,
|
||||
);
|
||||
}
|
||||
@@ -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 { type ClientManager } from "../state/ClientSession";
|
||||
import { useClient } from "../ClientContext";
|
||||
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 { useRegistrationTerms } from "../auth/useRegistrationTerms";
|
||||
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
|
||||
import { JoinExistingCallModal } from "./JoinExistingCallModal";
|
||||
import { useRecaptcha } from "../auth/useRecaptcha";
|
||||
import { Form } from "../form/Form";
|
||||
@@ -36,17 +36,13 @@ import { useOptInAnalytics } from "../settings/settings";
|
||||
import { ExternalLink, Link } from "../button/Link";
|
||||
import { useUrlParams } from "../UrlParams";
|
||||
|
||||
interface Props {
|
||||
clientManager: ClientManager;
|
||||
}
|
||||
|
||||
export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
const { register } = clientManager;
|
||||
export const UnauthenticatedView: FC = () => {
|
||||
const { setClient } = useClient();
|
||||
const { header } = useUrlParams();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error>();
|
||||
const [optInAnalytics] = useOptInAnalytics();
|
||||
const { recaptchaKey } = useRegistrationTerms();
|
||||
const { recaptchaKey, register } = useInteractiveRegistration();
|
||||
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
|
||||
|
||||
const [joinExistingCallModalOpen, setJoinExistingCallModalOpen] =
|
||||
@@ -71,9 +67,7 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
setLoading(true);
|
||||
const recaptchaResponse = await execute();
|
||||
const userName = generateRandomName();
|
||||
// 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(
|
||||
const [client, session] = await register(
|
||||
userName,
|
||||
secureRandomString(16),
|
||||
displayName,
|
||||
@@ -89,12 +83,15 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
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") {
|
||||
// Wrapped once more, as a bare function would be taken for an updater
|
||||
setOnFinished(() => () => {
|
||||
setSignedIn();
|
||||
setOnFinished(() => {
|
||||
setClient(client, session);
|
||||
const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName);
|
||||
navigate(`/${aliasLocalpart}`)?.catch((error) => {
|
||||
logger.error("Failed to navigate to alias localpart", error);
|
||||
@@ -109,10 +106,14 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 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");
|
||||
|
||||
setSignedIn();
|
||||
setClient(client, session);
|
||||
await navigate(
|
||||
getRelativeRoomUrl(
|
||||
createRoomResult.roomId,
|
||||
@@ -129,7 +130,14 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
reset();
|
||||
});
|
||||
},
|
||||
[register, reset, execute, navigate, setJoinExistingCallModalOpen],
|
||||
[
|
||||
register,
|
||||
reset,
|
||||
execute,
|
||||
navigate,
|
||||
setJoinExistingCallModalOpen,
|
||||
setClient,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -141,7 +149,7 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
|
||||
<HeaderLogo />
|
||||
</LeftNav>
|
||||
<RightNav hideMobile>
|
||||
<UserMenuContainer clientManager={clientManager} />
|
||||
<UserMenuContainer />
|
||||
</RightNav>
|
||||
</Header>
|
||||
)}
|
||||
|
||||
@@ -25,19 +25,25 @@ describe("useGroupCallRooms", () => {
|
||||
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 sticky %s membership",
|
||||
(type) => {
|
||||
const room = mockCallRoom({
|
||||
stickyEvents: [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.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 knocked room without any call events", () => {
|
||||
const room = mockCallRoom({
|
||||
@@ -61,8 +67,12 @@ describe("useGroupCallRooms", () => {
|
||||
const room = mockCallRoom({
|
||||
membership,
|
||||
legacyMemberState: true,
|
||||
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
|
||||
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
|
||||
stickyEvents: [
|
||||
new MatrixEvent({ type: EventType.RTCMembershipStable }),
|
||||
],
|
||||
timelineEvents: [
|
||||
new MatrixEvent({ type: EventType.RTCMembershipStable }),
|
||||
],
|
||||
});
|
||||
expect(listedRoomIds([room])).toEqual([]);
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import {
|
||||
type MatrixClient,
|
||||
type MatrixEvent,
|
||||
type RoomMember,
|
||||
type Room,
|
||||
RoomEvent,
|
||||
@@ -143,19 +144,25 @@ const roomHasCallMembershipEvents = (room: Room): boolean => {
|
||||
|
||||
// Check for recent calls using sticky events.
|
||||
for (const sticky of room._unstable_getStickyEvents()) {
|
||||
if (sticky.getType() === EventType.RTCMembership) {
|
||||
if (isRtcMembershipEvent(sticky)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, check recent event history to see if anyone had
|
||||
// sent a call membership in here.
|
||||
return timeline
|
||||
.getEvents()
|
||||
.some((e) => e.getType() === EventType.RTCMembership);
|
||||
return timeline.getEvents().some(isRtcMembershipEvent);
|
||||
// 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[]>([]);
|
||||
|
||||
|
||||
+11
-26
@@ -16,14 +16,10 @@ import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { App, loadStandaloneClientSession } from "./App";
|
||||
import { App } 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";
|
||||
|
||||
@@ -53,30 +49,19 @@ if (fatalError !== null) {
|
||||
}
|
||||
|
||||
Initializer.initBeforeReact()
|
||||
.then(async (widget) => {
|
||||
.then((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={vm} widget={widget} />
|
||||
<App
|
||||
vm={
|
||||
new AppViewModel(globalScope, {
|
||||
controlledAudioDevices,
|
||||
callIntent,
|
||||
})
|
||||
}
|
||||
widget={widget}
|
||||
/>
|
||||
</StrictMode>,
|
||||
);
|
||||
})
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from "react";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { useHostBridge } from "../HostBridge";
|
||||
import { useClientState } from "../ClientContext";
|
||||
import { ElementCallReactionEventType, type ReactionOption } from ".";
|
||||
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
|
||||
import { useBehavior } from "../useBehavior";
|
||||
@@ -72,7 +72,9 @@ export const ReactionsSenderProvider = ({
|
||||
/** Our own membership, which the reactions relate to, and the current reactions. */
|
||||
vm: CallViewModel;
|
||||
}): JSX.Element => {
|
||||
const { supportsReactions } = useHostBridge();
|
||||
const clientState = useClientState();
|
||||
const supportsReactions =
|
||||
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
|
||||
const myMembershipIdentifier = `${client.getUserId()}:${client.getDeviceId()}`;
|
||||
|
||||
const localMember = useBehavior(vm.localMember$);
|
||||
|
||||
+16
-14
@@ -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,23 +137,24 @@ beforeEach(() => {
|
||||
);
|
||||
});
|
||||
|
||||
function createCallView(
|
||||
async 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: {
|
||||
@@ -168,7 +169,6 @@ function createCallView(
|
||||
getMembersWithMembership: () => [carol],
|
||||
getMxcAvatarUrl: () => null,
|
||||
getJoinRule: () => JoinRule.Invite,
|
||||
hasEncryptionStateEvent: () => false,
|
||||
});
|
||||
const rtcSession = new MockRTCSession(room, []).withMemberships(
|
||||
constant([localRtcMember]),
|
||||
@@ -180,7 +180,7 @@ function createCallView(
|
||||
<TooltipProvider>
|
||||
<MediaDevicesContext value={mockMediaDevices({})}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={createAppBackgroundEffects$(testScope())}
|
||||
effects={createAppBackgroundEffects(testScope())}
|
||||
>
|
||||
<CallView
|
||||
backend={
|
||||
@@ -204,6 +204,8 @@ function createCallView(
|
||||
</HostBridgeProvider>
|
||||
</BrowserRouter>,
|
||||
);
|
||||
// Let the homeserver capability check resolve, which the call waits for
|
||||
await act(flushPromises);
|
||||
return {
|
||||
getByText,
|
||||
rtcSession: rtcSession.asMockedSession(),
|
||||
@@ -212,7 +214,7 @@ function createCallView(
|
||||
|
||||
test.skip("CallView plays a leave sound asynchronously in SPA mode", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { getByText, rtcSession } = createCallView(nullHostBridge);
|
||||
const { getByText, rtcSession } = await createCallView(nullHostBridge);
|
||||
const leaveButton = getByText("Leave");
|
||||
await user.click(leaveButton);
|
||||
expect(playSound).toHaveBeenCalledWith("left");
|
||||
@@ -242,7 +244,7 @@ test.skip("CallView plays a leave sound synchronously in widget mode", async ()
|
||||
soundDuration: {},
|
||||
});
|
||||
|
||||
const { getByText, rtcSession } = createCallView(hostBridge);
|
||||
const { getByText, rtcSession } = await createCallView(hostBridge);
|
||||
const leaveButton = getByText("Leave");
|
||||
await user.click(leaveButton);
|
||||
await flushPromises();
|
||||
@@ -275,7 +277,7 @@ test("Should ask the host to close when all other left and play a sound", async
|
||||
soundDuration: {},
|
||||
});
|
||||
|
||||
const { getByText } = createCallView(hostBridge);
|
||||
const { getByText } = await createCallView(hostBridge);
|
||||
const leaveButton = getByText("SimulateOtherLeft");
|
||||
await user.click(leaveButton);
|
||||
await flushPromises();
|
||||
@@ -292,7 +294,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$ };
|
||||
|
||||
createCallView(hostBridge, false, { preload: true });
|
||||
await 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();
|
||||
@@ -317,7 +319,7 @@ test("Should not ask the host to close when auto leave due to error", async () =
|
||||
close,
|
||||
};
|
||||
|
||||
const { getByText } = createCallView(hostBridge);
|
||||
const { getByText } = await createCallView(hostBridge);
|
||||
const leaveButton = getByText("SimulateErrorLeft");
|
||||
await user.click(leaveButton);
|
||||
await flushPromises();
|
||||
@@ -340,7 +342,7 @@ test.skip("CallView leaves the session when an error occurs", async () => {
|
||||
);
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
const { rtcSession } = createCallView(nullHostBridge);
|
||||
const { rtcSession } = await createCallView(nullHostBridge);
|
||||
await user.click(screen.getByRole("button", { name: "Panic!" }));
|
||||
screen.getByText("Something went wrong");
|
||||
expect(leaveRTCSession).toHaveBeenCalledWith(
|
||||
@@ -357,7 +359,7 @@ test.skip("CallView shows errors that occur during joining", async () => {
|
||||
onTestFinished(() => {
|
||||
enterRTCSession.mockReset();
|
||||
});
|
||||
createCallView(nullHostBridge, false);
|
||||
await createCallView(nullHostBridge, false);
|
||||
await user.click(screen.getByRole("button", { name: "Join call" }));
|
||||
screen.getByText("Call is not supported");
|
||||
});
|
||||
@@ -379,7 +381,7 @@ test("user can reconnect after losing the connection", async () => {
|
||||
},
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
createCallView(nullHostBridge, true);
|
||||
await 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
|
||||
|
||||
+41
-5
@@ -13,7 +13,12 @@ import {
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { type MatrixClient, JoinRule, type Room } from "matrix-js-sdk";
|
||||
import {
|
||||
type MatrixClient,
|
||||
JoinRule,
|
||||
type Room,
|
||||
UNSTABLE_MSC4354_STICKY_EVENTS,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
Room as LivekitRoom,
|
||||
isE2EESupported as isE2EESupportedBrowser,
|
||||
@@ -146,7 +151,7 @@ export const CallView: FC<Props> = ({
|
||||
// rebuilt.
|
||||
const [joined, setJoined] = useState(false);
|
||||
const muteStates = useMuteStates();
|
||||
const e2eeSystem = useRoomEncryptionSystem(backend);
|
||||
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
|
||||
|
||||
// One slot for every join of this call: leaving and joining again, to
|
||||
// reconnect or from the lobby, happens on the same one
|
||||
@@ -166,7 +171,35 @@ export const CallView: FC<Props> = ({
|
||||
return (): void => scope.end();
|
||||
}, [backend, e2eeSystem, externalRtcSession]);
|
||||
|
||||
if (muteStates === null || slot === null) return null;
|
||||
// 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;
|
||||
|
||||
return (
|
||||
<LoadedCallView
|
||||
@@ -180,6 +213,7 @@ export const CallView: FC<Props> = ({
|
||||
joined={joined}
|
||||
setJoined={setJoined}
|
||||
muteStates={muteStates}
|
||||
stickyEventsSupported={stickyEventsSupported}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -225,8 +259,6 @@ 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
|
||||
@@ -251,6 +283,8 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -283,6 +317,7 @@ 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>(
|
||||
@@ -621,6 +656,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
media={media}
|
||||
muteStates={muteStates}
|
||||
e2eeSystem={e2eeSystem}
|
||||
stickyEventsSupported={stickyEventsSupported}
|
||||
//otelGroupCallMembership={otelGroupCallMembership}
|
||||
onShareClick={onShareClick}
|
||||
/>
|
||||
|
||||
@@ -14,23 +14,6 @@ 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;
|
||||
|
||||
@@ -7,6 +7,7 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
@@ -20,8 +21,10 @@ import { BrowserRouter } from "react-router-dom";
|
||||
import { TooltipProvider } from "@vector-im/compound-web";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
import { ActiveCall, InCallView } from "./InCallView";
|
||||
import { ActiveCall, InCallView, rtcParticipationOptions } from "./InCallView";
|
||||
import { getUrlParams } from "../UrlParams";
|
||||
import {
|
||||
mockConfig,
|
||||
mockMediaDevices,
|
||||
mockMuteStates,
|
||||
mockRtcMembership,
|
||||
@@ -43,14 +46,18 @@ 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, type RTCSlot } from "@element-hq/matrixrtc-sdk";
|
||||
import {
|
||||
constant,
|
||||
MatrixRTCMode,
|
||||
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";
|
||||
@@ -233,7 +240,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
|
||||
<BrowserRouter>
|
||||
<MediaDevicesContext value={mockMediaDevices({})}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={createAppBackgroundEffects$(testScope())}
|
||||
effects={createAppBackgroundEffects(testScope())}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<ActiveCall
|
||||
@@ -246,6 +253,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
|
||||
onShareClick={null}
|
||||
e2eeSystem={{ kind: E2eeType.NONE }}
|
||||
media={fakeLocalMedia()}
|
||||
stickyEventsSupported
|
||||
onLeft={(): void => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
@@ -255,6 +263,32 @@ 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());
|
||||
@@ -302,7 +336,7 @@ describe("ActiveCall", () => {
|
||||
<RootElementProvider value={root}>
|
||||
<MediaDevicesContext value={mediaDevices}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={createAppBackgroundEffects$(testScope())}
|
||||
effects={createAppBackgroundEffects(testScope())}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<ActiveCall
|
||||
@@ -315,6 +349,7 @@ describe("ActiveCall", () => {
|
||||
onShareClick={null}
|
||||
e2eeSystem={{ kind: E2eeType.NONE }}
|
||||
media={fakeLocalMedia()}
|
||||
stickyEventsSupported
|
||||
onLeft={(): void => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
|
||||
+21
-19
@@ -55,7 +55,7 @@ import { SpotlightTile } from "../tile/SpotlightTile";
|
||||
import {
|
||||
type EncryptionSystem,
|
||||
type LocalMedia,
|
||||
type MatrixRTCMode,
|
||||
MatrixRTCMode,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
import { E2eeType } from "../e2ee/e2eeType";
|
||||
import { makeGridLayout } from "../grid/GridLayout";
|
||||
@@ -194,6 +194,8 @@ 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",
|
||||
@@ -229,7 +231,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
|
||||
const capture = captureSettings();
|
||||
const rtcParticipation = props.slot.join({
|
||||
...rtcParticipationOptions(urlParams),
|
||||
...rtcParticipationOptions(urlParams, props.stickyEventsSupported),
|
||||
// Without a lobby nothing was captured and the join captures itself
|
||||
publish:
|
||||
props.media.requests.length > 0
|
||||
@@ -290,6 +292,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
|
||||
backgroundEffectsState$,
|
||||
props.client,
|
||||
props.media,
|
||||
props.stickyEventsSupported,
|
||||
rootElement,
|
||||
]);
|
||||
|
||||
@@ -413,7 +416,6 @@ 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$);
|
||||
@@ -636,7 +638,6 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
showRingingStatus={showRingingStatus}
|
||||
focusable={!contentObscured}
|
||||
className={classNames(className, styles.tile)}
|
||||
itemClassName={styles.spotlightItem}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
@@ -662,7 +663,6 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
return (
|
||||
<SpotlightTile
|
||||
className={styles.tile}
|
||||
itemClassName={styles.spotlightItem}
|
||||
data-maximised
|
||||
vm={layout.spotlight}
|
||||
expanded
|
||||
@@ -753,10 +753,6 @@ 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(
|
||||
@@ -768,9 +764,7 @@ 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={classNames(styles.inRoom, {
|
||||
[styles.overflowing]: overflowing,
|
||||
})}
|
||||
className={styles.inRoom}
|
||||
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
|
||||
@@ -789,7 +783,7 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
{screenShareToast}
|
||||
{earpieceOverlay}
|
||||
<ReactionsOverlay vm={vm} />
|
||||
{footer}
|
||||
<CallFooter ref={footerRef} vm={footerVm} />
|
||||
{showModals && (
|
||||
<>
|
||||
<RageshakeRequestModal {...rageshakeRequestModalProps} />
|
||||
@@ -867,16 +861,24 @@ 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 {
|
||||
// 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,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: urlParams.sendNotificationType,
|
||||
callIntent: urlParams.callIntent,
|
||||
timings: {
|
||||
|
||||
@@ -22,7 +22,6 @@ 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(
|
||||
|
||||
@@ -29,14 +29,14 @@ import { useRoomEncryptionSystem } from "../e2ee/sharedKeyManagement";
|
||||
import { QrCode } from "../QrCode";
|
||||
|
||||
interface Props {
|
||||
room: Pick<Room, "roomId" | "name" | "hasEncryptionStateEvent">;
|
||||
room: Pick<Room, "roomId" | "name">;
|
||||
open: boolean;
|
||||
onDismiss: () => void;
|
||||
}
|
||||
|
||||
export const InviteModal: FC<Props> = ({ room, open, onDismiss }) => {
|
||||
const { t } = useTranslation();
|
||||
const e2eeSystem = useRoomEncryptionSystem(room);
|
||||
const e2eeSystem = useRoomEncryptionSystem(room.roomId);
|
||||
|
||||
const url = useMemo(
|
||||
() => getAbsoluteRoomUrl(room.roomId, e2eeSystem, room.name),
|
||||
|
||||
+41
-21
@@ -5,40 +5,60 @@ 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 {
|
||||
SpotlightViewIcon,
|
||||
type ReactNode,
|
||||
useState,
|
||||
type FC,
|
||||
type ComponentType,
|
||||
type SVGAttributes,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Menu, OptionMenuItem } from "@vector-im/compound-web";
|
||||
import {
|
||||
GridIcon,
|
||||
SpotlightViewIcon,
|
||||
} from "@vector-im/compound-design-tokens/assets/web/icons";
|
||||
|
||||
import { type LayoutSwitchViewModel } from "../state/LayoutSwitchViewModel";
|
||||
import {
|
||||
type LayoutMode,
|
||||
type LayoutSwitchViewModel,
|
||||
} from "../state/LayoutSwitchViewModel";
|
||||
import { useBehavior } from "../useBehavior";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Switch } from "@vector-im/compound-web";
|
||||
import { LayoutSwitchButton } from "../button";
|
||||
|
||||
interface Props {
|
||||
interface LayoutSwitchProps {
|
||||
vm: LayoutSwitchViewModel;
|
||||
className?: string;
|
||||
size?: "md" | "lg";
|
||||
}
|
||||
|
||||
export const LayoutSwitch: FC<Props> = ({ vm, className }) => {
|
||||
export const LayoutSwitch: FC<LayoutSwitchProps> = ({ vm, ...props }) => {
|
||||
const { t } = useTranslation();
|
||||
const layout = useBehavior(vm.layout$);
|
||||
const name = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<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}
|
||||
const menuItem = (
|
||||
value: LayoutMode,
|
||||
label: string,
|
||||
Icon: ComponentType<SVGAttributes<SVGElement>>,
|
||||
): ReactNode => (
|
||||
<OptionMenuItem
|
||||
label={label}
|
||||
Icon={Icon}
|
||||
checked={layout === value}
|
||||
onSelect={() => vm.setLayout(value)}
|
||||
/>
|
||||
);
|
||||
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -17,23 +17,17 @@ 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";
|
||||
|
||||
interface Props {
|
||||
/** Null where the session is a host's and not ours to manage. */
|
||||
clientManager: ClientManager | null;
|
||||
}
|
||||
|
||||
export const RoomAuthView: FC<Props> = ({ clientManager }) => {
|
||||
export const RoomAuthView: FC = () => {
|
||||
const { header } = useUrlParams();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error>();
|
||||
|
||||
const { registerPasswordlessUser, recaptchaId } =
|
||||
useRegisterPasswordlessUser(clientManager);
|
||||
useRegisterPasswordlessUser();
|
||||
|
||||
const onSubmit = useCallback(
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
@@ -67,10 +61,7 @@ export const RoomAuthView: FC<Props> = ({ clientManager }) => {
|
||||
<HeaderLogo />
|
||||
</LeftNav>
|
||||
<RightNav>
|
||||
<UserMenuContainer
|
||||
preventNavigation
|
||||
clientManager={clientManager}
|
||||
/>
|
||||
<UserMenuContainer preventNavigation />
|
||||
</RightNav>
|
||||
</Header>
|
||||
)}
|
||||
|
||||
@@ -1,109 +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 { 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
Reference in New Issue
Block a user