Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(multi-screen): whiteboard as a second-screen source (#17581)
Abhay Madan6ae7ad653154
diff --git a/lang/main.json b/lang/main.jsonindex ffd61532ac..1794a6b471 100644--- a/lang/main.json+++ b/lang/main.json@@ -836,6 +836,13 @@"youAreAlone": "You are the only one in the meeting"},"me": "me",+ "multiScreen": {+ "noParticipants": "No participants",+ "showOnStage": "Show {{name}} on the second screen",+ "unpinFromStage": "Stop featuring {{name}} on the second screen",+ "whiteboardInactive": "Open the whiteboard in the meeting to show it on the second screen",+ "whiteboardTitle": "Whiteboard"+ },"notify": {"OldElectronAPPTitle": "Security vulnerability!","allowAll": "Allow All",diff --git a/react/features/multi-screen/components/SecondScreenGallery.web.tsx b/react/features/multi-screen/components/SecondScreenGallery.web.tsxnew file mode 100644index 0000000000..83ebd8a0d9--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenGallery.web.tsx@@ -0,0 +1,203 @@+import React, { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { makeStyles } from 'tss-react/mui';++import { getGalleryGridDimensions } from '../functions.web';+import { useDominantSpeakerId, useSecondScreenParticipantIds } from '../hooks.web';++import SecondScreenTile from './SecondScreenTile';++/**+ * The type of the React {@code Component} props of {@link SecondScreenGallery}.+ */+interface IProps {++ /**+ * The second-screen window, needed to render tracks in its own realm.+ */+ win: Window;+}++/**+ * Maximum number of columns in the gallery grid.+ */+const MAX_GALLERY_COLUMNS = 5;++/**+ * Gap between gallery tiles in pixels. Must match the {@code gap} in the styles,+ * or the tile-size math mis-counts the gaps and the grid overflows.+ */+const GALLERY_GAP = 8;++/**+ * The styles, injected into the second window via its own Emotion cache.+ */+const useStyles = makeStyles()(() => {+ return {+ gallery: {+ boxSizing: 'border-box',+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: GALLERY_GAP,+ padding: GALLERY_GAP,+ backgroundColor: '#040404',+ overflow: 'hidden'+ },+ row: {+ display: 'flex',+ justifyContent: 'center',+ gap: GALLERY_GAP+ },+ placeholder: {+ width: '100%',+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: '#040404'+ },+ message: {+ fontSize: 16,+ color: 'rgba(255, 255, 255, 0.5)'+ }+ };+});++/**+ * The tile-grid (gallery) layout for a second-screen window: every participant in+ * a responsive grid sized to the window. Tiles use the realm-safe {@link+ * SecondScreenTile}; the grid is measured through the popup window's own+ * {@code ResizeObserver} so it reflows to that window (including page-zoom).+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement}+ */+const SecondScreenGallery = ({ win }: IProps) => {+ const { classes } = useStyles();+ const { t } = useTranslation();+ const participantIds = useSecondScreenParticipantIds();+ const dominantSpeakerId = useDominantSpeakerId();++ // Container dimensions, tracked via a ResizeObserver bound through a callback+ // ref so it (re)attaches when the grid mounts (including when participants+ // arrive after the window opened) and tears down when it unmounts. The grid+ // lives in the SECONDARY window while this code runs in the main window's+ // realm, so the observer, rAF and resize listener are taken from that window;+ // otherwise the main window's observer never sees the popup's own reflows+ // (most visibly page-zoom).+ const [ dimensions, setDimensions ] = useState<{ height: number; width: number; } | null>(null);+ const cleanupRef = useRef<(() => void) | null>(null);++ const attachGridRef = useCallback((element: HTMLDivElement | null) => {+ cleanupRef.current?.();+ cleanupRef.current = null;++ if (!element) {+ return;+ }++ const ownerWindow = element.ownerDocument.defaultView ?? window;+ const ResizeObserverCtor = ownerWindow.ResizeObserver ?? ResizeObserver;+ let frame = 0;++ const measure = () => {+ const width = element.clientWidth;+ const height = element.clientHeight;++ // Skip a no-op measurement so it never re-enters the observer.+ setDimensions(prev =>+ ((prev && prev.width === width && prev.height === height) ? prev : { height,+ width }));+ };++ // Defer the measurement out of the observer/resize callback: updating+ // state there resizes the tiles synchronously, raising the benign+ // "ResizeObserver loop" overlay error.+ const schedule = () => {+ ownerWindow.cancelAnimationFrame(frame);+ frame = ownerWindow.requestAnimationFrame(measure);+ };++ const observer = new ResizeObserverCtor(schedule);++ observer.observe(element);++ // Page-zoom fires resize on the popup but does not always reach a+ // cross-document ResizeObserver, so re-measure on it explicitly too.+ ownerWindow.addEventListener('resize', schedule);++ cleanupRef.current = () => {+ ownerWindow.cancelAnimationFrame(frame);+ ownerWindow.removeEventListener('resize', schedule);+ observer.disconnect();+ };++ measure();+ }, []);++ const count = participantIds.length;++ // Defensive: the local participant is normally first in the list, so this is+ // only hit in transient pre-join/teardown states. It keeps the second screen+ // from flashing blank rather than being a common path.+ if (count === 0) {+ return (+ <div className = { classes.placeholder }>+ <div className = { classes.message }>+ { t('multiScreen.noParticipants') }+ </div>+ </div>+ );+ }++ // The grid is always rendered so attachGridRef can measure it; the tiles wait+ // for the first measurement, avoiding a frame of mis-sized tiles.+ let tiles: React.ReactNode = null;++ if (dimensions) {+ const { columns, rows } = getGalleryGridDimensions(count, MAX_GALLERY_COLUMNS);++ // The container has GALLERY_GAP padding on every side, so subtract it twice+ // (derived from the constant, not hardcoded, so the two stay in sync). Clamp+ // so a very small window never yields a negative tile size.+ const availableWidth = dimensions.width - ((columns - 1) * GALLERY_GAP) - (2 * GALLERY_GAP);+ const availableHeight = dimensions.height - ((rows - 1) * GALLERY_GAP) - (2 * GALLERY_GAP);+ const tileWidth = Math.max(0, Math.floor(availableWidth / columns));+ const tileHeight = Math.max(0, Math.floor(availableHeight / rows));+ const galleryRows: string[][] = [];++ for (let i = 0; i < count; i += columns) {+ galleryRows.push(participantIds.slice(i, i + columns));+ }++ tiles = galleryRows.map((row, rowIndex) => (+ <div+ className = { classes.row }+ key = { `row-${rowIndex}` }>+ { row.map(pid => (+ <SecondScreenTile+ height = { tileHeight }+ isActiveSpeaker = { pid === dominantSpeakerId }+ key = { pid }+ participantId = { pid }+ width = { tileWidth }+ win = { win } />+ )) }+ </div>+ ));+ }++ return (+ <div+ className = { classes.gallery }+ ref = { attachGridRef }>+ { tiles }+ </div>+ );+};++export default SecondScreenGallery;diff --git a/react/features/multi-screen/components/SecondScreenSingle.web.tsx b/react/features/multi-screen/components/SecondScreenSingle.web.tsxnew file mode 100644index 0000000000..80041b6186--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenSingle.web.tsx@@ -0,0 +1,99 @@+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 SecondScreenSingle}.+ */+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 the single-source second-screen case: the resolved meeting track+ * full-bleed (via {@link SecondScreenVideo}), falling back to the backing+ * participant's avatar when there is no live video. Kept separate from+ * {@link SecondScreenView} so the {@code resolveSource} selector only runs for this+ * fall-through case, not for the tile/stage layouts that resolve their own state.+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement}+ */+const SecondScreenSingle = ({ id, win }: IProps) => {+ const source = useSelector((state: IReduxState) => state['features/multi-screen'].screens[id]?.source);+ const { participant, track } = useSelector(+ (state: IReduxState): IResolved =>+ (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 SecondScreenSingle;diff --git a/react/features/multi-screen/components/SecondScreenStage.web.tsx b/react/features/multi-screen/components/SecondScreenStage.web.tsxnew file mode 100644index 0000000000..a28deb9e4b--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenStage.web.tsx@@ -0,0 +1,211 @@+import React, { useCallback } from 'react';+import { useDispatch, useSelector, useStore } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../app/types';+import Avatar from '../../base/avatar/components/Avatar';+import { getParticipantDisplayName, isScreenShareParticipantById } from '../../base/participants/functions';+import { setSecondScreen } from '../actions.web';+import { resolveSource } from '../functions.web';+import { useDominantSpeakerId, useSecondScreenParticipantIds } from '../hooks.web';+import { ISecondScreenSource } from '../types';++import SecondScreenStageTile from './SecondScreenStageTile';+import SecondScreenVideo from './SecondScreenVideo';++/**+ * The type of the React {@code Component} props of {@link SecondScreenStage}.+ */+interface IProps {++ /**+ * The id of the second-screen window this layout renders into.+ */+ id: string;++ /**+ * The second-screen window, needed to render tracks in its own realm.+ */+ win: Window;+}++/**+ * The avatar size, in pixels, for a camera-off featured participant.+ */+const FEATURED_AVATAR_SIZE = 160;++/**+ * The styles, injected into the second window via its own Emotion cache.+ */+const useStyles = makeStyles()(() => {+ return {+ stage: {+ display: 'flex',+ flexDirection: 'row',+ width: '100%',+ height: '100%',+ backgroundColor: '#292929',+ overflow: 'hidden'+ },+ main: {+ position: 'relative',+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ minWidth: 0,+ minHeight: 0+ },+ avatar: {+ position: 'absolute',+ top: '50%',+ left: '50%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ transform: 'translate(-50%, -50%)'+ },+ nameOverlay: {+ position: 'absolute',+ bottom: 16,+ left: '50%',+ maxWidth: '50%',+ padding: '6px 16px',+ backgroundColor: 'rgba(0, 0, 0, 0.6)',+ borderRadius: 3,+ color: '#fff',+ fontSize: 13,+ lineHeight: '18px',+ fontWeight: 600,+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ transform: 'translateX(-50%)'+ },+ filmstrip: {+ boxSizing: 'border-box',+ width: 188,+ flexShrink: 0,+ overflow: 'hidden'+ },+ filmstripInner: {+ boxSizing: 'border-box',+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: 8,+ padding: 8,+ backgroundColor: '#040404',+ overflowX: 'hidden',+ overflowY: 'auto',+ scrollbarWidth: 'thin',+ '&::-webkit-scrollbar': {+ width: 8+ },+ '&::-webkit-scrollbar-thumb': {+ backgroundColor: 'rgba(255, 255, 255, 0.2)',+ borderRadius: 4+ }+ }+ };+});++/**+ * Re-renders the featured area only when the resolved track or participant+ * actually changes, not on every unrelated redux update.+ *+ * @param {Object} a - The previous resolved source.+ * @param {Object} b - The next resolved source.+ * @returns {boolean}+ */+const _featuredEquals = (a: ReturnType<typeof resolveSource>, b: ReturnType<typeof resolveSource>) =>+ a.track === b.track && a.participant === b.participant;++/**+ * The stage layout for a second-screen window: one participant (or shared screen)+ * featured large, with a filmstrip of everyone down the side. The featured+ * participant follows the source ({@code role: 'stage'} tracks the active speaker;+ * {@code participant: X} pins X). Clicking a filmstrip tile re-pins through the+ * external API ({@code setSecondScreen}), so the API stays the single control+ * plane. All video is rendered via the realm-safe {@link SecondScreenVideo} clone+ * leaf, never {@code VideoTrack} (whose attach would cross window realms).+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement}+ */+const SecondScreenStage = ({ id, win }: IProps) => {+ const { classes } = useStyles();+ const dispatch = useDispatch();+ const store = useStore<IReduxState>();++ const source = useSelector((state: IReduxState) => state['features/multi-screen'].screens[id]?.source);+ const screenId = useSelector((state: IReduxState) => state['features/multi-screen'].screens[id]?.screenId);+ const { participant: featured, track } = useSelector(+ (state: IReduxState) => (source ? resolveSource(state, source) : { participant: undefined, track: null }),+ _featuredEquals);++ const featuredId = featured?.id;+ const name = useSelector((state: IReduxState) => (featuredId ? getParticipantDisplayName(state, featuredId) : ''));++ const participantIds = useSecondScreenParticipantIds();+ const dominantSpeakerId = useDominantSpeakerId();++ const pinnedId = source?.participant ?? null;+ const hasFilmstrip = participantIds.length > 1;++ const _onSelect = useCallback((participantId: string) => {+ let next: ISecondScreenSource;++ if (pinnedId === participantId) {+ next = { role: 'stage' };+ } else if (isScreenShareParticipantById(store.getState(), participantId)) {+ next = { media: 'desktop', participant: participantId };+ } else {+ next = { media: 'camera', participant: participantId };+ }++ dispatch(setSecondScreen(id, next, screenId));+ }, [ dispatch, id, pinnedId, screenId, store ]);++ return (+ <div className = { classes.stage }>+ <div className = { classes.main }>+ { track ? (+ <SecondScreenVideo+ track = { track }+ win = { win } />+ ) : (+ <div className = { classes.avatar }>+ <Avatar+ participantId = { featuredId }+ size = { FEATURED_AVATAR_SIZE } />+ </div>+ ) }+ { name && (+ <div className = { classes.nameOverlay }>+ { name }+ </div>+ ) }+ </div>+ { hasFilmstrip && (+ <div className = { classes.filmstrip }>+ <div className = { classes.filmstripInner }>+ { participantIds.map(pid => (+ <SecondScreenStageTile+ isActiveSpeaker = { pid === dominantSpeakerId }+ key = { pid }+ onSelect = { _onSelect }+ participantId = { pid }+ pinned = { pid === pinnedId }+ win = { win } />+ )) }+ </div>+ </div>+ ) }+ </div>+ );+};++export default SecondScreenStage;diff --git a/react/features/multi-screen/components/SecondScreenStageTile.web.tsx b/react/features/multi-screen/components/SecondScreenStageTile.web.tsxnew file mode 100644index 0000000000..646c778a3b--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenStageTile.web.tsx@@ -0,0 +1,135 @@+import React, { useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { useSelector } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../app/types';+import Icon from '../../base/icons/components/Icon';+import { IconPin } from '../../base/icons/svg';+import { getParticipantDisplayName } from '../../base/participants/functions';++import SecondScreenTile from './SecondScreenTile';++/**+ * The type of the React {@code Component} props of {@link SecondScreenStageTile}.+ */+interface IProps {++ /**+ * Whether this participant is the dominant speaker (drives the speaking ring).+ */+ isActiveSpeaker: boolean;++ /**+ * Called with this tile's participant id when it is clicked, to feature it on+ * the stage (or unfeature it when it is already pinned).+ */+ onSelect: (participantId: string) => void;++ /**+ * The id of the participant (a person or a virtual screenshare) this tile+ * previews and pins to the stage on click.+ */+ participantId: string;++ /**+ * Whether this participant is explicitly pinned to the stage (shows the pin+ * badge; a click then unpins).+ */+ pinned: boolean;++ /**+ * The second-screen window, needed to render a track in its own realm.+ */+ win: Window;+}++/**+ * The filmstrip tile width and height in pixels (16:9).+ */+const TILE_WIDTH = 160;+const TILE_HEIGHT = 90;++/**+ * The styles, injected into the second window via its own Emotion cache.+ */+const useStyles = makeStyles()(() => {+ return {+ item: {+ position: 'relative',+ flexShrink: 0,+ padding: 0,+ background: 'none',+ border: '2px solid transparent',+ borderRadius: 6,+ cursor: 'pointer',+ lineHeight: 0,+ transition: 'border-color 0.2s ease',+ '&:hover': {+ borderColor: 'rgba(255, 255, 255, 0.4)'+ }+ },+ pin: {+ position: 'absolute',+ top: 6,+ right: 6,+ zIndex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 4,+ backgroundColor: 'rgba(0, 0, 0, 0.7)',+ borderRadius: 4,+ color: '#fff',+ lineHeight: 0,+ pointerEvents: 'none'+ }+ };+});++/**+ * A clickable filmstrip tile in the second-screen stage layout: the shared {@link+ * SecondScreenTile} wrapped in a button that pins the participant to the stage by+ * dispatching {@code setSecondScreen} through the external-API control plane+ * (handled by the parent's {@code onSelect}). A pin badge marks the pinned tile;+ * clicking it again unpins. Memoized so a dominant-speaker or pin change only+ * re-renders the affected tiles.+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement}+ */+const SecondScreenStageTile = ({ isActiveSpeaker, onSelect, participantId, pinned, win }: IProps) => {+ const { classes } = useStyles();+ const { t } = useTranslation();+ const name = useSelector((state: IReduxState) => getParticipantDisplayName(state, participantId));++ const _onClick = useCallback(() => {+ onSelect(participantId);+ }, [ onSelect, participantId ]);++ return (+ <button+ aria-label = { t(pinned ? 'multiScreen.unpinFromStage' : 'multiScreen.showOnStage', { name }) }+ aria-pressed = { pinned }+ className = { classes.item }+ onClick = { _onClick }+ type = 'button'>+ <SecondScreenTile+ height = { TILE_HEIGHT }+ isActiveSpeaker = { isActiveSpeaker }+ participantId = { participantId }+ width = { TILE_WIDTH }+ win = { win } />+ { pinned && (+ <span className = { classes.pin }>+ <Icon+ color = '#fff'+ size = { 14 }+ src = { IconPin } />+ </span>+ ) }+ </button>+ );+};++export default React.memo(SecondScreenStageTile);diff --git a/react/features/multi-screen/components/SecondScreenTile.web.tsx b/react/features/multi-screen/components/SecondScreenTile.web.tsxnew file mode 100644index 0000000000..3b045e5b09--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenTile.web.tsx@@ -0,0 +1,147 @@+import React from 'react';+import { useSelector } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../app/types';+import Avatar from '../../base/avatar/components/Avatar';+import {+ getParticipantById,+ getParticipantDisplayName,+ isScreenShareParticipantById+} from '../../base/participants/functions';+import { getVideoTrackByParticipant } from '../../base/tracks/functions.any';++import SecondScreenVideo from './SecondScreenVideo';++/**+ * The type of the React {@code Component} props of {@link SecondScreenTile}.+ */+interface IProps {++ /**+ * The tile height in pixels.+ */+ height: number;++ /**+ * Whether this participant is the dominant speaker (drives the speaking ring).+ */+ isActiveSpeaker: boolean;++ /**+ * The id of the participant (a person or a virtual screenshare) this tile+ * previews.+ */+ participantId: string;++ /**+ * The tile width in pixels.+ */+ width: number;++ /**+ * The second-screen window, needed to render a track in its own realm.+ */+ win: Window;+}++/**+ * The styles, injected into the second window via its own Emotion cache (see+ * {@code SecondScreenPortals}). The dominant-speaker ring colour matches the main+ * window's thumbnail indicator (Jitsi's action01 token).+ */+const useStyles = makeStyles()(() => {+ return {+ tile: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ boxSizing: 'border-box',+ backgroundColor: '#292929',+ border: '3px solid transparent',+ borderRadius: 4,+ overflow: 'hidden',+ transition: 'border-color 0.2s ease'+ },+ speaking: {+ borderColor: '#4687ED'+ },+ avatar: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'+ },+ bottom: {+ position: 'absolute',+ bottom: 6,+ left: 6,+ display: 'flex',+ alignItems: 'center',+ gap: 4,+ maxWidth: 'calc(100% - 12px)',+ padding: '3px 6px',+ backgroundColor: 'rgba(0, 0, 0, 0.6)',+ borderRadius: 4,+ color: '#fff'+ },+ name: {+ minWidth: 0,+ fontSize: 12,+ lineHeight: '16px',+ fontWeight: 600,+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis'+ }+ };+});++/**+ * Renders one participant's tile: their camera or shared screen (via the+ * realm-safe {@link SecondScreenVideo} clone leaf) or their avatar, with their+ * name and a dominant-speaker ring. Used both as a gallery cell and inside a+ * stage filmstrip button. Memoized so a dominant-speaker change only re-renders+ * the tiles whose ring flips.+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement}+ */+const SecondScreenTile = ({ height, isActiveSpeaker, participantId, width, win }: IProps) => {+ const { classes, cx } = useStyles();+ const name = useSelector((state: IReduxState) => getParticipantDisplayName(state, participantId));+ const isScreenshare = useSelector((state: IReduxState) => isScreenShareParticipantById(state, participantId));+ const videoTrack = useSelector(+ (state: IReduxState) => getVideoTrackByParticipant(state, getParticipantById(state, participantId)));+ const track = videoTrack?.jitsiTrack && !videoTrack.muted+ ? (videoTrack.jitsiTrack.getTrack() as MediaStreamTrack) ?? null+ : null;++ const avatarSize = Math.max(24, Math.floor(Math.min(height / 2, width - 30, 150)));++ return (+ <div+ className = { cx(classes.tile, isActiveSpeaker && classes.speaking) }+ style = {{ height: `${height}px`, width: `${width}px` }}>+ { track ? (+ <SecondScreenVideo+ fit = { isScreenshare ? 'contain' : 'cover' }+ track = { track }+ win = { win } />+ ) : (+ <div className = { classes.avatar }>+ <Avatar+ participantId = { participantId }+ size = { avatarSize } />+ </div>+ ) }+ <div className = { classes.bottom }>+ <span className = { classes.name }>+ { name }+ </span>+ </div>+ </div>+ );+};++export default React.memo(SecondScreenTile);diff --git a/react/features/multi-screen/components/SecondScreenVideo.web.tsx b/react/features/multi-screen/components/SecondScreenVideo.web.tsxindex 102bfc6285..18ac86aacf 100644--- a/react/features/multi-screen/components/SecondScreenVideo.web.tsx+++ b/react/features/multi-screen/components/SecondScreenVideo.web.tsx@@ -5,6 +5,12 @@ import React, { useEffect, useRef } from 'react';*/interface IProps {+ /**+ * How the video fills its box: {@code contain} (default; never crops, used for+ * the stage and shared screens) or {@code cover} (camera tiles).+ */+ fit?: 'contain' | 'cover';+/*** The native meeting track to render in the second window.*/@@ -19,13 +25,12 @@ interface IProps {}/**- * Full-bleed style for the second-screen video; {@code contain} so shared screens- * and slides are never cropped.+ * Base full-bleed style for the second-screen video; object-fit is applied per+ * instance from the {@code fit} prop.*/const VIDEO_STYLE: React.CSSProperties = {background: '#000',height: '100%',- objectFit: 'contain',width: '100%'};@@ -41,7 +46,7 @@ const VIDEO_STYLE: React.CSSProperties = {* @param {IProps} props - The component props.* @returns {ReactElement}*/-const SecondScreenVideo = ({ track, win }: IProps) => {+const SecondScreenVideo = ({ fit = 'contain', track, win }: IProps) => {const videoRef = useRef<HTMLVideoElement>(null);useEffect(() => {@@ -67,7 +72,7 @@ const SecondScreenVideo = ({ track, win }: IProps) => {muted = { true }playsInline = { true }ref = { videoRef }- style = { VIDEO_STYLE } />+ style = {{ ...VIDEO_STYLE, objectFit: fit }} />);};diff --git a/react/features/multi-screen/components/SecondScreenView.web.tsx b/react/features/multi-screen/components/SecondScreenView.web.tsxindex f651e0639a..c58fd5acd4 100644--- a/react/features/multi-screen/components/SecondScreenView.web.tsx+++ b/react/features/multi-screen/components/SecondScreenView.web.tsx@@ -2,11 +2,11 @@ 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';+import SecondScreenGallery from './SecondScreenGallery';+import SecondScreenSingle from './SecondScreenSingle';+import SecondScreenStage from './SecondScreenStage';+import SecondScreenWhiteboard from './SecondScreenWhiteboard';/*** The type of the React {@code Component} props of {@link SecondScreenView}.@@ -25,75 +25,44 @@ interface IProps {}/**- * 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}.+ * Routes a single second-screen window to a layout from its redux source+ * descriptor. A {@code whiteboard} source renders the {@link SecondScreenWhiteboard}+ * iframe; a {@code tile} source renders the {@link SecondScreenGallery} grid; a+ * stage or participant source renders the {@link SecondScreenStage} layout+ * (featured participant plus filmstrip); any other source renders the single+ * track/avatar via {@link SecondScreenSingle}. Each layout resolves its own state,+ * so the potentially expensive {@code resolveSource} selector only runs where it is+ * needed. 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;+ const source = useSelector((state: IReduxState) => state['features/multi-screen'].screens[id]?.source);++ if (source?.role === 'whiteboard') {+ return <SecondScreenWhiteboard />;+ }- return source ? resolveSource(state, source) : { participant: undefined, track: null };- },- _resolvedEquals);+ if (source?.role === 'tile') {+ return (+ <SecondScreenGallery+ win = { win } />+ );+ }- if (track) {+ if (source && (source.role === 'stage' || Boolean(source.participant))) {return (- <SecondScreenVideo- track = { track }+ <SecondScreenStage+ id = { id }win = { win } />);}return (- <div style = { CONTAINER_STYLE }>- <Avatar- participantId = { participant?.id }- size = { AVATAR_SIZE } />- </div>+ <SecondScreenSingle+ id = { id }+ win = { win } />);};diff --git a/react/features/multi-screen/components/SecondScreenWhiteboard.web.tsx b/react/features/multi-screen/components/SecondScreenWhiteboard.web.tsxnew file mode 100644index 0000000000..2724e9e161--- /dev/null+++ b/react/features/multi-screen/components/SecondScreenWhiteboard.web.tsx@@ -0,0 +1,105 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import { useSelector } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../app/types';+import { getURLWithoutParams } from '../../base/connection/utils';+import { getLocalParticipant } from '../../base/participants/functions';+import {+ getCollabDetails,+ getCollabServerUrl,+ getWhiteboardInfoForURIString,+ isWhiteboardEnabled+} from '../../whiteboard/functions';++/**+ * The styles, injected into the second window via its own Emotion cache.+ */+const useStyles = makeStyles()(() => {+ return {+ whiteboard: {+ width: '100%',+ height: '100%',+ border: 'none',+ backgroundColor: '#fff'+ },+ placeholder: {+ width: '100%',+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: '#040404'+ },+ message: {+ fontSize: 16,+ color: 'rgba(255, 255, 255, 0.5)'+ }+ };+});++/**+ * Renders the meeting's shared whiteboard on a second screen by loading the+ * standalone whiteboard page ({@code static/whiteboard.html}) in an iframe,+ * pointed at the same collaboration room as the meeting. The iframe runs the+ * whiteboard (Excalidraw) in its own browsing context, so there are no+ * cross-window-realm issues, and it stays live via the shared collab server.+ * This is the kind of non-video content the portal makes possible and a+ * {@code <video>} second screen cannot. Requires the whiteboard to be open in the+ * meeting (so the collaboration details exist); otherwise a hint is shown.+ *+ * @returns {ReactElement}+ */+const SecondScreenWhiteboard = () => {+ const { classes } = useStyles();+ const { t } = useTranslation();+ const whiteboardEnabled = useSelector(isWhiteboardEnabled);+ const collabDetails = useSelector(getCollabDetails);+ const collabServerUrl = useSelector(getCollabServerUrl);+ const locationURL = useSelector((state: IReduxState) => state['features/base/connection'].locationURL);+ const defaultRemoteDisplayName = useSelector(+ (state: IReduxState) => state['features/base/config'].defaultRemoteDisplayName);+ const localParticipantName+ = useSelector((state: IReduxState) => getLocalParticipant(state)?.name)+ || defaultRemoteDisplayName || 'Fellow Jitster';++ // Build the standalone whiteboard URL from the canonical meeting location+ // (base/connection), not window.location: the latter can carry a+ // `#config.x=...` fragment whose own `/` characters break the path+ // derivation in getWhiteboardInfoForURIString. Strip hash/query first.+ const url = whiteboardEnabled && collabDetails && collabServerUrl && locationURL+ ? getWhiteboardInfoForURIString(+ getURLWithoutParams(locationURL).href,+ collabServerUrl,+ collabDetails,+ localParticipantName)+ : undefined;++ if (!url) {+ return (+ <div className = { classes.placeholder }>+ <div className = { classes.message }>+ { t('multiScreen.whiteboardInactive') }+ </div>+ </div>+ );+ }++ // Scope the embedded whiteboard, mirroring the native WebView's no-multi-window+ // and navigation-interception scoping: allow the same-origin app to run and+ // export drawings, but block top-level navigation and form submission.+ // allow-same-origin is required for the collab/storage session; combined with+ // allow-scripts the boundary is soft for same-origin content, so this is+ // defense-in-depth rather than a hard sandbox.+ return (+ <iframe+ allow = 'clipboard-read; clipboard-write'+ className = { classes.whiteboard }+ sandbox = 'allow-same-origin allow-scripts allow-downloads allow-popups'+ src = { url }+ title = { t('multiScreen.whiteboardTitle') } />+ );+};++export default SecondScreenWhiteboard;diff --git a/react/features/multi-screen/functions.web.ts b/react/features/multi-screen/functions.web.tsindex 5b209fbb62..4f90f68c22 100644--- a/react/features/multi-screen/functions.web.ts+++ b/react/features/multi-screen/functions.web.ts@@ -2,9 +2,13 @@ import createCache, { EmotionCache } from '@emotion/cache';import { IReduxState, IStore } from '../app/types';import { MEDIA_TYPE, VIDEO_TYPE } from '../base/media/constants';-import { getParticipantById } from '../base/participants/functions';+import { getParticipantById, isScreenShareParticipant } from '../base/participants/functions';import { IParticipant } from '../base/participants/types';-import { getTrackByMediaTypeAndParticipant, getVideoTrackByParticipant } from '../base/tracks/functions.any';+import {+ getTrackByMediaTypeAndParticipant,+ getVideoTrackByParticipant,+ getVirtualScreenshareParticipantTrack+} from '../base/tracks/functions.any';import { getLargeVideoParticipant } from '../large-video/functions';import { removeSecondScreen, setSecondScreenWindow } from './actions.web';@@ -20,6 +24,16 @@ import { ISecondScreenSource } from './types';*/const SECOND_SCREEN_CACHE_KEY = 'secondscreen';+/**+ * The app's base font stack, mirroring the baseFontFamily SCSS variable. The+ * second window does not load the app's global stylesheet, so without setting this+ * on its body the text falls back to the browser default serif font. The+ * open_sanslight webfont is also not loaded in the popup, so it falls through to+ * the system sans-serif, which is the intended look.+ */+const SECOND_SCREEN_FONT_FAMILY+ = '-apple-system, BlinkMacSystemFont, open_sanslight, \'Helvetica Neue\', Helvetica, Arial, sans-serif';+/*** 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@@ -107,9 +121,18 @@ export function resolveSource(state: IReduxState, source: ISecondScreenSource) {participant = iTrack ? getParticipantById(state, iTrack.participantId) : undefined;} else if (source.participant) {participant = getParticipantById(state, source.participant);- const mediaType = source.media === 'desktop' ? MEDIA_TYPE.SCREENSHARE : MEDIA_TYPE.VIDEO;- iTrack = getTrackByMediaTypeAndParticipant(tracks, mediaType, source.participant);+ // A virtual screenshare participant (<owner>-v<n>) owns no track under its+ // own id: its screenshare track is owned by the endpoint id, so resolve it+ // through the owner, else a pinned screenshare falls back to the avatar. For+ // a real participant, media selects camera vs. screen, keeping the surface+ // identical to the external API on master.+ iTrack = isScreenShareParticipant(participant)+ ? getVirtualScreenshareParticipantTrack(tracks, source.participant)+ : getTrackByMediaTypeAndParticipant(+ tracks,+ source.media === 'desktop' ? MEDIA_TYPE.SCREENSHARE : MEDIA_TYPE.VIDEO,+ source.participant);}const track = iTrack && !iTrack.muted@@ -147,6 +170,27 @@ export function getSecondScreenSignature(state: IReduxState): string {.join('|');}+/**+ * Computes the tile-grid dimensions (columns and rows) for a number of+ * participants, using a Jitsi-style heuristic:+ * {@code columns = min(ceil(sqrt(n)), maxColumns, n)}. Pure, so it is easy to+ * unit-test in isolation.+ *+ * @param {number} count - The number of participants to lay out.+ * @param {number} maxColumns - The maximum number of columns allowed.+ * @returns {Object} The grid dimensions as { columns, rows }.+ */+export function getGalleryGridDimensions(count: number, maxColumns: number): { columns: number; rows: number; } {+ if (count <= 0) {+ return { columns: 1, rows: 1 };+ }++ const columns = Math.min(Math.ceil(Math.sqrt(count)), maxColumns, count);+ const rows = Math.ceil(count / columns);++ return { columns, rows };+}+/*** Computes the {@code window.open} features string, placing the window on a* physical screen via the Window Management API. Rejects if the API is@@ -178,7 +222,18 @@ function buildWindow(win: Window): HTMLElement {doc.title = 'Jitsi Meet';Object.assign(doc.documentElement.style, { height: '100%' });- Object.assign(doc.body.style, { margin: '0', height: '100%', background: '#000', overflow: 'hidden' });++ // The popup does not load the app's global stylesheet, so set the base+ // typography (font + text colour) here, otherwise text falls back to the+ // browser default serif font in black.+ Object.assign(doc.body.style, {+ margin: '0',+ height: '100%',+ background: '#000',+ color: '#fff',+ fontFamily: SECOND_SCREEN_FONT_FAMILY,+ overflow: 'hidden'+ });const root = doc.createElement('div');diff --git a/react/features/multi-screen/hooks.web.ts b/react/features/multi-screen/hooks.web.tsnew file mode 100644index 0000000000..495fd7f6c2--- /dev/null+++ b/react/features/multi-screen/hooks.web.ts@@ -0,0 +1,50 @@+import { useMemo } from 'react';+import { useSelector } from 'react-redux';++import { IReduxState } from '../app/types';+import {+ getDominantSpeakerParticipant,+ getLocalParticipant,+ getLocalScreenShareParticipant+} from '../base/participants/functions';++/**+ * Returns the ordered participant ids for a second-screen layout: the local+ * participant first, then your own shared screen (a virtual participant) when+ * sharing, then the remote participants. Mirrors the main filmstrip ordering.+ *+ * The remote ids come from the filmstrip's {@code remoteParticipants} array,+ * which is reassigned immutably on join/leave (the base participants map is+ * mutated in place, so selecting it directly would not re-render on membership+ * changes).+ *+ * @returns {string[]}+ */+export function useSecondScreenParticipantIds(): string[] {+ const localId = useSelector((state: IReduxState) => getLocalParticipant(state)?.id);+ const localScreenShareId = useSelector((state: IReduxState) => getLocalScreenShareParticipant(state)?.id);+ const remoteParticipantIds = useSelector((state: IReduxState) => state['features/filmstrip'].remoteParticipants);++ return useMemo(() => {+ const ids: string[] = [];++ if (localId) {+ ids.push(localId);+ }+ if (localScreenShareId) {+ ids.push(localScreenShareId);+ }++ return ids.concat(remoteParticipantIds);+ }, [ localId, localScreenShareId, remoteParticipantIds ]);+}++/**+ * Returns the id of the conference dominant speaker, or {@code null}. Drives the+ * speaking ring on the second-screen tiles.+ *+ * @returns {string | null}+ */+export function useDominantSpeakerId(): string | null {+ return useSelector((state: IReduxState) => getDominantSpeakerParticipant(state)?.id ?? null);+}diff --git a/react/features/multi-screen/middleware.web.ts b/react/features/multi-screen/middleware.web.tsindex 90cd2c4ef1..a279c78826 100644--- a/react/features/multi-screen/middleware.web.ts+++ b/react/features/multi-screen/middleware.web.ts@@ -11,47 +11,64 @@ import './subscriber.web';/*** Middleware that reconciles the live second-screen windows with the requested- * state, and tears them all down when the conference ends.+ * state, tears them all down when the conference ends, and closes any that are+ * still open when the main window itself goes away.** @param {IStore} store - The redux store.* @returns {Function}*/-MiddlewareRegistry.register((store: IStore) => next => action => {- switch (action.type) {- case SET_SECOND_SCREEN: {- const result = next(action);+MiddlewareRegistry.register((store: IStore) => {- openOrUpdateSecondScreen(store, action.id, action.screenId)- .catch(e => logger.error('Failed to open second screen', e));+ // Close every second-screen window when the main window goes away (tab closed,+ // reloaded, or navigated away). The CONFERENCE_LEFT/FAILED path below only+ // covers leaving the meeting from within the app; closing the main window+ // directly dispatches neither, so without this the popups are orphaned on the+ // second display. Closing from an unloading opener is best-effort. Skip+ // event.persisted (bfcache eviction): the page may be restored via pageshow+ // with the second screens still expected, so only tear down on a real unload.+ window.addEventListener('pagehide', (event: PageTransitionEvent) => {+ if (!event.persisted) {+ closeAllSecondScreens(store);+ }+ });- return result;- }- case REMOVE_SECOND_SCREEN: {+ return next => action => {+ switch (action.type) {+ case SET_SECOND_SCREEN: {+ const result = next(action);- // 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);+ openOrUpdateSecondScreen(store, action.id, action.screenId)+ .catch(e => logger.error('Failed to open second screen', e));- closeSecondScreenHandle(handle, action.id);+ return result;+ }+ case REMOVE_SECOND_SCREEN: {- return result;- }- case RESET_SECOND_SCREENS:+ // 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);- // Same ordering: close the windows while their entries are still in state.- closeAllSecondScreens(store);+ closeSecondScreenHandle(handle, action.id);- return next(action);- case CONFERENCE_FAILED:- case CONFERENCE_LEFT:+ return result;+ }+ case RESET_SECOND_SCREENS:++ // Same ordering: close the windows while their entries are still in state.+ closeAllSecondScreens(store);- // Resetting closes every second-screen window (via the RESET_SECOND_SCREENS- // case above), so there is no need to close them explicitly here.- store.dispatch(resetSecondScreens());- break;- }+ return next(action);+ case CONFERENCE_FAILED:+ case CONFERENCE_LEFT:- return next(action);+ // Resetting closes every second-screen window (via the RESET_SECOND_SCREENS+ // case above), so there is no need to close them explicitly here.+ store.dispatch(resetSecondScreens());+ break;+ }++ return next(action);+ };});diff --git a/react/features/multi-screen/types.ts b/react/features/multi-screen/types.tsindex 1494b19996..0ff623befd 100644--- a/react/features/multi-screen/types.ts+++ b/react/features/multi-screen/types.ts@@ -18,9 +18,10 @@ export interface ISecondScreenSource {participant?: string;/**- * A role to follow: the active-speaker stage, or the current screenshare.+ * What the window shows: the active-speaker stage, the current screenshare,+ * a tile grid of every participant, or the shared whiteboard.*/- role?: 'stage' | 'screenshare';+ role?: 'stage' | 'screenshare' | 'tile' | 'whiteboard';}/**