Compare commits

..
Author SHA1 Message Date
fkwpandClaude Fable 5.1 535e0b0df1 Add the FEATURES_SPEC process for turning explorations into specs and PRs
FEATURES_SPEC/AGENTS.md describes how an exploration is distilled into a
feature spec and how a spec is turned into PRs against a current main; the
product spec template is the sidecar a brainstorming session fills in.

The folder is excluded from oxfmt: a product spec is immutable once a spec
leaves draft, and the process documents are prose in their own style.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 15:25:21 +02:00
Johannes Marbach 029622f07b Merge pull request #4251 from element-hq/renovate/npm-postcss-selector-parser-vulnerability
Update dependency postcss-selector-parser to v7.1.3 [SECURITY]
2026-09-10 07:42:07 +02:00
renovate[bot] 251535d371 Update dependency postcss-selector-parser to v7.1.3 [SECURITY] 2026-09-09 17:42:33 +00:00
Timo 5c6fa7c864 Merge pull request #4233 from element-hq/valere/component_ec_M1
ElementCall as a react component: refactor + a local dev harness
2026-09-09 19:39:30 +02:00
Timo K. be4023dd66 fix layout in spotlight (top inset) 2026-09-09 19:20:31 +02:00
Timo K. be5f3390f7 more tests 2026-09-09 17:01:16 +02:00
Timo K. 59ef5f5400 ci 2026-09-09 16:05:18 +02:00
Timo K. 2ac95df75f update readmes 2026-09-09 12:15:19 +02:00
Timo K. 7821b465a5 Merge branch 'main' into valere/component_ec_M1 2026-09-09 10:23:47 +02:00
Robin b90ed5bdf7 Merge pull request #4247 from element-hq/fix-cd
Fix call.element.dev not updating after branch rename
2026-09-09 09:07:51 +02:00
Robin 1d7e2288f7 Fix call.element.dev not updating after branch rename 2026-09-09 08:49:08 +02:00
Robin 61eeb8171a Merge pull request #4242 from element-hq/delayed-leave-timings
Adapt delayed leave timings when delegation is available
2026-09-09 08:19:58 +02:00
Robin cff8766aa6 Delegate delayed leaves in LocalMember rather than LocalTransport
IMO this is where the delegation calls should have lived all along, since the leave event is part of the membership lifecycle, and we otherwise end up with an awkward hack to ignore transport updates.

Doing this now ensures that the client won't send any delegation requests if delegation is unsupported, and prepares the code for a future change in which we use the dedicated delegation endpoint from the CS API.
2026-09-08 21:22:52 +02:00
Robin 5cfe7ea4df Base JWT service endpoint choice directly on the MatrixRTC mode
Since we removed the extra 'legacy' mode, meaning there's nothing simplified anymore by translating things over to a JWT service version.

(Also, simplify some things by making the mode static for the duration of a call.)
2026-09-08 21:22:52 +02:00
Robin d38daef567 Reflect session config always being defined 2026-09-08 21:22:52 +02:00
Robin 09782a4d84 Give JWT token fetch procedures more appropriate names 2026-09-08 21:22:52 +02:00
Robin 839e36abd4 Make delegation support check fail immediately in case of CORS errors 2026-09-08 21:22:52 +02:00
Timo K. 3485ce47bc Merge branch 'main' into valere/component_ec_M1 2026-09-08 20:05:27 +02:00
Timo K. 273ee3b632 add allowJoinUnmutedViaIntent to the bridge
This allows us to control to never start unmuted in spa but be able to
start unmuted in widget and component mode.
2026-09-08 18:12:40 +02:00
Timo K.andClaude Fable 5.1 486ecbfda0 Stop offering media downloads on the component's host bridge
`downloadMedia` exists because a widget's client cannot fetch media: it
has no access token, and its only route to a file is MSC4039 over the
widget API. A component host hands over a client that does hold
credentials, so Element Call fetches media with it and the callback was
never needed there. It comes off `ElementCallHostBridge`, leaving a host
with only what it must understand, and stays on the internal HostBridge
for the widget.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 17:14:55 +02:00
Timo K.andClaude Fable 5.1 b722cc277e Make the theme a prop, next to the language
The theme is state — what Element Call should look like right now — and
so belongs beside `language` as a prop, not on the imperative handle
(where it was a request, `setTheme`, because the internal host bridge
speaks the widget API and a widget's host sends theme changes as
requests) and not in the configuration (where `config.theme` only ever
set the starting theme).

The `theme` prop feeds the same channel the rest of Element Call listens
to for a host's theme, replayed so that whatever subscribes after the
host has set it still hears the current one. Changing it re-themes the
container and nothing else; unlike the language, it is per component.
`setTheme` and `config.theme` are gone, and the harness gets a theme
picker in place of its per-pane buttons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 17:02:24 +02:00
Timo K.andClaude Fable 5.1 f994586eeb Speak every language in the component, not just English
The component bundled English alone: the standalone app fetches its
locale files at runtime from URLs its own build emits, which a host
serving the library from elsewhere could not resolve, so bundling one
language was the self-contained option. Now every locale is a chunk of
its own that the host's bundler loads the first time it is needed, with
English still bundled in so that the fallback never waits.

Element Call starts in the browser's language and follows the host's own
setting through a `language` prop; `supportedLanguages` says what it
accepts. Translations are shared by every Element Call on the page, so
the most recently set language wins for all of them. The harness gets a
language picker, and the app and the component share the parsing of
locale paths.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 16:03:48 +02:00
Timo K.andClaude Fable 5.1 b7285064fd Let the shell say where home is, and drop the router from the call
The call reached for react-router in five places to send the user
"home": on leaving without a lobby, from the lobby's recents link, from
the post-call screen, from the error page's return button and from the
header logo. Home is the standalone app's home page; the call has no
idea where that is, and a component has no such place at all — its host
decides what follows a call. Yet the component had to mount a
MemoryRouter just so those hooks would not throw.

`useLeaveToHome` is the way home as the shell supplies it: the app
provides `navigate("/")` from inside its router, the component provides
nothing, and everything that used to link to "/" now either calls it or,
when there is none, offers no way out. The logo becomes a plain logo,
the recents and "not now" links disappear, the error page's button does
too. `ClientProvider`'s logout goes the same way. The component no
longer renders a router.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:39:00 +02:00
Timo K.andClaude Fable 5.1 f5a94ce702 Offer a component host only the configuration it can use
`ElementCallConfiguration` was every URL parameter, which put the widget
plumbing (widgetId, parentUrl, isWidget), the user's identity, the
homeserver, the analytics and Sentry settings, and the standalone app's
shared room secret in front of a host that has no business setting any
of them — the component reads none of those. It is now the behavioural
configuration a widget's URL can carry plus the two properties a host
has a say in: the theme and the background. The background is now
actually applied to the component's root, which it was not before.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:39:00 +02:00
Timo K.andClaude Fable 5.1 3dc7cfe10b Say "component" for the component
"Embedded" already means something here: the embedded package is the
widget build. Where a comment meant Element Call running as a React
component inside a host application, it now says so, and the params it
starts from are `componentProperties`. "Host" stays the word for the
application on the other side, whether that is a widget container or an
application rendering the component.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:39:00 +02:00
Timo K.andClaude Fable 5.1 f70fba1dd6 Rename GroupCallView to CallView, and fold ElementCallView into it
Three layers stood between a shell and the call: `ElementCall` (the
component), `ElementCallView` and `GroupCallView`. The middle one only
held the `joined` flag and the mute state, both of which nothing outside
the call reads any more, so it is folded into the view it wrapped. That
view is now `CallView`, since "group call" is a name from before
Element Call handled anything else.

Its docstring says what it is: the whole lifecycle of a call — lobby,
the call itself, and what comes after — with the lobby and the post-call
screen each present or skipped depending on the parameters and the host.
Both the standalone RoomPage and the component render it directly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 8e8bc5ddde Talk to a component host in callbacks, not observables
The component exposed the internal HostBridge to hosts as-is, which
carried the host's requests as rxjs observables. That made rxjs part of
the public API of a package that bundles its own copy of it, so a host
would build bridges with a different rxjs than the one Element Call
consumed them with — and asked every host to learn rxjs to change the
theme.

A component host now implements plain async callbacks for what Element
Call tells it (`ElementCallHostBridge`, all optional), and makes its own
requests through an imperative handle on the component's `ref`
(`ElementCallHandle`: setTheme, join, hangUp, setDeviceMute), each
resolving once Element Call has acted and rejecting when nothing in
Element Call can. `component/host.ts` adapts that to the HostBridge the
rest of Element Call still speaks, with a bridge whose identity never
changes, so a host re-creating its callbacks on render restarts nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 d18e82c546 Catch the component's errors inside the component
Only the call body sat inside an error boundary; anything thrown in the
lobby, the mute state or the providers propagated into the host's React
tree, where React unmounts everything up to the nearest boundary — the
host's, or the host's whole application. The standalone app has a
boundary at its top; the component now has the same, showing the error
page inside its container and asking the host to stop keeping it on
screen.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 779ee7a008 Finish measuring the root rather than the viewport
The move from media queries to `@container element-call` queries left a
few places still asking the viewport: the room header's compact size
and the lobby's footer placement went through `useMediaQuery`, the
lobby's video preview was `50vh` tall, the reaction picker was capped at
`100vw`, and the content insets and the gradient background were sized
from `100vw`/`100vh`. Embedded in a corner of a host's page, each of
those answered for the page rather than the corner.

`useRootSizeMatches` is `useMediaQuery` for the root element, built on
the same `observeElementSize$` the layout uses; the lengths become
container units. Container units resolve against the nearest query
container, and there are others in the tree (the spotlight layouts, the
media tiles), so base.css says when they may be used.

jsdom gives the body no size at all, which would have every such query
read as a tiny window; the test setup now gives it a desktop's, matching
what the media query mock already answered.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 7cd21476f7 Say outright whether the profile is ours to change
Whether to offer the profile settings was inferred from whether the host
could close Element Call. For a component with no host bridge — the
default — nothing could, so an embedded Element Call let the user edit
the profile of an account that belongs to the host application.

`HostBridge.supportsProfileChanges` states it directly: true standalone,
where Element Call signed the user in itself; false for a widget's host
and for anything embedding the component (which sets it itself, since
the client it hands over is its own). The profile tab and the profile
shortcut follow that. What a host's ability to close us still decides —
what to show after the call ends — is a question about who owns our
lifetime, and stays keyed on `close`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 f0359259f9 Format base.css
The formatter wants the layered import of the Compound design tokens on
one line; "de-globalise styles" left it wrapped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00
Timo K.andClaude Fable 5.1 7137e6ec14 Update the developer settings snapshot for the scoped pre style
"de-globalise styles" gave the tab's <pre> elements a class instead of
styling the bare element, but did not update the snapshot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:56:10 +02:00
Timo K.andClaude Fable 5.1 6ae4f0539a Leave the page title to the page
The call and the lobby each set `document.title`, so a component
embedded in a host renamed the host's tab to "Element Call | <room>".
The title belongs to whoever owns the page: the standalone app's
RoomPage now sets it, for whichever room it has got as far as knowing
about, and the call itself no longer touches it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:53:50 +02:00
Timo K.andClaude Fable 5.1 bc58aed0d7 Keep keyboard shortcuts within Element Call's root
The call's shortcuts were listened for on the window and allowed
whenever focus was inside the standalone app's `#root` — which, for a
component embedded in a host, is the host's own root, or nothing. So m,
v and space fired while the user typed in the host's composer, and two
Element Calls on one page both answered every key.

Listen on the element Element Call treats as its root instead (the body
standalone, so nothing changes there), and judge whether a key press is
spoken for by what has focus — a dialog or a text field — rather than by
where it sits in the DOM, since the modals are now portalled to that
same root.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:52:34 +02:00
Timo K.andClaude Fable 5.1 608f107f8d End the component's media device scope on unmount
The component built its `MediaDevices` once, in a scope nothing ever
ended, so every mount left device observers running for the rest of the
page's life. Building it in an effect ties the scope to the component's
lifetime — and to the options it was built with, which were previously
frozen at first render.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:50:17 +02:00
Timo K.andClaude Fable 5.1 a010cc983f Compare the component's config by value
Everything downstream of the component's params — the mute state, the
call view model and with it the media connection — is keyed on the
identity of the params object, which was memoised on the identity of
the `config` prop. A host writing `config={{ ... }}` inline, which is
the natural way to write it, therefore tore the whole call down on
every render. The harness happened to pass a constant, so nothing
noticed.

`useStableValue` hands out the same object for as long as a deep
comparison says nothing changed, so an inline config costs nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:49:19 +02:00
Johannes Marbach 00d0adc3c4 Merge pull request #4222 from element-hq/renovate/all-minor-patch
Update all non-major dependencies
2026-09-08 11:40:20 +02:00
Johannes Marbach ddc5a50529 Disable new react compiler rules 2026-09-08 11:29:36 +02:00
renovate[bot] 27734a1a02 Update all non-major dependencies 2026-09-08 06:13:17 +00:00
Timo K. 489c1af426 test resizing via @container 2026-09-07 17:35:25 +02:00
Timo K. 365204d04c fix media queries in component based element call. 2026-09-07 14:50:36 +02:00
Johannes Marbach 14c61db43d Merge pull request #4241 from element-hq/matthew/encryption-mismatch-logging
Log track encryption flag and cryptor events for remote tracks
2026-09-07 13:30:50 +02:00
Johannes Marbach 65e1b845a7 Apply suggestion from @Johennes 2026-09-07 13:18:00 +02:00
Robin 6a9583a2ce Adapt delayed leave timings when delegation is available
Splits the config options for the timings of a delayed leave event into two sets: one for when delegation is available (as you can relax the timings and get more stable calls this way), and another for when it's unavailable (as we must continue to gracefully downgrade even after Matrix 2.0 is fully rolled out).

This works by bluntly hitting the delegation endpoints without auth before joining to check for a 404.
2026-09-07 13:10:54 +02:00
Matthew Hodgson eddd95ba41 Log track encryption flag and cryptor events for remote tracks
Extends the [RemoteTracks] logging from #4235 with the per-publication
encryption flag and the ParticipantEncryptionStatusChanged /
EncryptionError room events.

If a publisher encrypts frames while the subscriber believes the
publication is unencrypted, livekit-client bypasses the cryptor and hands
raw ciphertext to the decoder, which is audible as loud noise bursts.
The reverse mismatch (or a missing/invalid key) drops frames instead.
Neither case is visible in a rageshake today.
2026-09-07 11:53:01 +01:00
Johannes Marbach a376280c91 Merge pull request #4240 from element-hq/renovate/livekit-client
Update dependency livekit-client to v2.22.2
2026-09-07 08:07:34 +02:00
renovate[bot] 1e9a5cfa20 Update ghcr.io/element-hq/element-web:develop Docker digest to 6ed62b2 (#4239)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-09-07 02:04:08 +00:00
renovate[bot] d204b36b55 Update dependency livekit-client to v2.22.2 2026-09-07 01:56:21 +00:00
renovate[bot] a03f23e720 Update ghcr.io/element-hq/element-web:develop Docker digest to a4e9c8c (#4238)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-09-06 02:02:35 +00:00
renovate[bot] 210d94af18 Update ghcr.io/element-hq/element-web:develop Docker digest to 3221e92 (#4237)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-09-05 02:55:22 +00:00
Timo K.andClaude Fable 5.1 218ee46b7d Make the component installable as a git dependency
`component/package.json` describes the built component as a package
(`@element-hq/element-call-component`: entry, stylesheet subpath, types,
peer dependencies) so that a host can depend on
`github:element-hq/element-call#<ref>&path:/component`. Its `prepare`
script builds on install, since nothing is published yet.

For that the component build now lands in `component/dist` instead of the
repository's `dist`, and `pnpm build:component` also emits the type
declarations (`component/tsconfig.build.json`, `build:component:types`),
which previously had to be produced by hand.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 15:29:55 +02:00
Timo K. 38c28a1c8f scaling based on component size instead webview size 2026-09-04 14:16:40 +02:00
Timo K. f5458bb03e de-globalise styles 2026-09-04 13:51:47 +02:00
renovate[bot]andRobin 70f6e785ce Update ghcr.io/element-hq/element-web:develop Docker digest to 724b468 (#4226)
* Update ghcr.io/element-hq/element-web:develop Docker digest to a9bd290

* Fix Element Web integration tests

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Robin <robin@robin.town>
2026-09-04 09:18:19 +00:00
Johannes Marbach 0ad31cfc4d Merge pull request #4232 from element-hq/matthew/screenshare-watchdog
Surface screen share failures instead of silently doing nothing
2026-09-04 07:54:23 +02:00
Johannes Marbach bae8da3ddc Reformat 2026-09-04 07:44:16 +02:00
Johannes Marbach b22eba7af9 Add further tests 2026-09-04 07:39:58 +02:00
Robin cd7510e054 Merge pull request #4235 from element-hq/matthew/remote-track-logging
Log remote participant and track events per LiveKit connection
2026-09-03 20:22:27 +02:00
Robin 054913d17d Use testScope in ObservableScope tests 2026-09-03 20:11:18 +02:00
Matthew Hodgson dee4b05695 Diagnostics for duplicate participant matches and mid-delivery scope teardown
Warn when ConnectionManagerData merges participants from a second
connection to the same SFU URL, when more than one LiveKit participant
matches a member's backend identity, and when a scope is ended while one
of its behaviors is still delivering a value (which strands the later
bound subscribers on the old value). The per-member match log now also
names the connection the participant came from.
2026-09-03 18:43:18 +01:00
Matthew Hodgson b1393998a7 Report re-entrancy depth and tag torn behaviors
A single re-entrant emission can only strand a contiguous run of a
behavior's subscribers, so a tile that is both 'speaking' and 'waiting
for media' (a middle subscriber stranded) implies a nested re-entry.
Report the nesting depth and log each new depth once instead of only the
first re-entry, and tag splitBehavior-derived behaviors with their field
name so the warning identifies which behavior tore.
2026-09-03 18:08:53 +01:00
Matthew Hodgson 2ab2197c01 Warn when a behavior is re-entered while delivering a value
rxjs delivers a nested emission to every subscriber and then resumes
delivering the outer, older value to the remaining subscribers, which
leaves them permanently out of sync. Log the first occurrence per
behavior with a stack trace so the re-entrant path can be identified
from a rageshake.
2026-09-03 17:26:38 +01:00
Valere ace78de749 Cover Element Call as a component with end-to-end tests
The widget tests cannot reach what makes a component different, because the
iframe used to guarantee it: that Element Call stays inside the space it was
given, and that two of them can exist in one page. So the development harness
gets driven by Playwright.

Three tests. Two components in one page holding a real call between two devices
of one account. The settings dialog and the reaction picker staying inside the
container the host gave, asserted by bounding box. And the host bridge
reporting in both directions, including a host-initiated mute coming back as a
report of the new state.

The containment test is the one worth having: both of the escapes found by
running the harness by hand — the settings dialog centred on the window, and
the reaction picker at 82vh landing below the container — would have failed it,
and neither was visible to typechecking, linting or the unit tests.

Users and rooms are created through the Synapse admin and client-server APIs
rather than by driving an interface, and the harness now takes its credentials
from its own query string so that a test can say which account and room to use.
A host reading its own URL is proper; it was Element Call doing so that was the
mistake.

Playwright gains a second web server for the harness on port 3001, a Vite dev
server whether or not the app itself is served from Docker, since the harness is
a development page with nothing to build.
2026-09-03 18:09:12 +02:00
Matthew Hodgson 0b95fd5a65 Log remote member participant matching and tile waiting state
A tile shows "Waiting for media" for as long as its MatrixRTC member
cannot be matched to a LiveKit participant. Log each transition of that
match and of the tile's waitingForMedia state so rageshakes can tie a
stuck tile to the LiveKit participant and track events.
2026-09-03 17:07:08 +01:00
Matthew Hodgson f8f5caaa09 Log remote participant and track events per LiveKit connection
Rageshakes contained nothing about the state of remote tracks, so a tile
showing the wrong mute or video state for a member could not be
diagnosed. Log connect/disconnect, publish/unpublish, subscribe/
unsubscribe, subscription failures, remote mute/unmute and stream state
changes on each Connection's logger, and remove the listeners when the
connection scope ends.
2026-09-03 16:50:30 +01:00
Valere 3361ce2b60 Keep what the component draws inside the container it was given
Opening settings in an embedded call put the dialog in the middle of the host's
window, spilling outside the container, and with two calls on a page the second
drew over the first's dialog.

The container established a stacking context but not a containing block, which
are two different things and only the first had been done. `position: fixed`
resolves against the viewport unless an ancestor makes itself the containing
block, so the modal scrim and dialog in Overlay.module.css — `fixed`, `inset:
0`, centred, because in the standalone app they are meant to cover the page —
were positioned and sized against the window. Layout and paint containment
makes the container the containing block for those descendants and clips what
we paint to our own box. The second-call-on-top symptom goes with it, since the
dialog now stays inside the first call's box and there is nothing to overlap.
Two sibling components still cannot draw over one another by construction,
neither being able to leave its own stacking context, but that only shows if a
host overlaps them.

Containment clips a box measured in viewport units but cannot resize it, so
anything positioned that way is simply put somewhere outside the container and
disappears. That applied to the reactions overlay, a `100vw` by `100vh` box, and
to the reaction picker, which sits at `82vh` so as to appear near the footer it
belongs to. Both are positioned against whatever Element Call treats as its
root — `[data-overlay-container]` in the app, which is the size of the page, and
the host's container when embedded — so percentages mean the same thing there
and the right thing here. The earpiece overlay is `inset: 0` with no viewport
units, so containment is enough for it.

Three viewport-relative sizes remain, all of which need more than a change of
unit: the lobby's video preview is `50vh` on a flex item with an aspect ratio,
`--content-inset-*` ramps up to a desktop inset from the window width, and the
picker's `max-width` cap is the window's.

The clipping cuts both ways: a menu near the edge of a small container is
trimmed rather than overflowing into the host. That is the trade an embedded
component makes.
2026-09-03 17:30:16 +02:00
Valere c0a54dcaf9 Derive the component's defaults from an intent, not the host's URL
The component seeded its parameters with `computeUrlParams()`, which reads
`window.location`. Element Call is not the page any more, so what it found
there was the host's URL: no `widgetId`, therefore not a widget, therefore no
intent, therefore the standalone app's preset.

The visible symptom was the Element Call logo in the footer of a call embedded
in someone else's application, since `showLogo` follows `header ===
HeaderStyle.Standard`. The rest of that preset mattered more. A hosted call
defaulted to `perParticipantE2EE: false` and `confineToRoom: false` — so
unencrypted, and willing to take the user out of the room a host had put them
in — and a host could not correct either without naming every parameter
itself, nor even name `header`, since the enums were not exported.

So the intent presets move out of `computeUrlParams` into
`configurationForIntent`, and the component builds its parameters from an
intent plus the properties a host has no URL to supply. `intent` becomes a
prop, defaulting to joining an existing group call: the lobby first, confined
to the room, encrypted per participant, and no Element Call branding in
someone else's interface. A host that knows which button the user pressed
should say which.

One deliberate difference from the widget presets: the background defaults to
solid rather than the gradient, which is drawn by a `position: fixed`
pseudo-element and would escape the container to cover the host.

`UserIntent.Unknown` still means the standalone preset, so the app and widget
are unchanged — including a widget that names no intent, which has always been
given those defaults.
2026-09-03 16:39:14 +02:00
Valere 9f5fa6049f Add a harness for Element Call embedded as a component
`pnpm dev:component` serves a page that stands in for a host application: it
signs in twice against the development backend and shows two calls side by
side, in resizable boxes, with furniture of its own around them. Two devices of
one account, so a real call happens between the two components and anything
Element Call keeps once per process rather than once per call shows itself.

The host bridge is driven by hand and reports both directions in a log along
the bottom, which is the first exercise the theme, hang-up and device-mute
requests have had outside widget mode. Each pane can be unmounted and remounted
to see what Element Call leaves behind, and there is a `position: fixed` dialog
belonging to the host to see whether it covers the calls. The page uses none of
Element Call's design tokens, so anything that looks styled outside a pane came
from Element Call reaching out of its container. It reaches Element Call only
through the component's public interface, which is how the exports missing from
that interface came to light.

Three things about the component build the harness turned up on the way, all
too small to be worth their own commits:

- It copied `public/` into `dist/`, including the developer's own gitignored
  config.json, into output we would publish. `publicDir: false`, as the
  embedded build already does. The sdk build has the same leak; untouched.
- `pnpm lint:externals` now exists, which the build config already claimed it
  did. It reads the external list out of that config and fails if the source
  imports React, the Matrix SDK or LiveKit by a path the list does not name.
  Since the bundler silently ignores the pattern form of that option, an
  unnamed subpath is bundled with no warning at all — which is how a host would
  end up with a second React.
- `lint:oxlint` ran over `src playwright`, so nothing in `component/` had ever
  been linted.

Serving a page also meant the shared plugin list could no longer inject the
app's HTML entry point unconditionally, so that is now optional — and off for
the library build too, which never had an HTML page to inject it into.
2026-09-03 16:11:39 +02:00
Valere db0f6837ce Give the component what the app shell was providing
The component built and typechecked in the previous commit, but only because
nothing had rendered it. Everything Element Call needs that `src/main.tsx`
side-loads was missing from it.

Its stylesheet: only main.tsx imported index.css, so the library build emitted
CSS-module styles with every `--cpd-*` and `--font-size-*` unresolved. Split
into base.css, which both the app and the component import, and the rules that
are about owning a page, which only the app does. The split is a straight move
— comment-stripped and sorted, the old file and the two new ones differ by
exactly one line — and that line is the deliberate part: `.no-scroll-body`
becomes `body.no-scroll-body`. Element Call adds that class to whatever it
treats as its root, and since the root can now be a container, `position:
fixed` would have taken that container out of the host's layout. Pinning the
page is what it always meant.

Its translations: `initializeElementCall` called `i18n.init` with neither
resources nor a backend, so every key would have rendered as itself. English is
bundled in. The app fetches locale files from URLs its own build emits, which a
host serving the library from somewhere else could not resolve, so how a host
picks a language is left open.

And the types a host needs: `HostBridge` alone is not enough to implement
`HostBridge` — `HostRequest`, `DeviceMuteState`, `DeviceMuteRequest` and
`JoinCallData` all appear in its signatures, and `ConfigOptions` in
`initializeElementCall`'s.
2026-09-03 16:10:26 +02:00
Matthew Hodgson bf5482db8c Surface screen share failures instead of silently doing nothing
toggleScreenSharing only had `.catch(logger.error)`, so a getDisplayMedia
request that hangs (element-call-rageshakes#17152: Element Desktop on
Windows, the user pressed the screen share button 14 times in 25 seconds
and the log shows nothing but the toggle lines and livekit-client's
"waiting for pending publication promise timed out") left the user with
a button that does nothing and us with no evidence of why.

Log when a toggle is requested and when it completes or fails, with the
elapsed time, so a hang is visible in the logs. Explicit failures other
than the user cancelling the picker show as a non-modal "Could not start
screen sharing" toast. Nothing is inferred from a toggle taking a long
time: the user may simply be choosing what to share.
2026-09-03 15:01:35 +01:00
Valere 979b521563 Build Element Call as a component a host can import
Adds component/index.tsx as a fourth build target: <ElementCall client
roomId /> and an initializeElementCall to await once beforehand. It gives
Element Call everything it would otherwise take from the page it is on —
the parameters, the host bridge, media devices, translations, a container
to confine itself to — and hands it the host's client rather than finding
one of its own.

React, the Matrix SDK and LiveKit stay external, since the host has them
and a second copy of any would not merely be wasteful: React would hold
two sets of hooks and the client would run two sync loops. Every subpath
has to be listed by name, because the pattern and callback forms of
rollupOptions.external are silently ignored here — a lesson worth the
comment that records it.

Element Call's own navigation runs in a MemoryRouter, so being embedded
cannot disturb the host's URL. ClientContext and GroupCallView both
navigate, so some router has to be present.

The bundle is not yet a reasonable size: library mode base64-inlines
assets referenced through import.meta.url, so MediaPipe's vision runtime
lands in it whole. Left for its own change, since the fix — loading the
background blur transformer lazily — is worth doing for the standalone app
too.
2026-09-03 15:18:03 +02:00
Valere a166fbbd08 Let the component own its mute state
ElementCallView took muteStates as a prop, which would have meant an
embedder building one before it could show a call. It could not simply make
its own: RoomPage created one on mount whichever branch it went on to
render, and two would both report the user's mute state to the host,
talking over each other.

Move the construction into a useMuteStates hook, and give the lobby shown
while waiting to be let into a room its own component. Each lobby now holds
mute state only while it is on screen, so there is never a second one, and
the component can own the call's.

KnockLobbyView also takes the room summary and label handling that RoomPage
was assembling on its behalf, leaving the page with arriving at a call
rather than being in one.
2026-09-03 15:15:51 +02:00
Valere 856e055d30 Find Element Call's root by attribute, not by being the body
Six selectors named `body` directly — the gradient backdrop and the
platform font overrides in index.css, and the iOS adjustments in
AppBar.module.css and Modal.module.css — so they only applied when Element
Call owned the page. A host mounting it into a container would have got an
interface decorated correctly and styled incorrectly, with nothing to show
that anything was wrong.

Mark the root element with data-element-call-root and match on that
instead. Scoping this way keeps the selectors more specific than they were,
rather than less: widening them to a bare [data-platform=…] would have
dropped specificity from (0,1,1) to (0,1,0) and changed which rules win.

The platform attribute moves with them, from the initializer's write onto
document.body to a layout effect on the root, alongside the theme — so it
still lands before anything is painted.

No visual change while Element Call owns the page: the root is the body,
which now carries the attribute, so every rewritten selector matches the
element it always did.
2026-09-03 12:55:52 +02:00
Valere 1bfb018d90 Introduce ElementCallView
Being in a call and deciding to show one are different jobs, but RoomPage
did both: routing, authentication, resolving room aliases and knocking, and
then the call itself. Only the first set belongs to whatever is hosting
Element Call.

Add ElementCallView as the seam between them. It takes a client and a call
to join, and owns whether the user has joined — which is the call's own
business rather than its host's. RoomPage keeps everything about arriving
at a call and renders this for the call itself.

Nothing else moves yet. muteStates is still passed in, because the
standalone shell shares one with the lobby it shows while waiting to be let
into a room, and two instances would both report the user's mute state to
the host.
2026-09-03 12:10:04 +02:00
Johannes Marbach d765267c43 Merge pull request #4229 from element-hq/matthew/fix-rageshake-flush
Fix periodic rageshake log flush never running
2026-09-03 07:29:51 +02:00
Matthew Hodgson 698a98a9c8 Test that logs are flushed to IndexedDB periodically 2026-09-02 18:55:18 +01:00
Matthew Hodgson 2db24e2868 Fix periodic rageshake log flush never running
The throttled flush callback returned this.flush instead of calling it
(regressed in #2607), so logs were only persisted to IndexedDB on
rageshake submission or beforeunload. When the host removes the widget
iframe at hangup, the whole call's logs were lost, so a rageshake filed
from a later call carries nothing from the affected one.
2026-09-02 18:46:12 +01:00
135 changed files with 8227 additions and 2847 deletions
+2 -2
View File
@@ -5,7 +5,7 @@
> Every PR must have a linked issue
> that a maintainer has reviewed and approved **before you started writing code**.
> PRs that don't meet this requirement will not be reviewed.
> See [CONTRIBUTING.md](https://github.com/element-hq/element-call/blob/livekit/CONTRIBUTING.md) for ElementCall decided for this approach.
> See [CONTRIBUTING.md](https://github.com/element-hq/element-call/blob/main/CONTRIBUTING.md) for ElementCall decided for this approach.
## Content
@@ -39,7 +39,7 @@ Uncomment the markdown table below and fill in the last line:
## Checklist
- [ ] A linked, pre-approved issue exists for this feature or UI change.
- [ ] I have read [CONTRIBUTING.md](https://github.com/element-hq/element-call/blob/livekit/CONTRIBUTING.md) in full.
- [ ] I have read [CONTRIBUTING.md](https://github.com/element-hq/element-call/blob/main/CONTRIBUTING.md) in full.
- [ ] Pull request includes screenshots or videos for any UI changes.
- [ ] Tests written for new code (and existing touched code where feasible).
- [ ] Linter and other CI checks pass.
+5 -5
View File
@@ -6,7 +6,7 @@ on:
- opened
- labeled
push:
branches: [livekit, full-mesh]
branches: [main]
jobs:
build_full_element_call:
# Use the full package vite build
@@ -22,8 +22,8 @@ jobs:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
deploy_develop:
# Deploy livekit branch to call.element.dev after build completes
if: github.ref == 'refs/heads/livekit'
# Deploy main branch to call.element.dev after build completes
if: github.ref == 'refs/heads/main'
needs: build_full_element_call
runs-on: ubuntu-latest
steps:
@@ -43,8 +43,8 @@ jobs:
}
})
docker_for_develop:
# Build docker and publish docker for livekit branch after build completes
if: github.ref == 'refs/heads/livekit'
# Build docker and publish docker for main branch after build completes
if: github.ref == 'refs/heads/main'
needs: build_full_element_call
permissions:
contents: write
+1 -1
View File
@@ -2,5 +2,5 @@
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"printWidth": 80,
"sortPackageJson": false,
"ignorePatterns": ["pnpm-lock.yaml", "node_modules", "dist"]
"ignorePatterns": ["pnpm-lock.yaml", "node_modules", "dist", "FEATURES_SPEC"]
}
+11
View File
@@ -39,6 +39,17 @@
"jsdoc/check-property-names": "error",
"jsdoc/require-param-description": "warn",
"react/display-name": "error",
// TODO: These React Compiler-based rules joined oxlint's correctness
// category in v1.81 and flag many pre-existing patterns, including hooks
// like useLatest/useInitial/useReactiveState that intentionally access
// refs during render. Re-evaluate them when adopting the React Compiler.
"react/immutability": "off",
"react/no-deriving-state-in-effects": "off",
"react/preserve-manual-memoization": "off",
"react/refs": "off",
"react/set-state-in-effect": "off",
"react/static-components": "off",
"react/use-memo": "off",
// TODO: Re-enable once oxlint supports lint rules that rely on TypeScript type-awareness.
// "rxjs/no-exposed-subjects": "error",
// "rxjs/finnish": [
+415
View File
@@ -0,0 +1,415 @@
# FEATURE_SPEC — Agent Instructions
This folder holds **feature specs distilled from experiments**. A spec is the durable
artifact of an exploration; the exploration branch is not. Each spec must contain
enough information for an agent to produce mergeable PRs against a *current* `main`
without access to the original branch.
## What this folder is not
- Not a design-doc archive. Specs that are not intended to be implemented do not
belong here.
- Not a place for narrative. Prose that does not constrain the implementation or its
verification should be cut.
- Not a substitute for the PR description. The spec explains *why* and *what must be
true*; the PR explains *this diff*.
## File naming
`YYYY-MM_Snake_Case_Title.md` — e.g. `2026-09_Raise_Hand_Improvements.md`
The filename is immutable once committed. Renames break links from PRs, issues and
the drift log. If scope changes fundamentally, write a new spec and set
`supersedes:` / `superseded_by:`.
A sidecar `YYYY-MM_Snake_Case_Title.product.md` holds the product spec — user stories,
functional requirements, success criteria. Copy `_TEMPLATE.product.md`. Product owns
it; see "Brainstorming: the product spec".
An optional sidecar `YYYY-MM_Snake_Case_Title.notes.md` holds lessons learned,
narrative, dead-end logs and anything else that is worth keeping but does not
constrain the implementation. Rules:
- The sidecar is **never load-bearing**. Agents do not read it to derive
implementation, and nothing in it may contradict or extend the spec. If a note
constrains the work, it belongs in `## Decisions`, `## Rejected alternatives` or
`## Measurements` instead.
- Agents may append to it (an observation from a drift check, a wrong turn during
implementation) and must never rewrite or delete existing content.
- An agent that is `blocked` may read the sidecar to draft an open question, but
quotes what it found rather than acting on it.
- No sidecar is required. An empty one is worse than none.
## Style: facts only
Applies to the spec file only. The product spec is prose by design and the notes
sidecar is unconstrained. The spec is re-read on every regeneration, where prose costs context
and dilutes the contract, so:
- Bullets, not paragraphs. Declarative present tense. No motivation, no background,
no summary of what the code currently does beyond locating the change.
- Name things instead of describing them — a path, a symbol, an event type, a command,
an event id. A reference is shorter and more precise than a sentence about it. Which
kind of reference is allowed depends on the section; see "Reference durability".
- One line per decision plus at most one sentence of rationale. If the rationale needs
more, the extra goes in the sidecar.
- No judgement adjectives (clean, elegant, proper, obviously) and no hedging (should
probably, might be nice). Either it is a constraint or it is not in the spec.
- `## Problem` is at most five bullets.
- Target under 200 lines for the whole spec; over 300 lines, split the feature or move
material to the sidecar.
The test for any line: does it constrain the implementation, constrain its
verification, or record a measured fact? If not, delete it or move it to the sidecar.
## Reference durability
The spec must stay implementable against a `main` nobody has seen yet, so which
references are allowed depends on how fast they rot. Most to least durable:
1. Protocol identifiers — `m.reaction`, `m.call.member`, `m.relates_to`, a reaction
key. MSC-bound; effectively permanent.
2. Observable behaviour. Permanent.
3. Concept names — membership, participation, session.
4. Test names. Survive file moves and renames, because the test moves with the code.
5. Exported symbols. Survive refactors sometimes.
6. File paths. Rot fast.
7. Line numbers. Never.
Per section:
- `## Problem`, `## Measurements`, `## Slicing plan`, `## Drift log` — any reference,
paths and internal symbols included. These describe the codebase **as of `base`**. A
reference going stale here is a finding for the drift check, not a defect, and
removing the concrete references would leave the drift check with nothing to verify.
- `## Decisions`, `## Acceptance criteria` — levels 1 to 4 only. No file paths, no
internal symbols. This is the part that has to hold against a future `main`.
- An acceptance criterion that is not user-observable is tagged `[internal]` and
anchored by **its test name**, not by the symbol under test. The test name moves with
a refactor; the symbol does not.
`[internal]` ACs are legitimate and expected: an invariant that no current consumer can
observe is exactly what protects the consumer that does not exist yet. Tagging them
keeps visible which ACs defend a product requirement and which defend a code
invariant.
## Required frontmatter
```yaml
---
status: draft # see state machine below
blocked_from: null # state to return to when leaving `blocked`
title: Raise hand improvements
owner: <human handle> # a human, always
signoff: # join condition for leaving exploration.signoff
eng: pending
design: pending
product: pending
experiment_ref: <branch name or commit sha of the spike, if any>
base: <sha of main the spec was validated against>
repos: [matrix-js-sdk, element-call] # in dependency order
specs: [MSC4143] # protocol documents touched, if any
supersedes: []
superseded_by: null
---
```
`base` is mandatory and is what makes drift detectable. `owner` is a human even when
every section was drafted by an agent.
## Brainstorming: the product spec
The usual entry point is a human handing an agent a one-line feature idea. The output
of that session is `<stem>.product.md`, not code and not a feature spec. Copy
`_TEMPLATE.product.md` and fill it.
Ownership: an agent may create and fill this file during `brainstorm`. From `draft`
onwards **product owns it and agents do not edit it** — not to fix wording, not to
resolve a marker, not to reconcile it with the code. Agents raise mismatches in the
feature spec's `## Open questions`.
If product's source of truth lives outside the repo (a tracker, a design doc), put its
URL in the header `**Source**:` line and keep the requirement text and ids in the repo
anyway. The ids are what the feature spec references; a link alone cannot be traced.
Agent behaviour during the session:
- **Ask, do not assume.** An unanswered question is recorded as
`[NEEDS CLARIFICATION: <the question>]`, inline where the answer would go. Filling a
gap with a plausible guess is the main failure mode of this state — the marker is a
deliverable, not a defect.
- Ask in one round of at most five questions, ordered by how much the answer changes
the shape of the feature. Do not interview.
- **No implementation in the product spec.** No file paths, symbols, libraries, event
types, API shapes or framework names. If a requirement cannot be stated without them,
it is not a product requirement.
- Every user story must be independently deployable and demonstrable on its own. A
story that only makes sense once another story ships is not a story; merge it.
- More than four priority levels means more than one feature. Split before `draft`.
- Never invent an SC number. Ask for the target, or mark it
`[NEEDS CLARIFICATION]`.
For protocol and infrastructure work, success criteria may be expressed as observable
client behaviour or a wire-level invariant ("a client joining mid-session converges
within one sync"), but still never as a code path or an internal API.
`FR-###` and `SC-###` ids are immutable once assigned. Product may revise the document
at any time, including after `in_production`, but a changed requirement gets a **new
id** and the old one is marked superseded — never edited in place. Renumbering silently
breaks every AC that references it, and there is no way to detect that afterwards.
A new or changed FR after `implement` does not amend the current spec's scope. It is
either a new feature spec or the next iteration; the mapping table simply shows an
unmapped FR, which is the intended signal.
## Traceability
The product spec states intent; the feature spec states what must be true and how it is
checked. They are kept in sync by ids, not by duplication.
- Every `FR-###` maps to at least one acceptance criterion. Tag the AC with its
origin: `AC2 [FR-003] — <observable behaviour>`.
- Every `SC-###` maps to an entry in `## Measurements` with a method. An SC with no
measurement blocks `exploration.signoff`.
- Every user story maps to at least one slice. **Slice order follows story priority**
(P1 first) unless a technical dependency overrides it, and the override is recorded
in the slicing plan with its reason.
- An AC with no `FR` origin is allowed and expected — implementation-level invariants
have no counterpart in the product spec. The converse is not: an unmapped FR is an
incomplete spec.
- Agents do not resolve a mismatch between the two. The product spec wins on intent,
the feature spec wins on verification; a genuine contradiction is `blocked`.
## Status state machine
Transitions are explicit; an agent may perform only the ones marked (agent).
```
brainstorm ─► draft ─► exploration ─► implement ─► qa ─► in_production
│ │ │
└──────────────┴────────┴──► blocked ──► (blocked_from)
│
└──► abandoned
```
Exploration has sub-states, written dotted in `status`:
```
exploration.scoping ─► exploration.iterating ─► exploration.signoff
▲ │ │
└───────────────────────┴──────────────────────┘
```
- `brainstorm` → `draft`: human. Requires `<stem>.product.md` to exist with at least one
P1 story carrying acceptance scenarios, every FR and SC id assigned, and every
remaining `[NEEDS CLARIFICATION]` copied into the feature spec's `## Open questions`.
- `draft` → `exploration.scoping`: human. Requires `## Problem` and `## Out of scope`.
Scoping before the branch exists is what keeps exploration from becoming the
long-lived branch this folder replaces.
- `exploration.scoping` → `.iterating`: human. `experiment_ref` must name the branch.
- `.iterating` → `.signoff`: human. Requires `## Decisions`, `## Acceptance criteria`,
`## Rejected alternatives` and `## Measurements` to be complete, no
`[NEEDS CLARIFICATION]` left in the product spec, and full traceability (below).
- `.signoff` → `implement`: **only when all three sign-offs in `signoff:` are `ok`.**
This is a join, not a sequence — a single reviewer cannot advance it. On entering
`implement`, the exploration branch stops being a base: it is reference material,
and implementation branches off current `main` (see "Turning a spec into PRs").
- `.signoff` → `.iterating`: human, on any sign-off returning changes. Reset the
rejecting role to `pending`; leave the others as they are.
- `implement` → `qa`: (agent) when every acceptance criterion is covered, as recorded
in `## PRs`, and the feature flag is enabled in the QA environment.
- `qa` → `in_production`: human. The flag is on by default in production.
- `qa` → `implement`: (agent) when a QA finding needs code. See "QA feedback".
- any active state → `blocked`: (agent) when drift or an unresolved question prevents
progress. Requires a drift-log entry and `blocked_from: <state>`. Do not guess and
continue. Leaving `blocked` returns to `blocked_from`, never to a fixed state.
- any state → `abandoned`: human only.
`in_production` is terminal. A production regression does not reopen the spec: it
either is an ordinary bug fix with no spec, or it is a new spec. The acceptance
criteria remain as the regression contract (see "QA feedback").
## QA feedback
The point of the `qa` state is not to record that testing happened. It is to make the
spec a better regeneration source than it was before implementation. So:
- Every reproduced QA finding becomes **either** a new acceptance criterion **or** a
new entry in `## Rejected alternatives`. Never a prose note, never only a bug
tracker link.
- (agent) may **append** ACs during `qa`, with provenance:
`AC7 [qa: <issue ref>] — <observable behaviour>` plus its check. Appending is
allowed; rewriting or reordering existing ACs is not.
- A finding that invalidates a decision does not become an AC. It sets `blocked` — a
decision is human-owned in every state.
- A finding that is out of scope goes to `## Out of scope` with its issue ref, so the
next regeneration does not treat it as a gap.
This also applies after `in_production`: a production bug that reveals a missing AC is
appended with `[prod: <ref>]` provenance without any state change.
## Required sections
Order matters — agents read top-down and the first three sections are the contract.
1. **`## Problem`** — up to five bullets. What breaks today, for whom, observably,
with the file or symbol where it breaks.
2. **`## Decisions`** — the choices the exploration settled, each with a one-line
rationale. **Human-owned. An agent must never add, remove or reword a decision.**
If a decision is missing, set `blocked` and ask.
3. **`## Acceptance criteria`** — the load-bearing section. Each item must be
mechanically checkable and name its check:
- `AC1 [FR-002] — <observable behaviour>` / `check: yarn vitest run src/reactions/ReactionsReader.test.tsx -t "backfill"`
- `AC2 [FR-002] — <observable behaviour>` / `check: manual, <exact steps>`
- `AC3 [internal] — <invariant>` / `check: yarn vitest run <file> -t "<test name>"`
An acceptance criterion without a check is a wish; reject the spec (`blocked`).
4. **`## Rejected alternatives`** — what the experiment tried and why it failed,
including measurements. This exists so regeneration does not re-walk dead ends. If
this section is empty for a spec with an `experiment_ref`, the spec is incomplete.
5. **`## Measurements`** — numbers from the experiment with the method used to obtain
them (command, hardware, load profile). Numbers without a method are not usable as
regression baselines and must be marked `unverified`. A baseline states its direction: a
count that unrelated work grows — tests passing, test files — is a floor (`≥ n`); a
cost — latency, CPU, bundle size — is a ceiling (`≤ n`). An exact count is stale as
soon as `main` moves and is not a drift finding.
6. **`## Out of scope`** — explicit non-goals, so agents stop expanding the diff.
7. **`## Slicing plan`** — ordered, independently mergeable PRs (see below).
8. **`## Drift log`** — append-only, agent-written.
9. **`## PRs`** — append-only list of `#<n> — <state> — <ACs covered>`.
Optional: `## Open questions` (blocks `exploration.signoff`), `## Migration / compat` (mandatory
whenever wire format, event schema, or a published API changes).
## Turning a spec into PRs
Run these steps in order. Do not skip step 2.
1. **Fetch and pin.** `git fetch origin` and record `origin/main`'s sha as `head`.
Never start from the exploration branch, and never rebase it — the branch is
reference material, not a base.
2. **Drift check** against `base..head`:
- Do all files, symbols and modules named in the spec still exist?
- Have the invariants in `## Decisions` been contradicted by changes in main?
- Do the commands in `## Acceptance criteria` still run?
Write the result as a drift-log entry. On a contradicted decision: set `blocked`,
do not implement.
3. **Re-derive the slicing plan** if drift changed it. Each slice must:
- build and pass CI on its own,
- be reviewable in one sitting (target < 400 changed lines, hard stop at 800 —
split further rather than exceeding it),
- map to at least one acceptance criterion, and
- land behind a flag or be inert if it is not the last slice of a user-visible
change.
4. **Implement one slice at a time**, branch `spec/<spec-slug>/<n>-<short>` off the
pinned `head`. Tests for the slice's ACs go in the same PR as the code. A PR merges
only when every check of every AC it lists passes on that PR: automated checks in
CI, manual checks performed by a human reviewer with the result recorded in the PR
description. An AC is *covered* once such a PR has merged.
5. **Open the PR** linking the spec path and listing the ACs it covers. Update
`## PRs` and `status`.
6. **Do not touch merged or reviewed slices.** See the regeneration rule.
## The regeneration rule
Regeneration from spec is only allowed **before a human has reviewed the PR**.
Once review has started, the PR is a shared artifact: rebase, fix forward, push
incremental commits. Regenerating discards the reviewer's context and silently
invalidates their approvals. If regeneration is unavoidable after review, close the
old PR with an explanation and open a new one — never force-push a fresh generation
over a reviewed branch.
## Cross-repo and protocol work
When `repos` has more than one entry, PRs are opened in `repos` order and each PR
body states which upstream PR it depends on. Merging out of order is a spec
violation, not an optimisation.
When `specs` is non-empty:
- the implementation PR references the section of the MSC it implements,
- unmerged MSCs require the implementation to be feature-flagged and documented as
unstable (unstable prefixes, not stable identifiers), and
- any deviation from the MSC text is recorded in `## Drift log`, not silently
resolved in favour of the code.
## Drift-log format
Append-only, newest last:
```
### 2026-09-14 — drift check (base 4f2a1c9 → head 9b17e02)
- `ReactionsReader.getLastReactionEvent` now takes a `CallMembership` instead of an
event id → AC2 and AC3 check commands still valid, slice 3 needs rework
- BLOCKING: decision D2 assumes a membership event change may keep a hand raised; main
now clears all reaction relations on membership replacement. Needs owner decision.
```
Drift entries are never rewritten or deleted, including entries that were later
resolved. The log is the record of why the implementation diverged from the
exploration.
## Hard rules
- Never fill a `[NEEDS CLARIFICATION]` marker with a guess, in any state.
- Never put file paths, symbols or library names in the product spec.
- Never reference a file path or an internal symbol in `## Decisions` or
`## Acceptance criteria`. Behaviour, protocol identifiers, concepts and test names
only.
- Never edit `<stem>.product.md` after `draft`, and never renumber an FR or SC id.
- Never add a line that does not constrain the implementation, constrain its
verification, or record a measured fact. It goes in the sidecar or nowhere.
- Never modify `## Decisions`, `## Problem`, or `## Acceptance criteria`. These are
the human contract. Propose changes in `## Open questions` and set `blocked`.
- Never invent measurements or acceptance checks. Absent is better than plausible.
- Never widen scope past `## Out of scope`, even when the fix looks trivial.
- Never open a PR while `status` is `draft`, any `exploration.*`, or `blocked`.
- Never delete a spec file. Terminal states are `in_production` or `abandoned`.
- If the spec and current `main` disagree about how the system works, **main wins as
description, the spec wins as intent** — record the difference and stop.
## Spec template
```markdown
---
status: draft
blocked_from: null
title:
owner:
signoff:
eng: pending
design: pending
product: pending
experiment_ref:
base:
repos: []
specs: []
supersedes: []
superseded_by: null
---
## Problem
## Decisions
- D1 — <decision> — <why>
## Acceptance criteria
- AC1 [FR-###] — <observable behaviour>
- check: <command or exact manual steps>
- AC2 [internal] — <invariant>
- check: <command, anchored by test name>
## Rejected alternatives
- <approach> — <why it failed> — <evidence>
## Measurements
- <metric>: <value> (method: <command / setup>)
## Out of scope
## Slicing plan
1. <slice> — covers AC1 — depends on: none
## Drift log
## PRs
```
+117
View File
@@ -0,0 +1,117 @@
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Feature Spec**: `[YYYY-MM_Title.md]` <!-- status lives in the feature spec's frontmatter, not here -->
**Owner**: [product handle]
**Source**: [URL of the tracker/doc this mirrors, or "this file"]
**Input**: User description: "$ARGUMENTS"
## User Scenarios & Testing *(mandatory)*
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
- Developed independently
- Tested independently
- Deployed independently
- Demonstrated to users independently
-->
### User Story 1 - [Brief Title] (Priority: P1)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 2 - [Brief Title] (Priority: P2)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 3 - [Brief Title] (Priority: P3)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
[Add more user stories as needed, each with an assigned priority]
### Edge Cases
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right edge cases.
-->
- What happens when [boundary condition]?
- How does system handle [error scenario]?
## Requirements *(mandatory)*
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->
### Functional Requirements
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
*Example of marking unclear requirements:*
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->
### Measurable Outcomes
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
+104 -5
View File
@@ -36,8 +36,9 @@ You can find the latest development version continuously deployed to
✅ **Decentralized & Federated** – No central authority; works across Matrix
homeservers.
✅ **End-to-End Encrypted** – Secure and private calls.
✅ **Standalone & Widget Mode** – Use as an independent app or embed in Matrix
clients.
✅ **Standalone, Widget & Component Mode** – Use as an independent app, embed
in Matrix clients as a widget, or (experimentally) mount it as a React component
inside your own application.
✅ **WebRTC-based** – No additional software required.
✅ **Scalable with LiveKit** – Supports large meetings via SFU
([MSC4195: MatrixRTC using LiveKit backend](https://github.com/hughns/matrix-spec-proposals/blob/hughns/matrixrtc-livekit/proposals/4195-matrixrtc-livekit.md)).
@@ -90,7 +91,9 @@ and voice calls within Matrix rooms.
Element Call offers two packaging options: one for standalone or widget
deployment, and another for seamless widget-based integration into messenger
apps. Below is an overview of each option.
apps. A third, experimental option builds it as a React component library for
applications that want to render a call inside their own page rather than in an
iframe. Below is an overview of each option.
**Full Package** – Supports both **Standalone** and **Widget** mode. It is
hosted as a static web page and can be accessed via a URL when used as a widget.
@@ -107,6 +110,11 @@ recommended method for embedding Element Call.
<img src="./docs/embedded_package.drawio.png" alt="Element Call Embedded Package">
</p>
**Component Package (experimental)** – A library build of Element Call as a
React component, consumed as a dependency by a host application that already
has a Matrix client. See
[Element Call as a component](#element-call-as-a-component-experimental) below.
For more details on the packages, see the
[Embedded vs. Standalone Guide](./docs/embedded_standalone.md).
@@ -213,6 +221,94 @@ See also:
- [Developing with linked packages](./docs/linking.md)
#### Element Call as a component (experimental)
Element Call can also be embedded directly into another React application
rather than being loaded in an iframe as a widget. `pnpm build:component`
builds it as a library into `component/dist` (the bundle, its stylesheet and
type declarations), and
```sh
pnpm dev:component
```
serves a harness on port 3001 that stands in for such an application: it signs
in twice against the development backend and shows two calls side by side, in
resizable boxes, with page furniture of its own around them. Use it to see how
Element Call behaves when it does not own the page — the size it is given,
whether it stays inside its container, and what it says to its host, which is
logged along the bottom. The harness is served with the same development
certificate as the app, so unless the development CA is trusted, the browser
needs a certificate exception for `https://localhost:3001` as well (see the
note under [Backend](#backend)). It reads the same `public/config.json` as
`pnpm dev` if one exists, and runs with Element Call's defaults otherwise.
The call lays itself out for the size of the element it is mounted in, not the
window: a host that shrinks the container to a corner of its page gets the
picture-in-picture layout, just as a host that shrank the whole iframe used to.
The breakpoints in the stylesheets the component uses are
`@container element-call` queries against its root element for the same reason;
for the standalone app the root is the page, so they mean what the media queries
they replaced did. (The standalone-only views, such as the home and login pages,
still use plain media queries, since the component never shows them.)
The component's stylesheet is confined to the element it is mounted in: the
build rewrites every selector so that it matches only Element Call's root or
what is inside it, with `html`, `body` and `:root` standing for that root (see
`component/build/scopeStylesToRoot.ts`). A host's own page keeps its styles,
and Element Call brings its own fonts and design tokens along.
The component speaks every language the app does. English is bundled in; the
other locales are split into chunks the host's bundler loads the first time
they are needed. It starts in the browser's language, and follows the host's
own language setting through the `language` prop (`supportedLanguages` lists
the tags it accepts, and anything else falls back to its base language or to
English). The `theme` prop works the same way and takes the same values as the
widget's `theme` URL parameter: `light`, `dark`, `light-high-contrast` or
`dark-high-contrast`. Both can change while a call is running without
disturbing it.
A host must call and await `initializeElementCall(config)` once before
rendering the component: it loads the `Intl` polyfills, applies the
deployment-wide `config.json`-style configuration and sets up translations.
The component itself takes the host's `client` and the `roomId` to call in, an
`intent` saying what the user asked for (which decides whether to show the
lobby, ring, and so on), an optional `config` overriding what the intent
implies, and an optional `hostBridge` through which Element Call tells the host
that the user has joined or hung up, that it wants to stay on screen, and so
on. The host makes its own requests (`join`, `hangUp`, `setDeviceMute`) through
the handle exposed on `ref`. The full API is documented in the type declarations
(`component/index.tsx` and `component/host.ts`).
A few things differ from the widget on purpose: the component draws a solid
background rather than a gradient unless told otherwise, never offers to edit
the user's profile (the account is the host's), scopes its keyboard shortcuts to
its own root element so that several instances can share a page, and only shows
its own post-call and error screens when the host has not supplied a `close()`
callback; with one, it asks the host to unmount it instead. The
[global JS controls](./docs/controls.md) on `window` are unchanged and remain
page-wide, so with several instances on one page they apply to all of them.
The package is not published yet. A host installs it as a git dependency on the
`component` directory of this repository,
```json
"@element-hq/element-call-component": "github:element-hq/element-call#main&path:/component"
```
whose `prepare` script runs the build on install. That build needs pnpm (via
Corepack) on the host's machine, runs a full `pnpm install` of this repository
and is memory-hungry, since it inherits the `--max-old-space-size` setting of
the app build; the host's pnpm also has to allow it to run at all
(`allowBuilds` in its `pnpm-workspace.yaml`). Note that `component/` is a pnpm
project of its own for this reason, so pnpm commands run from inside that
directory target it rather than the repository; run them from the repository
root. The host imports the component from
`@element-hq/element-call-component` and the stylesheet from
`@element-hq/element-call-component/style.css`, and has to provide `react`,
`react-dom`, `matrix-js-sdk` and `livekit-client` itself, since the bundle leaves
them external.
### Backend
A docker compose file `docker-compose-dev.yml` is provided to start the
@@ -274,7 +370,10 @@ running Playwright by following
However the Playwright tests are run, an element-call instance must be running
on https://localhost:3000 (this is configured in `playwright.config.ts`) - this
is what will be tested.
is what will be tested. The tests under `playwright/component` instead drive
the component harness (`pnpm dev:component`) on https://localhost:3001, which
Playwright starts as a second web server; it is always a Vite dev server, even
when the app itself is served from Docker with `USE_DOCKER`.
The local backend environment should be running for the test to work:
`pnpm backend`
@@ -373,7 +472,7 @@ We do this so that we can reuse the labels between repositories.
## 📝 Copyright & License
Copyright 2021-2025 New Vector Ltd
Copyright 2021-2026 New Vector Ltd
This software is dual-licensed by New Vector Ltd (Element). It can be used
either:
+43
View File
@@ -0,0 +1,43 @@
/*
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 container a host mounts us into. It fills whatever space the host gives
it, and nothing we draw may leave it.
That takes two separate things, which are easy to mistake for one. `isolation`
gives us a stacking context, so nothing inside can be layered above the host's
own interface. Containment makes us the containing block for `position: fixed`
descendants, and clips what we paint to our own box: without it, the modal
scrim and dialog — which are positioned `fixed` and centred, since in the app
they are meant to cover the page — resolve against the viewport and appear in
the middle of the host's window rather than in the middle of the call.
The clipping cuts both ways: a menu near the edge of a small container is
trimmed rather than overflowing into the host. That is the trade being a
component rather than a page makes. */
.root {
display: flex;
flex-direction: column;
inline-size: 100%;
block-size: 100%;
isolation: isolate;
contain: layout paint;
position: relative;
background-color: var(--cpd-color-bg-canvas-default);
color: var(--cpd-color-text-primary);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-tap-highlight-color: transparent;
}
/* Compound's overlay container, which holds tooltips and popovers, has to fill
the container for the elements inside it to be positioned against it. The
standalone page does the same for the container under `#root`. */
.root > [data-overlay-container] {
position: relative;
block-size: 100%;
}
+112
View File
@@ -0,0 +1,112 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import { ROOT_SELECTOR, scopeStylesToRoot } from "./scopeStylesToRoot";
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
const isRoot = `:where(${ROOT_SELECTOR})`;
async function scope(css: string, file = "base.css"): Promise<string> {
const result = await postcss([scopeStylesToRoot()]).process(css, {
from: file,
});
return result.css;
}
describe("scopeStylesToRoot", () => {
it("makes the root stand in for the document", async () => {
expect(await scope("html { line-height: 1.15 }")).toBe(
`${isRoot} { line-height: 1.15 }`,
);
expect(await scope("body { margin: 0 }")).toBe(`${isRoot} { margin: 0 }`);
expect(await scope(":root { --a: 1 }")).toBe(`${isRoot} { --a: 1 }`);
expect(await scope("body.no-scroll-body { position: fixed }")).toBe(
`${isRoot}.no-scroll-body { position: fixed }`,
);
expect(await scope("body .x { color: red }")).toBe(
`${isRoot} .x { color: red }`,
);
});
it("collapses selectors that all became the root", async () => {
expect(await scope("html, body, input { font: inherit }")).toBe(
`${isRoot},input${inRoot} { font: inherit }`,
);
});
it("confines everything else to the root and what is inside it", async () => {
expect(await scope("h1 { margin: 0 }")).toBe(`h1${inRoot} { margin: 0 }`);
expect(await scope(".cpd-theme-dark { --a: 1 }")).toBe(
`.cpd-theme-dark${inRoot} { --a: 1 }`,
);
expect(await scope("* { box-sizing: border-box }")).toBe(
`*${inRoot} { box-sizing: border-box }`,
);
expect(await scope(".a > .b + .c { color: red }")).toBe(
`.a>.b+.c${inRoot} { color: red }`,
);
});
it("keeps pseudo-elements last", async () => {
expect(await scope("button::-moz-focus-inner { border: 0 }")).toBe(
`button${inRoot}::-moz-focus-inner { border: 0 }`,
);
expect(await scope(".a .b:hover::after { content: '' }")).toBe(
`.a .b:hover${inRoot}::after { content: '' }`,
);
expect(await scope("p:first-letter { color: red }")).toBe(
`p${inRoot}:first-letter { color: red }`,
);
});
it("leaves alone what already names the root", async () => {
const css = `${ROOT_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(css)).toBe(css);
});
it("reaches into layers and media queries", async () => {
expect(
await scope(
"@layer normalize { h1 { margin: 0 } } @media (min-width: 1px) { p { margin: 0 } }",
),
).toBe(
`@layer normalize { h1${inRoot} { margin: 0 } } @media (min-width: 1px) { p${inRoot} { margin: 0 } }`,
);
});
it("does not touch keyframes or nested rules", async () => {
expect(
await scope("@keyframes spin { from { opacity: 0 } to { opacity: 1 } }"),
).toBe("@keyframes spin { from { opacity: 0 } to { opacity: 1 } }");
expect(
await scope(
".a { color: red; &:hover { color: blue } .b { color: green } }",
),
).toBe(
`.a${inRoot} { color: red; &:hover { color: blue } .b { color: green } }`,
);
});
it("only touches the bare selectors of a CSS module", async () => {
const file = "Settings.module.css";
expect(await scope("pre { font-size: 1px }", file)).toBe(
`pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".modal pre { font-size: 1px }", file)).toBe(
`.modal pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".box_abc12 { border: 0 }", file)).toBe(
".box_abc12 { border: 0 }",
);
expect(await scope(".a .b_abc12:hover { border: 0 }", file)).toBe(
".a .b_abc12:hover { border: 0 }",
);
});
});
+161
View File
@@ -0,0 +1,161 @@
/*
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 AtRule,
type Container,
type Document,
type Plugin,
type Rule,
} from "postcss";
import selectorParser, {
type Node,
type Pseudo,
type Selector,
} from "postcss-selector-parser";
/**
* How the stylesheets find Element Call's root element. The attribute is put
* there by `useTheme`, on the container the host gives the component.
*/
export const ROOT_SELECTOR = "[data-element-call-root]";
// Both are `:where()`, which has no specificity of its own, so the rules keep
// exactly the weight they had before being scoped and nothing in Element Call's
// cascade changes — only where it applies.
//
// The root, or anything inside it. Appended to the element a rule is about,
// rather than prepended to the whole selector, so that a rule about the root
// itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
// The root itself, standing in for the document.
const IS_ROOT = `:where(${ROOT_SELECTOR})`;
/**
* Confines a stylesheet to Element Call's root element, for the build of
* Element Call as a component.
*
* As a page of its own, Element Call can style the document: normalize.css and
* Compound speak of `html`, `body` and bare elements, and the design tokens are
* declared on `:root`. As a component, all of that would land on the host's
* document too. This rewrites every selector so that it matches only the root
* or its descendants:
*
* - `html`, `body` and `:root` become the root element, which is what stands in
* for the document inside a host.
* - Everything else keeps its selector and gains `:where([data-element-call-root],
* [data-element-call-root] *)` on the element it styles.
* - Selectors that already name the root are left alone, as are keyframe
* selectors and rules nested inside another rule, which are relative to it.
*
* CSS modules are scoped by their class names already, so only their selectors
* that would match by element alone — `pre` rather than `.pre` — are touched.
*
* The root's fonts and design tokens are still inherited by everything inside
* it, the way they were from `body` and `:root`, and `@font-face` declarations
* stay global, which they are by nature.
*/
export function scopeStylesToRoot(): Plugin {
return {
postcssPlugin: "element-call-scope-styles-to-root",
Once(root) {
const isModule =
root.source?.input.file?.endsWith(".module.css") ?? false;
root.walkRules((rule) => {
if (isRelative(rule)) return;
rule.selector = (isModule ? scopeBare : scopeAll).processSync(
rule.selector,
{ lossless: false },
);
});
},
};
}
/** Whether a rule's selectors are relative to something other than the document. */
function isRelative(rule: Rule): boolean {
let parent: Container | Document | undefined = rule.parent;
while (parent !== undefined) {
if (parent.type === "rule") return true;
if (parent.type === "atrule") {
const { name } = parent as AtRule;
if (name.endsWith("keyframes") || name === "page") return true;
}
parent = parent.parent;
}
return false;
}
const processor = (isModule: boolean): ReturnType<typeof selectorParser> =>
selectorParser((selectors) => {
selectors.each((selector) => {
scopeSelector(selector, isModule);
});
// Mapping `html, body` onto the root leaves the same selector twice
const seen = new Set<string>();
selectors.each((selector) => {
const text = String(selector).trim();
if (seen.has(text)) selector.remove();
else seen.add(text);
});
});
// Everything, for stylesheets that speak of the document; only what a class
// does not already confine, for CSS modules
const scopeAll = processor(false);
const scopeBare = processor(true);
function scopeSelector(selector: Selector, isModule: boolean): void {
if (String(selector).includes(ROOT_SELECTOR)) return;
const compounds = splitCompounds(selector);
if (compounds.length === 0) return;
// Something said of the document is said of the root instead
const document = compounds[0].find(isDocumentSelector);
if (document !== undefined) {
document.replaceWith(pseudo(IS_ROOT));
return;
}
const subject = compounds.at(-1)!;
if (isModule && subject.some((node) => node.type === "class")) return;
// Pseudo-elements have to come last in a compound selector
const pseudoElement = subject.find(isPseudoElement);
if (pseudoElement === undefined) selector.append(pseudo(IN_ROOT));
else selector.insertBefore(pseudoElement, pseudo(IN_ROOT));
}
/** The compound selectors making up a complex selector, in order. */
function splitCompounds(selector: Selector): Node[][] {
const compounds: Node[][] = [[]];
for (const node of selector.nodes) {
if (node.type === "combinator") compounds.push([]);
else if (node.type !== "comment") compounds.at(-1)!.push(node);
}
return compounds.filter((compound) => compound.length > 0);
}
function isDocumentSelector(node: Node): boolean {
return (
(node.type === "tag" && (node.value === "html" || node.value === "body")) ||
(node.type === "pseudo" && node.value === ":root")
);
}
function isPseudoElement(node: Node): node is Pseudo {
if (node.type !== "pseudo") return false;
return (
node.value.startsWith("::") ||
[":before", ":after", ":first-line", ":first-letter"].includes(node.value)
);
}
function pseudo(text: string): Pseudo {
return selectorParser().astSync(text).nodes[0].nodes[0].clone() as Pseudo;
}
+46
View File
@@ -0,0 +1,46 @@
/*
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 ElementCallHostBridge } from "../index";
/**
* A host bridge that reports everything it is told, so that the harness can
* watch what Element Call says to its host. (What the host says to Element
* Call goes through the component's handle, and is logged by the pane.)
*/
export function createDevHostBridge(
log: (message: string) => void,
/** What the host does when Element Call asks to be closed. */
onClose: () => void,
): ElementCallHostBridge {
/**
* Records something Element Call told the host. Nothing is sent anywhere, so
* this is only asynchronous because a real host's answer would have to be.
*/
const told = async (message: string): Promise<void> => {
log(`→ ${message}`);
await Promise.resolve();
};
return {
setAlwaysOnScreen: async (alwaysOnScreen): Promise<void> =>
await told(`setAlwaysOnScreen(${alwaysOnScreen})`),
contentLoaded: async (): Promise<void> => await told("contentLoaded"),
notifyJoined: async (): Promise<void> => await told("notifyJoined"),
notifyHungUp: async (): Promise<void> => await told("notifyHungUp"),
notifyDeviceMute: async (state): Promise<void> =>
await told(
`notifyDeviceMute(audio: ${state.audio_enabled}, video: ${state.video_enabled})`,
),
// Present because this host really can dismiss Element Call, which is what
// makes it offer a close affordance at all
close: async (): Promise<void> => {
await told("close");
onClose();
},
};
}
+140
View File
@@ -0,0 +1,140 @@
/*
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.
*/
.credentials {
display: flex;
flex-direction: column;
gap: 8px;
max-inline-size: 420px;
margin: 48px auto;
padding: 24px;
background-color: #ffffff;
border: 1px solid #d4d4d8;
border-radius: 8px;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
}
.error {
color: #b91c1c;
}
.harness {
display: grid;
grid-template-rows: auto 1fr auto;
block-size: 100%;
}
.header,
.paneBar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-block-end: 1px solid #d4d4d8;
background-color: #ffffff;
}
.header h1 {
font-size: 16px;
margin: 0;
}
.middle {
display: flex;
min-block-size: 0;
}
.sidebar {
flex: 0 0 220px;
padding: 12px;
border-inline-end: 1px solid #d4d4d8;
background-color: #ffffff;
overflow-y: auto;
}
.panes {
display: flex;
flex-wrap: wrap;
/* So that a pane is the size it was dragged to, rather than being stretched
to fill the row */
align-items: flex-start;
align-content: flex-start;
gap: 16px;
padding: 16px;
flex: 1;
min-inline-size: 0;
overflow: auto;
}
.pane {
display: flex;
flex-direction: column;
border: 1px solid #d4d4d8;
border-radius: 8px;
overflow: hidden;
background-color: #ffffff;
}
.paneBar {
flex-wrap: wrap;
gap: 6px;
border-block-end: none;
}
/* The space the host gives Element Call. Resizable so that the sizes it has to
cope with can be found by dragging rather than by rebuilding, and `overflow:
hidden` both to enable the resize handle and to show up anything inside Element
Call that does not fit the box it was given. */
.paneCall {
inline-size: 560px;
block-size: 420px;
min-inline-size: 180px;
min-block-size: 180px;
resize: both;
overflow: hidden;
}
.log {
max-block-size: 180px;
overflow-y: auto;
padding: 8px 12px;
border-block-start: 1px solid #d4d4d8;
background-color: #ffffff;
font-size: 12px;
}
.log h2 {
font-size: 13px;
margin: 0 0 4px;
}
.log ol {
margin: 0;
padding: 0;
list-style: none;
}
/* A host overlay, which Element Call must not be able to draw over */
.dialogScrim {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background-color: rgb(0 0 0 / 50%);
z-index: 10;
}
.dialog {
padding: 24px;
border-radius: 8px;
background-color: #ffffff;
}
+380
View File
@@ -0,0 +1,380 @@
/*
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 FormEvent,
type ReactNode,
useCallback,
useMemo,
useRef,
useState,
} from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import {
ElementCall,
type ElementCallHandle,
supportedLanguages,
} from "../index";
import { createDevHostBridge } from "./DevHostBridge";
import { createSession, joinRoom } from "./session";
import styles from "./Harness.module.css";
interface Credentials {
homeserver: string;
username: string;
password: string;
room: string;
}
const CREDENTIALS_KEY = "element-call-component-harness";
const DEFAULT_CREDENTIALS: Credentials = {
homeserver: "https://synapse.m.localhost",
username: "",
password: "",
room: "",
};
/**
* The credentials to start with: the last ones used, so that a reload does not
* mean typing them again, overridden by anything in the query string.
*
* A host reading its own URL is entirely proper — it was Element Call doing so
* that was the mistake. It lets the end-to-end tests, or a shared link, say
* which account and room to use.
*/
function loadCredentials(): Credentials {
let stored: Partial<Credentials> = {};
try {
const json = localStorage.getItem(CREDENTIALS_KEY);
if (json !== null) stored = JSON.parse(json) as Credentials;
} catch (e) {
logger.warn("Could not read the stored harness credentials", e);
}
const query = new URLSearchParams(location.search);
const fromUrl = Object.fromEntries(
(["homeserver", "username", "password", "room"] as const)
.map((name) => [name, query.get(name)])
.filter(([, value]) => value !== null),
) as Partial<Credentials>;
return { ...DEFAULT_CREDENTIALS, ...stored, ...fromUrl };
}
interface Session {
label: string;
client: MatrixClient;
}
type State =
| { phase: "credentials" }
| { phase: "starting"; progress: string }
| { phase: "started"; roomId: string; sessions: Session[] }
| { phase: "failed"; error: string };
interface LogEntry {
pane: string;
message: string;
at: string;
}
/**
* One Element Call component, with the controls a host would have over it: the
* requests it can make of Element Call, and the ability to take it off screen
* altogether.
*/
const Pane: FC<{
session: Session;
roomId: string;
theme: string | undefined;
language: string | undefined;
log: (pane: string, message: string) => void;
}> = ({ session, roomId, theme, language, log }): ReactNode => {
const [mounted, setMounted] = useState(true);
const bridge = useMemo(
() =>
createDevHostBridge(
(message) => log(session.label, message),
() => setMounted(false),
),
[log, session.label],
);
// What the host asks of Element Call goes through the component's handle.
// Worth saying out loud when a request is refused — asking to hang up when
// there is no call, say — since that is the sort of thing the harness is for.
const handle = useRef<ElementCallHandle>(null);
const ask = (
name: string,
make: (handle: ElementCallHandle) => Promise<unknown>,
): void => {
if (handle.current === null) {
log(session.label, `← ${name}: not mounted`);
return;
}
log(session.label, `← ${name}`);
make(handle.current).then(
(reply) =>
log(
session.label,
`→ ${name} acknowledged${reply === undefined ? "" : `: ${JSON.stringify(reply)}`}`,
),
(e: unknown) => log(session.label, `→ ${name} refused: ${e}`),
);
};
return (
<section className={styles.pane} data-testid="call-pane">
<div className={styles.paneBar}>
<strong>{session.label}</strong>
<code>{session.client.getDeviceId()}</code>
<button onClick={(): void => setMounted((m) => !m)}>
{mounted ? "Unmount" : "Mount"}
</button>
<button
onClick={(): void =>
ask(
"setDeviceMute(audio: false)",
async (h) => await h.setDeviceMute({ audio_enabled: false }),
)
}
>
Mute
</button>
<button
onClick={(): void => ask("hangUp", async (h) => await h.hangUp())}
>
Hang up
</button>
</div>
{/* Resizable, because how Element Call copes with the size it is given is
one of the things we cannot find out from the standalone app */}
<div className={styles.paneCall} data-testid="call-container">
{mounted && (
<ElementCall
ref={handle}
client={session.client}
roomId={roomId}
hostBridge={bridge}
theme={theme}
language={language}
/>
)}
</div>
</section>
);
};
/** Host furniture, to make it visible if Element Call styles anything but itself. */
const HostChrome: FC = (): ReactNode => (
<nav className={styles.sidebar}>
<h2>Host chrome</h2>
<p>
This column belongs to the host. If Element Call&apos;s stylesheet reaches
outside its own container, it shows up here.
</p>
<hr />
<ul>
<li>Some room</li>
<li>Another room</li>
</ul>
<button>A host button</button>
</nav>
);
/**
* A dialog of the host's own, over the top of the calls. Element Call as a
* component has to sit underneath this — being unable to is one of the reasons
* for a component rather than an iframe.
*/
const HostDialog: FC<{ onClose: () => void }> = ({ onClose }): ReactNode => (
<div className={styles.dialogScrim}>
<div className={styles.dialog}>
<h2>A dialog belonging to the host</h2>
<p>This should cover the calls completely.</p>
<button onClick={onClose}>Close</button>
</div>
</div>
);
/**
* Stands in for a host application using the Element Call component: it owns the Matrix
* clients, the page and the space each call is given, and reaches Element Call
* only through the component's public interface.
*
* Two calls at once, from two devices of the same account, so that a real call
* happens between them and anything Element Call keeps once per process rather
* than once per call shows itself.
*/
export const Harness: FC = (): ReactNode => {
const [credentials, setCredentials] = useState(loadCredentials);
const [state, setState] = useState<State>({ phase: "credentials" });
const [entries, setEntries] = useState<LogEntry[]>([]);
const [dialogOpen, setDialogOpen] = useState(false);
// The host's language setting, which Element Call follows. Undefined means
// the host has none and Element Call uses the browser's.
const [language, setLanguage] = useState<string | undefined>(undefined);
const [theme, setTheme] = useState<string | undefined>(undefined);
const log = useCallback((pane: string, message: string): void => {
setEntries((entries) =>
[
...entries,
{ pane, message, at: new Date().toLocaleTimeString() },
].slice(-100),
);
}, []);
const start = useCallback(
(event: FormEvent): void => {
event.preventDefault();
localStorage.setItem(CREDENTIALS_KEY, JSON.stringify(credentials));
const { homeserver, username, password, room } = credentials;
const progress = (message: string): void =>
setState({ phase: "starting", progress: message });
progress("Starting");
void (async (): Promise<void> => {
try {
// One at a time: two logins at once from the same account is the
// shape of request homeservers rate limit
const sessions: Session[] = [];
for (const label of ["Call A", "Call B"])
sessions.push({
label,
client: await createSession(
homeserver,
username,
password,
(message) => progress(`${label}: ${message}`),
),
});
progress("Joining the room");
let roomId = room;
for (const { client } of sessions)
roomId = await joinRoom(client, roomId);
setState({ phase: "started", roomId, sessions });
} catch (e) {
logger.error("The harness could not start", e);
setState({ phase: "failed", error: `${e}` });
}
})();
},
[credentials],
);
const field = (
name: keyof Credentials,
label: string,
type = "text",
): ReactNode => (
<label className={styles.field}>
{label}
<input
type={type}
value={credentials[name]}
onChange={(e): void =>
setCredentials((c) => ({ ...c, [name]: e.target.value }))
}
/>
</label>
);
if (state.phase !== "started")
return (
<form className={styles.credentials} onSubmit={start}>
<h1>Element Call component harness</h1>
<p>
Signs in twice and shows the Element Call component twice, in a page
that is not Element Call&apos;s own.
</p>
{field("homeserver", "Homeserver")}
{field("username", "Username")}
{field("password", "Password", "password")}
{field("room", "Room ID or alias")}
<button type="submit" disabled={state.phase === "starting"}>
Start
</button>
{state.phase === "starting" && <p>{state.progress}</p>}
{state.phase === "failed" && (
<p className={styles.error}>{state.error}</p>
)}
</form>
);
return (
<div className={styles.harness}>
<header className={styles.header}>
<h1>Element Call component harness</h1>
<code>{state.roomId}</code>
<button onClick={(): void => setDialogOpen(true)}>
Open a host dialog
</button>
<label>
Theme{" "}
<select
value={theme ?? ""}
onChange={(e): void => setTheme(e.target.value || undefined)}
>
<option value="">Element Call&apos;s choice</option>
<option value="light">light</option>
<option value="dark">dark</option>
</select>
</label>
<label>
Language{" "}
<select
value={language ?? ""}
onChange={(e): void => setLanguage(e.target.value || undefined)}
>
<option value="">Browser default</option>
{supportedLanguages.map((tag) => (
<option key={tag} value={tag}>
{tag}
</option>
))}
</select>
</label>
</header>
<div className={styles.middle}>
<HostChrome />
<main className={styles.panes}>
{state.sessions.map((session) => (
<Pane
key={session.label}
session={session}
roomId={state.roomId}
theme={theme}
language={language}
log={log}
/>
))}
</main>
</div>
<section className={styles.log} data-testid="bridge-log">
<h2>Host bridge</h2>
<ol>
{entries.map((entry, i) => (
<li key={i}>
<code>{entry.at}</code> <strong>{entry.pane}</strong>{" "}
{entry.message}
</li>
))}
</ol>
</section>
{dialogOpen && <HostDialog onClose={(): void => setDialogOpen(false)} />}
</div>
);
};
+23
View File
@@ -0,0 +1,23 @@
/*
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 host page's own styles. Deliberately plain, and deliberately not using
Element Call's design tokens: the harness should look like it does because of
this file, not because Element Call styled it. */
html,
body,
#root {
height: 100%;
}
body {
margin: 0;
font-family: system-ui, sans-serif;
background-color: #f4f4f5;
color: #18181b;
}
+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<!--
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.
-->
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Element Call component harness</title>
</head>
<body>
<!-- Deliberately plain: this page stands in for a host application, so
anything it looks like must have come from the host's own styles or from
Element Call reaching outside its container. -->
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
+42
View File
@@ -0,0 +1,42 @@
/*
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 { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { logger } from "matrix-js-sdk/lib/logger";
import { type ConfigOptions, initializeElementCall } from "../index";
import { Harness } from "./Harness";
// After Element Call's, so that the host has the last word on its own page
import "./host.css";
/**
* The development app's own `config.json`, so that the harness runs Element
* Call the way `pnpm dev` does. It is not in the repository — developers copy
* it from `config/config.devenv.json` — so its absence is expected rather than
* an error.
*/
async function loadConfig(): Promise<ConfigOptions> {
try {
const response = await fetch("/config.json");
if (response.ok) return (await response.json()) as ConfigOptions;
logger.warn(
`No config.json (${response.status}); running with Element Call's defaults`,
);
} catch (e) {
logger.warn("Could not read config.json", e);
}
return {};
}
await initializeElementCall(await loadConfig());
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Harness />
</StrictMode>,
);
+79
View File
@@ -0,0 +1,79 @@
/*
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 {
ClientEvent,
createClient,
type MatrixClient,
MemoryStore,
SyncState,
} from "matrix-js-sdk";
/**
* Logs in and brings up a client the way a host application would, so that the
* component is handed a real one rather than something Element Call built for
* itself.
*
* Everything is kept in memory and a fresh login happens on every reload. That
* costs a device on the development homeserver each time, which is harmless,
* and buys the harness two clients that cannot tread on each other's storage.
* Persisting the login to make reloads quicker would mean persisting the
* crypto store too: reusing a device ID with a fresh crypto store generates new
* device keys, and uploading them conflicts with the ones the server already
* holds.
*/
export async function createSession(
homeserver: string,
username: string,
password: string,
onProgress: (message: string) => void,
): Promise<MatrixClient> {
onProgress("Logging in");
const login = await createClient({ baseUrl: homeserver }).login(
"m.login.password",
{ identifier: { type: "m.id.user", user: username }, password },
);
const client = createClient({
baseUrl: homeserver,
accessToken: login.access_token,
userId: login.user_id,
deviceId: login.device_id,
store: new MemoryStore(),
useAuthorizationHeader: true,
fallbackICEServerAllowed: true,
});
onProgress(`Setting up crypto for ${login.device_id}`);
await client.initRustCrypto({ useIndexedDB: false });
onProgress(`Syncing ${login.device_id}`);
await client.startClient();
await new Promise<void>((resolve) => {
const onSync = (state: SyncState): void => {
if (state !== SyncState.Prepared && state !== SyncState.Syncing) return;
client.off(ClientEvent.Sync, onSync);
resolve();
};
client.on(ClientEvent.Sync, onSync);
});
return client;
}
/**
* The room to call in, joining it if this session is not in it yet — a host
* hands Element Call a room it already knows about, so the harness has to get
* itself into that position first.
*/
export async function joinRoom(
client: MatrixClient,
roomIdOrAlias: string,
): Promise<string> {
const room = await client.joinRoom(roomIdOrAlias);
return room.roomId;
}
+161
View File
@@ -0,0 +1,161 @@
/*
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 { renderHook } from "@testing-library/react";
import { createRef } from "react";
import { describe, expect, test, vi } from "vitest";
import {
type ElementCallHandle,
type ElementCallHostBridge,
useComponentHostBridge,
} from "./host";
describe("useComponentHostBridge", () => {
test("keeps one identity while the host supplies new objects", () => {
const { result, rerender } = renderHook(
({ supplied }: { supplied: ElementCallHostBridge }) =>
useComponentHostBridge(supplied, undefined, undefined),
{ initialProps: { supplied: {} } },
);
const first = result.current;
rerender({ supplied: { notifyJoined: async () => {} } });
expect(result.current).toBe(first);
});
test("forwards to whatever the host most recently supplied", async () => {
const before = vi.fn().mockResolvedValue(undefined);
const after = vi.fn().mockResolvedValue(undefined);
const { result, rerender } = renderHook(
({ supplied }: { supplied: ElementCallHostBridge }) =>
useComponentHostBridge(supplied, undefined, undefined),
{ initialProps: { supplied: { notifyJoined: before } } },
);
rerender({ supplied: { notifyJoined: after } });
await result.current.notifyJoined();
expect(before).not.toHaveBeenCalled();
expect(after).toHaveBeenCalledOnce();
});
test("is quiet about what the host did not implement", async () => {
const { result } = renderHook(() =>
useComponentHostBridge(undefined, undefined, undefined),
);
await expect(result.current.contentLoaded()).resolves.toBeUndefined();
await expect(
result.current.notifyDeviceMute({
audio_enabled: true,
video_enabled: false,
}),
).resolves.toBeUndefined();
expect(result.current.supportsReactions).toBe(true);
// Starting the user unmuted unasked is something a host has to opt into
expect(result.current.allowJoinUnmutedViaIntent).toBe(false);
});
test("lets the host allow joining unmuted on the intent", () => {
const { result, rerender } = renderHook(
({ supplied }: { supplied: ElementCallHostBridge }) =>
useComponentHostBridge(supplied, undefined, undefined),
{ initialProps: { supplied: {} } },
);
expect(result.current.allowJoinUnmutedViaIntent).toBe(false);
// Read through to whatever the host most recently said
rerender({ supplied: { allowJoinUnmutedViaIntent: true } });
expect(result.current.allowJoinUnmutedViaIntent).toBe(true);
});
test("only has a close when the host has one, since that is a signal", () => {
const { result, rerender } = renderHook(
({ supplied }: { supplied: ElementCallHostBridge }) =>
useComponentHostBridge(supplied, undefined, undefined),
{ initialProps: { supplied: {} } },
);
expect(result.current.close).toBeUndefined();
const close = vi.fn().mockResolvedValue(undefined);
rerender({ supplied: { close } });
expect(result.current.close).toBeDefined();
});
test("never offers profile changes, since the account is the host's", () => {
const { result } = renderHook(() =>
useComponentHostBridge(undefined, undefined, undefined),
);
expect(result.current.supportsProfileChanges).toBe(false);
});
describe("the handle", () => {
test("delivers a request to what is listening and resolves on its reply", async () => {
const ref = createRef<ElementCallHandle>();
const { result } = renderHook(() =>
useComponentHostBridge(undefined, ref, undefined),
);
const received = vi.fn();
result.current.deviceMute$.subscribe(({ data, reply }) => {
received(data);
reply({ audio_enabled: data.audio_enabled!, video_enabled: true });
});
await expect(
ref.current!.setDeviceMute({ audio_enabled: false }),
).resolves.toEqual({ audio_enabled: false, video_enabled: true });
expect(received).toHaveBeenCalledWith({ audio_enabled: false });
});
test("refuses a request nothing in Element Call is listening for", async () => {
const ref = createRef<ElementCallHandle>();
renderHook(() => useComponentHostBridge(undefined, ref, undefined));
await expect(ref.current!.hangUp()).rejects.toThrow(
"Nothing in Element Call can hang up right now",
);
});
});
describe("the theme", () => {
test("reaches a subscriber that arrives after it was set", () => {
const { result } = renderHook(() =>
useComponentHostBridge(undefined, undefined, "light"),
);
const names: (string | undefined)[] = [];
result.current.themeChange$.subscribe(({ data }) =>
names.push(data.name),
);
expect(names).toEqual(["light"]);
});
test("follows the prop", () => {
const { result, rerender } = renderHook(
({ theme }: { theme: string | undefined }) =>
useComponentHostBridge(undefined, undefined, theme),
{ initialProps: { theme: "light" } },
);
const names: (string | undefined)[] = [];
result.current.themeChange$.subscribe(({ data }) =>
names.push(data.name),
);
rerender({ theme: "dark" });
expect(names).toEqual(["light", "dark"]);
});
test("says nothing when the host leaves the theme to Element Call", () => {
const { result } = renderHook(() =>
useComponentHostBridge(undefined, undefined, undefined),
);
const names: (string | undefined)[] = [];
result.current.themeChange$.subscribe(({ data }) =>
names.push(data.name),
);
expect(names).toEqual([]);
});
});
});
+201
View File
@@ -0,0 +1,201 @@
/*
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.
*/
/**
* How a host application and the Element Call component talk to each other.
*
* Inside Element Call the host is a {@link HostBridge}, which carries the
* host's requests as rxjs observables because that is what the widget API and
* the view models work in. A host should not have to know about rxjs, or agree
* with us on a version of it, so a component host sees neither: it implements
* plain async callbacks for what Element Call tells it, and makes its own
* requests through an imperative handle on the component, the way it would
* call `play()` on a video element. This module adapts the one to the other.
*/
import { type Ref, useEffect, useImperativeHandle } from "react";
import { ReplaySubject, Subject } from "rxjs";
import {
type DeviceMuteRequest,
type DeviceMuteState,
type HostBridge,
type HostRequest,
} from "../src/HostBridge";
import { type JoinCallData } from "../src/widget";
import { useInitial } from "../src/useInitial";
import { useLatest } from "../src/useLatest";
/**
* What Element Call tells the application hosting it as a component.
* Everything is optional: a host implements what it wants to hear about.
*
* Compared by nothing — Element Call always calls whichever one it was most
* recently given, so this may be written inline.
*/
export interface ElementCallHostBridge {
/**
* Asks the host to keep Element Call on screen (or stop doing so), so that a
* call in progress is not torn down when the user navigates elsewhere.
*/
setAlwaysOnScreen?(alwaysOnScreen: boolean): Promise<void>;
/** Tells the host that Element Call has finished loading. */
contentLoaded?(): Promise<void>;
/** Tells the host that the user has joined the call. */
notifyJoined?(): Promise<void>;
/** Tells the host that the user has hung up. */
notifyHungUp?(): Promise<void>;
/** Tells the host the user's current audio and video mute state. */
notifyDeviceMute?(state: DeviceMuteState): Promise<void>;
/**
* Asks the host to close Element Call: to unmount the component. Its
* presence is what makes Element Call offer a close button on its error
* screens, and leave the host to decide what is shown once a call has ended.
* Without it, Element Call shows its own post-call screen, if it has one for
* the situation, or nothing.
*/
close?(): Promise<void>;
/**
* Whether Element Call may send and receive reactions in this room.
* Defaults to true.
*/
readonly supportsReactions?: boolean;
/**
* Whether the user may start unmuted when the intent skips the lobby, so
* that they never see their devices before joining. Defaults to false: the
* user starts muted and unmutes themselves. A host that chose the intent on
* the user's behalf, and is sure they expect to be heard and seen at once,
* says so here — as a Matrix client hosting Element Call as a widget does.
*/
readonly allowJoinUnmutedViaIntent?: boolean;
}
/**
* What a host can ask of a mounted Element Call, reached through the
* component's `ref`. Each request resolves once Element Call has acted on it,
* and rejects if nothing in Element Call is in a position to act: hanging up
* when there is no call, say.
*/
export interface ElementCallHandle {
/**
* Joins the call, when Element Call was configured to `preload` and is
* waiting to be told to. Says which devices to join with.
*/
join(devices: JoinCallData): Promise<void>;
/** Leaves the call. */
hangUp(): Promise<void>;
/**
* Changes the mute state, for whichever of audio and video is given, and
* reports the state that results.
*/
setDeviceMute(request: DeviceMuteRequest): Promise<DeviceMuteState>;
}
/** Hands a request to Element Call and waits for it to be acknowledged. */
async function request<Data, Reply>(
listeners: Subject<HostRequest<Data, Reply>>,
what: string,
data: Data,
): Promise<Reply> {
if (!listeners.observed)
throw new Error(`Nothing in Element Call can ${what} right now`);
return await new Promise((resolve) =>
listeners.next({ data, reply: resolve }),
);
}
/**
* The {@link HostBridge} the rest of Element Call sees, built from what a
* component host supplies and wired to the handle it is given.
*
* The bridge is created once and never changes identity — everything that
* depends on it would otherwise restart when the host re-rendered with a new
* object — and forwards each call to whatever the host most recently passed.
*/
export function useComponentHostBridge(
supplied: ElementCallHostBridge | undefined,
ref: Ref<ElementCallHandle> | undefined,
/** The theme the host wants, or undefined to leave it to Element Call. */
theme: string | undefined,
): HostBridge {
const latest = useLatest(supplied ?? {});
const requests = useInitial(() => ({
// The theme is state, not an event: a `theme` prop rather than a request
// on the handle. It travels this channel because that is how the rest of
// Element Call hears about a host's theme, and replays so that whatever
// subscribes after the host has set it — everything, on first render —
// still hears the current one.
themeChange$: new ReplaySubject<HostRequest<{ name?: string }>>(1),
join$: new Subject<HostRequest<JoinCallData>>(),
hangUp$: new Subject<HostRequest<Record<string, never>>>(),
deviceMute$: new Subject<HostRequest<DeviceMuteRequest, DeviceMuteState>>(),
}));
useEffect(() => {
if (theme !== undefined)
requests.themeChange$.next({ data: { name: theme }, reply: () => {} });
}, [requests, theme]);
const bridge = useInitial((): HostBridge => ({
setAlwaysOnScreen: async (alwaysOnScreen) => {
await latest.current.setAlwaysOnScreen?.(alwaysOnScreen);
},
contentLoaded: async () => {
await latest.current.contentLoaded?.();
},
notifyJoined: async () => {
await latest.current.notifyJoined?.();
},
notifyHungUp: async () => {
await latest.current.notifyHungUp?.();
},
notifyDeviceMute: async (state) => {
await latest.current.notifyDeviceMute?.(state);
},
// Whether these exist is itself information, so they are read through
// rather than wrapped unconditionally
get close() {
const close = latest.current.close;
return close === undefined
? undefined
: async (): Promise<void> => await close();
},
// Not offered to a component host: the client it hands over holds the
// credentials to fetch media itself. A widget's client does not, which
// is what the internal bridge's `downloadMedia` is for.
get supportsReactions(): boolean {
return latest.current.supportsReactions ?? true;
},
get allowJoinUnmutedViaIntent(): boolean {
return latest.current.allowJoinUnmutedViaIntent ?? false;
},
// Whatever the host says or does not say, the account is its own: it
// signed the user in and handed us the client. So Element Call never
// offers to edit the profile from inside a component.
supportsProfileChanges: false,
...requests,
}));
useImperativeHandle(
ref,
(): ElementCallHandle => ({
join: async (devices) =>
await request(requests.join$, "join a call", devices),
hangUp: async () => await request(requests.hangUp$, "hang up", {}),
setDeviceMute: async (muteRequest) =>
await request(
requests.deviceMute$,
"change the mute state",
muteRequest,
),
}),
[requests],
);
return bridge;
}
+358
View File
@@ -0,0 +1,358 @@
/*
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.
*/
/**
* EXPERIMENTAL
*
* Element Call as a React component, for an application that wants to show a
* call inside itself rather than in an iframe.
*
* The host supplies the client and says which room to call in; Element Call
* supplies the call. Everything it would otherwise take from the page it is on
* — the URL, the document body, a Matrix session of its own — comes from the
* host instead, or is confined to the container it is mounted in.
*/
// The design tokens, fonts and element defaults every Element Call stylesheet
// builds on. Written for a page, they speak of `html`, `body` and bare
// elements; the component build confines them, and every other stylesheet in
// this bundle, to the root element below (see build/scopeStylesToRoot.ts), so
// that the host's document is left as it was.
//
// Where these land relative to the component stylesheets is the bundler's
// choice — the standalone app puts them first, this build puts them in the
// middle — so nothing in base.css may depend on winning or losing against a
// component's own rules at equal specificity. It currently does not: what it
// declares unlayered is custom properties on Element Call's root, which
// components inherit rather than compete with, and everything from Compound
// sits in a `@layer`, which loses to unlayered rules either way.
import "../src/base.css";
import {
type FC,
type JSX,
type ReactNode,
type Ref,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { I18nextProvider } from "react-i18next";
import { TooltipProvider } from "@vector-im/compound-web";
import { ErrorBoundary } from "@sentry/react";
import { shouldPolyfill as shouldPolyfillSegmenter } from "@formatjs/intl-segmenter/should-polyfill";
import { shouldPolyfill as shouldPolyfillDurationFormat } from "@formatjs/intl-durationformat/should-polyfill.js";
import LanguageDetector from "i18next-browser-languagedetector";
import EN from "../locales/en/app.json";
import { CallView } from "../src/room/CallView";
import { ErrorPage } from "../src/FullScreenView";
import { ClientProvider } from "../src/ClientContext";
import { HostBridgeProvider } from "../src/HostBridge";
import { RootElementProvider, useRootElement } from "../src/RootElementContext";
import {
configurationForIntent,
componentProperties,
type UrlConfiguration,
type UrlParams,
UrlParamsProvider,
type UrlProperties,
UserIntent,
useUrlParams,
} from "../src/UrlParams";
import { MediaDevicesContext } from "../src/MediaDevicesContext";
import { MediaDevices } from "../src/state/MediaDevices";
import { ObservableScope } from "../src/state/ObservableScope";
import { ProcessorProvider } from "../src/livekit/TrackProcessorContext";
import { Config } from "../src/config/Config";
import { type ConfigOptions } from "../src/config/ConfigOptions";
import { i18n } from "../src/utils/i18n";
import { useTheme } from "../src/useTheme";
import { useStableValue } from "../src/useStableValue";
import styles from "./ElementCall.module.css";
import {
type ElementCallHandle,
type ElementCallHostBridge,
useComponentHostBridge,
} from "./host";
import { supportedLanguages, translationsBackend } from "./localization";
// The languages Element Call can be shown in
export { supportedLanguages } from "./localization";
// How the host and Element Call talk to each other, and what they say
export { type ElementCallHandle, type ElementCallHostBridge } from "./host";
export {
type DeviceMuteRequest,
type DeviceMuteState,
} from "../src/HostBridge";
export { type JoinCallData } from "../src/widget";
// The deployment-wide configuration, as distinct from ElementCallConfiguration
// above, which is per call
export { type ConfigOptions } from "../src/config/ConfigOptions";
// The values that appear in ElementCallConfiguration and in the intent
export {
BackgroundStyle,
HeaderStyle,
UserIntent,
type UrlConfiguration,
} from "../src/UrlParams";
/**
* How Element Call should behave. Everything is optional; anything left out
* takes the default that {@link ElementCallProps.intent} implies.
*
* This is the behaviour a widget can be configured with through its URL, plus
* the one fact about the call a host has a say in here, the background. The
* rest of what a widget's URL carries — who the user is, how to reach the
* homeserver, where to report analytics, the shared secret of a room that is
* encrypted with one — a component host supplies by other routes, or not at
* all; and what can change while the call is running, the theme and the
* language, is a prop of its own.
*/
export type ElementCallConfiguration = Partial<UrlConfiguration> &
Partial<Pick<UrlProperties, "background">>;
export interface ElementCallProps {
/**
* The client to place the call with. Element Call does not authenticate
* anyone or manage a session of its own; this one is the host's.
*/
client: MatrixClient;
/** The room to call in. The host's client must already know about it. */
roomId: string;
/**
* What the user asked for — whether they started the call or joined one that
* was already running, and whether it is a call in a group or a DM. Element
* Call decides what each of those means: whether to show the lobby first,
* whether to ring, and so on.
*
* Defaults to joining an existing group call, which is the most conservative
* reading, but a host that knows which button the user pressed should say so.
*/
intent?: UserIntent;
/**
* How Element Call should behave, overriding whatever {@link intent} implies.
* A host that finds itself setting a lot of these probably wants a different
* intent instead.
*
* Compared by value, so it is fine to write this inline; only a change to
* what it says restarts anything.
*/
config?: ElementCallConfiguration;
/**
* What Element Call tells the host while the call is running: that the user
* has joined or hung up, that it would like to be kept on screen, and so on.
* Without one, Element Call assumes nobody is listening.
*/
hostBridge?: ElementCallHostBridge;
/**
* What the host tells Element Call: to hang up, to mute, to join. Available
* once the component has rendered.
*/
ref?: Ref<ElementCallHandle>;
/**
* The theme to show Element Call in, `light` or `dark`. Left out, Element
* Call picks. Changes take effect at once, and cost nothing else.
*/
theme?: string;
/**
* The language to show Element Call in, as a BCP 47 tag: one of
* {@link supportedLanguages}, or something that falls back to one (`de-AT`
* to `de`). Left out, the browser's language is used.
*
* Translations are one thing shared by every Element Call on the page, so
* the most recently set language wins for all of them.
*/
language?: string;
}
/**
* Prepares the things Element Call needs before it can be shown: translations,
* `Intl` polyfills for older browsers, and its configuration.
*
* Await this once, before rendering {@link ElementCall}.
*/
export async function initializeElementCall(
config: ConfigOptions = {},
): Promise<void> {
const polyfills: Promise<unknown>[] = [];
if (shouldPolyfillSegmenter())
polyfills.push(import("@formatjs/intl-segmenter/polyfill-force"));
if (shouldPolyfillDurationFormat())
polyfills.push(import("@formatjs/intl-durationformat/polyfill-force.js"));
await Promise.all(polyfills);
Config.initWith(config);
await i18n
.use(translationsBackend)
.use(new LanguageDetector())
.init({
fallbackLng: "en",
defaultNS: "app",
keySeparator: ".",
nsSeparator: false,
pluralSeparator: "_",
contextSeparator: "|",
supportedLngs: [...supportedLanguages],
interpolation: { escapeValue: false },
// English is bundled in, so the fallback never has to be loaded; every
// other language arrives from the backend when first asked for.
partialBundledLanguages: true,
resources: { en: { app: EN } },
detection: {
// The browser's language, until the host says otherwise through the
// `language` prop. Nothing is remembered: the choice is the host's.
order: ["navigator"],
caches: [],
},
});
}
/** Applies the theme and background to the container, before it is painted. */
const Decoration: FC<{ children: JSX.Element }> = ({ children }) => {
useTheme();
const { background } = useUrlParams();
const rootElement = useRootElement();
useLayoutEffect(() => {
rootElement.setAttribute("data-background", background);
}, [rootElement, background]);
return children;
};
export const ElementCall: FC<ElementCallProps> = ({
client,
roomId,
intent = UserIntent.JoinExistingCall,
config,
hostBridge: suppliedHostBridge,
ref,
theme,
language,
}): ReactNode => {
const hostBridge = useComponentHostBridge(suppliedHostBridge, ref, theme);
useEffect(() => {
if (language !== undefined)
i18n
.changeLanguage(language)
.catch((e) => logger.error(`Could not switch to ${language}`, e));
}, [language]);
// The container is what Element Call decorates and portals into, so nothing
// inside can render until we have it.
const [container, setContainer] = useState<HTMLDivElement | null>(null);
// Element Call has no URL of its own to read any of this from, and the
// host's URL is not Element Call's business, so the defaults come from the
// intent with the host's wishes over the top.
//
// Everything downstream — the mute state, the call view model and with it
// the media connection — is keyed on the identity of this object, so it has
// to be stable for as long as its contents are. A host writing `config`
// inline would otherwise tear the call down on every render.
const stableConfig = useStableValue(config);
const params = useMemo(
(): UrlParams => ({
...componentProperties,
roomId,
...configurationForIntent(intent),
...stableConfig,
}),
[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 [mediaDevices, setMediaDevices] = useState<MediaDevices | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setMediaDevices(
new MediaDevices(scope, { controlledAudioDevices, callIntent }),
);
return (): void => {
setMediaDevices(null);
scope.end();
};
}, [controlledAudioDevices, callIntent]);
const room = client.getRoom(roomId);
const rtcSession = useMemo(
() => (room === null ? null : client.matrixRTC.getRoomSession(room)),
[client, room],
);
if (rtcSession === null)
logger.error(
`Element Call was asked to call in ${roomId}, which its host's client does not know about`,
);
// Everything the call needs is in hand once these exist, and the first
// render with them is where the call itself appears: the moment the host
// is told that Element Call has loaded, as the widget tells its client once
// its own initialisation is over. Once per mount, however often the pieces
// are later swapped out.
const ready =
container !== null && rtcSession !== null && mediaDevices !== null;
const announcedLoaded = useRef(false);
useEffect(() => {
if (!ready || announcedLoaded.current) return;
announcedLoaded.current = true;
hostBridge
.contentLoaded()
.catch((e) => logger.error("Could not tell the host we had loaded", e));
}, [ready, hostBridge]);
return (
<I18nextProvider i18n={i18n}>
<HostBridgeProvider value={hostBridge}>
<UrlParamsProvider value={params}>
<div ref={setContainer} className={styles.root}>
{ready && (
<RootElementProvider value={container}>
{/* Whatever goes wrong in here is shown in here. Left to
propagate, an error would unmount the host's own tree. */}
<ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
// A broken call should not hold the host on screen
onError={() => void hostBridge.setAlwaysOnScreen(false)}
>
<Decoration>
<TooltipProvider>
<ClientProvider client={client}>
<MediaDevicesContext value={mediaDevices}>
<ProcessorProvider>
<CallView
client={client}
rtcSession={rtcSession}
isPasswordlessUser={false}
confineToRoom={params.confineToRoom}
preload={params.preload}
skipLobby={params.skipLobby}
/>
</ProcessorProvider>
</MediaDevicesContext>
</ClientProvider>
</TooltipProvider>
</Decoration>
</ErrorBoundary>
</RootElementProvider>
)}
</div>
</UrlParamsProvider>
</HostBridgeProvider>
</I18nextProvider>
);
};
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, test } from "vitest";
import { supportedLanguages, translationsBackend } from "./localization";
const read = async (
language: string,
namespace = "app",
): Promise<Record<string, unknown>> =>
await new Promise((resolve, reject) =>
translationsBackend.read(language, namespace, (error, data) => {
if (error) reject(error);
else resolve(data as Record<string, unknown>);
}),
);
describe("component translations", () => {
test("offer every language in locales/, tagged as its directory is", () => {
expect(supportedLanguages).toContain("en");
expect(supportedLanguages).toContain("de");
expect(supportedLanguages).toContain("zh-Hans");
expect(new Set(supportedLanguages).size).toBe(supportedLanguages.length);
});
test("load a language's translations on demand", async () => {
const de = await read("de");
expect(de).toHaveProperty("action");
expect(de).not.toEqual(await read("en"));
});
test("refuse a language there are no translations for", async () => {
await expect(read("xx")).rejects.toThrow("No app translations for xx");
});
test("refuse a namespace there are no translations for", async () => {
await expect(read("en", "other")).rejects.toThrow(
"No other translations for en",
);
});
});
+55
View File
@@ -0,0 +1,55 @@
/*
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.
*/
/**
* Translations for Element Call as a component.
*
* The standalone app fetches its locale files at runtime from URLs its own
* build emits, which a host serving the library from somewhere else could not
* resolve. The component instead has the bundler split every locale into a
* chunk of its own, loaded the first time its language is asked for; English,
* the fallback, is bundled in so that the first paint never waits for it.
*/
import { type BackendModule, type ResourceKey } from "i18next";
import { languageOfLocalePath } from "../src/utils/i18n";
/** Every locale, as a lazily imported module. */
const translations = import.meta.glob<{ default: ResourceKey }>(
"../locales/*/app.json",
);
/**
* The languages Element Call can be shown in, as BCP 47 tags — `en`, `de`,
* `zh-Hans` and so on. A language that is not one of these falls back to its
* base language where there is one (`de-AT` to `de`), and to English otherwise.
*/
export const supportedLanguages: readonly string[] = [
...new Set(Object.keys(translations).map(languageOfLocalePath)),
];
/** Loads translations on demand. */
export const translationsBackend: BackendModule = {
type: "backend",
init(): void {},
read(language: string, namespace: string, callback): void {
const load = translations[`../locales/${language}/${namespace}.json`];
if (load === undefined) {
callback(new Error(`No ${namespace} translations for ${language}`), null);
return;
}
load().then(
(module) => callback(null, module.default),
(error: unknown) =>
callback(
error instanceof Error ? error : new Error(String(error)),
null,
),
);
},
};
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@element-hq/element-call-component",
"version": "0.0.0",
"description": "Element Call as a React component. Consumed straight from the repository as a git dependency (github:element-hq/element-call#<ref>&path:/component): the host's package manager runs `prepare`, which builds `dist/`.",
"license": "SEE LICENSE IN ../README.md",
"repository": {
"type": "git",
"url": "https://github.com/element-hq/element-call",
"directory": "component"
},
"type": "module",
"devEngines": {
"packageManager": {
"name": "pnpm"
}
},
"files": [
"dist"
],
"main": "./dist/element-call.js",
"module": "./dist/element-call.js",
"types": "./dist/types/component/index.d.ts",
"exports": {
".": {
"types": "./dist/types/component/index.d.ts",
"default": "./dist/element-call.js"
},
"./style.css": "./dist/element-call.css"
},
"sideEffects": [
"*.css"
],
"scripts": {
"prepare": "cd .. && pnpm install --frozen-lockfile && pnpm build:component"
},
"peerDependencies": {
"livekit-client": "^2.18.1",
"matrix-js-sdk": "*",
"react": "^19",
"react-dom": "^19"
}
}
+9
View File
@@ -0,0 +1,9 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: false
excludeLinksFromLockfile: false
importers:
.: {}
+14
View File
@@ -0,0 +1,14 @@
# Makes `component/` a pnpm project of its own rather than a directory inside
# the repository's workspace. That matters when a host installs the component
# straight from this repository (`github:element-hq/element-call#…&path:/component`):
# pnpm prepares such a dependency by running `pnpm install` in this directory,
# and only a project root gets its `prepare` script (see package.json) run, which
# is what builds `dist/`. Inside the repository's own workspace the install
# would silently target the repository instead and build nothing.
#
# Consequence for development: pnpm commands run from within this directory see
# this project, not the repository; run them from the repository root.
# Nothing to install here: the peers in package.json are the host's, and the
# build runs against the repository's own node_modules (see `prepare`).
autoInstallPeers: false
+20
View File
@@ -0,0 +1,20 @@
{
// Declaration output for the component package (`pnpm build:component:types`).
// The root tsconfig only type-checks; this one emits `.d.ts` files, and nothing
// else, for everything the component's entry point reaches. The layout under
// `dist/types` mirrors the repository (`component/index.d.ts`, `src/…`), which
// is what `package.json` points its `types` at.
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": false,
"emitDeclarationOnly": true,
"declaration": true,
"declarationMap": false,
"rootDir": "..",
"outDir": "./dist/types"
},
// The entry point, plus the ambient declarations (CSS modules, `?react` SVGs,
// `import.meta.env`, …) that the sources it reaches rely on.
"include": ["./index.tsx", "../src/@types/*.d.ts"],
"exclude": []
}
-2
View File
@@ -9,8 +9,6 @@
"matrix_rtc_session": {
"wait_for_key_rotation_ms": 3000,
"membership_event_expiry_ms": 180000000,
"delayed_leave_event_delay_ms": 18000,
"delayed_leave_event_restart_ms": 4000,
"network_error_retry_ms": 100
}
}
-2
View File
@@ -13,8 +13,6 @@
"matrix_rtc_session": {
"wait_for_key_rotation_ms": 3000,
"membership_event_expiry_ms": 180000000,
"delayed_leave_event_delay_ms": 18000,
"delayed_leave_event_restart_ms": 4000,
"network_error_retry_ms": 100
}
}
-2
View File
@@ -9,8 +9,6 @@
"matrix_rtc_session": {
"wait_for_key_rotation_ms": 3000,
"membership_event_expiry_ms": 180000000,
"delayed_leave_event_delay_ms": 18000,
"delayed_leave_event_restart_ms": 4000,
"network_error_retry_ms": 100
},
"posthog": {
-2
View File
@@ -9,8 +9,6 @@
"matrix_rtc_session": {
"wait_for_key_rotation_ms": 3000,
"membership_event_expiry_ms": 180000000,
"delayed_leave_event_delay_ms": 18000,
"delayed_leave_event_restart_ms": 4000,
"network_error_retry_ms": 100
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ 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:c107ec33fa349cb5c14fd03a4e13352d64ef264416dac96d273aa07b4004171f
image: ghcr.io/element-hq/element-web:develop@sha256:6ed62b2963ae098a1f79521eb516834dcf29452168e281cc359d9cfb4380adf6
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:c107ec33fa349cb5c14fd03a4e13352d64ef264416dac96d273aa07b4004171f
image: ghcr.io/element-hq/element-web:develop@sha256:6ed62b2963ae098a1f79521eb516834dcf29452168e281cc359d9cfb4380adf6
+1
View File
@@ -3,6 +3,7 @@
This folder contains documentation for setup, usage, and development of Element Call.
- [Embedded vs standalone mode](./embedded_standalone.md)
- [Element Call as a React component (experimental)](../README.md#element-call-as-a-component-experimental)
- [Url format and parameters](./url_params.md)
- [Global JS controls](./controls.md)
- [MatrixRTC modes](./matrix_rtc_modes.md)
+3
View File
@@ -3,6 +3,9 @@
Element Call is available as two different packages: Full Package and Embedded Package.
The Full Package is designed for standalone use, while the Embedded Package is designed for widget mode only.
There is also an experimental third option, a build of Element Call as a React component for applications
that want to render a call inside their own page rather than in an iframe; see
[Element Call as a component](../README.md#element-call-as-a-component-experimental) in the README.
The table below provides a comparison of the two packages:
+7 -1
View File
@@ -9,7 +9,13 @@ import { type KnipConfig } from "knip";
export default {
vite: {
config: ["vite.config.ts", "vite-embedded.config.ts", "vite-sdk.config.ts"],
config: [
"vite.config.ts",
"vite-embedded.config.ts",
"vite-sdk.config.ts",
"vite-component.config.ts",
"vite-component-dev.config.ts",
],
},
entry: ["src/main.tsx", "eslint/index.js", "i18next.config.ts"],
ignoreBinaries: [
+1
View File
@@ -116,6 +116,7 @@
"peer_connection_timeout_description": "Connection to the media server timed out. Try switching to a different network or disabling your VPN. If the problem persists, see our <0>troubleshooting guide</0> or contact your server administrator.",
"room_creation_restricted": "Failed to create call",
"room_creation_restricted_description": "Call creation might be restricted to authorized users only. Try again later, or contact your server admin if the problem persists.",
"screen_share_failed": "Could not start screen sharing",
"sticky_events_required": "Homeserver does not support Matrix 2.0 calls",
"sticky_events_required_description": "This deployment is configured to use Matrix 2.0 call mode, but the homeserver does not advertise support for sticky events (MSC4354). Ask your server admin to upgrade, or switch the deployment to a compatible mode.",
"unexpected_ec_error": "An unexpected error occurred (<0>Error Code:</0> <1>{{ errorCode }}</1>). Please contact your server admin."
+13 -5
View File
@@ -6,6 +6,7 @@
"dev": "pnpm dev:full",
"dev:full": "vite",
"dev:embedded": "vite --config vite-embedded.config.js",
"dev:component": "vite --config vite-component-dev.config.ts",
"build": "pnpm build:full",
"build:full": "NODE_OPTIONS=--max-old-space-size=16384 vite build",
"build:full:production": "pnpm build:full",
@@ -16,13 +17,19 @@
"build:sdk:development": "pnpm build:sdk --mode development",
"build:sdk": "pnpm build:full --config vite-sdk.config.js",
"build:sdk:production": "pnpm build:sdk",
"build:component": "pnpm build:component:js && pnpm build:component:types",
"build:component:js": "pnpm build:full --config vite-component.config.js",
"build:component:types": "tsc -p component/tsconfig.build.json",
"build:component:production": "pnpm build:component",
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:types",
"serve": "vite preview",
"format": "oxfmt",
"format:check": "oxfmt --check; rc=$?; [[ $rc -ne 0 ]] && printf '\\033[46;30m INFO \\033[0m To fix, run: pnpm format\\n' >&2; exit $rc",
"lint": "pnpm lint:types && pnpm lint:oxlint && pnpm lint:knip",
"lint:oxlint": "oxlint src playwright",
"lint:oxlint-fix": "oxlint --fix src playwright",
"lint": "pnpm lint:types && pnpm lint:oxlint && pnpm lint:knip && pnpm lint:externals",
"lint:oxlint": "oxlint src component playwright",
"lint:oxlint-fix": "oxlint --fix src component playwright",
"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",
@@ -81,7 +88,7 @@
"@vitejs/plugin-react": "^6.0.2",
"@vitest/browser-playwright": "^4.1.5",
"@vitest/coverage-v8": "^4.0.18",
"@vitest/ui": "4.1.10",
"@vitest/ui": "4.1.11",
"babel-plugin-react-compiler": "^1.0.0",
"classnames": "^2.3.1",
"copy-to-clipboard": "^3.3.3",
@@ -101,12 +108,13 @@
"node-stdlib-browser": "^1.3.1",
"normalize.css": "^8.0.1",
"observable-hooks": "^4.2.3",
"oxfmt": "^0.61.0",
"oxfmt": "^0.66.0",
"oxlint": "^1.70.0",
"oxlint-tsgolint": "^0.25.0",
"pako": "^2.0.4",
"postcss": "^8.4.41",
"postcss-preset-env": "^10.0.0",
"postcss-selector-parser": "^7.1.1",
"posthog-js": "1.408.2",
"qrcode": "^1.5.4",
"react": "19",
+31 -9
View File
@@ -11,6 +11,8 @@ import { join } from "path";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { COMPONENT_HARNESS_URL } from "./playwright/component/harness.ts";
const baseURL = process.env.USE_DOCKER
? "http://localhost:8080"
: "https://localhost:3000";
@@ -84,6 +86,11 @@ export default defineConfig({
// enumerateDevices work on CI runners without real hardware.
"media.navigator.streams.fake": true,
"media.navigator.permission.disabled": true,
// Vite serves HTTPS over HTTP/2, and Firefox intermittently stalls
// on Node's HTTP/2 server with a page that never finishes loading
// (one run in five or so, locally). Every server in the suite
// still speaks HTTP/1.1, so nothing is lost by insisting on it.
"network.http.http2.enabled": false,
},
},
},
@@ -115,14 +122,29 @@ export default defineConfig({
],
/* Run your local dev server before starting the tests */
webServer: {
command: "./scripts/playwright-webserver-command.sh",
url: baseURL,
reuseExistingServer: !process.env.CI,
ignoreHTTPSErrors: true,
gracefulShutdown: {
signal: "SIGTERM",
timeout: 500,
webServer: [
{
command: "./scripts/playwright-webserver-command.sh",
url: baseURL,
reuseExistingServer: !process.env.CI,
ignoreHTTPSErrors: true,
gracefulShutdown: {
signal: "SIGTERM",
timeout: 500,
},
},
},
{
// The harness that embeds Element Call as a component. Always a Vite dev
// server, whether or not the app itself is being served from Docker,
// since there is nothing to build: it is a development page only.
command: "pnpm dev:component",
url: COMPONENT_HARNESS_URL,
reuseExistingServer: !process.env.CI,
ignoreHTTPSErrors: true,
gracefulShutdown: {
signal: "SIGTERM",
timeout: 500,
},
},
],
});
+285
View File
@@ -0,0 +1,285 @@
/*
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, type Locator, type Page, test } from "@playwright/test";
import {
createUserAndRoom,
expectWithin,
resizeContainer,
startHarness,
} from "./harness.ts";
import { SpaHelpers } from "../spa-helpers.ts";
/**
* Element Call embedded as a React component, driven through the development
* harness in `component/dev`.
*
* What these cover that the widget tests cannot is everything that follows from
* sharing a page with a host: whether Element Call stays inside the space it
* was given, and whether two of it can exist at once. As a widget, the iframe
* guaranteed both.
*/
// Each test signs in twice, sets up crypto twice and syncs twice before
// anything is on screen, and then waits for media to connect; the waits below
// 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);
// Each component shows a lobby of its own, and neither has joined anything
// just by being rendered
for (const index of [0, 1])
await expect(panes.nth(index).getByTestId("lobby_joinCall")).toBeVisible({
timeout: 60_000,
});
for (const index of [0, 1])
await panes.nth(index).getByTestId("lobby_joinCall").click();
// Two devices of one account, so each component should see itself and the
// other. This is the part that proves two Element Calls in one page are two
// calls, and not one shared thing wearing two hats.
for (const index of [0, 1])
await expect(panes.nth(index).getByTestId("videoTile")).toHaveCount(2, {
timeout: 60_000,
});
});
test("keeps its modals inside the container it was given", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("containment");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
const container = pane.getByTestId("call-container");
// In the flat container the harness gives it by default, Element Call hides
// its controls a few seconds after the call starts, as it would in a flat
// window. A full-size container keeps them on screen to be clicked.
await resizeContainer(container, { width: 900, height: 640 });
await pane.getByTestId("lobby_joinCall").click({ timeout: 60_000 });
await expect(pane.getByTestId("footer-container")).toBeVisible({
timeout: 60_000,
});
// Both of these are positioned `fixed`, and were centred on the window
// 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 expectWithin(pane.getByRole("dialog"), container);
await pane.getByTestId("modal_close").click();
await pane.getByRole("button", { name: "Reactions" }).click();
await expectWithin(
pane.getByRole("dialog", { name: "Pick reaction" }),
container,
);
});
test("keeps the call inside the container, wherever the host put it", async ({
page,
}) => {
const { username, roomId } = await createUserAndRoom("tileswithin");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
const container = pane.getByTestId("call-container");
// Large enough for the layout switch to be offered
await resizeContainer(container, { width: 900, height: 640 });
await pane.getByTestId("lobby_joinCall").click({ timeout: 60_000 });
await expect(pane.getByTestId("footer-container")).toBeVisible({
timeout: 60_000,
});
// The spotlight layout draws its tile in the fixed grid, which is positioned
// against Element Call's root rather than laid out in flow. The harness puts
// 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();
const tile = pane.getByTestId("videoTile").first();
await expect(tile).toBeVisible({ timeout: 60_000 });
await expectWithin(tile, container);
});
test("leaves the host's own page unstyled", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("hoststyles");
const panes = await startHarness(page, username, roomId);
await expect(panes.first().getByTestId("lobby_joinCall")).toBeVisible({
timeout: 60_000,
});
// Element Call's stylesheet is written for a page of its own: normalize.css
// gives `html` a line height, Compound gives `body` its font and feature
// settings, and the design tokens live on `:root`. None of that may reach the
// host's document — the harness sets none of these itself, so anything other
// than the browser's defaults here came from us.
const host = await page.evaluate(() => {
const html = getComputedStyle(document.documentElement);
const body = getComputedStyle(document.body);
return {
lineHeight: html.lineHeight,
fontFeatureSettings: body.fontFeatureSettings,
token: html.getPropertyValue("--cpd-color-text-primary"),
};
});
expect(host).toEqual({
lineHeight: "normal",
fontFeatureSettings: "normal",
token: "",
});
// While inside the container, the same rules do apply
const root = panes.first().locator("[data-element-call-root]");
await expect(root).toHaveCSS("font-feature-settings", /"kern"/);
});
test("tells its host what it is doing", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("hostbridge");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
const log = page.getByTestId("bridge-log");
// Every component reports to its host through the bridge, whether that host
// is a widget container or an application embedding it directly
await expect(log).toContainText("contentLoaded", { timeout: 60_000 });
await pane.getByTestId("lobby_joinCall").click({ timeout: 60_000 });
await expect(log).toContainText("notifyJoined", { timeout: 60_000 });
await expect(log).toContainText("setAlwaysOnScreen(true)", {
timeout: 60_000,
});
// And takes instructions back: the host asking for a mute should come back
// as the component reporting the new state
await pane.getByRole("button", { name: "Mute" }).click();
await expect(log).toContainText("notifyDeviceMute(audio: false", {
timeout: 30_000,
});
});
test("lays itself out for the space it is given, not the page", async ({
page,
}) => {
const { username, roomId } = await createUserAndRoom("containersize");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
const container = pane.getByTestId("call-container");
const call = pane.locator("[data-layout]");
await pane.getByTestId("lobby_joinCall").click({ timeout: 60_000 });
await expect(call).toBeVisible({ timeout: 60_000 });
await expect(call).not.toHaveAttribute("data-layout", "pip");
// As a widget, Element Call's container and its window were one and the same:
// a host wanting a picture-in-picture made the iframe small, and Element Call
// saw the window shrink. A component gets no such signal from the window,
// which stays as large as it ever was; only the container changes.
await resizeContainer(container, { width: 300, height: 300 });
await expect(call).toHaveAttribute("data-layout", "pip");
await resizeContainer(container, { width: 900, height: 700 });
await expect(call).not.toHaveAttribute("data-layout", "pip");
});
/**
* The shape of a call at whatever size it has been given: the layout it chose,
* how much of the height the tile and the footer take, and which controls the
* footer shows. Two calls with the same shape look the same, participants aside.
*/
async function callShape(scope: Page | Locator): Promise<{
layout: string | null;
tileHeight: number;
footerHeight: number;
buttons: (string | null)[];
}> {
const call = scope.locator("[data-layout]");
const footer = scope.getByTestId("footer-container");
await expect(footer).toBeVisible();
// The tile arrives with the media connection, which can take a while
const tile = scope.getByTestId("videoTile").first();
await expect(tile).toBeVisible({ timeout: 60_000 });
const tileBox = (await tile.boundingBox())!;
const footerBox = (await footer.boundingBox())!;
// Buttons and switches alike: the mute controls are switches
const buttons = await footer
.locator("button")
.filter({ visible: true })
.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("aria-label")),
);
return {
layout: await call.getAttribute("data-layout"),
tileHeight: Math.round(tileBox.height),
footerHeight: Math.round(footerBox.height),
buttons,
};
}
test("looks the same in a small container as in a small window", async ({
page,
browser,
}) => {
// Two calls to set up, one of them through the harness's two logins
test.setTimeout(300_000);
const size = { width: 300, height: 300 };
// The reference is Element Call owning a window of that size, which is what
// a mobile app's webview or a browser's picture-in-picture gives it, and
// what its small-window styling was written for.
// No permissions to grant: each browser is launched with fake media that is
// handed out without asking (see playwright.config.ts), and Firefox rejects
// a request for `camera` or `microphone` outright
const referenceContext = await browser.newContext({
viewport: size,
ignoreHTTPSErrors: true,
});
const referencePage = await referenceContext.newPage();
await referencePage.goto("/");
await SpaHelpers.createCall(referencePage, "Reference", "smallwindow", true);
const reference = await callShape(referencePage);
await referencePage.screenshot({
path: test.info().outputPath("small-window.png"),
});
// The component gets a container of that size, in a window that is far larger
const { username, roomId } = await createUserAndRoom("smallcontainer");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
const container = pane.getByTestId("call-container");
await resizeContainer(container, size);
await pane.getByTestId("lobby_joinCall").click({ timeout: 60_000 });
await expect(pane.locator("[data-layout]")).toBeVisible({ timeout: 60_000 });
const component = await callShape(pane);
await container.screenshot({
path: test.info().outputPath("small-container.png"),
});
await referenceContext.close();
// The breakpoints in Element Call's stylesheets are container queries, so a
// small container gets the compact footer a small window does, rather than
// the full-width one the window's own size would call for
expect(component).toEqual(reference);
// And that footer is the compact one: a single row of controls, not the
// full-height bar with its logo and layout switch that a large window gets
expect(component.footerHeight).toBeLessThan(size.height / 3);
expect(component.tileHeight + component.footerHeight).toBeLessThanOrEqual(
size.height,
);
});
+126
View File
@@ -0,0 +1,126 @@
/*
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, type Locator, type Page } from "@playwright/test";
import { SynapseAdmin } from "../utils/synapse-admin.ts";
/**
* Where the component harness is served — `component/dev`, which embeds Element
* Call the way a host application would. Not the `baseURL` the rest of the
* suite uses: these tests drive a page that contains Element Call rather than
* Element Call itself.
*/
export const COMPONENT_HARNESS_URL = "https://localhost:3001";
const HOMESERVER_URL = "https://synapse.m.localhost";
const PASSWORD = "foobarbaz1!";
/**
* Registers a user through the Synapse admin API and creates a room for it to
* call in, without touching a browser. The harness signs into this account
* twice, giving two devices in one page and so a real call between the two
* components.
*/
export async function createUserAndRoom(
name: string,
): Promise<{ username: string; roomId: string }> {
const username = `${name}_${Date.now()}`;
const { access_token: accessToken } = await SynapseAdmin.forHomeserver(
HOMESERVER_URL,
).registerUser(username, PASSWORD, name);
const response = await fetch(
`${HOMESERVER_URL}/_matrix/client/v3/createRoom`,
{
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ name: `${name}'s call`, preset: "private_chat" }),
},
);
if (!response.ok)
throw new Error(
`Could not create a room: ${response.status} ${await response.text()}`,
);
const { room_id: roomId } = (await response.json()) as { room_id: string };
return { username, roomId };
}
/**
* Opens the harness signed in as the given user, and waits for both embedded
* calls to appear.
*
* @returns The two containers the host gave Element Call, in order.
*/
export async function startHarness(
page: Page,
username: string,
roomId: string,
): Promise<Locator> {
const query = new URLSearchParams({
homeserver: HOMESERVER_URL,
username,
password: PASSWORD,
room: roomId,
});
await page.goto(`${COMPONENT_HARNESS_URL}/?${query.toString()}`);
await page.getByRole("button", { name: "Start" }).click();
const panes = page.getByTestId("call-pane");
// Two logins, two crypto setups and two initial syncs happen first
await expect(panes).toHaveCount(2, { timeout: 120_000 });
return panes;
}
/**
* Asserts that one element is drawn entirely inside another.
*
* This is the check that being a component rather than an iframe costs us: an
* iframe could not paint outside itself whatever its stylesheets said, whereas
* a component shares the page and has to be made to stay put.
*/
export async function expectWithin(
inner: Locator,
outer: Locator,
): Promise<void> {
await expect(inner).toBeVisible();
const innerBox = await inner.boundingBox();
const outerBox = await outer.boundingBox();
if (innerBox === null || outerBox === null)
throw new Error("Expected both elements to be laid out");
// A pixel of slack, for subpixel layout
const slack = 1;
expect(innerBox.x).toBeGreaterThanOrEqual(outerBox.x - slack);
expect(innerBox.y).toBeGreaterThanOrEqual(outerBox.y - slack);
expect(innerBox.x + innerBox.width).toBeLessThanOrEqual(
outerBox.x + outerBox.width + slack,
);
expect(innerBox.y + innerBox.height).toBeLessThanOrEqual(
outerBox.y + outerBox.height + slack,
);
}
/**
* Gives one of the harness's containers a new size. Element Call lays itself
* out for the size of its container, so this is how a test puts it into a
* particular mode: a flat or narrow one, a picture-in-picture, or a full-size
* window, without the window itself changing at all.
*/
export async function resizeContainer(
container: Locator,
size: { width: number; height: number },
): Promise<void> {
await container.evaluate((element, { width, height }) => {
element.style.width = `${width}px`;
element.style.height = `${height}px`;
}, size);
}
+1 -1
View File
@@ -153,7 +153,7 @@ export const widgetTest = test.extend<MyFixtures>({
// Accept the DM invite from brooks
// This how playwright record selects the DM invite in the room list
await ewPage2.getByRole("option", { name: "Open room" }).click();
await ewPage2.getByRole("button", { name: "Open room" }).click();
await ewPage2.getByRole("button", { name: "Start chatting" }).click();
}
+1496 -1508
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1,3 +1,7 @@
supportedArchitectures:
os: [current, linux]
cpu: [current, arm64]
libc: [current, glibc]
minimumReleaseAgeExclude:
- "@vector-im/compound-design-tokens"
- "@vector-im/compound-web"
+140
View File
@@ -0,0 +1,140 @@
/*
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.
*/
/**
* Checks that the component build leaves the packages a host must supply to
* the host.
*
* A host application already has React, the Matrix SDK and LiveKit, and a
* second copy of any of them is worse than dead weight: React would hold two
* sets of hooks, and the Matrix client would run two sync loops. So the
* component build lists them as external — but that list has to name every
* subpath, since the bundler silently ignores the pattern and callback forms
* of the option, and an import it does not cover is bundled with no warning at
* all. That is the failure this guards against.
*
* It reads the list from the build config itself, so there is one copy of it,
* and compares it against every import of those packages in the source.
*
* The comparison is deliberately over-approximate: it looks at all of `src`
* rather than only the modules the component actually pulls in, so it will
* sometimes ask for a subpath that only the standalone app imports. Listing
* one the component never imports costs nothing — the bundler ignores it —
* whereas missing one costs a duplicate package.
*/
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { loadConfigFromFile } from "vite";
const CONFIG = "vite-component.config.ts";
const SOURCES = ["src", "component"];
/** The packages whose duplication would break a host, rather than merely enlarge it. */
const MUST_BE_EXTERNAL = [
"react",
"react-dom",
"matrix-js-sdk",
"livekit-client",
];
const isTestFile = (name) =>
name.includes(".test.") || name.includes(".stories.");
/** Every source file under the given directories, recursively. */
async function* sourceFiles(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) yield* sourceFiles(path);
else if (/\.(ts|tsx)$/.test(entry.name) && !isTestFile(entry.name))
yield path;
}
}
/**
* The module specifiers a source file imports. Covers `from "…"` (which is
* both static imports and re-exports), bare `import "…"` for side effects, and
* dynamic `import("…")`.
*/
function imports(source) {
const specifiers = [];
for (const pattern of [
/\bfrom\s*["']([^"']+)["']/g,
/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,
/^\s*import\s+["']([^"']+)["']/gm,
])
for (const [, specifier] of source.matchAll(pattern))
specifiers.push(specifier);
return specifiers;
}
/**
* Whether a specifier is an import of one of the packages we care about.
*
* Imports carrying a resource query — `?worker`, `?inline` and friends — are
* not, whatever package they name. Those ask the bundler for a script to run
* in a context of its own, which has to be self-contained and shares no state
* with the host's copy of anything. Worker sub-builds do not inherit this
* option anyway.
*/
const mustBeExternal = (specifier) =>
!specifier.includes("?") &&
MUST_BE_EXTERNAL.some(
(pkg) => specifier === pkg || specifier.startsWith(`${pkg}/`),
);
const loaded = await loadConfigFromFile(
{ command: "build", mode: "production" },
CONFIG,
);
if (loaded === null) {
console.error(`Could not load ${CONFIG}`);
process.exit(1);
}
const declared = new Set(loaded.config.build?.rollupOptions?.external ?? []);
if (declared.size === 0) {
console.error(
`${CONFIG} declares nothing external. Either the option moved, or the ` +
`list is empty; either way this check is not looking at what it thinks.`,
);
process.exit(1);
}
// Where each missing specifier is imported, so the message can point at it
const missing = new Map();
const seen = new Set();
for (const dir of SOURCES)
for await (const file of sourceFiles(dir)) {
const source = await readFile(file, "utf8");
for (const specifier of imports(source)) {
if (!mustBeExternal(specifier)) continue;
seen.add(specifier);
if (declared.has(specifier)) continue;
const files = missing.get(specifier) ?? [];
files.push(file);
missing.set(specifier, files);
}
}
if (missing.size > 0) {
console.error(
`${CONFIG} does not declare these imports external, so the component ` +
`build would bundle its own copy of them:\n`,
);
for (const [specifier, files] of [...missing].sort())
console.error(` ${specifier}\n imported by ${files.join(", ")}`);
console.error(`\nAdd each one to the \`external\` list in ${CONFIG}.`);
process.exit(1);
}
// Deliberately no complaint about declarations nothing imports. Some of them
// cannot be seen from the source at all — `react/jsx-runtime` is injected by
// the JSX transform — and an extra declaration is inert, so there is nothing
// to warn about.
console.log(
`${declared.size} external declarations cover all ${seen.size} imports of ${MUST_BE_EXTERNAL.join(", ")}.`,
);
+3
View File
@@ -60,6 +60,7 @@ import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { initializeWidget } from "../src/widget";
import { type Connection } from "../src/state/CallViewModel/remoteMembers/Connection";
import { createWidgetHostBridge } from "../src/HostBridge";
import { observeElementSize$ } from "../src/utils/elementSize";
interface MatrixRTCSdk {
/**
@@ -151,6 +152,8 @@ export async function createMatrixRTCSdk(
...callViewModelOptionsFromParams(urlParams),
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
hostBridge,
// The SDK owns its page, so the body is the space it has
windowSize$: scope.behavior(observeElementSize$(document.body)),
},
of({}),
of({}),
+41 -11
View File
@@ -5,8 +5,21 @@ 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 JSX, Suspense, useEffect, useState } from "react";
import { BrowserRouter, Route, useLocation, Routes } from "react-router-dom";
import {
type FC,
type JSX,
Suspense,
useCallback,
useEffect,
useState,
} from "react";
import {
BrowserRouter,
Route,
useLocation,
useNavigate,
Routes,
} from "react-router-dom";
import * as Sentry from "@sentry/react";
import { TooltipProvider } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
@@ -40,6 +53,7 @@ import {
nullHostBridge,
} from "./HostBridge";
import { useInitial } from "./useInitial";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
@@ -57,6 +71,20 @@ const LocationUrlParamsProvider: FC<SimpleProviderProps> = ({ children }) => {
return <UrlParamsProvider value={urlParams}>{children}</UrlParamsProvider>;
};
/**
* Supplies the way home. Only the app has one — its home page, with the list
* of recent calls — so this, too, lives in the app shell.
*/
const HomeProvider: FC<SimpleProviderProps> = ({ children }) => {
const navigate = useNavigate();
const leaveToHome = useCallback(() => {
navigate("/")?.catch((e) => logger.error("Failed to navigate home", e));
}, [navigate]);
return (
<LeaveToHomeProvider value={leaveToHome}>{children}</LeaveToHomeProvider>
);
};
const BackgroundProvider: FC<SimpleProviderProps> = ({ children }) => {
const { pathname } = useLocation();
const { background } = useUrlParams();
@@ -143,15 +171,17 @@ export const App: FC<Props> = ({ vm, widget }) => {
<HostBridgeProvider value={hostBridge}>
<BrowserRouter>
<LocationUrlParamsProvider>
<BackgroundProvider>
<ThemeProvider>
<TooltipProvider>
<Suspense fallback={null}>
<MaybeAppBar>{content}</MaybeAppBar>
</Suspense>
</TooltipProvider>
</ThemeProvider>
</BackgroundProvider>
<HomeProvider>
<BackgroundProvider>
<ThemeProvider>
<TooltipProvider>
<Suspense fallback={null}>
<MaybeAppBar>{content}</MaybeAppBar>
</Suspense>
</TooltipProvider>
</ThemeProvider>
</BackgroundProvider>
</HomeProvider>
</LocationUrlParamsProvider>
</BrowserRouter>
</HostBridgeProvider>
+3 -3
View File
@@ -68,7 +68,7 @@
}
/* Hide everything but the subtitle in small windows */
@media (max-height: 450px) {
@container element-call (max-height: 450px) {
.bar {
display: none;
}
@@ -131,7 +131,7 @@
}
}
body[data-platform="ios"] {
[data-element-call-root][data-platform="ios"] {
.bar > header {
grid-template-rows: minmax(var(--cpd-space-11x), auto) var(--cpd-space-4x);
grid-template-areas: "primaryButton title secondaryButton";
@@ -166,7 +166,7 @@ body[data-platform="ios"] {
}
/* Hide everything but the subtitle in small windows */
@media (max-height: 450px) {
@container element-call (max-height: 450px) {
.bar:has(.subtitle) > header {
grid-template-rows: var(--cpd-space-4x) minmax(var(--cpd-space-5x), auto);
grid-template-areas: "." "subtitle";
+7 -7
View File
@@ -16,13 +16,13 @@ import {
useMemo,
type JSX,
} from "react";
import { useNavigate } from "react-router-dom";
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 { useHostBridge } from "./HostBridge";
import { useLeaveToHome } from "./LeaveToHomeContext";
import {
PosthogAnalytics,
RegistrationType,
@@ -136,9 +136,9 @@ interface Props {
/**
* The client Element Call should use.
*
* When a host embeds Element Call it 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
* 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.
*/
@@ -146,7 +146,7 @@ interface Props {
}
export const ClientProvider: FC<Props> = ({ children, client }) => {
const navigate = useNavigate();
const leaveToHome = useLeaveToHome();
const hostBridge = useHostBridge();
// null = signed out, undefined = loading
@@ -249,10 +249,10 @@ export const ClientProvider: FC<Props> = ({ children, client }) => {
await client.clearStores();
clearSession();
setInitClientState(null);
await navigate("/");
leaveToHome?.();
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [navigate, initClientState?.client]);
}, [leaveToHome, initClientState?.client]);
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
+15 -16
View File
@@ -20,7 +20,7 @@ import { logger } from "matrix-js-sdk/lib/logger";
import { RageshakeButton } from "./settings/RageshakeButton";
import styles from "./ErrorView.module.css";
import { useUrlParams } from "./UrlParams";
import { LinkButton } from "./button";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { useHostBridge } from "./HostBridge.ts";
interface Props {
@@ -50,6 +50,7 @@ export const ErrorView: FC<Props> = ({
const { t } = useTranslation();
const { confineToRoom } = useUrlParams();
const hostBridge = useHostBridge();
const leaveToHome = useLeaveToHome();
const onReload = useCallback(() => {
window.location.href = "/";
@@ -73,21 +74,19 @@ export const ErrorView: FC<Props> = ({
};
// Whether the error is considered fatal or pathname is `/` then reload the all app.
// If not then navigate to home page.
const ReturnToHomeButton = (): ReactElement => {
if (fatal || location.pathname === "/") {
return (
<Button kind="tertiary" className={styles.homeLink} onClick={onReload}>
{t("return_home_button")}
</Button>
);
} else {
return (
<LinkButton kind="tertiary" className={styles.homeLink} to="/">
{t("return_home_button")}
</LinkButton>
);
}
// If not then navigate to home page. Neither applies when there is no home
// to go to.
const ReturnToHomeButton = (): ReactElement | null => {
if (leaveToHome === null) return null;
return (
<Button
kind="tertiary"
className={styles.homeLink}
onClick={fatal || location.pathname === "/" ? onReload : leaveToHome}
>
{t("return_home_button")}
</Button>
);
};
return (
+6 -1
View File
@@ -30,6 +30,11 @@ Please see LICENSE in the repository root for full details.
display: none;
align-items: center;
text-decoration: none;
/* A button when it leads home, so undo the browser's button styling */
background: none;
border: none;
padding: 0;
cursor: pointer;
}
.leftNav.hideMobile {
@@ -107,7 +112,7 @@ Please see LICENSE in the repository root for full details.
gap: var(--cpd-space-1-5x);
}
@media (min-width: 800px) {
@container element-call (min-width: 800px) {
.headerLogo,
.leftNav.hideMobile,
.rightNav.hideMobile {
+26 -7
View File
@@ -6,8 +6,13 @@ Please see LICENSE in the repository root for full details.
*/
import classNames from "classnames";
import { type Ref, type FC, type HTMLAttributes, type ReactNode } from "react";
import { Link } from "react-router-dom";
import {
type Ref,
type FC,
type HTMLAttributes,
type ReactNode,
useCallback,
} from "react";
import { useTranslation } from "react-i18next";
import { Heading, Text } from "@vector-im/compound-web";
import { UserProfileIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
@@ -16,7 +21,8 @@ import styles from "./Header.module.css";
import Logo from "./icons/Logo.svg?react";
import { Avatar, Size } from "./Avatar";
import { EncryptionLock } from "./room/EncryptionLock";
import { useMediaQuery } from "./useMediaQuery";
import { useRootSizeMatches } from "./useRootSize";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { DisconnectedBanner } from "./DisconnectedBanner";
interface HeaderProps extends HTMLAttributes<HTMLElement> {
@@ -112,17 +118,30 @@ interface HeaderLogoProps {
className?: string;
}
/**
* The logo, which is also the way home — when there is a home to go to. As a
* component there is not, and it is just the logo.
*/
export const HeaderLogo: FC<HeaderLogoProps> = ({ className }) => {
const { t } = useTranslation();
const leaveToHome = useLeaveToHome();
const onClick = useCallback(() => leaveToHome?.(), [leaveToHome]);
if (leaveToHome === null)
return (
<div className={classNames(styles.headerLogo, className)}>
<Logo />
</div>
);
return (
<Link
<button
type="button"
className={classNames(styles.headerLogo, className)}
to="/"
onClick={onClick}
aria-label={t("header_label")}
>
<Logo />
</Link>
</button>
);
};
@@ -142,7 +161,7 @@ export const RoomHeaderInfo: FC<RoomHeaderInfoProps> = ({
participantCount,
}) => {
const { t } = useTranslation();
const size = useMediaQuery("(max-width: 550px)") ? "sm" : "lg";
const size = useRootSizeMatches(({ width }) => width <= 550) ? "sm" : "lg";
return (
<div className={styles.roomHeaderInfo} data-size={size}>
+18
View File
@@ -247,6 +247,16 @@ describe("createWidgetHostBridge", () => {
});
});
test("does not offer profile changes, since the host signed the user in", () => {
const bridge = createWidgetHostBridge(mockWidget({}));
expect(bridge.supportsProfileChanges).toBe(false);
});
test("allows joining unmuted on the intent, since the host asked for the call", () => {
const bridge = createWidgetHostBridge(mockWidget({}));
expect(bridge.allowJoinUnmutedViaIntent).toBe(true);
});
describe("supportsReactions", () => {
const capabilities = [
"org.matrix.msc2762.send.event:m.reaction",
@@ -278,6 +288,10 @@ describe("nullHostBridge", () => {
expect(nullHostBridge.close).toBeUndefined();
});
test("supports profile changes, since Element Call signed the user in itself", () => {
expect(nullHostBridge.supportsProfileChanges).toBe(true);
});
test("offers no media download, so Element Call uses its own client", () => {
expect(nullHostBridge.downloadMedia).toBeUndefined();
});
@@ -285,4 +299,8 @@ describe("nullHostBridge", () => {
test("supports reactions, since nothing is mediating its homeserver access", () => {
expect(nullHostBridge.supportsReactions).toBe(true);
});
test("does not allow joining unmuted on the intent, since nobody vouched for it", () => {
expect(nullHostBridge.allowJoinUnmutedViaIntent).toBe(false);
});
});
+30 -2
View File
@@ -51,7 +51,7 @@ export interface HostRequest<Data, Reply = void> {
* Element Call's view of the application hosting it.
*
* Element Call can run as its own page, as a widget inside a Matrix client, or
* embedded directly into one. Only the last two give it a host, and each of
* as a component inside one. Only the last two give it a host, and each of
* them reaches it by a different route — so everything Element Call needs from
* whatever is hosting it goes through this interface, rather than being
* expressed in terms of the widget API.
@@ -96,10 +96,26 @@ export interface HostBridge {
/** The host wants to change, or read back, the device mute state. */
deviceMute$: Observable<HostRequest<DeviceMuteRequest, DeviceMuteState>>;
// What the host is capable of.
// What the host is, and is capable of.
/**
* Whether Element Call may offer to change the user's profile — their
* display name and avatar. Only when the account is Element Call's own,
* which is to say standalone: a widget's host and an application hosting
* the component both signed the user in themselves, so the profile is theirs
* to manage and Element Call must not offer to edit it.
*/
readonly supportsProfileChanges: boolean;
/** Whether the host permits Element Call to send and receive reactions. */
readonly supportsReactions: boolean;
/**
* Whether the user may be put into a call unmuted on the strength of the
* intent alone, when the lobby is skipped and so they get no chance to check
* their devices first. A host that asked for the call on the user's behalf
* has that much of their trust; standalone Element Call does not, and starts
* them muted instead.
*/
readonly allowJoinUnmutedViaIntent: boolean;
/**
* Fetches media on Element Call's behalf, for hosts that do not give it
* direct access to the homeserver. Absent when Element Call should fetch
@@ -122,9 +138,15 @@ export const nullHostBridge: HostBridge = {
join$: NEVER,
hangUp$: NEVER,
deviceMute$: NEVER,
// Standalone, the account is Element Call's own: it signed the user in, so
// it may offer to change the profile.
supportsProfileChanges: true,
// Standalone Element Call reaches the homeserver itself, so nothing is
// withholding these from it.
supportsReactions: true,
// Standalone, nobody vouched for the intent: it came from a URL, which is
// not enough to switch the user's camera and microphone on unasked.
allowJoinUnmutedViaIntent: false,
};
/** Bridges to a host that Element Call is a widget of. */
@@ -176,6 +198,12 @@ export function createWidgetHostBridge(widget: WidgetHelpers): HostBridge {
join$: requests(ElementWidgetActions.JoinCall),
hangUp$: requests(ElementWidgetActions.HangupCall),
deviceMute$: requests(ElementWidgetActions.DeviceMute),
// The client we are a widget of signed the user in, so the profile is its
// to manage
supportsProfileChanges: false,
// The client we are a widget of asked for this call on the user's behalf,
// so its intent may be trusted to say whether they start unmuted
allowJoinUnmutedViaIntent: true,
// Element Call needs the host's permission to send reactions on its behalf.
// Read on access rather than up front: the widget API negotiates its
// capabilities asynchronously, and the bridge is built before that settles.
+29
View File
@@ -0,0 +1,29 @@
/*
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";
/**
* How the user leaves the call for wherever they came from: the standalone
* app's home page, with its list of recent calls.
*
* The call itself has no idea where that is, or whether there is such a place
* at all. Standalone there is, and the shell navigates to it; as a component
* there is not — the host decides what happens after a call — so nothing is
* supplied, and the call offers no way out of its own. This is what lets the
* call be rendered without a router.
*/
const LeaveToHomeContext = createContext<(() => void) | null>(null);
export const LeaveToHomeProvider = LeaveToHomeContext.Provider;
/**
* The way out of the call, or null when there is nowhere to go and the call
* should not offer one.
*/
export const useLeaveToHome = (): (() => void) | null =>
use(LeaveToHomeContext);
+1 -1
View File
@@ -48,7 +48,7 @@ Please see LICENSE in the repository root for full details.
--handle-inset-block-end: var(--cpd-space-4x);
}
body[data-platform="ios"] .drawer {
[data-element-call-root][data-platform="ios"] .drawer {
--border-radius: 10px;
--handle-block-size: 5px;
--handle-inline-size: 36px;
+17 -13
View File
@@ -12,23 +12,27 @@ import { createContext, use } from "react";
*
* Element Call decorates this element with the theme, layout and background
* attributes its stylesheets key off, and portals its modals into it. When
* Element Call owns the page this is simply the document body; the intent is
* that when embedded in a host application it becomes the container the host
* mounted it into, so that Element Call does not reach outside its own subtree.
* Element Call owns the page this is simply the document body; as a component
* it is the container the host mounted it into, so that Element Call does not
* reach outside its own subtree.
*
* That intent is not yet achievable: several selectors still name `body`
* directly — `body[data-background="gradient"]` and `body[data-platform=…]` in
* `index.css`, and `body[data-platform="ios"]` in `AppBar.module.css` and
* `Modal.module.css` — and `Initializer.initBeforeReact` writes
* `data-platform` straight onto the body. So anything other than the body will
* be decorated correctly and styled incorrectly, silently. Until those are
* scoped, treat this as preparation rather than a working seam.
* The stylesheets find this element by its `data-element-call-root` attribute,
* which {@link useTheme} sets along with the platform and theme, so they no
* longer depend on it being the body.
*
* What remains body-specific is the standalone page's own furniture: the
* `body` rule in `index.css` still sets the page background and margin, and
* `index.html` starts the body hidden with `no-theme` until the theme lands.
* Neither applies when a host mounts Element Call into a container of its own.
*/
// No provider is exported yet: nothing supplies a root element, so every
// consumer falls back to the document body. M1 adds one along with the
// component that mounts Element Call into a container.
const RootElementContext = createContext<HTMLElement | null>(null);
/**
* Supplies the element Element Call should confine itself to. The standalone
* and widget builds need no provider, since for them that element is the body.
*/
export const RootElementProvider = RootElementContext.Provider;
/**
* The element Element Call should decorate and portal into.
*
+92
View File
@@ -11,10 +11,14 @@ import { logger } from "matrix-js-sdk/lib/logger";
import * as PlatformMod from "../src/Platform";
import {
BackgroundStyle,
configurationForIntent,
getRoomIdentifierFromUrl,
computeUrlParams,
HeaderStyle,
getUrlParams,
componentProperties,
UserIntent,
} from "../src/UrlParams";
import { mockConfig } from "./utils/test";
@@ -335,6 +339,50 @@ describe("UrlParams", () => {
callIntent: "audio",
});
});
it("accepts start_call_dm_voice", () => {
expect(
computeUrlParams(
"?intent=start_call_dm_voice&widgetId=1234&parentUrl=parent.org",
),
).toMatchObject({
...startNewCallDefaults("desktop"),
// A DM rings the other side and waits for them, whichever platform
sendNotificationType: "ring",
autoLeaveWhenOthersLeft: true,
waitForCallPickup: true,
callIntent: "audio",
});
});
it("accepts join_existing_dm", () => {
expect(
computeUrlParams(
"?intent=join_existing_dm&widgetId=1234&parentUrl=parent.org",
),
).toMatchObject({
...joinExistingCallDefaults("desktop"),
// Straight in: the other side is already waiting
skipLobby: true,
autoLeaveWhenOthersLeft: true,
waitForCallPickup: false,
callIntent: "video",
});
});
it("accepts join_existing_dm_voice", () => {
expect(
computeUrlParams(
"?intent=join_existing_dm_voice&widgetId=1234&parentUrl=parent.org",
),
).toMatchObject({
...joinExistingCallDefaults("desktop"),
skipLobby: true,
autoLeaveWhenOthersLeft: true,
waitForCallPickup: false,
callIntent: "audio",
});
});
});
describe("skipLobby", () => {
@@ -424,4 +472,48 @@ describe("UrlParams", () => {
);
});
});
// What Element Call runs with when a host embeds it as a component, which
// has no URL of its own for any of this to come from
describe("hosted defaults", () => {
it("assume nothing about a session or a page", () => {
expect(componentProperties).toMatchObject({
// The host is not a widget host, and supplies the client itself, so
// none of the widget or session plumbing applies
isWidget: false,
widgetId: null,
parentUrl: null,
userId: null,
deviceId: null,
baseUrl: null,
homeserver: null,
// The gradient is drawn by a `position: fixed` pseudo-element, which
// would escape the container and cover the host's own interface
background: BackgroundStyle.Solid,
});
});
it("keep a hosted call inside its room", () => {
const hosted = configurationForIntent(UserIntent.JoinExistingCall);
expect(hosted).toMatchObject({
// A host owns navigation, so Element Call must not offer a way out of
// the room
confineToRoom: true,
perParticipantE2EE: true,
// The lobby first, so that the user picks their devices rather than
// being thrown into the call by the act of being rendered
skipLobby: false,
});
// No Element Call branding inside someone else's application
expect(hosted.header).not.toBe(HeaderStyle.Standard);
});
it("fall back to the standalone app's when no intent is stated", () => {
expect(configurationForIntent(UserIntent.Unknown)).toMatchObject({
confineToRoom: false,
header: HeaderStyle.Standard,
perParticipantE2EE: false,
});
});
});
});
+136 -76
View File
@@ -354,6 +354,136 @@ export const getUrlParams = (
return params;
};
/**
* The configuration implied by what the user meant to do — if they pressed a
* Start Call button this would be `start_call`, and if they pressed Join Call,
* `join_existing`.
*
* These are platform-specific defaults, so that a host can start a call by
* saying what the user asked for rather than by setting every parameter itself,
* and so that what each intent means is Element Call's decision, made in one
* place. A host that wants something else states it alongside the intent.
*
* {@link UserIntent.Unknown} means no intent was stated, and gives the
* standalone app's defaults: Element Call owns the whole page, so it offers the
* way out of the room that a hosted call must not.
*/
export function configurationForIntent(intent: UserIntent): UrlConfiguration {
// Only constants and `platform` here, so that this depends on nothing but
// the intent.
let preset: UrlConfiguration = {
confineToRoom: true,
preload: false,
header: platform === "desktop" ? HeaderStyle.None : HeaderStyle.AppBar,
showControls: true,
hideScreensharing: false,
allowIceFallback: true,
perParticipantE2EE: true,
controlledAudioDevices: platform === "desktop" ? false : true,
skipLobby: true,
returnToLobby: false,
sendNotificationType: "notification",
autoLeaveWhenOthersLeft: false,
waitForCallPickup: false,
};
switch (intent) {
case UserIntent.StartNewCall:
preset.skipLobby = false;
preset.callIntent = "video";
break;
case UserIntent.JoinExistingCall:
// On desktop this will be overridden based on which button was used to join the call
preset.skipLobby = false;
preset.callIntent = "video";
break;
case UserIntent.StartNewCallVoice:
preset.skipLobby = false;
preset.callIntent = "audio";
break;
case UserIntent.JoinExistingCallVoice:
// On desktop this will be overridden based on which button was used to join the call
preset.skipLobby = false;
preset.callIntent = "audio";
break;
case UserIntent.StartNewCallDMVoice:
preset.callIntent = "audio";
// Fall through
case UserIntent.StartNewCallDM:
preset.skipLobby = true;
preset.sendNotificationType = "ring";
preset.autoLeaveWhenOthersLeft = true;
preset.waitForCallPickup = true;
preset.callIntent = preset.callIntent ?? "video";
break;
case UserIntent.JoinExistingCallDMVoice:
preset.callIntent = "audio";
// Fall through
case UserIntent.JoinExistingCallDM:
// On desktop this will be overridden based on which button was used to join the call
preset.skipLobby = true;
preset.autoLeaveWhenOthersLeft = true;
preset.callIntent = preset.callIntent ?? "video";
break;
// Non widget usecase defaults
default:
preset = {
confineToRoom: false,
preload: false,
header: HeaderStyle.Standard,
showControls: true,
hideScreensharing: false,
allowIceFallback: false,
perParticipantE2EE: false,
controlledAudioDevices: false,
skipLobby: false,
returnToLobby: false,
sendNotificationType: undefined,
autoLeaveWhenOthersLeft: false,
waitForCallPickup: false,
};
}
return preset;
}
/**
* The {@link UrlProperties} for Element Call running as a component inside a
* host application.
*
* It has no URL of its own to read these from, and it does not need most of
* them: the widget plumbing does not apply, the Matrix client and the analytics
* configuration come from the host by other routes, and what is left is either
* the host's to state through the component's props or Element Call's own
* default.
*/
export const componentProperties: UrlProperties = {
widgetId: null,
parentUrl: null,
isWidget: false,
roomId: null,
userId: null,
displayName: null,
deviceId: null,
baseUrl: null,
lang: null,
fonts: [],
fontScale: null,
posthogUserId: null,
posthogApiHost: null,
posthogApiKey: null,
e2eEnabled: true,
password: null,
viaServers: null,
homeserver: null,
rageshakeSubmitUrl: null,
sentryDsn: null,
sentryEnvironment: null,
theme: null,
// Solid rather than the gradient the standalone app defaults to: the gradient
// is drawn by a `position: fixed` pseudo-element, which would escape the
// container Element Call was given and cover the host's own interface.
background: BackgroundStyle.Solid,
};
/**
* Gets the app parameters for the current URL.
* @param search The URL search string
@@ -383,78 +513,7 @@ export const computeUrlParams = (search = "", hash = ""): UrlParams => {
const intent = !isWidget
? UserIntent.Unknown
: (parser.getEnumParam("intent", UserIntent) ?? UserIntent.Unknown);
// Here we only use constants and `platform` to determine the intent preset.
let intentPreset: UrlConfiguration = {
confineToRoom: true,
preload: false,
header: platform === "desktop" ? HeaderStyle.None : HeaderStyle.AppBar,
showControls: true,
hideScreensharing: false,
allowIceFallback: true,
perParticipantE2EE: true,
controlledAudioDevices: platform === "desktop" ? false : true,
skipLobby: true,
returnToLobby: false,
sendNotificationType: "notification",
autoLeaveWhenOthersLeft: false,
waitForCallPickup: false,
};
switch (intent) {
case UserIntent.StartNewCall:
intentPreset.skipLobby = false;
intentPreset.callIntent = "video";
break;
case UserIntent.JoinExistingCall:
// On desktop this will be overridden based on which button was used to join the call
intentPreset.skipLobby = false;
intentPreset.callIntent = "video";
break;
case UserIntent.StartNewCallVoice:
intentPreset.skipLobby = false;
intentPreset.callIntent = "audio";
break;
case UserIntent.JoinExistingCallVoice:
// On desktop this will be overridden based on which button was used to join the call
intentPreset.skipLobby = false;
intentPreset.callIntent = "audio";
break;
case UserIntent.StartNewCallDMVoice:
intentPreset.callIntent = "audio";
// Fall through
case UserIntent.StartNewCallDM:
intentPreset.skipLobby = true;
intentPreset.sendNotificationType = "ring";
intentPreset.autoLeaveWhenOthersLeft = true;
intentPreset.waitForCallPickup = true;
intentPreset.callIntent = intentPreset.callIntent ?? "video";
break;
case UserIntent.JoinExistingCallDMVoice:
intentPreset.callIntent = "audio";
// Fall through
case UserIntent.JoinExistingCallDM:
// On desktop this will be overridden based on which button was used to join the call
intentPreset.skipLobby = true;
intentPreset.autoLeaveWhenOthersLeft = true;
intentPreset.callIntent = intentPreset.callIntent ?? "video";
break;
// Non widget usecase defaults
default:
intentPreset = {
confineToRoom: false,
preload: false,
header: HeaderStyle.Standard,
showControls: true,
hideScreensharing: false,
allowIceFallback: false,
perParticipantE2EE: false,
controlledAudioDevices: false,
skipLobby: false,
returnToLobby: false,
sendNotificationType: undefined,
autoLeaveWhenOthersLeft: false,
waitForCallPickup: false,
};
}
const intentPreset = configurationForIntent(intent);
const properties: UrlProperties = {
widgetId,
@@ -536,8 +595,9 @@ const UrlParamsContext = createContext<UrlParams | null>(null);
/**
* Supplies the parameters Element Call should run with.
*
* The standalone and widget builds derive these from the URL, but an embedder
* has no URL of its own to put them in, so it provides them directly instead.
* The standalone and widget builds derive these from the URL, but the
* component has no URL of its own to read them from, so its host provides them
* directly instead.
*
* TODO: `UrlParams` is no longer an accurate name now that these need not come
* from a URL. Renaming it touches every consumer, so it is left until the rest
@@ -557,8 +617,8 @@ export const useUrlParams = (): UrlParams =>
/**
* Derives {@link UrlParams} from the current router location.
*
* Only meaningful when Element Call owns the URL; embedders provide the params
* directly through {@link UrlParamsProvider}.
* Only meaningful when Element Call owns the URL; the component is given its
* params directly through {@link UrlParamsProvider}.
*/
export const useUrlParamsFromLocation = (): UrlParams => {
const { search, hash } = useLocation();
+223
View File
@@ -0,0 +1,223 @@
/*
Copyright 2021-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.
*/
/* The styles Element Call needs wherever it is shown: the design tokens, fonts
and element defaults its own stylesheets build on top of.
Split out from index.css so that Element Call as a component can have these
without also being given the standalone page's layout, which would style the
host's own document. What remains here still speaks of the
document — normalize.css and the typography below use bare element selectors,
and the custom properties are declared on `:root` — which is right for the
page, and is why the component build rewrites it: there every selector is
confined to Element Call's root element (see component/build/scopeStylesToRoot.ts),
with `html`, `body` and `:root` becoming that element. Nothing needs to be
written differently here for that to work, but nothing here may rely on
reaching the host's document either.
Nothing here should depend on where it lands relative to Element Call's
component stylesheets: the bundler decides that, and it decides differently for
the app and for the component build. */
@layer normalize, compound-legacy, compound;
@import url("@fontsource/inter/400.css");
@import url("@fontsource/inter/500.css");
@import url("@fontsource/inter/600.css");
@import url("@fontsource/inter/700.css");
@import url("@fontsource/inconsolata/400.css");
@import url("@fontsource/inconsolata/700.css");
@import url("normalize.css/normalize.css") layer(normalize);
@import url("@vector-im/compound-design-tokens/assets/web/css/compound-design-tokens.css") layer(compound);
@import url("@vector-im/compound-web/dist/style.css") layer(compound.components);
:root {
--font-scale: 1;
--font-size-micro: calc(10px * var(--font-scale));
--font-size-caption: calc(12px * var(--font-scale));
--font-size-body: calc(15px * var(--font-scale));
--font-size-subtitle: calc(18px * var(--font-scale));
--font-size-title: calc(24px * var(--font-scale));
--font-size-headline: calc(32px * var(--font-scale));
--cpd-color-border-accent: var(--cpd-color-green-800);
/* The distance to inset non-full-width content from the edge of Element
Call's root along the inline axis. This ramps up from 16px for typical mobile
windows, to 96px for typical desktop windows, and accounts for the safe area.
Container units resolve where the property is used, so this must only be used
by elements whose nearest query container is the root. */
--content-inset-left: calc(
env(safe-area-inset-left) +
min(
var(--cpd-space-24x),
max(var(--cpd-space-4x), calc((100cqw - 900px) / 3))
)
);
--content-inset-right: calc(
env(safe-area-inset-right) +
min(
var(--cpd-space-24x),
max(var(--cpd-space-4x), calc((100cqw - 900px) / 3))
)
);
--small-drop-shadow: 0px 1.2px 2.4px 0px rgba(0, 0, 0, 0.15);
--big-drop-shadow: 0px 0px 24px 0px #1b1d221a;
--subtle-drop-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
--call-view-overlay-layer: 1;
--call-view-header-footer-layer: 2;
}
:root,
[class*="cpd-theme-"] {
--video-tile-background: var(--cpd-color-bg-subtle-secondary);
}
/* The breakpoints in Element Call's stylesheets are container queries against
this element rather than media queries against the viewport. For the standalone
app the two are the same thing, since the root is the page; for a host that
embeds Element Call in a corner of its own page they are not, and it is the
corner that the layout has to fit.
For the same reason, lengths that were once a share of the viewport (`100vw`)
are a share of the nearest query container (`100cqw`). Container units cannot
name their container, so they only mean this element where no other query
container — a spotlight layout, a media tile — lies in between; check that
before using one further down the tree. */
[data-element-call-root] {
container: element-call / size;
}
.cpd-theme-dark {
--cpd-color-border-accent: var(--cpd-color-green-1100);
--stopgap-color-on-solid-accent: var(--cpd-color-text-primary);
--stopgap-background-85: rgba(16, 19, 23, 0.85);
}
@media (min-height: 330px) {
[data-element-call-root][data-background="gradient"]::before {
content: "";
position: fixed;
/* Chromium abruptly fades our images to fully transparent at the edge of
the element. If we just make the element a little bigger than the viewport,
this is no longer visible. */
inset: -20px;
background-image: url("graphics/mobile-gradient.png");
background-size: 1400px 305px;
background-position: bottom;
background-repeat: no-repeat;
}
[data-element-call-root][data-background="gradient"][data-platform="desktop"]::before {
background-image: url("graphics/desktop-gradient.png");
background-size: max(1440px, 100cqw) max(1440px, 100cqh);
background-position: center;
}
}
/* We use this to not render the page at all until we know the theme.*/
.no-theme {
opacity: 0;
}
/* On Android and iOS, prefer native system fonts. The global.css file of
Compound Web is where these variables ultimately get consumed to set the page's
font-family. */
[data-element-call-root][data-platform="android"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
[data-element-call-root][data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
@layer compound-legacy {
h1,
h2,
h3,
h4,
h5,
h6,
p,
a {
margin-top: 0;
}
/* Headline Semi Bold */
h1 {
font-weight: 600;
font-size: var(--font-size-headline);
}
/* Title */
h2 {
font-weight: 600;
font-size: var(--font-size-title);
}
/* Subtitle */
h3 {
font-weight: 600;
font-size: var(--font-size-subtitle);
}
/* Body Semi Bold */
h4 {
font-weight: 600;
font-size: var(--font-size-body);
}
h1,
h2,
h3 {
line-height: 1.2;
}
/* Body */
p {
font-size: var(--font-size-body);
line-height: var(--font-size-title);
}
hr {
width: calc(100% - 24px);
border: none;
border-top: 1px solid var(--cpd-color-border-interactive-secondary);
color: var(--cpd-color-border-interactive-secondary);
overflow: visible;
text-align: center;
height: 5px;
font-weight: 600;
font-size: var(--font-size-body);
line-height: 24px;
margin: 0 12px;
}
summary {
font-size: var(--font-size-body);
}
details > :not(summary) {
margin-left: var(--font-size-body);
}
details[open] > summary {
margin-bottom: var(--font-size-body);
}
}
/* normalize.css sets the focus rings on buttons in Firefox to an unusual custom
outline, which is inconsistent with our other components and is not sufficiently
visible to be accessible. This resets it back to 'auto'. */
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: auto;
}
+40
View File
@@ -0,0 +1,40 @@
/*
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 MouseEvent, type ReactNode, useCallback } from "react";
import { Link } from "@vector-im/compound-web";
import { useLeaveToHome } from "../LeaveToHomeContext";
interface Props {
className?: string;
children: ReactNode;
}
/**
* A link out of the call, to wherever the user came from. Renders nothing when
* there is nowhere to go (see {@link useLeaveToHome}).
*/
export const LeaveToHomeLink: FC<Props> = ({ className, children }) => {
const leaveToHome = useLeaveToHome();
const onClick = useCallback(
(e: MouseEvent<HTMLAnchorElement>) => {
e.preventDefault();
leaveToHome?.();
},
[leaveToHome],
);
if (leaveToHome === null) return null;
// Where this leads is the shell's business, so the link has no address of
// its own to offer
return (
<Link className={className} href="#" onClick={onClick}>
{children}
</Link>
);
};
+8 -3
View File
@@ -10,7 +10,7 @@
width: fit-content;
}
@media (max-width: 420px) {
@container element-call (max-width: 420px) {
.reactionPopupMenu {
--reaction-button-padding: 8px;
--reaction-button-fontsize: 16px;
@@ -19,7 +19,12 @@
}
div.reactionPopupMenuRoot.reactionPopupMenuModal {
--overlay-top: 82vh;
/* Down near the footer it belongs to, rather than centred like other modals.
A percentage, not a viewport unit: the overlay is positioned `fixed`, so this
resolves against the page in the standalone app and against the container
when a host embeds us — where 82vh would put it below the container
entirely. */
--overlay-top: 82%;
width: fit-content;
}
@@ -30,7 +35,7 @@ div.reactionPopupMenuRoot {
.reactionPopupMenuRoot > div {
width: fit-content;
max-width: 100vw;
max-width: 100cqw;
}
div.reactionPopupMenuRoot.reactionPopupMenuModal > div > div {
+8 -8
View File
@@ -77,7 +77,7 @@ Please see LICENSE in the repository root for full details.
}
/*First hide the logo*/
@media (max-width: 750px) {
@container element-call (max-width: 750px) {
.logo {
display: none;
}
@@ -94,7 +94,7 @@ Please see LICENSE in the repository root for full details.
With the logo hidden >500px is enough space to show overflow, buttons, layout.
Once we exceed 500 we hide everything except the buttons.
*/
@media (max-width: 500px) {
@container element-call (max-width: 500px) {
.footer {
grid-template-areas: "buttons buttons buttons";
}
@@ -115,27 +115,27 @@ Once we exceed 500 we hide everything except the buttons.
}
}
@media (max-height: 800px) {
@container element-call (max-height: 800px) {
.footer {
padding-block: var(--cpd-space-8x)
calc(env(safe-area-inset-bottom) + var(--cpd-space-8x));
}
}
@media (max-height: 400px) {
@container element-call (max-height: 400px) {
.footer {
padding-block: var(--cpd-space-4x)
calc(env(safe-area-inset-bottom) + var(--cpd-space-4x));
}
}
@media (max-width: 370px) {
@container element-call (max-width: 370px) {
.shareScreen {
display: none;
}
/* PIP custom css */
@media (max-height: 400px) {
@container element-call (max-height: 400px) {
.shareScreen {
display: flex;
}
@@ -148,13 +148,13 @@ Once we exceed 500 we hide everything except the buttons.
}
}
@media (max-width: 320px) {
@container element-call (max-width: 320px) {
.raiseHand {
display: none;
}
}
@media (min-width: 800px) {
@container element-call (min-width: 800px) {
.buttons {
gap: var(--cpd-space-4x);
}
+5 -6
View File
@@ -36,7 +36,7 @@ export class Config {
*
* Does nothing if the config has already been initialized, including by
* {@link Config.initWith}, so that the regular startup path can run unchanged
* when an embedder has already supplied the config.
* when a component host has already supplied the config.
*/
public static async init(): Promise<void> {
if (!Config.internalInstance?.initPromise) {
@@ -66,16 +66,15 @@ export class Config {
}
/**
* Initializes the config from an object supplied by the embedder, instead of
* fetching `config.json`.
* Initializes the config from an object supplied by the application hosting
* the component, instead of fetching `config.json`.
*
* {@link Config.init} derives the location of `config.json` from
* `window.location`, which only makes sense while Element Call owns the page.
* When it is embedded in a host application the host owns the configuration
* and passes it in here.
* As a component, the host owns the configuration and passes it in here.
*
* The config goes through the same validation and defaulting as a fetched
* one, so that an injected config behaves identically to a hosted one.
* one, so that a supplied config behaves identically to a fetched one.
*
* Replaces any config initialized earlier.
*/
+55 -33
View File
@@ -24,6 +24,35 @@ export enum MatrixRTCMode {
Matrix_2_0 = "matrix_2_0",
}
export interface DelayedLeaveTimings {
/**
* The delay (in milliseconds) with which delayed leave events are sent.
*
* If the server receives no keep-alives from the client for any longer than
* this duration, it will send the leave event, automatically removing the
* user from the call.
*/
delay_ms?: number;
/**
* How frequently (in milliseconds) the client sends keep-alives to the server
* to restart the timer for a delayed leave event. Should be less than
* {@link DelayedLeaveTimings.delay_ms}.
*/
restart_ms?: number;
/**
* The time (in milliseconds) after which we consider a delayed event restart HTTP request to have failed.
* Setting this to a lower value will result in more frequent retries, but then we will also give up earlier.
*
* In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs
* helps by keeping more delayed event reset candidates in flight,
* improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,
* but only applies to calls to the `_unstable_updateDelayedEvent` endpoint with a body of `{action:"restart"}`.)
*/
restart_timeout_ms?: number;
}
export interface ConfigOptions {
/**
* The Posthog endpoint to which analytics data will be sent.
@@ -184,29 +213,6 @@ export interface ConfigOptions {
*/
wait_for_key_rotation_ms?: number;
/**
* The duration (in milliseconds) after the most recent keep-alive (delayed leave event restart)
* that the server waits before sending the leave MatrixRTC membership event.
*/
delayed_leave_event_delay_ms?: number;
/**
* The time (in milliseconds) after which we consider a delayed event restart http request to have failed.
* Setting this to a lower value will result in more frequent retries but also a higher chance of failiour.
*
* In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs
* helps by keeping more delayed event reset candidates in flight,
* improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,
* but only applies to calls to the `_unstable_updateDelayedEvent` endpoint with a body of `{action:"restart"}`.)
*/
delayed_leave_event_restart_local_timeout_ms?: number;
/**
* The time interval (in milliseconds) at which the client sends membership keep-alive
* messages to the server by restarting the timer for the delayed leave event.
*/
delayed_leave_event_restart_ms?: number;
/**
* How long we wait before retrying after a network error on any of the requests.
*/
@@ -231,9 +237,28 @@ export interface ConfigOptions {
* Defaults to the js-sdk default (undefined). Which means that rotation will always happen.
*/
key_rotation_participant_limit?: number;
/**
* Timing options for delayed leave events, which are used to remove a user
* from a call when they lose connection.
*/
delayed_leave?: DelayedLeaveTimings;
/**
* Timing options for delayed leave events, in cases where the ability to
* send the event can be delegated to the SFU.
*
* We recommend setting {@link DelayedLeaveTimings.delay_ms} >>
* {@link sync_disconnect_grace_period_ms} here.
*/
delegated_delayed_leave?: DelayedLeaveTimings;
};
}
export interface ResolvedDelayedLeaveTimings extends DelayedLeaveTimings {
delay_ms: number; // Required
}
// Overrides members from ConfigOptions that are always provided by the
// default config and are therefore non-optional.
export interface ResolvedConfigOptions extends ConfigOptions {
@@ -257,19 +282,15 @@ export interface ResolvedConfigOptions extends ConfigOptions {
>
>;
};
matrix_rtc_session: {
wait_for_key_rotation_ms?: number;
delayed_leave_event_delay_ms: number;
delayed_leave_event_restart_local_timeout_ms?: number;
delayed_leave_event_restart_ms?: number;
matrix_rtc_session: ConfigOptions["matrix_rtc_session"] & {
network_error_retry_ms: number;
membership_event_expiry_ms?: number;
key_rotation_participant_limit?: number;
delayed_leave: ResolvedDelayedLeaveTimings;
delegated_delayed_leave: ResolvedDelayedLeaveTimings;
};
}
export const DEFAULT_CONFIG: ResolvedConfigOptions = {
sync_disconnect_grace_period_ms: 10000,
sync_disconnect_grace_period_ms: 10_000,
ssla: "https://static.element.io/legal/element-software-and-services-license-agreement-uk-1.pdf",
media_quality: {
video_codec: "vp8",
@@ -285,7 +306,8 @@ export const DEFAULT_CONFIG: ResolvedConfigOptions = {
},
},
matrix_rtc_session: {
delayed_leave_event_delay_ms: 10000,
network_error_retry_ms: 1000,
network_error_retry_ms: 1_000,
delayed_leave: { delay_ms: 18_000, restart_ms: 4_000 },
delegated_delayed_leave: { delay_ms: 3_600_000, restart_ms: 300_000 },
},
};
+1 -1
View File
@@ -30,7 +30,7 @@ Please see LICENSE in the repository root for full details.
block-size: 140px;
}
@media (max-width: 600px) {
@container element-call (max-width: 600px) {
/* Give the PiP a portrait aspect ratio */
.pip[data-size="sm"] {
inline-size: 88px;
+1 -1
View File
@@ -25,7 +25,7 @@ Please see LICENSE in the repository root for full details.
var(--content-inset-left);
}
@media (min-width: 600px) {
@container element-call (min-width: 600px) {
.pip {
inline-size: 180px;
block-size: 135px;
+9 -182
View File
@@ -5,64 +5,11 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
@layer normalize, compound-legacy, compound;
/* Styles for Element Call as a page of its own. The parts that apply wherever
Element Call is shown live in base.css; these are about owning the document,
and are not loaded when a host embeds Element Call as a component. */
@import url("@fontsource/inter/400.css");
@import url("@fontsource/inter/500.css");
@import url("@fontsource/inter/600.css");
@import url("@fontsource/inter/700.css");
@import url("@fontsource/inconsolata/400.css");
@import url("@fontsource/inconsolata/700.css");
@import url("normalize.css/normalize.css") layer(normalize);
@import url("@vector-im/compound-design-tokens/assets/web/css/compound-design-tokens.css") layer(compound);
@import url("@vector-im/compound-web/dist/style.css") layer(compound.components);
:root {
--font-scale: 1;
--font-size-micro: calc(10px * var(--font-scale));
--font-size-caption: calc(12px * var(--font-scale));
--font-size-body: calc(15px * var(--font-scale));
--font-size-subtitle: calc(18px * var(--font-scale));
--font-size-title: calc(24px * var(--font-scale));
--font-size-headline: calc(32px * var(--font-scale));
--cpd-color-border-accent: var(--cpd-color-green-800);
/* The distance to inset non-full-width content from the edge of the window
along the inline axis. This ramps up from 16px for typical mobile windows, to
96px for typical desktop windows, and accounts for the safe area. */
--content-inset-left: calc(
env(safe-area-inset-left) +
min(
var(--cpd-space-24x),
max(var(--cpd-space-4x), calc((100vw - 900px) / 3))
)
);
--content-inset-right: calc(
env(safe-area-inset-right) +
min(
var(--cpd-space-24x),
max(var(--cpd-space-4x), calc((100vw - 900px) / 3))
)
);
--small-drop-shadow: 0px 1.2px 2.4px 0px rgba(0, 0, 0, 0.15);
--big-drop-shadow: 0px 0px 24px 0px #1b1d221a;
--subtle-drop-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
--call-view-overlay-layer: 1;
--call-view-header-footer-layer: 2;
}
:root,
[class*="cpd-theme-"] {
--video-tile-background: var(--cpd-color-bg-subtle-secondary);
}
.cpd-theme-dark {
--cpd-color-border-accent: var(--cpd-color-green-1100);
--stopgap-color-on-solid-accent: var(--cpd-color-text-primary);
--stopgap-background-85: rgba(16, 19, 23, 0.85);
}
@import url("./base.css");
body {
background-color: var(--cpd-color-bg-canvas-default);
@@ -74,39 +21,16 @@ body {
-webkit-tap-highlight-color: transparent;
}
@media (min-height: 330px) {
body[data-background="gradient"]::before {
content: "";
position: fixed;
/* Chromium abruptly fades our images to fully transparent at the edge of
the element. If we just make the element a little bigger than the viewport,
this is no longer visible. */
inset: -20px;
background-image: url("graphics/mobile-gradient.png");
background-size: 1400px 305px;
background-position: bottom;
background-repeat: no-repeat;
}
body[data-background="gradient"][data-platform="desktop"]::before {
background-image: url("graphics/desktop-gradient.png");
background-size: max(1440px, 100vw) max(1440px, 100vh);
background-position: center;
}
}
/* This prohibits the view to scroll for pages smaller than 122px in width
we use this for mobile pip webviews */
.no-scroll-body {
we use this for mobile pip webviews. Element Call adds this class to whatever
it treats as its root, but it is only ever the page that should be pinned like
this — done to a container inside a host application it would take that
container out of the host's layout — so the selector says so. */
body.no-scroll-body {
position: fixed;
width: 100%;
}
/* We use this to not render the page at all until we know the theme.*/
.no-theme {
opacity: 0;
}
html,
body,
#root {
@@ -123,104 +47,7 @@ body,
isolation: isolate;
}
/* On Android and iOS, prefer native system fonts. The global.css file of
Compound Web is where these variables ultimately get consumed to set the page's
font-family. */
body[data-platform="android"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
body[data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
@layer compound-legacy {
h1,
h2,
h3,
h4,
h5,
h6,
p,
a {
margin-top: 0;
}
/* Headline Semi Bold */
h1 {
font-weight: 600;
font-size: var(--font-size-headline);
}
/* Title */
h2 {
font-weight: 600;
font-size: var(--font-size-title);
}
/* Subtitle */
h3 {
font-weight: 600;
font-size: var(--font-size-subtitle);
}
/* Body Semi Bold */
h4 {
font-weight: 600;
font-size: var(--font-size-body);
}
h1,
h2,
h3 {
line-height: 1.2;
}
/* Body */
p {
font-size: var(--font-size-body);
line-height: var(--font-size-title);
}
hr {
width: calc(100% - 24px);
border: none;
border-top: 1px solid var(--cpd-color-border-interactive-secondary);
color: var(--cpd-color-border-interactive-secondary);
overflow: visible;
text-align: center;
height: 5px;
font-weight: 600;
font-size: var(--font-size-body);
line-height: 24px;
margin: 0 12px;
}
summary {
font-size: var(--font-size-body);
}
details > :not(summary) {
margin-left: var(--font-size-body);
}
details[open] > summary {
margin-bottom: var(--font-size-body);
}
}
#root > [data-overlay-container] {
position: relative;
height: 100%;
}
/* normalize.css sets the focus rings on buttons in Firefox to an unusual custom
outline, which is inconsistent with our other components and is not sufficiently
visible to be accessible. This resets it back to 'auto'. */
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: auto;
}
+2 -16
View File
@@ -30,7 +30,6 @@ import {
import { getUrlParams } from "./UrlParams";
import { Config } from "./config/Config";
import { seedSettingsFromConfig } from "./settings/settings";
import { platform } from "./Platform";
import { isFailure } from "./utils/fetch";
import { initializeWidget, type WidgetHelpers } from "./widget";
import { enableExtendedLivekitLogs } from "./settings/settings.ts";
@@ -38,7 +37,7 @@ import {
type AnalyticsConfig,
PosthogAnalytics,
} from "./analytics/PosthogAnalytics.ts";
import { i18n } from "./utils/i18n.ts";
import { i18n, languageOfLocalePath } from "./utils/i18n.ts";
// This generates a map of locale names to their URL (based on import.meta.url), which looks like this:
// {
@@ -57,17 +56,7 @@ const getLocaleUrl = (
): string | undefined => locales[`../locales/${language}/${namespace}.json`];
const supportedLngs = [
...new Set(
Object.keys(locales).map((url) => {
// The URLs are of the form ../locales/en/app.json
// This extracts the language code from the URL
const lang = url.match(/\/([^/]+)\/[^/]+\.json$/)?.[1];
if (!lang) {
throw new Error(`Could not parse locale URL ${url}`);
}
return lang;
}),
),
...new Set(Object.keys(locales).map(languageOfLocalePath)),
];
// A backend that fetches the locale files from the URLs generated by the glob above
@@ -229,9 +218,6 @@ export class Initializer {
);
}
// Add the platform to the DOM, so CSS can query it
document.body.setAttribute("data-platform", platform);
// livekit logging configuration
setLKLogExtension((level, msg, context) => {
// we pass a synthetic logger name of "livekit" to the rageshake to make it easier to read
+4 -4
View File
@@ -148,7 +148,7 @@ describe("getSFUConfigWithOpenID", () => {
// Verify, that the request contains the expected delay parameters
if (
body.delay_id === "mock_delay_id" &&
body.delay_timeout === 10000 &&
body.delay_timeout === 3600000 &&
body.delay_cs_api_url === "https://homeserverserver.org/cs_api"
) {
return {
@@ -229,7 +229,7 @@ describe("getSFUConfigWithOpenID", () => {
expect(calls[0][0]).toStrictEqual("https://sfu.example.org/get_token");
expect(calls[0][1]).toStrictEqual({
// check if it uses correct delayID!
body: '{"room_id":"!example_room_id","slot_id":"m.call#ROOM","member":{"id":"@alice:example.org:DEVICE","claimed_user_id":"@alice:example.org","claimed_device_id":"DEVICE"},"delay_id":"mock_delay_id","delay_timeout":10000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
body: '{"room_id":"!example_room_id","slot_id":"m.call#ROOM","member":{"id":"@alice:example.org:DEVICE","claimed_user_id":"@alice:example.org","claimed_device_id":"DEVICE"},"delay_id":"mock_delay_id","delay_timeout":3600000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -239,7 +239,7 @@ describe("getSFUConfigWithOpenID", () => {
expect(calls[1][0]).toStrictEqual("https://sfu.example.org/sfu/get");
expect(calls[1][1]).toStrictEqual({
body: '{"room":"!example_room_id","device_id":"DEVICE","delay_id":"mock_delay_id","delay_timeout":10000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
body: '{"room":"!example_room_id","device_id":"DEVICE","delay_id":"mock_delay_id","delay_timeout":3600000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
headers: {
"Content-Type": "application/json",
},
@@ -284,7 +284,7 @@ describe("getSFUConfigWithOpenID", () => {
expect(calls[0][0]).toStrictEqual("https://sfu.example.org/get_token");
expect(calls[0][1]).toStrictEqual({
// check if it uses correct delayID!
body: '{"room_id":"!example_room_id","slot_id":"m.call#ROOM","member":{"id":"@alice:example.org:DEVICE","claimed_user_id":"@alice:example.org","claimed_device_id":"DEVICE"},"delay_id":"mock_delay_id","delay_timeout":10000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
body: '{"room_id":"!example_room_id","slot_id":"m.call#ROOM","member":{"id":"@alice:example.org:DEVICE","claimed_user_id":"@alice:example.org","claimed_device_id":"DEVICE"},"delay_id":"mock_delay_id","delay_timeout":3600000,"delay_cs_api_url":"https://matrix.homeserverserver.org"}',
method: "POST",
headers: {
"Content-Type": "application/json",
+15 -19
View File
@@ -19,7 +19,7 @@ import {
} from "../utils/errors";
import { doNetworkOperationWithRetry } from "../utils/matrix";
import { Config } from "../config/Config";
import { JwtEndpointVersion } from "../state/CallViewModel/localMember/LocalTransport";
import { MatrixRTCMode } from "../config/ConfigOptions";
/**
* Configuration and access tokens provided by the SFU on successful authentication.
@@ -80,11 +80,10 @@ export type OpenIDClientParts = Pick<
* @param serviceUrl The URL of the livekit SFU service
* @param roomId The room id used in the jwt request. This is NOT the livekit_alias. The jwt service will provide the alias. It maps matrix room ids <-> Livekit aliases.
* @param opts Additional options to modify which endpoint with which data will be used to acquire the jwt token.
* @param opts.forceJwtEndpoint This will use the old jwt endpoint which will create the rtc backend identity based on string concatenation
* instead of a hash.
* @param opts.matrixRTCMode Determines which version of the JWT endpoint to use, which affects whether the
* RTC backend identity is based on string concatenation (legacy) or a hash (Matrix 2.0).
* This function by default uses whatever is possible with the current jwt service installed next to the SFU.
* For remote connections this does not matter, since we will not publish there we can rely on the newest option.
* For our own connection we can only use the hashed version if we also send the new matrix2.0 sticky events.
* @param opts.delayEndpointBaseUrl The URL of the matrix homeserver.
* @param opts.delayId The delay id used for the jwt service to manage.
* @param logger optional logger.
@@ -97,7 +96,7 @@ export async function getSFUConfigWithOpenID(
serviceUrl: string,
roomId: string,
opts?: {
forceJwtEndpoint?: JwtEndpointVersion;
matrixRTCMode?: MatrixRTCMode;
delayEndpointBaseUrl?: string;
delayId?: string;
},
@@ -116,19 +115,18 @@ export async function getSFUConfigWithOpenID(
logger?.debug("Got openID token", openIdToken);
let sfuConfig: { url: string; jwt: string } | undefined;
const tryBothJwtEndpoints = opts?.forceJwtEndpoint === undefined; // This is for SFUs where we do not publish.
const tryBothJwtEndpoints = opts?.matrixRTCMode === undefined; // This is for SFUs where we do not publish.
const forceMatrix2Jwt =
opts?.forceJwtEndpoint === JwtEndpointVersion.Matrix_2_0;
const forceMatrix2Jwt = opts?.matrixRTCMode === MatrixRTCMode.Matrix_2_0;
// We want to start using the new endpoint (with optional delay delegation)
// if we can use both or if we are forced to use the new one.
if (tryBothJwtEndpoints || forceMatrix2Jwt) {
try {
logger?.info(
`Trying to get JWT with delegation for focus ${serviceUrl}...`,
`Trying to get JWT via default endpoint for focus ${serviceUrl}...`,
);
const sfuConfig = await getLiveKitJWTWithDelayDelegation(
const sfuConfig = await getLiveKitJWT(
membership,
serviceUrl,
roomId,
@@ -154,7 +152,7 @@ export async function getSFUConfigWithOpenID(
logger?.info(
`Trying to get JWT with legacy endpoint for focus ${serviceUrl}...`,
);
sfuConfig = await getLiveKitJWT(
sfuConfig = await getLiveKitJWTLegacy(
membership.deviceId,
serviceUrl,
roomId,
@@ -188,7 +186,7 @@ function extractFullConfigFromToken(sfuConfig: {
};
}
async function getLiveKitJWT(
async function getLiveKitJWTLegacy(
deviceId: string,
livekitServiceURL: string,
matrixRoomId: string,
@@ -204,11 +202,10 @@ async function getLiveKitJWT(
let bodyDalayParts: IDelayParams = {};
// Also check for empty string
if (delayId && delayEndpointBaseUrl) {
const delayTimeoutMs =
Config.get().matrix_rtc_session?.delayed_leave_event_delay_ms;
bodyDalayParts = {
delay_id: delayId,
delay_timeout: delayTimeoutMs,
delay_timeout:
Config.get().matrix_rtc_session.delegated_delayed_leave.delay_ms,
delay_cs_api_url: delayEndpointBaseUrl,
};
}
@@ -264,7 +261,7 @@ class NotSupportedError extends Error {
}
}
export async function getLiveKitJWTWithDelayDelegation(
export async function getLiveKitJWT(
membership: CallMembershipIdentityParts,
livekitServiceURL: string,
matrixRoomId: string,
@@ -288,11 +285,10 @@ export async function getLiveKitJWTWithDelayDelegation(
let bodyDalayParts = {};
// Also check for empty string
if (delayId && delayEndpointBaseUrl) {
const delayTimeoutMs =
Config.get().matrix_rtc_session?.delayed_leave_event_delay_ms;
bodyDalayParts = {
delay_id: delayId,
delay_timeout: delayTimeoutMs,
delay_timeout:
Config.get().matrix_rtc_session.delegated_delayed_leave.delay_ms,
delay_cs_api_url: delayEndpointBaseUrl,
};
}
+1 -1
View File
@@ -74,7 +74,7 @@ Please see LICENSE in the repository root for full details.
margin-bottom: 44px;
}
@media (min-width: 800px) {
@container element-call (min-width: 800px) {
.logo {
display: none;
}
+11 -9
View File
@@ -9,8 +9,6 @@ import { type FC, type FormEventHandler, useCallback, useState } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { Trans, useTranslation } from "react-i18next";
import { Button, Heading, Text } from "@vector-im/compound-web";
import { useNavigate } from "react-router-dom";
import { logger } from "matrix-js-sdk/lib/logger";
import styles from "./CallEndedView.module.css";
import feedbackStyle from "../input/FeedbackInput.module.css";
@@ -19,8 +17,9 @@ import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { FieldRow, InputField } from "../input/Input";
import { StarRatingInput } from "../input/StarRatingInput";
import { Link } from "../button/Link";
import { LinkButton } from "../button";
import { LeaveToHomeLink } from "../button/LeaveToHomeLink";
import { useLeaveToHome } from "../LeaveToHomeContext";
interface Props {
client: MatrixClient;
@@ -38,7 +37,7 @@ export const CallEndedView: FC<Props> = ({
endedCallId,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const leaveToHome = useLeaveToHome();
const { displayName } = useProfile(client);
const [surveySubmitted, setSurveySubmitted] = useState(false);
@@ -68,14 +67,12 @@ export const CallEndedView: FC<Props> = ({
setSurveySubmitted(true);
} else if (!confineToRoom) {
// if the user already has an account immediately go back to the home screen
navigate("/")?.catch((error) => {
logger.error("Failed to navigate to /", error);
});
leaveToHome?.();
}
}, 1000);
}, 1000);
},
[endedCallId, navigate, isPasswordlessUser, confineToRoom, starRating],
[endedCallId, leaveToHome, isPasswordlessUser, confineToRoom, starRating],
);
const createAccountDialog = isPasswordlessUser && (
@@ -87,6 +84,8 @@ export const CallEndedView: FC<Props> = ({
calls
</p>
</Trans>
{/* Only guests of the standalone app are ever passwordless, so this
route is always the standalone app's own. */}
<LinkButton className={styles.callEndedButton} to="/register">
{t("call_ended_view.create_account_button")}
</LinkButton>
@@ -157,7 +156,10 @@ export const CallEndedView: FC<Props> = ({
</main>
{!confineToRoom && (
<Text className={styles.footer}>
<Link to="/"> {t("call_ended_view.not_now_button")} </Link>
<LeaveToHomeLink>
{" "}
{t("call_ended_view.not_now_button")}{" "}
</LeaveToHomeLink>
</Text>
)}
</div>
@@ -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.
*/
// TODO-MULTI-SFU: Restore or discard these tests. The role of GroupCallView has
// TODO-MULTI-SFU: Restore or discard these tests. The role of CallView has
// changed (it no longer manages the connection to the same extent), so they may
// need extra work to adapt.
@@ -36,6 +36,8 @@ import userEvent, {
import { type RelationsContainer } from "matrix-js-sdk/lib/models/relations-container";
import { useState } from "react";
import { TooltipProvider } from "@vector-im/compound-web";
import { Subject } from "rxjs";
import { Room as LivekitRoom } from "livekit-client";
import { prefetchSounds } from "../soundUtils";
import { useAudioContext } from "../useAudioContext";
@@ -49,18 +51,19 @@ import {
mockRtcMembership,
MockRTCSession,
} from "../utils/test";
import { GroupCallView } from "./GroupCallView";
import { CallView } from "./CallView";
import { GroupCallErrorBoundary } from "./GroupCallErrorBoundary";
import {
type HostBridge,
HostBridgeProvider,
type HostRequest,
nullHostBridge,
} from "../HostBridge";
import { type JoinCallData } from "../widget";
import { MatrixRTCTransportMissingError } from "../utils/errors";
import { ProcessorProvider } from "../livekit/TrackProcessorContext";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { constant } from "../state/Behavior";
import { type MuteStates } from "../state/MuteStates.ts";
vi.mock("../soundUtils");
vi.mock("../useAudioContext");
@@ -119,7 +122,7 @@ beforeEach(() => {
playSoundLooping: vi.fn(),
soundDuration: {},
});
// A trivial implementation of Active call to ensure we are testing GroupCallView exclusively here.
// A trivial implementation of Active call to ensure we are testing CallView exclusively here.
(ActiveCall as MockedFunction<typeof ActiveCall>).mockImplementation(
({ onLeft: onLeave }) => {
return (
@@ -135,11 +138,13 @@ beforeEach(() => {
);
});
function createGroupCallView(
function createCallView(
hostBridge: HostBridge,
joined = true,
options: {
withErrorBoundary?: boolean;
/** Wait for the host to say when to join, rather than joining at once. */
preload?: boolean;
} = {},
): {
rtcSession: MatrixRTCSession;
@@ -172,23 +177,15 @@ function createGroupCallView(
constant([localRtcMember]),
);
rtcSession.joined = joined;
const muteState = {
audio: { enabled: false },
video: { enabled: false },
// TODO-MULTI-SFU: This cast isn't valid, it's likely the cause of some current test failures
} as unknown as MuteStates;
const groupCallView = (
<GroupCallView
const callView = (
<CallView
client={client}
isPasswordlessUser={false}
confineToRoom={false}
preload={false}
skipLobby={false}
preload={options.preload ?? false}
// Straight into the (mocked) call, past the lobby
skipLobby
rtcSession={rtcSession.asMockedSession()}
muteStates={muteState}
// TODO-MULTI-SFU: Make joined and setJoined work
joined={true}
setJoined={function (value: boolean): void {}}
/>
);
const { getByText } = render(
@@ -199,10 +196,10 @@ function createGroupCallView(
<ProcessorProvider>
{options.withErrorBoundary ? (
<GroupCallErrorBoundary recoveryActionHandler={vi.fn()}>
{groupCallView}
{callView}
</GroupCallErrorBoundary>
) : (
groupCallView
callView
)}
</ProcessorProvider>
</MediaDevicesContext>
@@ -216,9 +213,9 @@ function createGroupCallView(
};
}
test.skip("GroupCallView plays a leave sound asynchronously in SPA mode", async () => {
test.skip("CallView plays a leave sound asynchronously in SPA mode", async () => {
const user = userEvent.setup();
const { getByText, rtcSession } = createGroupCallView(nullHostBridge);
const { getByText, rtcSession } = createCallView(nullHostBridge);
const leaveButton = getByText("Leave");
await user.click(leaveButton);
expect(playSound).toHaveBeenCalledWith("left");
@@ -233,7 +230,7 @@ test.skip("GroupCallView plays a leave sound asynchronously in SPA mode", async
await waitFor(() => expect(leaveRTCSession).toHaveResolved());
});
test.skip("GroupCallView plays a leave sound synchronously in widget mode", async () => {
test.skip("CallView plays a leave sound synchronously in widget mode", async () => {
const user = userEvent.setup();
const hostBridge: HostBridge = { ...nullHostBridge, close: vi.fn() };
let resolvePlaySound: () => void;
@@ -248,7 +245,7 @@ test.skip("GroupCallView plays a leave sound synchronously in widget mode", asyn
soundDuration: {},
});
const { getByText, rtcSession } = createGroupCallView(hostBridge);
const { getByText, rtcSession } = createCallView(hostBridge);
const leaveButton = getByText("Leave");
await user.click(leaveButton);
await flushPromises();
@@ -281,7 +278,7 @@ test("Should ask the host to close when all other left and play a sound", async
soundDuration: {},
});
const { getByText } = createGroupCallView(hostBridge);
const { getByText } = createCallView(hostBridge);
const leaveButton = getByText("SimulateOtherLeft");
await user.click(leaveButton);
await flushPromises();
@@ -292,6 +289,26 @@ test("Should ask the host to close when all other left and play a sound", async
await waitFor(() => expect(close).toHaveBeenCalledOnce());
}, 80000);
test("Waits for the host to say when to join, when preloaded", async () => {
// Nothing to match device names against; the host names none anyway
vi.spyOn(LivekitRoom, "getLocalDevices").mockResolvedValue([]);
const join$ = new Subject<HostRequest<JoinCallData>>();
const hostBridge: HostBridge = { ...nullHostBridge, join$ };
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();
const reply = vi.fn();
act(() =>
join$.next({ data: { audioInput: null, videoInput: null }, reply }),
);
// Then in the call, and the host told so
await waitFor(() => expect(reply).toHaveBeenCalledOnce());
expect(screen.getByText("Leave")).toBeInTheDocument();
});
test("Should not ask the host to close when auto leave due to error", async () => {
const user = userEvent.setup();
@@ -303,7 +320,7 @@ test("Should not ask the host to close when auto leave due to error", async () =
close,
};
const { getByText } = createGroupCallView(hostBridge);
const { getByText } = createCallView(hostBridge);
const leaveButton = getByText("SimulateErrorLeft");
await user.click(leaveButton);
await flushPromises();
@@ -315,7 +332,7 @@ test("Should not ask the host to close when auto leave due to error", async () =
expect(close).not.toHaveBeenCalled();
});
test.skip("GroupCallView leaves the session when an error occurs", async () => {
test.skip("CallView leaves the session when an error occurs", async () => {
(ActiveCall as MockedFunction<typeof ActiveCall>).mockImplementation(() => {
const [error, setError] = useState<Error | null>(null);
if (error !== null) throw error;
@@ -326,7 +343,7 @@ test.skip("GroupCallView leaves the session when an error occurs", async () => {
);
});
const user = userEvent.setup();
const { rtcSession } = createGroupCallView(nullHostBridge);
const { rtcSession } = createCallView(nullHostBridge);
await user.click(screen.getByRole("button", { name: "Panic!" }));
screen.getByText("Something went wrong");
expect(leaveRTCSession).toHaveBeenCalledWith(
@@ -336,14 +353,14 @@ test.skip("GroupCallView leaves the session when an error occurs", async () => {
);
});
test.skip("GroupCallView shows errors that occur during joining", async () => {
test.skip("CallView shows errors that occur during joining", async () => {
const user = userEvent.setup();
// This should not mock this error that deep. it should only mock the CallViewModel.
enterRTCSession.mockRejectedValue(new MatrixRTCTransportMissingError(""));
onTestFinished(() => {
enterRTCSession.mockReset();
});
createGroupCallView(nullHostBridge, false);
createCallView(nullHostBridge, false);
await user.click(screen.getByRole("button", { name: "Join call" }));
screen.getByText("Call is not supported");
});
@@ -362,7 +379,7 @@ test("translates wrapped UnsupportedStickyEventsEndpointError to the StickyEvent
{ cause: stickyError },
);
const { rtcSession } = createGroupCallView(nullHostBridge, true, {
const { rtcSession } = createCallView(nullHostBridge, true, {
withErrorBoundary: true,
});
@@ -374,7 +391,7 @@ test("translates wrapped UnsupportedStickyEventsEndpointError to the StickyEvent
});
test("falls back to ConnectionLostError for unrecognised membership manager errors", async () => {
const { rtcSession } = createGroupCallView(nullHostBridge, true, {
const { rtcSession } = createCallView(nullHostBridge, true, {
withErrorBoundary: true,
});
@@ -390,7 +407,7 @@ test("falls back to ConnectionLostError for unrecognised membership manager erro
test("user can reconnect after a membership manager error", async () => {
const user = userEvent.setup();
const { rtcSession } = createGroupCallView(nullHostBridge, true);
const { rtcSession } = createCallView(nullHostBridge, true);
await act(() =>
rtcSession.emit(MatrixRTCSessionEvent.MembershipManagerError, undefined),
);
@@ -28,7 +28,6 @@ import {
MatrixRTCSessionEvent,
type MatrixRTCSession,
} from "matrix-js-sdk/lib/matrixrtc";
import { useNavigate } from "react-router-dom";
import { type JoinCallData } from "../widget";
import { LobbyView } from "./LobbyView";
@@ -57,7 +56,6 @@ import {
type CallEventSounds,
} from "./CallEventAudioRenderer";
import { useLatest } from "../useLatest";
import { usePageTitle } from "../usePageTitle";
import {
ConnectionLostError,
E2EENotSupportedError,
@@ -72,6 +70,8 @@ import { useAppBarTitle } from "../AppBar.tsx";
import { useBehavior } from "../useBehavior.ts";
import { useRootElement } from "../RootElementContext.ts";
import { useHostBridge } from "../HostBridge.ts";
import { useMuteStates } from "../state/useMuteStates.ts";
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
/**
* If there already are this many participants in the call, we automatically mute
@@ -86,18 +86,67 @@ declare global {
}
interface Props {
/** The client to place the call with. */
client: MatrixClient;
isPasswordlessUser: boolean;
confineToRoom: boolean;
preload: UrlParams["preload"];
skipLobby: UrlParams["skipLobby"];
/** The call to join. */
rtcSession: MatrixRTCSession;
/**
* Whether the user is signed in as a guest, and so should be offered the
* chance to create an account when the call ends.
*/
isPasswordlessUser: boolean;
/** Whether to keep the user in this call rather than letting them navigate. */
confineToRoom: boolean;
/** Whether to wait for the host to ask us to join. */
preload: UrlParams["preload"];
/** Whether to enter the call directly, without showing the lobby first. */
skipLobby: UrlParams["skipLobby"];
}
/**
* A call, from start to finish.
*
* This owns the whole lifecycle of being in a call: the lobby, where the user
* checks their camera and microphone before joining; the call itself; and the
* screen shown once it has ended. Not every call has every stage — the lobby
* is skipped when the user is put straight into the call, or when the host
* wants to say when to join; and after the call there may be a post-call
* screen, a return to the lobby, or nothing, depending on whether the host
* decides what comes next. The view decides which stages apply from the
* parameters it was started with and from what the host bridge says.
*
* It owns nothing about how Element Call came to be showing a call: no
* routing, no authentication, no resolving of room aliases. Those belong to
* whatever is hosting it — the standalone app's own shell, or an application
* embedding Element Call as a component. Both render this.
*/
export const CallView: FC<Props> = (props): ReactNode => {
// Whether the user is in the call is the call's own business, not its host's.
// Held here rather than below so that it survives the mute state being
// rebuilt.
const [joined, setJoined] = useState(false);
const muteStates = useMuteStates();
if (muteStates === null) return null;
return (
<LoadedCallView
{...props}
joined={joined}
setJoined={setJoined}
muteStates={muteStates}
/>
);
};
interface LoadedProps extends Props {
joined: boolean;
setJoined: (value: boolean) => void;
muteStates: MuteStates;
}
export const GroupCallView: FC<Props> = ({
/** {@link CallView}, once it has the mute state everything below needs. */
const LoadedCallView: FC<LoadedProps> = ({
client,
isPasswordlessUser,
confineToRoom,
@@ -117,10 +166,8 @@ export const GroupCallView: FC<Props> = ({
const hostBridge = useHostBridge();
// A host that can close us is a host that decides when we stop existing, so
// we neither show our own post-call screens nor assume we have time to
// finish what we are doing.
// TODO: this reads a capability as a proxy for who owns our lifetime. Worth
// finding a more direct way to express it — see the guidance in UrlParams.ts
// on naming behaviours rather than situations.
// finish what we are doing. (Whose account the user's is, by contrast, is
// stated outright: see `HostBridge.supportsProfileChanges`.)
const hostControlsLifetime = hostBridge.close !== undefined;
const muteAllAudio = useBehavior(muteAllAudio$);
@@ -139,9 +186,9 @@ export const GroupCallView: FC<Props> = ({
}, []);
useEffect(() => {
logger.info("[Lifecycle] GroupCallView Component mounted");
logger.info("[Lifecycle] CallView Component mounted");
return (): void => {
logger.info("[Lifecycle] GroupCallView Component unmounted");
logger.info("[Lifecycle] CallView Component unmounted");
};
}, []);
@@ -208,7 +255,6 @@ export const GroupCallView: FC<Props> = ({
if (passwordFromUrl) saveKeyForRoom(room.roomId, passwordFromUrl);
}, [passwordFromUrl, room.roomId]);
usePageTitle(roomName);
useAppBarTitle(roomName);
const matrixInfo = useMemo((): MatrixInfo => {
@@ -328,7 +374,7 @@ export const GroupCallView: FC<Props> = ({
// TODO refactor this + "joined" to just one callState
const [left, setLeft] = useState(false);
const navigate = useNavigate();
const leaveToHome = useLeaveToHome();
// TODO split this into leave and onDisconnect
const onLeft = useCallback(
@@ -387,7 +433,7 @@ export const GroupCallView: FC<Props> = ({
!confineToRoom &&
!PosthogAnalytics.instance.isEnabled()
)
void navigate("/");
leaveToHome?.();
// After this point the host could dispose of us at any moment!
try {
@@ -416,7 +462,7 @@ export const GroupCallView: FC<Props> = ({
isPasswordlessUser,
confineToRoom,
returnToLobby,
navigate,
leaveToHome,
],
);
+32 -21
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, test, vi } from "vitest";
import { describe, expect, onTestFinished, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import {
type FC,
@@ -14,7 +14,7 @@ import {
useCallback,
useState,
} from "react";
import { BrowserRouter } from "react-router-dom";
import { LeaveToHomeProvider } from "../LeaveToHomeContext";
import userEvent from "@testing-library/user-event";
import { ConnectionError } from "livekit-client";
import { MatrixError } from "matrix-js-sdk";
@@ -42,6 +42,9 @@ import {
nullHostBridge,
} from "../HostBridge.ts";
// Somewhere to go home to, so that the error pages offer the way
const leaveToHome = vi.fn();
test.each([
{
error: new MatrixRTCTransportMissingError("example.com"),
@@ -79,14 +82,14 @@ test.each([
const onErrorMock = vi.fn();
const { asFragment } = render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary
onError={onErrorMock}
recoveryActionHandler={vi.fn()}
>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText(expectedTitle);
@@ -106,15 +109,19 @@ test("should render the error page with link back to home", async () => {
};
const onErrorMock = vi.fn();
// From the home page itself the home button reloads instead of navigating,
// so be somewhere else for this test
window.history.pushState({}, "", "/room/somewhere");
onTestFinished(() => window.history.pushState({}, "", "/"));
const { asFragment } = render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary
onError={onErrorMock}
recoveryActionHandler={vi.fn()}
>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText("Call is not supported");
@@ -123,7 +130,11 @@ test("should render the error page with link back to home", async () => {
screen.getByText(/Error Code: MISSING_MATRIX_RTC_TRANSPORT/i),
).toBeInTheDocument();
await screen.findByRole("button", { name: "Return to home screen" });
// The way home is whatever the shell supplied, not a route of the call's own
await userEvent
.setup()
.click(screen.getByRole("button", { name: "Return to home screen" }));
expect(leaveToHome).toHaveBeenCalledOnce();
expect(onErrorMock).toHaveBeenCalledOnce();
expect(onErrorMock).toHaveBeenCalledWith(error);
@@ -155,11 +166,11 @@ test("ConnectionLostError: Action handling should reset error state", async () =
);
return (
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary recoveryActionHandler={reconnectCallback}>
<TestComponent fail={failState} />
</GroupCallErrorBoundary>
</BrowserRouter>
</LeaveToHomeProvider>
);
};
@@ -194,14 +205,14 @@ describe("Rageshake button", () => {
};
render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary
onError={vi.fn()}
recoveryActionHandler={vi.fn()}
>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
}
@@ -234,7 +245,7 @@ test("should have a close button when the host can dismiss us", async () => {
const user = userEvent.setup();
const onErrorMock = vi.fn();
const { asFragment } = render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<HostBridgeProvider value={hostBridge}>
<GroupCallErrorBoundary
onError={onErrorMock}
@@ -243,7 +254,7 @@ test("should have a close button when the host can dismiss us", async () => {
<TestComponent />
</GroupCallErrorBoundary>
</HostBridgeProvider>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText("Call is not supported");
@@ -273,11 +284,11 @@ test("should show technical details when error has a matrixError cause", async (
};
render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary onError={vi.fn()} recoveryActionHandler={vi.fn()}>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText("Something went wrong");
@@ -302,11 +313,11 @@ test("should not show technical details when error has no matrix error cause", a
};
render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary onError={vi.fn()} recoveryActionHandler={vi.fn()}>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText("Connection lost");
@@ -356,14 +367,14 @@ describe("LiveKit ConnectionError variants", () => {
};
const { asFragment } = render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary
onError={vi.fn()}
recoveryActionHandler={vi.fn()}
>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
// Check title
@@ -385,14 +396,14 @@ describe("LiveKit ConnectionError variants", () => {
};
const { asFragment } = render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<GroupCallErrorBoundary
onError={vi.fn()}
recoveryActionHandler={vi.fn()}
>
<TestComponent />
</GroupCallErrorBoundary>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
await screen.findByText("Connection timeout");
+1 -1
View File
@@ -75,7 +75,7 @@ spotlight tile is maximised and displaying video, apply a gradient background. *
background: none;
}
@media (max-width: 320px) {
@container element-call (max-width: 320px) {
.invite {
display: none;
}
+69 -1
View File
@@ -14,7 +14,7 @@ import {
type MockedFunction,
vi,
} from "vitest";
import { render, type RenderResult } from "@testing-library/react";
import { act, render, type RenderResult } from "@testing-library/react";
import { type LocalParticipant } from "livekit-client";
import { BehaviorSubject, of } from "rxjs";
import { BrowserRouter } from "react-router-dom";
@@ -51,6 +51,7 @@ import { AppBar } from "../AppBar";
import { type MatrixInfo } from "./VideoPreview";
import { ProcessorProvider } from "../livekit/TrackProcessorContext";
import { initializeWidget } from "../widget";
import { RootElementProvider } from "../RootElementContext";
initializeWidget();
vi.hoisted(
@@ -263,4 +264,71 @@ describe("ActiveCall", () => {
// Rendering at all proves ActiveCall created all of its view models
expect(await findByTestId("incall_leave")).toBeVisible();
});
it("lays the call out for the size of its root element", async () => {
// jsdom has no layout and no ResizeObserver: the root reports whatever
// size we say, and the observer notifies whenever we tell it to
let size = { width: 1000, height: 800 };
const root = document.createElement("div");
Object.defineProperty(root, "clientWidth", { get: () => size.width });
Object.defineProperty(root, "clientHeight", { get: () => size.height });
document.body.appendChild(root);
const observers: (() => void)[] = [];
const originalResizeObserver = window.ResizeObserver;
window.ResizeObserver = class {
public constructor(private readonly callback: ResizeObserverCallback) {}
public observe(): void {
observers.push(() => this.callback([], this as ResizeObserver));
}
public unobserve(): void {}
public disconnect(): void {}
} as unknown as typeof ResizeObserver;
try {
const mediaDevices = mockMediaDevices({});
const { rtcSession, matrixRoom } = getBasicRTCSession([local, alice]);
const { findByTestId, container } = render(
<BrowserRouter>
<RootElementProvider value={root}>
<MediaDevicesContext value={mediaDevices}>
<ProcessorProvider>
<TooltipProvider>
<RoomContext value={mockLivekitRoom({ localParticipant })}>
<ActiveCall
client={matrixRoom.client}
rtcSession={rtcSession.asMockedSession()}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
onLeft={(): void => {}}
/>
</RoomContext>
</TooltipProvider>
</ProcessorProvider>
</MediaDevicesContext>
</RootElementProvider>
</BrowserRouter>,
{ container: root },
);
await findByTestId("incall_leave");
const call = container.querySelector("[data-layout]")!;
expect(call.getAttribute("data-layout")).not.toBe("pip");
// The host shrinks the container to a corner of its page. The window has
// not changed at all — what matters is the element we were given.
size = { width: 300, height: 300 };
act(() => observers.forEach((notify) => notify()));
expect(call.getAttribute("data-layout")).toBe("pip");
size = { width: 1000, height: 800 };
act(() => observers.forEach((notify) => notify()));
expect(call.getAttribute("data-layout")).not.toBe("pip");
} finally {
window.ResizeObserver = originalResizeObserver;
root.remove();
}
});
});
+48 -8
View File
@@ -29,6 +29,8 @@ import { Header, LeftNav, RightNav, RoomHeaderInfo } from "../Header";
import { HeaderStyle, useUrlParams } from "../UrlParams";
import { useCallViewKeyboardShortcuts } from "../useCallViewKeyboardShortcuts";
import { useHostBridge } from "../HostBridge.ts";
import { useRootElement } from "../RootElementContext";
import { observeElementSize$ } from "../utils/elementSize";
import styles from "./InCallView.module.css";
import { GridTile } from "../tile/GridTile";
import { SettingsModal, defaultSettingsTab } from "../settings/SettingsModal";
@@ -120,6 +122,9 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const hostBridge = useHostBridge();
const mediaDevices = useMediaDevices();
const trackProcessorState$ = useTrackProcessorObservable$();
// The element we have to draw the call in: the page, or the container a host
// gave us. Its size, not the window's, decides how the call is laid out.
const rootElement = useRootElement();
useEffect(() => {
rootLogger.info("START CALL VIEW SCOPE");
const scope = new ObservableScope();
@@ -139,7 +144,10 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
hostBridge,
autoLeaveWhenOthersLeft,
waitForCallPickup: waitForCallPickup && sendNotificationType === "ring",
matrixRTCMode$: matrixRTCModeSetting.value$,
// We merely sample the current mode here, so the user would need to
// manually rejoin to switch to a different one.
matrixRTCMode: matrixRTCModeSetting.value$.value,
windowSize$: scope.behavior(observeElementSize$(rootElement)),
},
reactionsReader.raisedHands$,
reactionsReader.reactions$,
@@ -165,6 +173,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
mediaDevices,
trackProcessorState$,
props.client,
rootElement,
]);
useEffect(() => {
@@ -258,6 +267,20 @@ export const InCallView: FC<InCallViewProps> = ({
// Merge the refs so they can attach to the same element
const containerRef = useMergedRefs(containerRef1, containerRef2);
// The fixed grid is positioned against Element Call's root, so offsets
// handed to it have to be measured from there rather than from the
// viewport. Standalone the two are the same, the root being the page; for a
// component the root sits wherever the host put it, and measuring from the
// viewport would push the grid down by that much again. Taken at the same
// moment as `bounds`, so that the two agree however the host has scrolled.
const rootElement = useRootElement();
const rootTop = useMemo(
() => rootElement.getBoundingClientRect().top,
// eslint-disable-next-line react-hooks/exhaustive-deps
[rootElement, bounds],
);
const topWithinRoot = bounds.top - rootTop;
const { showControls, header: headerStyle } = useUrlParams();
const muteAllAudio = useBehavior(muteAllAudio$);
@@ -277,6 +300,7 @@ export const InCallView: FC<InCallViewProps> = ({
const audioParticipants = useBehavior(vm.livekitRoomItems$);
const participantCount = useBehavior(vm.participantCount$);
const reconnecting = useBehavior(vm.reconnecting$);
const screenShareError = useBehavior(vm.screenShareError$);
const layout = useBehavior(vm.layout$);
const edgeToEdge = useBehavior(vm.edgeToEdge$);
const overflowing = useBehavior(vm.overflowing$);
@@ -322,11 +346,8 @@ export const InCallView: FC<InCallViewProps> = ({
const openProfile = useMemo(
() =>
// A host that can dismiss us is a host that owns the user's account, so
// their profile is not ours to edit.
// TODO: another use of the close capability as a proxy — see the note in
// GroupCallView.
hostBridge.close === undefined
// The profile is only ours to edit when the account is ours
hostBridge.supportsProfileChanges
? (): void => {
setSettingsTab("profile");
setSettingsOpen(true);
@@ -409,6 +430,21 @@ export const InCallView: FC<InCallViewProps> = ({
);
}
const onDismissScreenShareToast = useCallback(
() => vm.dismissScreenShareError(),
[vm],
);
const screenShareToast = (
<Toast
onDismiss={onDismissScreenShareToast}
open={screenShareError !== null}
autoDismiss={5000}
modal={false}
>
{t("error.screen_share_failed")}
</Toast>
);
// The reconnecting toast cannot be dismissed
const onDismissReconnectingToast = useCallback(() => {}, []);
// We need to use a non-modal toast to avoid trapping focus within the toast.
@@ -542,7 +578,7 @@ export const InCallView: FC<InCallViewProps> = ({
className={styles.fixedGrid}
style={{
// If not edge-to-edge, consume the header insets right here.
insetBlockStart: edgeToEdge ? 0 : bounds.top + headerBounds.height,
insetBlockStart: edgeToEdge ? 0 : topWithinRoot + headerBounds.height,
height: edgeToEdge ? "100%" : gridBounds.height,
// If edge-to-edge, compute new safe area insets that account for the
// header and footer, passing them down to the tiles.
@@ -553,7 +589,7 @@ export const InCallView: FC<InCallViewProps> = ({
// itself. Otherwise account for the safe area and header size
// as part of the InCallView.
headerStyle === HeaderStyle.AppBar
? `${bounds.top}px`
? `${topWithinRoot}px`
: `calc(env(safe-area-inset-top) + ${headerBounds.height}px)`
: undefined,
"--call-view-safe-area-inset-bottom":
@@ -625,6 +661,9 @@ export const InCallView: FC<InCallViewProps> = ({
[styles.overflowing]: overflowing,
})}
ref={containerRef}
// Which layout the call has settled on, for tests and for anyone
// wondering why the call looks the way it does at the size it was given
data-layout={layout.type}
onPointerUp={onViewPointerUp}
onPointerMove={onPointerMove}
onPointerOut={onPointerOut}
@@ -644,6 +683,7 @@ export const InCallView: FC<InCallViewProps> = ({
<ReactionsAudioRenderer vm={vm} muted={muteAllAudio} />
<RingingAudioRenderer vm={ringingVm} muted={muteAllAudio} />
{reconnectingToast}
{screenShareToast}
{earpieceOverlay}
<ReactionsOverlay vm={vm} />
{footer}
+95
View File
@@ -0,0 +1,95 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { TooltipProvider } from "@vector-im/compound-web";
import { type MatrixClient, type RoomSummary } from "matrix-js-sdk";
import { KnockLobbyView } from "./KnockLobbyView";
import { LeaveToHomeProvider } from "../LeaveToHomeContext";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { type ProcessorState } from "../livekit/TrackProcessorContext";
import { mockMediaDevices } from "../utils/test";
vi.mock("@livekit/components-react", () => ({
usePreviewTracks: (): unknown[] => [],
}));
vi.mock("../livekit/TrackProcessorContext", () => ({
useTrackProcessor: (): ProcessorState => ({
supported: false,
processor: undefined,
}),
useTrackProcessorSync: (): void => {},
}));
vi.mock("react-use-measure", () => ({
default: (): [() => void, object] => [(): void => {}, {}],
}));
vi.mock("../settings/SettingsModal", () => ({
SettingsModal: (): null => null,
defaultSettingsTab: "general",
}));
const client = {
getUserId: () => "@user:example.org",
getDeviceId: () => "DEVICE",
} as Partial<MatrixClient> as MatrixClient;
// What peeking at a room we are not in tells us about it
const roomSummary = {
room_id: "!room:example.org",
name: "Knock Room",
"im.nheko.summary.encryption": "m.megolm.v1.aes-sha2",
} as Partial<RoomSummary> as RoomSummary;
function renderKnockLobby(knock: (() => void) | null): void {
render(
<LeaveToHomeProvider value={vi.fn()}>
<MediaDevicesContext value={mockMediaDevices({})}>
<TooltipProvider>
<KnockLobbyView
client={client}
roomSummary={roomSummary}
profile={{ displayName: "Test User", avatarUrl: "" }}
knock={knock}
confineToRoom={false}
hideHeader={false}
/>
</TooltipProvider>
</MediaDevicesContext>
</LeaveToHomeProvider>,
);
}
describe("KnockLobbyView", () => {
it("offers to ask to join, with what it knows of the room", async () => {
const knock = vi.fn();
renderKnockLobby(knock);
// The mute state arrives asynchronously, and the lobby with it
const button = await screen.findByTestId("lobby_joinCall");
expect(button).toHaveTextContent("Request to join call");
expect(button).toBeEnabled();
expect(screen.getByText("Knock Room")).toBeInTheDocument();
await userEvent.setup().click(button);
expect(knock).toHaveBeenCalledOnce();
});
it("waits once it has asked", async () => {
renderKnockLobby(null);
const button = await screen.findByTestId("lobby_joinCall");
expect(button).toHaveTextContent("Request sent!");
// Compound's button keeps focusable, saying so through ARIA instead
expect(button).toHaveAttribute("aria-disabled", "true");
});
});
+92
View File
@@ -0,0 +1,92 @@
/*
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 JSX, type ReactNode } from "react";
import { type MatrixClient, type RoomSummary } from "matrix-js-sdk";
import { useTranslation } from "react-i18next";
import { CheckIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import { LobbyView } from "./LobbyView";
import { E2eeType } from "../e2ee/e2eeType";
import { useMuteStates } from "../state/useMuteStates";
interface Props {
client: MatrixClient;
/** What we know about the room from peeking at it. */
roomSummary: RoomSummary;
/** The user's own name and avatar, to show in their own tile. */
profile: { displayName: string; avatarUrl: string };
/**
* Asks to be let in, if the room allows it. Absent once we have asked and
* are waiting for an answer.
*/
knock: (() => void) | null;
confineToRoom: boolean;
hideHeader: boolean;
}
/**
* The lobby shown while the user is outside a room they want to call in —
* either able to ask to join, or waiting for someone to answer.
*
* This belongs to the app shell rather than to the call: it exists precisely
* because there is no call to be in yet. It keeps its own mute state, which is
* why it is a component rather than part of the page — so that the call's mute
* state and this one are never alive at the same time, reporting over each
* other to the host.
*/
export const KnockLobbyView: FC<Props> = ({
client,
roomSummary,
profile,
knock,
confineToRoom,
hideHeader,
}): ReactNode => {
const { t } = useTranslation();
const muteStates = useMuteStates();
if (muteStates === null) return null;
const waitingForInvite = knock === null;
const enterLabel: string | JSX.Element = waitingForInvite ? (
<>
{t("lobby.waiting_for_invite")}
<CheckIcon />
</>
) : (
t("lobby.ask_to_join")
);
return (
<LobbyView
client={client}
matrixInfo={{
userId: client.getUserId() ?? "",
displayName: profile.displayName,
avatarUrl: profile.avatarUrl,
roomAlias: null,
roomId: roomSummary.room_id,
roomName: roomSummary.name ?? "",
roomAvatar: roomSummary.avatar_url ?? null,
e2eeSystem: {
kind: roomSummary["im.nheko.summary.encryption"]
? E2eeType.PER_PARTICIPANT
: E2eeType.NONE,
},
}}
onEnter={(): void => knock?.()}
enterLabel={enterLabel}
waitingForInvite={waitingForInvite}
confineToRoom={confineToRoom}
hideHeader={hideHeader}
participantCount={null}
muteStates={muteStates}
onShareClick={null}
/>
);
};
+2 -2
View File
@@ -28,13 +28,13 @@ Please see LICENSE in the repository root for full details.
color: var(--cpd-color-theme-primary) !important;
}
@media (max-width: 500px) {
@container element-call (max-width: 500px) {
.join {
width: 100%;
}
}
@media (min-height: 650px) {
@container element-call (min-height: 650px) {
.content {
gap: var(--cpd-space-10x);
}
+6 -3
View File
@@ -7,7 +7,7 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it, vi } from "vitest";
import { render } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { LeaveToHomeProvider } from "../LeaveToHomeContext";
import { TooltipProvider } from "@vector-im/compound-web";
import { type MatrixClient } from "matrix-js-sdk";
import { axe } from "vitest-axe";
@@ -26,6 +26,9 @@ import lobbyStyles from "./LobbyView.module.css";
import headerStyles from "../Header.module.css";
import { AppBar } from "../AppBar";
// Somewhere to go home to, so that the lobby offers the way back
const leaveToHome = vi.fn();
vi.mock("@livekit/components-react", () => ({
usePreviewTracks: (): unknown[] => [],
}));
@@ -93,14 +96,14 @@ function renderLobbyView(
/>
);
return render(
<BrowserRouter>
<LeaveToHomeProvider value={leaveToHome}>
<MediaDevicesContext value={mediaDevices}>
<TooltipProvider>
{withAppBar && <AppBar>{lobbyView}</AppBar>}
{!withAppBar && lobbyView}
</TooltipProvider>
</MediaDevicesContext>
</BrowserRouter>,
</LeaveToHomeProvider>,
);
}
+14 -16
View File
@@ -25,7 +25,6 @@ import {
Track,
} from "livekit-client";
import { useObservableEagerState } from "observable-hooks";
import { useNavigate } from "react-router-dom";
import inCallStyles from "./InCallView.module.css";
import styles from "./LobbyView.module.css";
@@ -34,9 +33,10 @@ import { type MatrixInfo, VideoPreview } from "./VideoPreview";
import { type MuteStates } from "../state/MuteStates";
import { InviteButton } from "../button/InviteButton";
import { SettingsModal, defaultSettingsTab } from "../settings/SettingsModal";
import { useMediaQuery } from "../useMediaQuery";
import { useRootSizeMatches } from "../useRootSize";
import { E2eeType } from "../e2ee/e2eeType";
import { Link } from "../button/Link";
import { LeaveToHomeLink } from "../button/LeaveToHomeLink";
import { useLeaveToHome } from "../LeaveToHomeContext";
import { useMediaDevices } from "../MediaDevicesContext";
import { ObservableScope } from "../state/ObservableScope";
import { useInitial } from "../useInitial";
@@ -44,7 +44,6 @@ import {
useTrackProcessor,
useTrackProcessorSync,
} from "../livekit/TrackProcessorContext";
import { usePageTitle } from "../usePageTitle";
import { getValue } from "../utils/observable";
import { useBehavior } from "../useBehavior";
import { CallFooter, type FooterSnapshot } from "../components/CallFooter";
@@ -87,7 +86,6 @@ export const LobbyView: FC<Props> = ({
const { t } = useTranslation();
usePageTitle(matrixInfo.roomName);
useAppBarPrimaryButtonIconKind("back");
const audioEnabled = useBehavior(muteStates.audio.enabled$);
const videoEnabled = useBehavior(muteStates.video.enabled$);
@@ -111,19 +109,19 @@ export const LobbyView: FC<Props> = ({
[setSettingsModalOpen],
);
const navigate = useNavigate();
const onLeaveClick = useCallback(() => {
navigate("/")?.catch((error) => {
logger.error("Failed to navigate to /", error);
});
}, [navigate]);
const hangup = confineToRoom ? undefined : onLeaveClick;
// Leaving the lobby means going back to wherever the user came from, if
// there is such a place
const leaveToHome = useLeaveToHome();
const hangup =
confineToRoom || leaveToHome === null ? undefined : leaveToHome;
const recentsButtonInFooter = useMediaQuery("(max-height: 500px)");
const recentsButtonInFooter = useRootSizeMatches(
({ height }) => height <= 500,
);
const recentsButton = !confineToRoom && (
<Link className={styles.recents} to="/">
<LeaveToHomeLink className={styles.recents}>
{t("lobby.leave_button")}
</Link>
</LeaveToHomeLink>
);
const devices = useMediaDevices();
@@ -209,7 +207,7 @@ export const LobbyView: FC<Props> = ({
return (): void => {
footerScope.end();
};
}, [devices, hangup, hideHeader, muteStates, onLeaveClick, openSettings]);
}, [devices, hangup, hideHeader, muteStates, openSettings]);
// TODO: Unify this component with InCallView, so we can get slick joining
// animations and don't have to feel bad about reusing its CSS
+9 -6
View File
@@ -3,8 +3,11 @@
display: inline;
z-index: 2;
pointer-events: none;
width: 100vw;
height: 100vh;
/* Percentages, not viewport units: the containing block is the element
Element Call treats as its root, which is the page in the standalone app but
the container a host gave us when embedded. */
width: 100%;
height: 100%;
left: 0;
top: 0;
}
@@ -16,7 +19,7 @@
animation-name: reaction-up;
width: fit-content;
position: relative;
top: 80vh;
top: 80%;
}
@keyframes reaction-up {
@@ -24,7 +27,7 @@
opacity: 1;
translate: 0 0;
scale: 200%;
top: 80vh;
top: 80%;
}
to {
@@ -48,7 +51,7 @@
.reaction {
font-size: 48pt;
animation-name: reaction-up-reduced;
top: calc(-50vh + (48pt / 2));
left: calc(50vw - (48pt / 2)) !important;
top: calc(-50% + (48pt / 2));
left: calc(50% - (48pt / 2)) !important;
}
}
+40 -94
View File
@@ -6,45 +6,30 @@ 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,
useState,
type ReactNode,
useRef,
type JSX,
} from "react";
import { type FC, useEffect, useState, type ReactNode, useRef } from "react";
import { type MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { Trans, useTranslation } from "react-i18next";
import {
CheckIcon,
UnknownSolidIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import { UnknownSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import { useClientLegacy } from "../ClientContext";
import { ErrorPage, FullScreenView, LoadingPage } from "../FullScreenView";
import { RoomAuthView } from "./RoomAuthView";
import { GroupCallView } from "./GroupCallView";
import { CallView } from "./CallView";
import { useRoomIdentifier, useUrlParams } from "../UrlParams";
import { useRegisterPasswordlessUser } from "../auth/useRegisterPasswordlessUser";
import { HomePage } from "../home/HomePage";
import { useHostBridge } from "../HostBridge.ts";
import { CallTerminatedMessage, useLoadGroupCall } from "./useLoadGroupCall";
import { LobbyView } from "./LobbyView";
import { E2eeType } from "../e2ee/e2eeType";
import { KnockLobbyView } from "./KnockLobbyView";
import { useProfile } from "../profile/useProfile";
import { useOptInAnalytics } from "../settings/settings";
import { Link } from "../button/Link";
import { ErrorView } from "../ErrorView";
import { useMediaDevices } from "../MediaDevicesContext";
import { MuteStates } from "../state/MuteStates";
import { ObservableScope } from "../state/ObservableScope";
import { calculateInitialMuteState } from "../state/initialMuteState.ts";
import { usePageTitle } from "../usePageTitle";
import { useRoomName } from "./useRoomName";
export const RoomPage: FC = (): ReactNode => {
const urlParams = useUrlParams();
const hostBridge = useHostBridge();
const { confineToRoom, preload, header, displayName, skipLobby } = urlParams;
const { t } = useTranslation();
const { roomAlias, roomId, viaServers } = useRoomIdentifier();
@@ -62,27 +47,20 @@ export const RoomPage: FC = (): ReactNode => {
const { avatarUrl, displayName: userDisplayName } = useProfile(client);
const groupCallState = useLoadGroupCall(client, roomIdOrAlias, viaServers);
const [joined, setJoined] = useState(false);
const devices = useMediaDevices();
const [muteStates, setMuteStates] = useState<MuteStates | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setMuteStates(
new MuteStates(
scope,
devices,
calculateInitialMuteState(
urlParams.skipLobby,
urlParams.callIntent,
urlParams.isWidget,
),
hostBridge,
),
);
return (): void => scope.end();
}, [devices, urlParams, hostBridge]);
// The page title is the page's to set, not the call's: a host embedding the
// call has a title of its own. So it is set here, for whichever room we have
// got as far as knowing about.
const roomName = useRoomName(
groupCallState.kind === "loaded" ? groupCallState.rtcSession.room : null,
);
usePageTitle(
roomName ??
(groupCallState.kind === "canKnock" ||
groupCallState.kind === "waitForInvite"
? groupCallState.roomSummary.name
: undefined),
);
useEffect(() => {
// If we've finished loading, are not already authed and we've been given a display name as
@@ -124,66 +102,34 @@ export const RoomPage: FC = (): ReactNode => {
switch (groupCallState.kind) {
case "loaded":
return (
muteStates && (
<GroupCallView
client={client!}
rtcSession={groupCallState.rtcSession}
joined={joined}
setJoined={setJoined}
isPasswordlessUser={passwordlessUser}
confineToRoom={confineToRoom}
preload={preload}
skipLobby={skipLobby || wasInWaitForInviteState.current}
muteStates={muteStates}
/>
)
<CallView
client={client!}
rtcSession={groupCallState.rtcSession}
isPasswordlessUser={passwordlessUser}
confineToRoom={confineToRoom}
preload={preload}
skipLobby={skipLobby || wasInWaitForInviteState.current}
/>
);
case "waitForInvite":
case "canKnock": {
wasInWaitForInviteState.current =
wasInWaitForInviteState.current ||
groupCallState.kind === "waitForInvite";
const knock =
groupCallState.kind === "canKnock" ? groupCallState.knock : null;
const label: string | JSX.Element =
groupCallState.kind === "canKnock" ? (
t("lobby.ask_to_join")
) : (
<>
{t("lobby.waiting_for_invite")}
<CheckIcon />
</>
);
return (
muteStates && (
<LobbyView
client={client!}
matrixInfo={{
userId: client!.getUserId() ?? "",
displayName: userDisplayName ?? "",
avatarUrl: avatarUrl ?? "",
roomAlias: null,
roomId: groupCallState.roomSummary.room_id,
roomName: groupCallState.roomSummary.name ?? "",
roomAvatar: groupCallState.roomSummary.avatar_url ?? null,
e2eeSystem: {
kind: groupCallState.roomSummary[
"im.nheko.summary.encryption"
]
? E2eeType.PER_PARTICIPANT
: E2eeType.NONE,
},
}}
onEnter={(): void => knock?.()}
enterLabel={label}
waitingForInvite={groupCallState.kind === "waitForInvite"}
confineToRoom={confineToRoom}
hideHeader={header !== "standard"}
participantCount={null}
muteStates={muteStates}
onShareClick={null}
/>
)
<KnockLobbyView
client={client!}
roomSummary={groupCallState.roomSummary}
profile={{
displayName: userDisplayName ?? "",
avatarUrl: avatarUrl ?? "",
}}
knock={
groupCallState.kind === "canKnock" ? groupCallState.knock : null
}
confineToRoom={confineToRoom}
hideHeader={header !== "standard"}
/>
);
}
case "loading":
+4 -2
View File
@@ -9,7 +9,9 @@ Please see LICENSE in the repository root for full details.
margin-left: var(--content-inset-left);
margin-right: var(--content-inset-right);
min-block-size: 0;
block-size: 50vh;
/* Half the height of Element Call's root, not of the viewport: embedded,
the two differ (see the note on container units in base.css) */
block-size: 50cqh;
aspect-ratio: 16 / 9;
max-width: 100%;
border-radius: var(--cpd-space-4x);
@@ -71,7 +73,7 @@ video.mirror {
);
}
@media (max-width: 550px) {
@container element-call (max-width: 550px) {
.preview {
margin-inline: 0;
border-radius: 0;
@@ -11,11 +11,10 @@ exports[`ConnectionLostError: Action handling should reset error state 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -92,7 +91,7 @@ exports[`ConnectionLostError: Action handling should reset error state 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -169,11 +168,10 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'internal' er
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -250,7 +248,7 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'internal' er
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -326,11 +324,10 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'notAllowed'
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -407,7 +404,7 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'notAllowed'
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -483,11 +480,10 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'serverUnreac
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -564,7 +560,7 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'serverUnreac
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -640,11 +636,10 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'serviceNotFo
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -721,7 +716,7 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'serviceNotFo
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -797,11 +792,10 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'timeout' err
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -878,7 +872,7 @@ exports[`LiveKit ConnectionError variants > should display LiveKit 'timeout' err
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -954,11 +948,10 @@ exports[`LiveKit ConnectionError variants > should link to troubleshoot guide wh
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1035,7 +1028,7 @@ exports[`LiveKit ConnectionError variants > should link to troubleshoot guide wh
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1111,11 +1104,10 @@ exports[`should have a close button when the host can dismiss us 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1192,7 +1184,7 @@ exports[`should have a close button when the host can dismiss us 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1265,11 +1257,10 @@ exports[`should render the error page with link back to home 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1346,7 +1337,7 @@ exports[`should render the error page with link back to home 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1419,11 +1410,10 @@ exports[`should report correct error for 'Call is not supported' 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1500,7 +1490,7 @@ exports[`should report correct error for 'Call is not supported' 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1573,11 +1563,10 @@ exports[`should report correct error for 'Connection lost' 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1654,7 +1643,7 @@ exports[`should report correct error for 'Connection lost' 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1731,11 +1720,10 @@ exports[`should report correct error for 'Homeserver does not support Matrix 2.
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1812,7 +1800,7 @@ exports[`should report correct error for 'Homeserver does not support Matrix 2.
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -1885,11 +1873,10 @@ exports[`should report correct error for 'Incompatible browser' 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -1966,7 +1953,7 @@ exports[`should report correct error for 'Incompatible browser' 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
@@ -2034,11 +2021,10 @@ exports[`should report correct error for 'Insufficient capacity' 1`] = `
<div
class="_nav_e4b327 _leftNav_e4b327"
>
<a
<button
aria-label="Element Call Home"
class="_headerLogo_e4b327"
data-discover="true"
href="/"
type="button"
>
<svg
fill="none"
@@ -2115,7 +2101,7 @@ exports[`should report correct error for 'Insufficient capacity' 1`] = `
fill="white"
/>
</svg>
</a>
</button>
</div>
<div
class="_nav_e4b327 _rightNav_e4b327"
+11 -10
View File
@@ -4,6 +4,7 @@ exports[`InCallView > rendering > renders 1`] = `
<div>
<div
class="_inRoom_4e7ff8"
data-layout="one-on-one-desktop"
>
<header
class="_header_e4b327 _header_4e7ff8"
@@ -171,7 +172,7 @@ exports[`InCallView > rendering > renders 1`] = `
class="_settingsLogoContainer_20b7b4"
>
<button
aria-labelledby="_r_8_"
aria-labelledby="_r_b_"
class="_icon-button_1215g_8 _settingsOnlyShowWide_20b7b4"
data-kind="secondary"
data-testid="settings-bottom-left"
@@ -306,7 +307,7 @@ exports[`InCallView > rendering > renders 1`] = `
class="_buttons_20b7b4"
>
<button
aria-labelledby="_r_d_"
aria-labelledby="_r_g_"
class="_button_1nw83_8 _settingsOnlyShowNarrow_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -331,7 +332,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_i_"
aria-labelledby="_r_l_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -356,7 +357,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_n_"
aria-labelledby="_r_q_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -381,7 +382,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-disabled="false"
aria-expanded="false"
aria-haspopup="true"
aria-labelledby="_r_s_"
aria-labelledby="_r_v_"
class="_button_1nw83_8 _raiseHand_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -404,7 +405,7 @@ exports[`InCallView > rendering > renders 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_14_"
aria-labelledby="_r_17_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -432,8 +433,8 @@ exports[`InCallView > rendering > renders 1`] = `
data-size="lg"
>
<input
aria-labelledby="_r_1a_"
name="_r_19_"
aria-labelledby="_r_1d_"
name="_r_1c_"
type="radio"
value="spotlight"
/>
@@ -452,9 +453,9 @@ exports[`InCallView > rendering > renders 1`] = `
/>
</svg>
<input
aria-labelledby="_r_1f_"
aria-labelledby="_r_1i_"
checked=""
name="_r_19_"
name="_r_1c_"
type="radio"
value="grid"
/>
@@ -88,7 +88,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
class="_link_13esb_8"
data-kind="primary"
data-size="md"
href="/"
href="#"
rel="noreferrer noopener"
>
Back to recents
@@ -320,7 +320,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
class="_link_13esb_8"
data-kind="primary"
data-size="md"
href="/"
href="#"
rel="noreferrer noopener"
>
Back to recents
@@ -598,7 +598,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
class="_link_13esb_8"
data-kind="primary"
data-size="md"
href="/"
href="#"
rel="noreferrer noopener"
>
Back to recents
+21 -8
View File
@@ -6,14 +6,27 @@ Please see LICENSE in the repository root for full details.
*/
import { type Room, RoomEvent } from "matrix-js-sdk";
import { useCallback } from "react";
import { useCallback, useSyncExternalStore } from "react";
import { useTypedEventEmitterState } from "../useEvents";
export function useRoomName(room: Room): string {
return useTypedEventEmitterState(
room,
RoomEvent.Name,
useCallback(() => room.name, [room]),
/**
* The room's name, kept up to date. Null when there is no room yet, for a
* caller that only sometimes has one.
*/
export function useRoomName(room: Room): string;
export function useRoomName(room: Room | null): string | null;
export function useRoomName(room: Room | null): string | null {
const subscribe = useCallback(
(onChange: () => void) => {
if (room === null) return (): void => {};
room.on(RoomEvent.Name, onChange);
return (): void => {
room.off(RoomEvent.Name, onChange);
};
},
[room],
);
return useSyncExternalStore(
subscribe,
useCallback(() => room?.name ?? null, [room]),
);
}
+1 -1
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
pre {
.pre {
font-size: var(--font-size-micro);
}
+2 -2
View File
@@ -680,9 +680,9 @@ export const DeveloperSettingsTab: FC<Props> = ({
<AudioProcessingSettings />
<Separator />
<p>{t("developer_mode.environment_variables")}</p>
<pre>{JSON.stringify(env, null, 2)}</pre>
<pre className={styles.pre}>{JSON.stringify(env, null, 2)}</pre>
<p>{t("developer_mode.url_params")}</p>
<pre>{JSON.stringify(urlParams, null, 2)}</pre>
<pre className={styles.pre}>{JSON.stringify(urlParams, null, 2)}</pre>
</>
);
};
+2 -3
View File
@@ -235,9 +235,8 @@ export const SettingsModal: FC<Props> = ({
};
const tabs = [audioTab, videoTab];
// A host that can dismiss us is a host that owns the user's account, so their
// profile is not ours to edit.
if (hostBridge.close === undefined) tabs.push(profileTab);
// The profile is only ours to edit when the account is ours
if (hostBridge.supportsProfileChanges) tabs.push(profileTab);
tabs.push(preferencesTab);
if (isRageshakeAvailable || import.meta.env.VITE_PACKAGE === "full") {
// for full package we want to show the analytics consent checkbox
@@ -380,7 +380,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
local
)
</p>
<pre>
<pre
class="_pre_2ddec4"
>
{
"region": "local",
"version": "1.2.3"
@@ -390,7 +392,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
<p>
Local Participant
</p>
<pre>
<pre
class="_pre_2ddec4"
>
localParticipantIdentity
</pre>
<p>
@@ -417,7 +421,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
remote
)
</p>
<pre>
<pre
class="_pre_2ddec4"
>
{
"region": "remote",
"version": "4.5.6"
@@ -427,7 +433,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
<p>
Local Participant
</p>
<pre>
<pre
class="_pre_2ddec4"
>
localParticipantIdentity
</pre>
<p>
@@ -674,7 +682,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
<p>
Environment variables
</p>
<pre>
<pre
class="_pre_2ddec4"
>
{
"MY_MOCK_ENV": 10,
"ENV": "test"
@@ -683,7 +693,9 @@ exports[`DeveloperSettingsTab > renders and matches snapshot 1`] = `
<p>
URL parameters
</p>
<pre>
<pre
class="_pre_2ddec4"
>
{
"mocked": true,
"answer": 42
+52
View File
@@ -0,0 +1,52 @@
/*
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, it, vi } from "vitest";
import { init as initRageshake } from "./rageshake";
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it("flushes logs to IndexedDB periodically without an explicit flush", async () => {
vi.useFakeTimers();
const add = vi.fn();
const txn = {
oncomplete: undefined as (() => void) | undefined,
onerror: undefined,
objectStore: (name: string) =>
name === "logs"
? {
add: (entry: unknown): void => {
add(entry);
queueMicrotask(() => txn.oncomplete?.());
},
}
: { put: vi.fn() },
};
const open = (): unknown => {
const req = {
result: { transaction: () => txn },
onsuccess: undefined as (() => void) | undefined,
};
queueMicrotask(() => req.onsuccess?.());
return req;
};
vi.stubGlobal("indexedDB", { open });
await initRageshake();
global.mx_rage_logger.log(1, "test", "hello from the buffer");
expect(add).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(2000);
expect(add).toHaveBeenCalledOnce();
expect(add.mock.calls[0][0]).toMatchObject({
lines: expect.stringContaining("hello from the buffer"),
});
});
+7 -4
View File
@@ -204,10 +204,13 @@ class IndexedDBLogStore {
// Throttled function to flush logs. We use throttle rather
// than debounce as we want logs to be written regularly, otherwise
// if there's a constant stream of logging, we'd never write anything.
private throttledFlush = throttle(() => this.flush, MAX_FLUSH_INTERVAL_MS, {
leading: false,
trailing: true,
});
private throttledFlush = throttle(
() => {
this.flush().catch((e) => logger.error("Failed to flush logs", e));
},
MAX_FLUSH_INTERVAL_MS,
{ leading: false, trailing: true },
);
/**
* Flush logs to disk.
+69 -71
View File
@@ -55,7 +55,6 @@ import { type IMembershipManager } from "matrix-js-sdk/lib/matrixrtc/IMembership
import {
createToggle$,
filterBehavior,
generateItem,
generateItems,
pauseWhen,
} from "../../utils/observable";
@@ -65,7 +64,10 @@ import {
showReactions,
} from "../../settings/settings";
import { Config } from "../../config/Config";
import { MatrixRTCMode } from "../../config/ConfigOptions";
import {
MatrixRTCMode,
type ResolvedDelayedLeaveTimings,
} from "../../config/ConfigOptions";
import { isFirefox, platform } from "../../Platform";
import { setPipEnabled$ } from "../../controls";
import { TileStore } from "../TileStore";
@@ -111,7 +113,6 @@ import {
} from "./localMember/LocalMember.ts";
import {
createLocalTransport$,
JwtEndpointVersion,
type LocalTransport,
} from "./localMember/LocalTransport.ts";
import {
@@ -204,14 +205,21 @@ export interface CallViewModelOptions {
livekitRoomFactory?: (options?: RoomOptions) => LivekitRoom;
/** Optional behavior overriding the local connection state, mainly for testing purposes. */
connectionState$?: Behavior<ConnectionState>;
/** Optional behavior overriding the computed window size, mainly for testing purposes. */
windowSize$?: Behavior<{ width: number; height: number }>;
/**
* The size of the space the call is drawn in: the page when Element Call
* owns it, or the container a host mounted it in when it is a component.
* The layout — whether the call is shown full size, flat, narrow or as a
* picture-in-picture — follows this rather than the size of the window, so
* that a component shrunk by its host adapts even though the window has not
* changed.
*/
windowSize$: Behavior<{ width: number; height: number }>;
/** Optional value overriding the local transport, for testing purposes. */
localTransport?: LocalTransport;
/** Optional value overriding the connection factory, for testing purposes. */
connectionFactory?: ConnectionFactory;
/** The version & compatibility mode of MatrixRTC that we should use. */
matrixRTCMode$?: Behavior<MatrixRTCMode>;
matrixRTCMode?: MatrixRTCMode;
/** Optional behavior overriding for the screensharing, for testing */
toggleScreensharing?: () => void;
}
@@ -222,7 +230,7 @@ export interface CallViewModelOptions {
*
* Callers share this rather than picking the fields out themselves. The
* defaults on {@link CallViewModelOptions} describe a standalone Element Call,
* so a widget or embedded caller that misses one does not get an error — it
* so a widget or component caller that misses one does not get an error — it
* quietly gets standalone behaviour instead.
*
* Note `autoLeaveWhenOthersLeft` and `waitForCallPickup` are deliberately not
@@ -263,6 +271,11 @@ const smallMobileCallThreshold = 3;
// with the interface
const showFooterMs = 4000;
/**
* The general shape of the space the call is drawn in. Called a window because
* that is what it is in the standalone app; for a component it is the container
* the host gave us, which may be a small corner of a large window.
*/
export type WindowMode = "normal" | "narrow" | "flat" | "pip";
interface LayoutScanState {
@@ -324,6 +337,11 @@ export interface CallViewModel {
* Whether we are sharing our screen.
*/
sharingScreen$: Behavior<boolean>;
/**
* The last error from toggling screen sharing, until dismissed.
*/
screenShareError$: Behavior<Error | null>;
dismissScreenShareError: () => void;
// UI interactions
/**
@@ -514,10 +532,8 @@ export function createCallViewModel$(
const configMatrixRTCMode = Config.get().matrix_rtc_mode as
| MatrixRTCMode
| undefined;
const matrixRTCMode$ =
configMatrixRTCMode !== undefined
? constant(configMatrixRTCMode)
: (options.matrixRTCMode$ ?? constant(MatrixRTCMode.Compatibility));
const matrixRTCMode =
configMatrixRTCMode ?? options.matrixRTCMode ?? MatrixRTCMode.Compatibility;
// Each hbar seperates a block of input variables required for the CallViewModel to function.
// The outputs of this block is written under the hbar.
@@ -551,38 +567,16 @@ export function createCallViewModel$(
memberId: uuidv4(),
};
const localTransport$ = scope.behavior(
matrixRTCMode$.pipe(
generateItem(
"CallViewModel localTransport$",
// Re-create LocalTransport whenever the mode changes
(mode) => ({ keys: [mode], data: undefined }),
(scope, _data$, mode) =>
options.localTransport ??
createLocalTransport$({
scope: scope,
memberships$: memberships$,
ownMembershipIdentity,
client,
delayId$: scope.behavior(
(
fromEvent(
matrixRTCSession,
MembershipManagerEvent.DelayIdChanged,
// The type of reemitted event includes the original emitted as the second arg.
) as Observable<[string | undefined, IMembershipManager]>
).pipe(map(([delayId]) => delayId ?? null)),
matrixRTCSession.delayId ?? null,
),
roomId: matrixRoom.roomId,
forceJwtEndpoint:
mode === MatrixRTCMode.Matrix_2_0
? JwtEndpointVersion.Matrix_2_0
: JwtEndpointVersion.Legacy,
}),
),
),
);
const localTransport =
options.localTransport ??
createLocalTransport$({
scope: scope,
memberships$: memberships$,
ownMembershipIdentity,
client,
roomId: matrixRoom.roomId,
matrixRTCMode,
});
const connectionFactory =
options.connectionFactory ??
@@ -600,8 +594,7 @@ export function createCallViewModel$(
scope: scope,
connectionFactory: connectionFactory,
localTransport$: scope.behavior(
localTransport$.pipe(
switchMap((t) => t.active$),
localTransport.active$.pipe(
catchError((e: unknown) => {
logger.info(
"could not pass local transport to createConnectionManager$. localTransport$ threw an error",
@@ -626,18 +619,6 @@ export function createCallViewModel$(
localUser: { userId, deviceId },
});
const connectOptions$ = scope.behavior(
matrixRTCMode$.pipe(
map((mode) => ({
encryptMedia: livekitKeyProvider !== undefined,
// TODO. This might need to get called again on each change of matrixRTCMode...
matrixRTCMode: mode,
sendNotificationType,
callIntent,
})),
),
);
const localMembership = createLocalMembership$({
scope,
homeserverConnected: createHomeserverConnected$(
@@ -646,12 +627,21 @@ export function createCallViewModel$(
matrixRTCSession,
),
muteStates,
joinMatrixRTC: (transport: LivekitTransportConfig) => {
joinMatrixRTC: (
transport: LivekitTransportConfig,
delayedLeaveTimings: ResolvedDelayedLeaveTimings,
) => {
return enterRTCSession(
matrixRTCSession,
ownMembershipIdentity,
transport,
connectOptions$.value,
{
encryptMedia: livekitKeyProvider !== undefined,
matrixRTCMode,
delayedLeaveTimings,
sendNotificationType,
callIntent,
},
);
},
createPublisherFactory: (connection: Connection) => {
@@ -667,11 +657,25 @@ export function createCallViewModel$(
);
},
connectionManager,
client,
matrixRTCSession,
localTransport$,
localTransport,
roomId: matrixRoom.roomId,
hideScreensharing,
hostBridge,
baseUrl: client.baseUrl,
ownMembershipIdentity,
delayId$: scope.behavior(
(
fromEvent(
matrixRTCSession,
MembershipManagerEvent.DelayIdChanged,
// The type of reemitted event includes the original emitted as the second arg.
) as Observable<[string | undefined, IMembershipManager]>
).pipe(map(([delayId]) => delayId ?? null)),
matrixRTCSession.delayId ?? null,
),
matrixRTCMode,
logger: logger.getChild(`[${Date.now()}]`),
});
@@ -1097,18 +1101,10 @@ export function createCallViewModel$(
const pipEnabled$ = scope.behavior(setPipEnabled$, false);
const windowSize$ =
options.windowSize$ ??
scope.behavior<{ width: number; height: number }>(
fromEvent(window, "resize").pipe(
startWith(null),
map(() => ({ width: window.innerWidth, height: window.innerHeight })),
),
);
// A guess at what the window's mode should be based on its size and shape.
// A guess at what the window's mode should be based on the size and shape of
// the space we have to draw in.
const naturalWindowMode$ = scope.behavior<WindowMode>(
windowSize$.pipe(
options.windowSize$.pipe(
map(({ width, height }) => {
if (height <= 400 && width <= 340) return "pip";
// Our layouts for flat windows are better at adapting to a small width
@@ -1922,6 +1918,8 @@ export function createCallViewModel$(
reconnecting$: localMembership.reconnecting$,
livekitRoomItems$,
connected$: localMembership.connected$,
screenShareError$: localMembership.screenShareError$,
dismissScreenShareError: localMembership.dismissScreenShareError,
};
}
@@ -238,7 +238,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
);
},
},
matrixRTCMode$: constant(mode),
matrixRTCMode: mode,
...options,
},
raisedHands$,
@@ -19,21 +19,28 @@ import {
beforeAll,
afterAll,
beforeEach,
afterEach,
} from "vitest";
import { BehaviorSubject, map, of } from "rxjs";
import { logger } from "matrix-js-sdk/lib/logger";
import { type LocalParticipant, type LocalTrack } from "livekit-client";
import fetchMock from "fetch-mock";
import { PosthogAnalytics } from "../../../analytics/PosthogAnalytics";
import { MatrixRTCMode } from "../../../config/ConfigOptions";
import {
MatrixRTCMode,
type ResolvedDelayedLeaveTimings,
} from "../../../config/ConfigOptions";
import { type HomeserverDisconnectReason } from "./HomeserverConnected";
import {
flushPromises,
mockConfig,
mockLivekitRoom,
mockLocalParticipant,
mockMuteStates,
withTestScheduler,
ownMemberMock,
testScope,
} from "../../../utils/test";
import {
TransportState,
@@ -41,6 +48,7 @@ import {
enterRTCSession,
PublishState,
TrackState,
watchScreenShareToggle,
} from "./LocalMember";
import {
FailToGetOpenIdToken,
@@ -57,6 +65,7 @@ import {
type LocalTransport,
type LocalTransportWithSFUConfig,
} from "./LocalTransport";
import * as openIDSFU from "../../../livekit/openIDSFU";
initializeWidget();
@@ -69,112 +78,137 @@ vi.mock("@livekit/components-core", () => ({
.mockReturnValue(of({ isScreenShareEnabled: false })),
}));
describe("LocalMembership", () => {
describe("enterRTCSession", () => {
it("It joins the correct Session", () => {
mockConfig({
livekit: { livekit_service_url: "http://my-default-service-url.com" },
});
const mockedSession = vi.mocked({
room: {
roomId: "roomId",
client: {
getDomain: vi.fn().mockReturnValue("example.org"),
getOpenIdToken: vi.fn().mockResolvedValue({
access_token: "ACCCESS_TOKEN",
token_type: "Bearer",
matrix_server_name: "localhost",
expires_in: 10000,
}),
},
},
memberships: [],
joinRTCSession: vi.fn(),
}) as unknown as MatrixRTCSession;
enterRTCSession(
mockedSession,
ownMemberMock,
{
livekit_alias: "roomId",
livekit_service_url: "http://my-livekit-service-url.com",
type: "livekit",
},
{
encryptMedia: true,
matrixRTCMode: MATRIX_RTC_MODE,
},
);
expect(mockedSession.joinRTCSession).toHaveBeenLastCalledWith(
{
deviceId: "DEVICE",
memberId: "@alice:example.org:DEVICE",
userId: "@alice:example.org",
},
[],
{
livekit_alias: "roomId",
livekit_service_url: "http://my-livekit-service-url.com",
type: "livekit",
},
expect.objectContaining({ manageMediaKeys: true }),
);
});
it("passes keyRotationParticipantLimit from config to joinRTCSession", () => {
mockConfig({
livekit: { livekit_service_url: "http://my-default-service-url.com" },
matrix_rtc_session: {
delayed_leave_event_delay_ms: 0,
network_error_retry_ms: 0,
key_rotation_participant_limit: 50,
},
});
const mockedSession = vi.mocked({
room: {
roomId: "roomId",
client: {
getDomain: vi.fn().mockReturnValue("example.org"),
getOpenIdToken: vi.fn().mockResolvedValue({
access_token: "ACCCESS_TOKEN",
token_type: "Bearer",
matrix_server_name: "localhost",
expires_in: 10000,
}),
},
},
memberships: [],
joinRTCSession: vi.fn(),
}) as unknown as MatrixRTCSession;
enterRTCSession(
mockedSession,
ownMemberMock,
{
livekit_alias: "roomId",
livekit_service_url: "http://my-livekit-service-url.com",
type: "livekit",
},
{
encryptMedia: true,
matrixRTCMode: MATRIX_RTC_MODE,
},
);
expect(mockedSession.joinRTCSession).toHaveBeenLastCalledWith(
expect.any(Object),
[],
expect.any(Object),
expect.objectContaining({
keyRotationParticipantLimit: 50,
}),
);
});
describe("watchScreenShareToggle", () => {
it("reports nothing when the toggle completes", async () => {
const onError = vi.fn();
watchScreenShareToggle(Promise.resolve(), true, logger, onError);
await flushPromises();
expect(onError).not.toHaveBeenCalled();
});
it("reports failures other than the user cancelling", async () => {
const onError = vi.fn();
const e = new Error("NotReadableError");
watchScreenShareToggle(Promise.reject(e), true, logger, onError);
await flushPromises();
expect(onError).toHaveBeenCalledWith(e);
});
it("does not report the user cancelling the picker", async () => {
const onError = vi.fn();
const cancelled = new DOMException("Permission denied", "NotAllowedError");
watchScreenShareToggle(Promise.reject(cancelled), true, logger, onError);
await flushPromises();
expect(onError).not.toHaveBeenCalled();
});
});
const timings: ResolvedDelayedLeaveTimings = {
delay_ms: 10000,
restart_ms: 4000,
restart_timeout_ms: 1000,
};
const delegatedTimings: ResolvedDelayedLeaveTimings = {
delay_ms: timings.delay_ms * 10,
restart_ms: timings.restart_ms! * 10,
restart_timeout_ms: timings.restart_timeout_ms! * 10,
};
const mockedClient = {
getDomain: vi.fn().mockReturnValue("example.org"),
getDeviceId: vi.fn().mockReturnValue("AAAA"),
getOpenIdToken: vi.fn().mockResolvedValue({
access_token: "ACCCESS_TOKEN",
token_type: "Bearer",
matrix_server_name: "localhost",
expires_in: 10000,
}),
};
describe("enterRTCSession", () => {
const transport: LivekitTransportConfig = {
livekit_alias: "roomId",
livekit_service_url: "http://my-livekit-service-url.com",
type: "livekit",
};
const options = {
encryptMedia: true,
matrixRTCMode: MATRIX_RTC_MODE,
delayedLeaveTimings: timings,
};
const mockedSession = vi.mocked({
room: {
roomId: "roomId",
client: mockedClient,
},
memberships: [],
joinRTCSession: vi.fn(),
}) as unknown as MatrixRTCSession;
beforeEach(() =>
mockConfig({
livekit: { livekit_service_url: "http://my-default-service-url.com" },
}),
);
it("It joins the correct Session", () => {
enterRTCSession(mockedSession, ownMemberMock, transport, options);
expect(mockedSession.joinRTCSession).toHaveBeenLastCalledWith(
{
deviceId: "DEVICE",
memberId: "@alice:example.org:DEVICE",
userId: "@alice:example.org",
},
[],
transport,
expect.objectContaining({ manageMediaKeys: true }),
);
});
it("passes keyRotationParticipantLimit from config to joinRTCSession", () => {
mockConfig({
livekit: { livekit_service_url: "http://my-default-service-url.com" },
matrix_rtc_session: {
network_error_retry_ms: 0,
key_rotation_participant_limit: 50,
delayed_leave: timings,
delegated_delayed_leave: timings,
},
});
enterRTCSession(mockedSession, ownMemberMock, transport, options);
expect(mockedSession.joinRTCSession).toHaveBeenLastCalledWith(
expect.any(Object),
[],
expect.any(Object),
expect.objectContaining({
keyRotationParticipantLimit: 50,
}),
);
});
it("uses the specified delayed leave timings", () => {
enterRTCSession(mockedSession, ownMemberMock, transport, options);
expect(mockedSession.joinRTCSession).toHaveBeenLastCalledWith(
expect.anything(),
expect.anything(),
expect.anything(),
expect.objectContaining({
delayedLeaveEventRestartMs: timings.restart_ms,
delayedLeaveEventDelayMs: timings.delay_ms,
delayedLeaveEventRestartLocalTimeoutMs: timings.restart_timeout_ms,
}),
);
});
});
describe("LocalMembership", () => {
const defaultCreateLocalMemberValues = {
options: constant({
encryptMedia: false,
@@ -202,8 +236,30 @@ describe("LocalMembership", () => {
roomId: "!test-room-id:example.org",
hideScreensharing: false,
hostBridge: nullHostBridge,
baseUrl: "https://matrix.example.org",
ownMembershipIdentity: ownMemberMock,
client: mockedClient,
delayId$: constant(null),
matrixRTCMode: MATRIX_RTC_MODE,
};
beforeEach(() => {
mockConfig({
livekit: { livekit_service_url: "http://my-default-service-url.com" },
matrix_rtc_session: {
network_error_retry_ms: 1000,
delayed_leave: timings,
delegated_delayed_leave: delegatedTimings,
},
});
fetchMock.catch(404);
});
afterEach(async () => {
void (await fetchMock.flush());
fetchMock.reset();
});
it("throws error on missing RTC config error", () => {
withTestScheduler(({ scope, hot, behavior, expectObservable }) => {
const localTransport$ = scope.behavior<null | LivekitTransportConfig>(
@@ -230,9 +286,8 @@ describe("LocalMembership", () => {
scope,
...defaultCreateLocalMemberValues,
connectionManager: mockConnectionManager,
localTransport$: behavior("a", { a: aLocalTransport }),
localTransport: aLocalTransport,
});
localMembership.requestJoinAndPublish();
expectObservable(localMembership.localMemberState$).toBe("ne", {
n: TransportState.Waiting,
@@ -275,9 +330,8 @@ describe("LocalMembership", () => {
scope,
...defaultCreateLocalMemberValues,
connectionManager: mockConnectionManager,
localTransport$: behavior("a", { a: aLocalTransport }),
localTransport: aLocalTransport,
});
localMembership.requestJoinAndPublish();
expectObservable(localMembership.localMemberState$).toBe("n-e", {
n: TransportState.Waiting,
@@ -293,8 +347,8 @@ describe("LocalMembership", () => {
const scope = new ObservableScope();
const aLocalTransport: LocalTransport = {
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
};
const mockConnectionManager = {
@@ -312,7 +366,7 @@ describe("LocalMembership", () => {
leaveRoomSession: vi.fn(),
},
connectionManager: mockConnectionManager,
localTransport$: new BehaviorSubject(aLocalTransport),
localTransport: aLocalTransport,
});
const expextedLog =
"'not connected yet' while updating the call intent (this is expected on startup)";
@@ -373,12 +427,90 @@ describe("LocalMembership", () => {
livekitRoom: mockLivekitRoom({}),
} as unknown as Connection;
const authCallSpy = vi
.spyOn(openIDSFU, "getSFUConfigWithOpenID")
.mockImplementation(() => mockedClient.getOpenIdToken());
afterEach(() => authCallSpy.mockClear());
it.each([
["no", null, timings],
[
"homeserver",
"https://matrix.example.org/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave",
delegatedTimings,
],
["transport", "/a/delegate_delayed_leave", delegatedTimings],
])(
"joins session with %s delegation support",
async (_serviceName, delegationUrl, delayedLeaveTimings) => {
const scope = testScope();
const joinMatrixRTC = vi.fn();
const delayId$ = new BehaviorSubject<string | null>(null);
if (delegationUrl !== null)
fetchMock.post(delegationUrl, () => ({ status: 401, body: {} }));
const localMembership = createLocalMembership$({
scope,
...defaultCreateLocalMemberValues,
connectionManager: {
connectionManagerData$: constant(
new Epoch(new ConnectionManagerData()),
),
},
joinMatrixRTC,
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
delayId$,
});
localMembership.requestJoinAndPublish();
void (await fetchMock.flush());
await flushPromises();
// Joins with timings appropriate for the level of delegation support
expect(joinMatrixRTC).toHaveBeenCalledWith(
aTransport,
delayedLeaveTimings,
);
expect(authCallSpy).not.toHaveBeenCalled();
delayId$.next("leave1");
await flushPromises();
if (delegationUrl === null) {
expect(authCallSpy).not.toHaveBeenCalled();
} else {
// Delegation is supported in this test case, so go on to check that
// LocalMember actually performs delegation
const expectDelegation = (delayId: string) =>
expect(authCallSpy).toHaveBeenLastCalledWith(
mockedClient,
ownMemberMock,
"a",
"!test-room-id:example.org",
{
matrixRTCMode: MATRIX_RTC_MODE,
delayEndpointBaseUrl: "https://matrix.example.org",
delayId,
},
expect.anything(),
);
expectDelegation("leave1");
delayId$.next("leave2"); // Can change delegated leaves
await flushPromises();
expectDelegation("leave2");
}
},
);
it("recreates publisher if new connection is used, always unpublish and end tracks", async () => {
const scope = new ObservableScope();
const activeTransport$ = new BehaviorSubject(aTransportWithSFUConfig);
const aLocalTransport: LocalTransport = {
advertised$: new BehaviorSubject(aTransport),
advertised$: constant(aTransport),
active$: activeTransport$,
};
@@ -416,7 +548,7 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject(aLocalTransport),
localTransport: aLocalTransport,
});
await flushPromises();
activeTransport$.next({
@@ -447,7 +579,7 @@ describe("LocalMembership", () => {
const publishers: Publisher[] = [];
const tracks$ = new BehaviorSubject<LocalTrack[]>([]);
const publishing$ = new BehaviorSubject<boolean>(false);
const publishing$ = constant<boolean>(false);
defaultCreateLocalMemberValues.createPublisherFactory.mockImplementation(
() => {
const p = {
@@ -471,8 +603,8 @@ describe("LocalMembership", () => {
>;
const aLocalTransport: LocalTransport = {
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
};
const connectionManagerData = new ConnectionManagerData();
@@ -484,7 +616,7 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject(aLocalTransport),
localTransport: aLocalTransport,
});
await flushPromises();
expect(publisherFactory).toHaveBeenCalledOnce();
@@ -512,7 +644,7 @@ describe("LocalMembership", () => {
new BehaviorSubject<null | LocalTransportWithSFUConfig>(null);
const aLocalTransport: LocalTransport = {
advertised$: new BehaviorSubject(aTransport),
advertised$: constant(aTransport),
active$: activeTransport$,
};
@@ -555,7 +687,7 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$,
},
localTransport$: new BehaviorSubject(aLocalTransport),
localTransport: aLocalTransport,
});
await flushPromises();
@@ -690,10 +822,10 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject({
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
}),
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
});
await flushPromises();
@@ -730,10 +862,10 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject({
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
}),
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
});
await flushPromises();
@@ -772,18 +904,19 @@ describe("LocalMembership", () => {
scope,
...defaultCreateLocalMemberValues,
homeserverConnected: {
combined$: new BehaviorSubject<
[boolean, HomeserverDisconnectReason | null]
>([true, null]),
combined$: constant<[boolean, HomeserverDisconnectReason | null]>([
true,
null,
]),
rtsSession$: constant(RTCMemberStatus.Connected),
},
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject({
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
}),
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
});
await flushPromises();
@@ -824,10 +957,10 @@ describe("LocalMembership", () => {
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport$: new BehaviorSubject({
advertised$: new BehaviorSubject(aTransport),
active$: new BehaviorSubject(aTransportWithSFUConfig),
}),
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
});
await flushPromises();
@@ -857,4 +990,98 @@ describe("LocalMembership", () => {
scope.end();
});
});
describe("toggleScreenSharing", () => {
let originalMediaDevices: MediaDevices | undefined;
beforeAll(() => {
mockConfig();
// Screen sharing is only offered when getDisplayMedia is available.
originalMediaDevices = navigator.mediaDevices;
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { getDisplayMedia: vi.fn() },
});
});
afterAll(() => {
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: originalMediaDevices,
});
});
const createMembershipWithConnection = (
connection: Connection | null,
): {
scope: ObservableScope;
localMembership: ReturnType<typeof createLocalMembership$>;
} => {
const scope = new ObservableScope();
const connectionManagerData = new ConnectionManagerData();
if (connection) connectionManagerData.add(connection, []);
const localMembership = createLocalMembership$({
scope,
...defaultCreateLocalMemberValues,
connectionManager: {
connectionManagerData$: constant(new Epoch(connectionManagerData)),
},
localTransport: {
advertised$: constant(aTransport),
active$: constant(aTransportWithSFUConfig),
},
});
return { scope, localMembership };
};
it("surfaces a failure and clears it on dismiss", async () => {
const error = new Error("NotReadableError");
const setScreenShareEnabled = vi.fn().mockRejectedValue(error);
const connection = {
state$: constant(ConnectionState.LivekitConnected),
transport: aTransport,
livekitRoom: mockLivekitRoom({
localParticipant: mockLocalParticipant({
isScreenShareEnabled: false,
setScreenShareEnabled,
}),
}),
} as unknown as Connection;
const { scope, localMembership } =
createMembershipWithConnection(connection);
await flushPromises();
expect(localMembership.toggleScreenSharing).not.toBeNull();
expect(localMembership.screenShareError$.value).toBeNull();
localMembership.toggleScreenSharing!();
await flushPromises();
expect(setScreenShareEnabled).toHaveBeenCalledWith(
true,
expect.any(Object),
undefined,
);
expect(localMembership.screenShareError$.value).toBe(error);
localMembership.dismissScreenShareError();
expect(localMembership.screenShareError$.value).toBeNull();
scope.end();
});
it("does nothing when there is no local participant", async () => {
// No connection means participant$ never resolves to a participant.
const { scope, localMembership } = createMembershipWithConnection(null);
await flushPromises();
expect(localMembership.toggleScreenSharing).not.toBeNull();
localMembership.toggleScreenSharing!();
await flushPromises();
expect(localMembership.screenShareError$.value).toBeNull();
scope.end();
});
});
});
@@ -15,6 +15,7 @@ import {
MediaDeviceFailure,
} from "livekit-client";
import { observeParticipantEvents } from "@livekit/components-core";
import { type MatrixClient } from "matrix-js-sdk";
import {
Status as RTCSessionStatus,
type LivekitTransport,
@@ -64,7 +65,10 @@ import {
screenShareCodec,
parseResolution,
} from "../../../settings/settings.ts";
import { MatrixRTCMode } from "../../../config/ConfigOptions.ts";
import {
MatrixRTCMode,
type ResolvedDelayedLeaveTimings,
} from "../../../config/ConfigOptions.ts";
import { Config } from "../../../config/Config.ts";
import {
ConnectionState,
@@ -74,6 +78,8 @@ import {
import { type HomeserverConnected } from "./HomeserverConnected.ts";
import { type LocalTransport } from "./LocalTransport.ts";
import { areLivekitTransportsEqual } from "../remoteMembers/MatrixLivekitMembers.ts";
import { or$ } from "../../../utils/observable.ts";
import { getSFUConfigWithOpenID } from "../../../livekit/openIDSFU.ts";
export enum TransportState {
/** Not even a transport is available to the LocalMembership */
@@ -135,10 +141,15 @@ interface Props {
muteStates: MuteStates;
connectionManager: IConnectionManager;
createPublisherFactory: (connection: Connection) => Publisher;
joinMatrixRTC: (transport: LivekitTransportConfig) => void;
joinMatrixRTC: (
transport: LivekitTransportConfig,
delayedLeaveTimings: ResolvedDelayedLeaveTimings,
) => void;
homeserverConnected: HomeserverConnected;
roomId: string;
localTransport$: Behavior<LocalTransport>;
ownMembershipIdentity: CallMembershipIdentityParts;
localTransport: LocalTransport;
client: Pick<MatrixClient, "getDeviceId" | "getOpenIdToken">;
matrixRTCSession: Pick<
MatrixRTCSession,
"updateCallIntent" | "leaveRoomSession"
@@ -147,6 +158,9 @@ interface Props {
hideScreensharing: boolean;
/** The application hosting Element Call, to be kept informed of join/leave. */
hostBridge: HostBridge;
baseUrl: string;
delayId$: Behavior<string | null>;
matrixRTCMode: MatrixRTCMode;
logger: Logger;
}
@@ -161,10 +175,12 @@ interface Props {
* @param props.createPublisherFactory Factory to create a publisher once we have a connection.
* @param props.joinMatrixRTC Callback to join the matrix RTC session once we have a transport.
* @param props.homeserverConnected The homeserver connected state.
* @param props.localTransport$ The transport to advertise in our membership.
* @param props.localTransport The transport to advertise in our membership.
* @param props.logger The logger to use.
* @param props.muteStates The mute states for video and audio.
* @param props.matrixRTCSession The matrix RTC session to join.
* @param props.baseUrl Base URL of the homeserver.
* @param props.delayId$ ID of the delayed leave event to delegate to the SFU.
* @param props.roomId The room ID used as the call identifier in analytics events.
* @param props.hideScreensharing Whether to hide the screen-sharing button.
* @param props.hostBridge The application hosting Element Call.
@@ -178,16 +194,21 @@ interface Props {
export const createLocalMembership$ = ({
scope,
connectionManager,
localTransport$,
localTransport,
homeserverConnected,
createPublisherFactory,
joinMatrixRTC,
logger: parentLogger,
muteStates,
client,
matrixRTCSession,
baseUrl,
roomId,
hideScreensharing,
hostBridge,
ownMembershipIdentity,
delayId$,
matrixRTCMode,
}: Props): {
/**
* This request to start audio and video tracks.
@@ -206,6 +227,11 @@ export const createLocalMembership$ = ({
* Callback to toggle screen sharing. If null, screen sharing is not possible.
*/
toggleScreenSharing: (() => void) | null;
/**
* The last error from toggling screen sharing, until dismissed.
*/
screenShareError$: Behavior<Error | null>;
dismissScreenShareError: () => void;
// tracks$: Behavior<LocalTrack[]>;
participant$: Behavior<LocalParticipant | null>;
connection$: Behavior<Connection | null>;
@@ -241,25 +267,69 @@ export const createLocalMembership$ = ({
return of(null);
};
// This is the transport that we will advertise in our membership.
const advertisedTransport$ = localTransport$.pipe(
switchMap((lt) => lt.advertised$),
async function checkDelegationSupport(
endpointUrl: string,
serviceName: string,
): Promise<boolean> {
logger.info(`Checking whether ${serviceName} supports delegation…`);
try {
// Bluntly hit the endpoint without auth to check for a 404. Unfortunately
// we can't wrap this in a retry loop, as many servers don't just disable
// delegation support, but in fact are from a time before the endpoint
// existed at all, therefore we can hit CORS errors which would just gum
// up the retry loop. (May be revisited after Matrix 2.0.)
const res = await fetch(endpointUrl, { method: "POST" });
if (res.status === 404) {
logger.warn(`${serviceName} does not support delegation`);
return false;
} else {
logger.info(`${serviceName} supports delegation`);
return true;
}
} catch (e) {
logger.warn(
`Failed to determine whether ${serviceName} supports delegation, assuming no support`,
e,
);
return false;
}
}
const homeserverSupportsDelegation = checkDelegationSupport(
baseUrl +
"/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave",
"homeserver",
);
// The transport that we will advertise in our membership, paired with info as
// to whether delayed event delegation is supported
const joinParams$ = localTransport.advertised$.pipe(
catchError(handleTransportError),
distinctUntilChanged(areLivekitTransportsEqual),
switchMap((transport) => {
if (transport === null) return of(null);
const transportSupportsDelegation = checkDelegationSupport(
transport.livekit_service_url + "/delegate_delayed_leave",
`transport ${transport.livekit_service_url}`,
);
return or$(
from(homeserverSupportsDelegation),
from(transportSupportsDelegation),
).pipe(
map((delegationSupported) => ({ transport, delegationSupported })),
startWith(null),
);
}),
);
// Unwrap the local transport and set the state of the LocalMembership to error in case the transport is an error.
const activeTransport$ = scope.behavior(
localTransport$.pipe(
switchMap((lt) => {
return combineLatest([lt.active$, lt.advertised$]).pipe(
map(([active, advertised]) => {
// Our policy is to not publish to another transport if our prefered transport is miss-configured
if (advertised == null) return null;
combineLatest([localTransport.active$, localTransport.advertised$]).pipe(
map(([active, advertised]) => {
// Our policy is to not publish to another transport if our prefered transport is miss-configured
if (advertised == null) return null;
return active?.transport ?? null;
}),
);
return active?.transport ?? null;
}),
catchError(handleTransportError),
distinctUntilChanged(areLivekitTransportsEqual),
@@ -617,16 +687,20 @@ export const createLocalMembership$ = ({
// Keep matrix rtc session in sync with advertisedTransport$, connectRequested$
scope.reconcile(
scope.behavior(
combineLatest([advertisedTransport$, joinAndPublishRequested$]),
),
async ([transport, shouldConnect]) => {
if (!transport) return;
scope.behavior(combineLatest([joinParams$, joinAndPublishRequested$])),
async ([joinParams, shouldConnect]) => {
if (!joinParams) return;
// if shouldConnect=false we will do the disconnect as the cleanup from the previous reconcile iteration.
if (!shouldConnect) return;
const sessionConfig = Config.get().matrix_rtc_session;
try {
joinMatrixRTC(transport);
joinMatrixRTC(
joinParams.transport,
joinParams.delegationSupported
? sessionConfig.delegated_delayed_leave
: sessionConfig.delayed_leave,
);
} catch (error) {
logger.error("Error entering RTC session", error);
if (error instanceof Error)
@@ -653,6 +727,34 @@ export const createLocalMembership$ = ({
),
);
// Delegate delayed leaves to the SFU
scope.reconcile(
scope.behavior(combineLatest([joinParams$, delayId$])),
async ([joinParams, delayId]) => {
if (joinParams?.delegationSupported && delayId !== null) {
try {
// This will technically cause the service to issue a new JWT token,
// but it's safe to discard. We're only interested in triggering
// delegation.
await getSFUConfigWithOpenID(
client,
ownMembershipIdentity,
joinParams.transport.livekit_service_url,
roomId,
{ matrixRTCMode, delayEndpointBaseUrl: baseUrl, delayId },
logger,
);
} catch (e) {
// TODO: Surface this to the user as a service interruption?
logger.error(
`Failed to delegate leave to ${joinParams.transport.livekit_service_url}`,
e,
);
}
}
},
);
// Pause upstream of all local media tracks when we're disconnected from
// MatrixRTC, because it can be an unpleasant surprise for the app to say
// 'reconnecting' and yet still be transmitting your media to others.
@@ -711,6 +813,7 @@ export const createLocalMembership$ = ({
),
);
const screenShareError$ = new BehaviorSubject<Error | null>(null);
let toggleScreenSharing: (() => void) | null = null;
if (
"getDisplayMedia" in (navigator.mediaDevices ?? {}) &&
@@ -782,13 +885,18 @@ export const createLocalMembership$ = ({
// We also allow screen sharing to be toggled even if the connection
// is still initializing or publishing tracks, because there's no
// technical reason to disallow this. LiveKit will publish if it can.
participant$.value
?.setScreenShareEnabled(
const participant = participant$.value;
if (!participant) return;
watchScreenShareToggle(
participant.setScreenShareEnabled(
targetScreenshareState,
screenshareSettings,
publishOptions,
)
.catch(logger.error);
),
targetScreenshareState,
logger,
(e) => screenShareError$.next(e),
);
};
}
@@ -807,11 +915,44 @@ export const createLocalMembership$ = ({
),
sharingScreen$,
toggleScreenSharing,
screenShareError$,
dismissScreenShareError: () => screenShareError$.next(null),
connection$: localConnection$,
internalLoggerRef: logger,
};
};
/**
* Logs the outcome of a screen share toggle and reports failures.
*
* getDisplayMedia may legitimately take a long time (the user is choosing
* what to share) or never settle at all, so nothing is inferred from silence:
* the request and its completion are logged with the elapsed time so that a
* hang is visible in the logs, and only an explicit rejection is reported.
*
* The user cancelling the picker rejects with a NotAllowedError; that is
* logged but not reported.
*/
export function watchScreenShareToggle(
toggle: Promise<unknown>,
enable: boolean,
logger: Logger,
onError: (e: Error) => void,
): void {
const what = `Screen share ${enable ? "start" : "stop"}`;
const started = Date.now();
const elapsed = (): string => `${Date.now() - started} ms`;
logger.info(`${what} requested`);
toggle.then(
() => logger.info(`${what} completed in ${elapsed()}`),
(e: unknown) => {
logger.error(`${what} failed after ${elapsed()}:`, e);
if (e instanceof DOMException && e.name === "NotAllowedError") return;
onError(e instanceof Error ? e : new Error(String(e)));
},
);
}
export function observeSharingScreen$(p: Participant): Observable<boolean> {
return observeParticipantEvents(
p,
@@ -825,6 +966,7 @@ export function observeSharingScreen$(p: Participant): Observable<boolean> {
interface EnterRTCSessionOptions {
encryptMedia: boolean;
matrixRTCMode: MatrixRTCMode;
delayedLeaveTimings: ResolvedDelayedLeaveTimings;
/** Whether and what kind of notification to send when joining. */
sendNotificationType?: RTCNotificationType;
/** The kind of call being placed. */
@@ -842,7 +984,8 @@ interface EnterRTCSessionOptions {
* @param ownMembershipIdentity - Options for entering the RTC session.
* @param transport - The LivekitTransport to use for this session.
* @param options - `encryptMedia`: Whether to encrypt media. `matrixRTCMode`: The
* Matrix RTC mode to use. `sendNotificationType`: Whether and what kind of
* Matrix RTC mode to use. `delayedLeaveTimings`: The preferred timings for
* delayed leave events. `sendNotificationType`: Whether and what kind of
* notification to send on join. `callIntent`: The kind of call being placed.
* @throws If the host could not be told that we are joining.
*/
@@ -851,14 +994,14 @@ export function enterRTCSession(
rtcSession: MatrixRTCSession,
ownMembershipIdentity: CallMembershipIdentityParts,
transport: LivekitTransportConfig,
options: EnterRTCSessionOptions,
): void {
const {
{
encryptMedia,
matrixRTCMode,
delayedLeaveTimings,
sendNotificationType: notificationType,
callIntent,
} = options;
}: EnterRTCSessionOptions,
): void {
PosthogAnalytics.instance.eventCallEnded.cacheStartCall(new Date());
PosthogAnalytics.instance.eventCallStarted.track(rtcSession.room.roomId);
@@ -866,7 +1009,11 @@ export function enterRTCSession(
// have started tracking by the time calls start getting created.
// groupCallOTelMembership?.onJoinCall();
const { matrix_rtc_session: matrixRtcSessionConfig } = Config.get();
const {
sync_disconnect_grace_period_ms: gracePeriod,
matrix_rtc_session: sessionConfig,
} = Config.get();
const retryInterval = sessionConfig.network_error_retry_ms;
const multiSFU =
matrixRTCMode === MatrixRTCMode.Compatibility ||
matrixRTCMode === MatrixRTCMode.Matrix_2_0;
@@ -883,16 +1030,11 @@ export function enterRTCSession(
};
}
// Calculates `maximumNetworkErrorRetryCount`. The connection is failed if EITHER:
// - The /sync loop is unresponsive for > `gracePeriod` ms, or
// - A delayed leave event is emitted (after `leaveDelay` ms period).
// Note: Use leaveDelay >> gracePeriod for delegated leave events.
const gracePeriod = Config.get().sync_disconnect_grace_period_ms;
const leaveDelay = matrixRtcSessionConfig?.delayed_leave_event_delay_ms;
const retryInterval = matrixRtcSessionConfig?.network_error_retry_ms;
// Set maximumNetworkErrorRetryCount such that we will consider the client
// disconnected as soon as either it fails to sync for longer than the grace
// period, or it is likely that a delayed leave event has been sent.
// Math.min is used to account for the respective worst case: /sync not available or leave event emitted.
const maxWaitTime = Math.min(gracePeriod, leaveDelay);
const maxWaitTime = Math.min(gracePeriod, delayedLeaveTimings.delay_ms);
const maximumNetworkErrorRetryCount =
Math.ceil(maxWaitTime / retryInterval) + 1;
@@ -907,18 +1049,14 @@ export function enterRTCSession(
notificationType,
callIntent,
manageMediaKeys: encryptMedia,
delayedLeaveEventRestartMs:
matrixRtcSessionConfig?.delayed_leave_event_restart_ms,
delayedLeaveEventDelayMs:
matrixRtcSessionConfig?.delayed_leave_event_delay_ms,
delayedLeaveEventRestartMs: delayedLeaveTimings.restart_ms,
delayedLeaveEventDelayMs: delayedLeaveTimings.delay_ms,
delayedLeaveEventRestartLocalTimeoutMs:
matrixRtcSessionConfig?.delayed_leave_event_restart_local_timeout_ms,
networkErrorRetryMs: matrixRtcSessionConfig?.network_error_retry_ms,
makeKeyDelay: matrixRtcSessionConfig?.wait_for_key_rotation_ms,
membershipEventExpiryMs:
matrixRtcSessionConfig?.membership_event_expiry_ms,
keyRotationParticipantLimit:
matrixRtcSessionConfig?.key_rotation_participant_limit,
delayedLeaveTimings.restart_timeout_ms,
networkErrorRetryMs: sessionConfig.network_error_retry_ms,
makeKeyDelay: sessionConfig.wait_for_key_rotation_ms,
membershipEventExpiryMs: sessionConfig.membership_event_expiry_ms,
keyRotationParticipantLimit: sessionConfig.key_rotation_participant_limit,
unstableSendStickyEvents: matrixRTCMode === MatrixRTCMode.Matrix_2_0,
maximumNetworkErrorRetryCount: maximumNetworkErrorRetryCount,
},
@@ -14,11 +14,8 @@ import {
type MockedObject,
vi,
} from "vitest";
import {
type CallMembership,
type LivekitTransportConfig,
} from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject, filter, lastValueFrom } from "rxjs";
import { type CallMembership } from "matrix-js-sdk/lib/matrixrtc";
import { lastValueFrom } from "rxjs";
import fetchMock from "fetch-mock";
import {
@@ -27,11 +24,7 @@ import {
ownMemberMock,
testScope,
} from "../../../utils/test";
import {
createLocalTransport$,
JwtEndpointVersion,
type LocalTransportWithSFUConfig,
} from "./LocalTransport";
import { createLocalTransport$ } from "./LocalTransport";
import { constant } from "../../Behavior";
import { Epoch, ObservableScope } from "../../ObservableScope";
import {
@@ -41,6 +34,7 @@ import {
import * as openIDSFU from "../../../livekit/openIDSFU";
import { customLivekitUrl } from "../../../settings/settings";
import { testJWTToken } from "../../../utils/test-fixtures";
import { MatrixRTCMode } from "../../../config/ConfigOptions";
describe("LocalTransport", () => {
const openIdResponse: openIDSFU.SFUConfig = {
@@ -61,14 +55,12 @@ describe("LocalTransport", () => {
// eslint-disable-next-line @typescript-eslint/naming-convention
_unstable_getRTCTransports: async () => Promise.resolve([]),
getDomain: () => "example.org",
baseUrl: "example.org",
// These won't be called in this error path but satisfy the type
getOpenIdToken: vi.fn(),
getDeviceId: vi.fn(),
},
ownMembershipIdentity: ownMemberMock,
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: constant("delay_id_mock"),
matrixRTCMode: MatrixRTCMode.Compatibility,
});
await flushPromises();
@@ -100,7 +92,6 @@ describe("LocalTransport", () => {
roomId: "!example_room_id",
memberships$: constant(new Epoch<CallMembership[]>([])),
client: {
baseUrl: "https://example.org",
getDomain: () => "example.org",
// eslint-disable-next-line @typescript-eslint/naming-convention
_unstable_getRTCTransports: async () => Promise.resolve([]),
@@ -108,8 +99,7 @@ describe("LocalTransport", () => {
getDeviceId: vi.fn(),
},
ownMembershipIdentity: ownMemberMock,
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: constant("delay_id_mock"),
matrixRTCMode: MatrixRTCMode.Compatibility,
});
active$.subscribe(
(o) => observations.push(o),
@@ -147,11 +137,9 @@ describe("LocalTransport", () => {
getDomain: () => "example.org",
getOpenIdToken: vi.fn(),
getDeviceId: vi.fn(),
baseUrl: "https://example.org",
},
ownMembershipIdentity: ownMemberMock,
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: constant("delay_id_mock"),
matrixRTCMode: MatrixRTCMode.Compatibility,
});
openIdResolver.resolve?.({
@@ -194,11 +182,9 @@ describe("LocalTransport", () => {
ownMembershipIdentity: ownMemberMock,
scope: testScope(),
roomId: "!example_room_id",
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: constant(null),
matrixRTCMode: MatrixRTCMode.Compatibility,
memberships$: constant(new Epoch<CallMembership[]>([])),
client: {
baseUrl: "https://example.org",
getDomain: vi.fn().mockReturnValue("example.org"),
// eslint-disable-next-line @typescript-eslint/naming-convention
_unstable_getRTCTransports: vi.fn().mockResolvedValue([]),
@@ -306,12 +292,10 @@ describe("LocalTransport", () => {
scope: testScope(),
ownMembershipIdentity: ownMemberMock,
roomId: "!example_room_id",
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: constant(null),
matrixRTCMode: MatrixRTCMode.Compatibility,
memberships$: constant(new Epoch<CallMembership[]>([])),
client: {
getDomain: () => "example.org",
baseUrl: "https://example.org",
// eslint-disable-next-line @typescript-eslint/naming-convention
_unstable_getRTCTransports: async () => Promise.resolve([]),
// These won't be called in this error path but satisfy the type
@@ -329,84 +313,4 @@ describe("LocalTransport", () => {
);
});
});
it("should not update advertised/active transport on delayID changes, but delay Id delegation should be called", async () => {
// For simplicity, we'll just use the config livekit
customLivekitUrl.setValue("https://lk.example.org");
const authCallSpy = vi
.spyOn(openIDSFU, "getSFUConfigWithOpenID")
.mockResolvedValue(openIdResponse);
const delayId$ = new BehaviorSubject<string | null>(null);
const { advertised$, active$ } = createLocalTransport$({
scope: testScope(),
ownMembershipIdentity: ownMemberMock,
roomId: "!example_room_id",
// We want multi-sdu
forceJwtEndpoint: JwtEndpointVersion.Legacy,
delayId$: delayId$,
memberships$: constant(new Epoch<CallMembership[]>([])),
client: {
getDomain: () => "example.org",
baseUrl: "https://example.org",
// eslint-disable-next-line @typescript-eslint/naming-convention
_unstable_getRTCTransports: async () => Promise.resolve([]),
// These won't be called in this error path but satisfy the type
getOpenIdToken: vi.fn(),
getDeviceId: vi.fn(),
},
});
const advertisedValues: LivekitTransportConfig[] = [];
const activeValues: LocalTransportWithSFUConfig[] = [];
advertised$
.pipe(filter((v) => v !== null))
.subscribe((t) => advertisedValues.push(t));
active$
.pipe(filter((v) => v !== null))
.subscribe((t) => activeValues.push(t));
await flushPromises();
// we have now an active and an advertised
expect(advertisedValues.length).toEqual(1);
expect(activeValues.length).toEqual(1);
expect(advertisedValues[0]!.livekit_service_url).toEqual(
"https://lk.example.org",
);
expect(activeValues[0]!.transport.livekit_service_url).toEqual(
"https://lk.example.org",
);
expect(authCallSpy).toHaveBeenCalledTimes(2);
// Now emits 3 new delays id
delayId$.next("delay_id_1");
await flushPromises();
delayId$.next("delay_id_2");
await flushPromises();
delayId$.next("delay_id_3");
await flushPromises();
// No new emissions should've happened, it is the same transport.
expect(advertisedValues.length).toEqual(1);
expect(activeValues.length).toEqual(1);
// Still we should have updated the delayID to auth
expect(authCallSpy).toHaveBeenCalledTimes(
4 * 2 /* 2 calls for each delayId ?? why */,
);
expect(authCallSpy).toHaveBeenLastCalledWith(
expect.anything(),
expect.anything(),
expect.anything(),
expect.anything(),
expect.objectContaining({
delayId: "delay_id_3",
}),
expect.anything(),
);
});
});

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