Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(multi-screen): render second screens via a React portal (#17547)

Abhay Madan64ac476bb755
diff --git a/package-lock.json b/package-lock.json
index 950aad2bd8..1b552b36b7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,6 +13,7 @@
"@amplitude/analytics-browser": "2.17.12",
"@amplitude/analytics-react-native": "1.5.16",
"@braintree/sanitize-url": "7.0.0",
+ "@emotion/cache": "11.11.0",
"@emotion/react": "11.10.6",
"@emotion/styled": "11.10.6",
"@giphy/js-fetch-api": "4.9.3",
diff --git a/package.json b/package.json
index 638e783375..1b51823f20 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"@amplitude/analytics-browser": "2.17.12",
"@amplitude/analytics-react-native": "1.5.16",
"@braintree/sanitize-url": "7.0.0",
+ "@emotion/cache": "11.11.0",
"@emotion/react": "11.10.6",
"@emotion/styled": "11.10.6",
"@giphy/js-fetch-api": "4.9.3",
diff --git a/react/features/conference/components/web/Conference.tsx b/react/features/conference/components/web/Conference.tsx
index 8f13154cd1..a990742f0e 100644
--- a/react/features/conference/components/web/Conference.tsx
+++ b/react/features/conference/components/web/Conference.tsx
@@ -24,6 +24,7 @@ import CalleeInfoContainer from '../../../invite/components/callee-info/CalleeIn
import LargeVideo from '../../../large-video/components/LargeVideo.web';
import LobbyScreen from '../../../lobby/components/web/LobbyScreen';
import { getIsLobbyVisible } from '../../../lobby/functions';
+import SecondScreenPortals from '../../../multi-screen/components/SecondScreenPortals';
import { getOverlayToRender } from '../../../overlay/functions.web';
import ParticipantsPane from '../../../participants-pane/components/web/ParticipantsPane';
import Prejoin from '../../../prejoin/components/web/Prejoin';
@@ -311,6 +312,7 @@ class Conference extends AbstractConference<IProps, any> {
}
</div>
<AudioTracksContainer />
+ <SecondScreenPortals />
{ _showPrejoin || _showLobby || (
<>
<span
diff --git a/react/features/multi-screen/components/SecondScreenPortals.web.tsx b/react/features/multi-screen/components/SecondScreenPortals.web.tsx
new file mode 100644
index 0000000000..296b454818
--- /dev/null
+++ b/react/features/multi-screen/components/SecondScreenPortals.web.tsx
@@ -0,0 +1,60 @@
+import { CacheProvider } from '@emotion/react';
+import React, { useMemo } from 'react';
+import ReactDOM from 'react-dom';
+import { useSelector } from 'react-redux';
+
+import { IReduxState } from '../../app/types';
+import { ISecondScreenHandle } from '../functions.web';
+
+import SecondScreenView from './SecondScreenView';
+
+/**
+ * An open second-screen window paired with its portal root.
+ */
+interface IOpenScreen {
+ handle: ISecondScreenHandle;
+ id: string;
+}
+
+/**
+ * Renders every open second-screen window's content into that window via a React
+ * portal. Mounted once in the conference, it observes the multi-screen redux
+ * state and (un)mounts a {@link SecondScreenView} per window as windows open and
+ * close. Because the windows are same-origin, React reconciles their DOM the same
+ * way it does the main document, so the second screens can host any component
+ * (avatars now, with layouts and a whiteboard later), not just a {@code <video>}.
+ * Each window's subtree is wrapped in its own Emotion {@code CacheProvider} (the
+ * cache's container is that window's head), so MUI/tss-react styles inject into
+ * the window directly, in dev and prod.
+ *
+ * @returns {ReactElement}
+ */
+const SecondScreenPortals = () => {
+ const screens = useSelector((state: IReduxState) => state['features/multi-screen'].screens);
+
+ const open = useMemo(() => Object.keys(screens).reduce<Array<IOpenScreen>>((acc, id) => {
+ const handle = screens[id].handle as ISecondScreenHandle | undefined;
+
+ if (handle?.root && !handle.win.closed) {
+ acc.push({ handle, id });
+ }
+
+ return acc;
+ }, []), [ screens ]);
+
+ return (
+ <>
+ { open.map(({ handle, id }) => ReactDOM.createPortal(
+ <CacheProvider value = { handle.cache }>
+ <SecondScreenView
+ id = { id }
+ win = { handle.win } />
+ </CacheProvider>,
+ handle.root,
+ id
+ )) }
+ </>
+ );
+};
+
+export default SecondScreenPortals;
diff --git a/react/features/multi-screen/components/SecondScreenVideo.web.tsx b/react/features/multi-screen/components/SecondScreenVideo.web.tsx
new file mode 100644
index 0000000000..102bfc6285
--- /dev/null
+++ b/react/features/multi-screen/components/SecondScreenVideo.web.tsx
@@ -0,0 +1,74 @@
+import React, { useEffect, useRef } from 'react';
+
+/**
+ * The type of the React {@code Component} props of {@link SecondScreenVideo}.
+ */
+interface IProps {
+
+ /**
+ * The native meeting track to render in the second window.
+ */
+ track: MediaStreamTrack;
+
+ /**
+ * The second-screen window the video is portaled into. Its own
+ * {@code MediaStream} constructor is used so the (child-realm) {@code <video>}
+ * renders the meeting track by reference.
+ */
+ win: Window;
+}
+
+/**
+ * Full-bleed style for the second-screen video; {@code contain} so shared screens
+ * and slides are never cropped.
+ */
+const VIDEO_STYLE: React.CSSProperties = {
+ background: '#000',
+ height: '100%',
+ objectFit: 'contain',
+ width: '100%'
+};
+
+/**
+ * Renders a meeting track into the second-screen window by cloning it and
+ * wrapping the clone in that window's own {@code MediaStream}. This mirrors the
+ * feature's original imperative {@code renderTrack}, but driven by React so the
+ * clone is stopped automatically when the component unmounts or the track
+ * changes. Cloning into the window's own {@code MediaStream} (rather than
+ * attaching the meeting-realm stream directly) keeps the {@code srcObject} in the
+ * same window realm as the {@code <video>}.
+ *
+ * @param {IProps} props - The component props.
+ * @returns {ReactElement}
+ */
+const SecondScreenVideo = ({ track, win }: IProps) => {
+ const videoRef = useRef<HTMLVideoElement>(null);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ let clone: MediaStreamTrack | undefined;
+
+ if (video) {
+ clone = track.clone();
+ video.srcObject = new (win as Window & { MediaStream: typeof MediaStream; }).MediaStream([ clone ]);
+ }
+
+ return () => {
+ clone?.stop();
+ if (video) {
+ video.srcObject = null;
+ }
+ };
+ }, [ track, win ]);
+
+ return (
+ <video
+ autoPlay = { true }
+ muted = { true }
+ playsInline = { true }
+ ref = { videoRef }
+ style = { VIDEO_STYLE } />
+ );
+};
+
+export default SecondScreenVideo;
diff --git a/react/features/multi-screen/components/SecondScreenView.web.tsx b/react/features/multi-screen/components/SecondScreenView.web.tsx
new file mode 100644
index 0000000000..f651e0639a
--- /dev/null
+++ b/react/features/multi-screen/components/SecondScreenView.web.tsx
@@ -0,0 +1,100 @@
+import React from 'react';
+import { useSelector } from 'react-redux';
+
+import { IReduxState } from '../../app/types';
+import Avatar from '../../base/avatar/components/Avatar';
+import { IParticipant } from '../../base/participants/types';
+import { resolveSource } from '../functions.web';
+
+import SecondScreenVideo from './SecondScreenVideo';
+
+/**
+ * The type of the React {@code Component} props of {@link SecondScreenView}.
+ */
+interface IProps {
+
+ /**
+ * The id of the second-screen window this view renders into.
+ */
+ id: string;
+
+ /**
+ * The second-screen window, needed to render a track in its own realm.
+ */
+ win: Window;
+}
+
+/**
+ * The resolved source: the meeting track to show (or {@code null}) and the
+ * participant backing it (for the avatar fallback).
+ */
+interface IResolved {
+ participant?: IParticipant;
+ track: MediaStreamTrack | null;
+}
+
+/**
+ * The size of the fallback avatar shown when the source has no live video.
+ */
+const AVATAR_SIZE = 200;
+
+/**
+ * Full-bleed, centered style for the avatar fallback on black.
+ */
+const CONTAINER_STYLE: React.CSSProperties = {
+ alignItems: 'center',
+ background: '#000',
+ display: 'flex',
+ height: '100%',
+ inset: 0,
+ justifyContent: 'center',
+ position: 'fixed',
+ width: '100%'
+};
+
+/**
+ * Re-renders only when the resolved track or backing participant actually
+ * changes, not on every unrelated redux update.
+ *
+ * @param {IResolved} a - The previous resolved source.
+ * @param {IResolved} b - The next resolved source.
+ * @returns {boolean}
+ */
+const _resolvedEquals = (a: IResolved, b: IResolved) => a.track === b.track && a.participant === b.participant;
+
+/**
+ * Renders a single second-screen window's content from its redux source
+ * descriptor: the resolved meeting track full-bleed (via {@link
+ * SecondScreenVideo}), falling back to the backing participant's avatar. Portaled
+ * into the second window by {@link SecondScreenPortals}.
+ *
+ * @param {IProps} props - The component props.
+ * @returns {ReactElement}
+ */
+const SecondScreenView = ({ id, win }: IProps) => {
+ const { participant, track } = useSelector(
+ (state: IReduxState): IResolved => {
+ const source = state['features/multi-screen'].screens[id]?.source;
+
+ return source ? resolveSource(state, source) : { participant: undefined, track: null };
+ },
+ _resolvedEquals);
+
+ if (track) {
+ return (
+ <SecondScreenVideo
+ track = { track }
+ win = { win } />
+ );
+ }
+
+ return (
+ <div style = { CONTAINER_STYLE }>
+ <Avatar
+ participantId = { participant?.id }
+ size = { AVATAR_SIZE } />
+ </div>
+ );
+};
+
+export default SecondScreenView;
diff --git a/react/features/multi-screen/functions.web.ts b/react/features/multi-screen/functions.web.ts
index 01702e1912..5b209fbb62 100644
--- a/react/features/multi-screen/functions.web.ts
+++ b/react/features/multi-screen/functions.web.ts
@@ -1,10 +1,11 @@
+import createCache, { EmotionCache } from '@emotion/cache';
+
import { IReduxState, IStore } from '../app/types';
import { MEDIA_TYPE, VIDEO_TYPE } from '../base/media/constants';
-import { getParticipantById, getParticipantDisplayName } from '../base/participants/functions';
+import { getParticipantById } from '../base/participants/functions';
import { IParticipant } from '../base/participants/types';
import { getTrackByMediaTypeAndParticipant, getVideoTrackByParticipant } from '../base/tracks/functions.any';
import { getLargeVideoParticipant } from '../large-video/functions';
-import { renderAvatarOnCanvas } from '../pip/functions';
import { removeSecondScreen, setSecondScreenWindow } from './actions.web';
import logger from './logger';
@@ -14,55 +15,34 @@ import { ISecondScreenSource } from './types';
// from the `@types/webscreens-window-placement` devDependency.
/**
- * A second-screen window, constructed via {@code window.open} in the same
- * origin/process as the meeting so its {@code <video>} can render the meeting's
- * tracks by reference.
+ * Emotion cache key for second-screen windows. Each window gets its own cache
+ * whose container is that window's {@code head}.
*/
-type ISecondScreenWindow = Window & { MediaStream: typeof MediaStream; };
+const SECOND_SCREEN_CACHE_KEY = 'secondscreen';
/**
- * A canvas {@code captureStream} track exposes a non-standard {@code requestFrame}
- * used to push a single frame on demand.
+ * The live, non-serializable handle backing a single second-screen window. It is
+ * stored on the redux entry (typed opaquely there as {@code unknown} because the
+ * shared/native build has no DOM lib) and read back with a cast. React renders the
+ * window's content into {@code root} via a portal, so the handle carries the
+ * window, its portal root, and a per-window Emotion cache; the rendered
+ * tracks/avatars are owned by the React tree and stopped on unmount.
*/
-type IFrameRequestingTrack = MediaStreamTrack & { requestFrame?: () => void; };
-
-/**
- * The live, non-serializable handles backing a single second-screen window. This
- * object is stored on the redux entry (typed opaquely there as {@code unknown}
- * because the shared/native build has no DOM lib) and mutated in place as the
- * rendered source changes — the same way the rest of the app keeps mutable
- * lib-jitsi-meet objects in redux.
- */
-interface ISecondScreenHandle {
-
- /**
- * The off-screen canvas used to render a participant's avatar when their
- * video is unavailable (created lazily, reused across redraws).
- */
- avatarCanvas?: HTMLCanvasElement;
-
- /**
- * The second window's {@code MediaStream} wrapping the avatar canvas track
- * (what {@code video.srcObject} points at while the avatar is shown).
- */
- avatarSrc?: MediaStream;
+export interface ISecondScreenHandle {
/**
- * The avatar canvas {@code captureStream} track (kept to push frames and to
- * stop it on teardown).
+ * The per-window Emotion cache (its {@code container} is this window's
+ * {@code head}), so the MUI/tss-react styles of the portaled components inject
+ * straight into the window in dev and prod, instead of being copied across
+ * documents (which breaks under Emotion's production "speedy" insertRule mode).
*/
- avatarTrack?: IFrameRequestingTrack;
+ cache: EmotionCache;
/**
- * The clone of the currently rendered meeting track (the meeting keeps its
- * own copy; the clone is stopped when swapped out or on teardown).
+ * The full-bleed root element in the second window that React portals the
+ * window's content into.
*/
- clone?: MediaStreamTrack;
-
- /**
- * The {@code <video>} in the second window.
- */
- video: HTMLVideoElement;
+ root: HTMLElement;
/**
* The second-screen window itself.
@@ -70,20 +50,6 @@ interface ISecondScreenHandle {
win: Window;
}
-/**
- * The avatar canvas is rendered at a modest 4:3 size and scaled up by the
- * full-bleed {@code <video>} (object-fit: contain) on the second screen.
- */
-const AVATAR_CANVAS_WIDTH = 640;
-const AVATAR_CANVAS_HEIGHT = 480;
-
-/**
- * Avatar colours, matched to the black second-screen window background.
- */
-const AVATAR_BACKGROUND = '#000';
-const AVATAR_TEXT_COLOR = '#fff';
-const AVATAR_FONT_FAMILY = 'Inter, sans-serif';
-
/**
* Returns the live window handle for a second screen, or {@code undefined} if
* its window has not been opened yet.
@@ -92,7 +58,7 @@ const AVATAR_FONT_FAMILY = 'Inter, sans-serif';
* @param {string} id - The window id.
* @returns {ISecondScreenHandle | undefined}
*/
-function getHandle(state: IReduxState, id: string): ISecondScreenHandle | undefined {
+export function getHandle(state: IReduxState, id: string): ISecondScreenHandle | undefined {
return state['features/multi-screen'].screens[id]?.handle as ISecondScreenHandle | undefined;
}
@@ -128,7 +94,7 @@ export function isSecondScreenEnabled(state: IReduxState): boolean {
* @param {ISecondScreenSource} source - The source descriptor.
* @returns {Object} The resolved native track (or {@code null}) and backing participant.
*/
-function resolveSource(state: IReduxState, source: ISecondScreenSource) {
+export function resolveSource(state: IReduxState, source: ISecondScreenSource) {
const tracks = state['features/base/tracks'];
let iTrack;
let participant: IParticipant | undefined;
@@ -200,105 +166,26 @@ async function computeFeatures(screenId?: number): Promise<string> {
}
/**
- * Builds the (empty) second-screen document: a full-bleed video on black. Uses
- * element styles (not a stylesheet/inline script) to stay CSP-safe.
+ * Builds the (empty) second-screen document: a full-bleed root on black that
+ * React portals the window's content into. Uses element styles (not a
+ * stylesheet/inline script) to stay CSP-safe.
*
* @param {Window} win - The opened window.
- * @returns {HTMLVideoElement}
+ * @returns {HTMLElement}
*/
-function buildWindow(win: Window): HTMLVideoElement {
+function buildWindow(win: Window): HTMLElement {
const doc = win.document;
doc.title = 'Jitsi Meet';
Object.assign(doc.documentElement.style, { height: '100%' });
Object.assign(doc.body.style, { margin: '0', height: '100%', background: '#000', overflow: 'hidden' });
- const video = doc.createElement('video');
-
- video.autoplay = true;
- video.muted = true;
- video.setAttribute('playsinline', '');
- Object.assign(video.style, {
- position: 'fixed', inset: '0', width: '100%', height: '100%', objectFit: 'contain', background: '#000'
- });
- doc.body.appendChild(video);
-
- return video;
-}
-
-/**
- * Renders a meeting track into a window's video by reference (cloning so the
- * meeting keeps its own copy), stopping any previously rendered clone.
- *
- * @param {ISecondScreenHandle} handle - The window handle.
- * @param {MediaStreamTrack} track - The track to render.
- * @returns {void}
- */
-function renderTrack(handle: ISecondScreenHandle, track: MediaStreamTrack) {
- if (handle.clone) {
- handle.clone.stop();
- handle.clone = undefined;
- }
- const clone = track.clone();
-
- handle.clone = clone;
- handle.video.srcObject = new (handle.win as ISecondScreenWindow).MediaStream([ clone ]);
-}
-
-/**
- * Renders a participant's avatar (image, initials, or default) into a window's
- * video as a fallback when there is no usable video track (e.g. the source muted
- * their camera). Reuses the PiP feature's canvas-avatar rendering and feeds it to
- * the window by reference, mirroring {@link renderTrack}.
- *
- * @param {IReduxState} state - The redux state.
- * @param {ISecondScreenHandle} handle - The window handle.
- * @param {IParticipant | undefined} participant - The participant whose avatar to render.
- * @returns {void}
- */
-function renderAvatar(state: IReduxState, handle: ISecondScreenHandle, participant: IParticipant | undefined) {
- if (handle.clone) {
- handle.clone.stop();
- handle.clone = undefined;
- }
-
- let canvas = handle.avatarCanvas;
-
- if (!canvas) {
- canvas = document.createElement('canvas');
- canvas.width = AVATAR_CANVAS_WIDTH;
- canvas.height = AVATAR_CANVAS_HEIGHT;
-
- // captureStream(0): on-demand; we push a frame via requestFrame() after each draw.
- const track = canvas.captureStream(0).getVideoTracks()[0] as IFrameRequestingTrack;
-
- handle.avatarCanvas = canvas;
- handle.avatarTrack = track;
-
- // The track is created in this (meeting) document; wrap it in the second window's
- // MediaStream so its <video> renders it by reference (same trick as renderTrack()).
- handle.avatarSrc = new (handle.win as ISecondScreenWindow).MediaStream([ track ]);
- }
-
- if (handle.video.srcObject !== handle.avatarSrc) {
- handle.video.srcObject = handle.avatarSrc ?? null;
- }
+ const root = doc.createElement('div');
- const ctx = canvas.getContext('2d');
+ Object.assign(root.style, { position: 'fixed', inset: '0', width: '100%', height: '100%' });
+ doc.body.appendChild(root);
- if (!ctx) {
- return;
- }
-
- const displayName = participant?.id ? getParticipantDisplayName(state, participant.id) : '';
- const customAvatarBackgrounds = state['features/dynamic-branding']?.avatarBackgrounds ?? [];
-
- // Reuses the PiP feature's canvas-avatar rendering (image → initials → default icon).
- renderAvatarOnCanvas(
- canvas, ctx, participant, displayName, customAvatarBackgrounds,
- null, AVATAR_BACKGROUND, AVATAR_FONT_FAMILY, AVATAR_TEXT_COLOR, AVATAR_TEXT_COLOR)
- .then(() => handle.avatarTrack?.requestFrame?.())
- .catch(e => logger.warn('Failed to render second-screen avatar', e));
+ return root;
}
/**
@@ -314,10 +201,10 @@ function notifySourceChanged(id: string, source: ISecondScreenSource, participan
}
/**
- * Resolves and renders the current source for a window, and notifies the
- * embedder. Reads the window's configuration and live handle from redux (the
- * single source of truth). Falls back to the participant's avatar when there is
- * no live video.
+ * Re-resolves a window's source and notifies the embedder of the participant now
+ * backing it. The actual rendering is performed by the React portal observing the
+ * same redux state ({@code SecondScreenView}); this only keeps the external-API
+ * {@code secondScreenSourceChanged} event in sync (e.g. on active-speaker change).
*
* @param {IStore} store - The redux store.
* @param {string} id - The window id.
@@ -326,34 +213,25 @@ function notifySourceChanged(id: string, source: ISecondScreenSource, participan
function applySource(store: IStore, id: string) {
const state = store.getState();
const entry = state['features/multi-screen'].screens[id];
- const handle = getHandle(state, id);
- if (!entry || !handle || handle.win.closed) {
+ if (!entry) {
return;
}
- const { track, participant } = resolveSource(state, entry.source);
+ const { participant } = resolveSource(state, entry.source);
- if (track) {
- renderTrack(handle, track);
- } else {
- renderAvatar(state, handle, participant);
- }
notifySourceChanged(id, entry.source, participant?.id ?? null);
}
/**
- * Stops a handle's tracks and (optionally) closes its window. Pure cleanup of
- * the live objects; the redux entry is removed by the caller's action.
+ * Closes the handle's window if requested. The rendered tracks/avatars and the
+ * window's Emotion cache are owned by the React portal and torn down when it
+ * unmounts; the redux entry is removed by the caller's action.
*
* @param {ISecondScreenHandle} handle - The window handle.
- * @param {boolean} closeWindow - Whether to also close the OS window.
+ * @param {boolean} closeWindow - Whether to close the OS window.
* @returns {void}
*/
function teardownHandle(handle: ISecondScreenHandle, closeWindow: boolean) {
- // MediaStreamTrack.stop() is infallible per spec, so no try/catch.
- handle.clone?.stop();
- handle.avatarTrack?.stop();
-
if (closeWindow && !handle.win.closed) {
handle.win.close();
}
@@ -394,18 +272,16 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen
const existing = getHandle(store.getState(), id);
- if (existing) {
- if (!existing.win.closed) {
- applySource(store, id);
-
- return;
- }
+ if (existing && !existing.win.closed) {
+ applySource(store, id);
- // The window was closed without us being notified; stop its tracks before reopening
- // (its handle is overwritten by the dispatch below), so nothing leaks.
- teardownHandle(existing, false);
+ return;
}
+ // If a previous window was closed without notifying us, its handle is
+ // overwritten below and React unmounts its portal content (stopping the cloned
+ // track and its Emotion cache) on its own, so there is nothing to tear down.
+
let features;
try {
@@ -428,7 +304,11 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen
return;
}
- const handle: ISecondScreenHandle = { win, video: buildWindow(win) };
+ const handle: ISecondScreenHandle = {
+ cache: createCache({ container: win.document.head, key: SECOND_SCREEN_CACHE_KEY }),
+ root: buildWindow(win),
+ win
+ };
store.dispatch(setSecondScreenWindow(id, handle));
win.addEventListener('pagehide', () => handleWindowClosed(store, id), { once: true });
@@ -443,17 +323,16 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen
}
/**
- * Closes a single second-screen window: tears down its live handle and notifies
- * the embedder. Called by the middleware as the window's entry is removed from
- * state, so it does not dispatch itself.
+ * Closes a window from an already-captured handle and notifies the embedder. The
+ * caller captures the handle and removes the redux entry first (unmounting the
+ * portal, which stops the cloned track, while the window is still open), then
+ * calls this to close the window.
*
- * @param {IStore} store - The redux store.
+ * @param {ISecondScreenHandle | undefined} handle - The captured window handle.
* @param {string} id - The window id.
* @returns {void}
*/
-export function closeSecondScreen(store: IStore, id: string) {
- const handle = getHandle(store.getState(), id);
-
+export function closeSecondScreenHandle(handle: ISecondScreenHandle | undefined, id: string) {
if (!handle) {
return;
}
@@ -461,6 +340,19 @@ export function closeSecondScreen(store: IStore, id: string) {
APP.API?.notifySecondScreenClosed?.({ id });
}
+/**
+ * Closes a single second-screen window by reading its handle from state. Used for
+ * bulk teardown (conference end); single removals use the captured-handle path
+ * ({@link closeSecondScreenHandle}) in the middleware.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} id - The window id.
+ * @returns {void}
+ */
+export function closeSecondScreen(store: IStore, id: string) {
+ closeSecondScreenHandle(getHandle(store.getState(), id), id);
+}
+
/**
* Closes every second-screen window.
*
diff --git a/react/features/multi-screen/middleware.web.ts b/react/features/multi-screen/middleware.web.ts
index 423a4be3e7..90cd2c4ef1 100644
--- a/react/features/multi-screen/middleware.web.ts
+++ b/react/features/multi-screen/middleware.web.ts
@@ -4,7 +4,7 @@ import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
import { REMOVE_SECOND_SCREEN, RESET_SECOND_SCREENS, SET_SECOND_SCREEN } from './actionTypes';
import { resetSecondScreens } from './actions.web';
-import { closeAllSecondScreens, closeSecondScreen, openOrUpdateSecondScreen } from './functions.web';
+import { closeAllSecondScreens, closeSecondScreenHandle, getHandle, openOrUpdateSecondScreen } from './functions.web';
import logger from './logger';
import './subscriber.web';
@@ -26,12 +26,18 @@ MiddlewareRegistry.register((store: IStore) => next => action => {
return result;
}
- case REMOVE_SECOND_SCREEN:
+ case REMOVE_SECOND_SCREEN: {
- // Tear down before next(action) removes the entry, since the live handle is read from state.
- closeSecondScreen(store, action.id);
+ // Capture the handle, then remove the entry first so the portal unmounts
+ // (stopping its cloned track) while the window is still open; only then
+ // close the window.
+ const handle = getHandle(store.getState(), action.id);
+ const result = next(action);
- return next(action);
+ closeSecondScreenHandle(handle, action.id);
+
+ return result;
+ }
case RESET_SECOND_SCREENS:
// Same ordering: close the windows while their entries are still in state.