import React, { useCallback, useEffect, useMemo, useReducer, useRef, useState, } from 'react'; import { FlatList, type StyleProp, StyleSheet, type ViewStyle, } from 'react-native'; import { type StreamVideoParticipant, type StreamVideoParticipantPatches, VisibilityState, } from '@stream-io/video-client'; import { useCall } from '@stream-io/video-react-bindings'; import { ComponentTestIds } from '../../../constants/TestIds'; import { ParticipantView as DefaultParticipantView, type ParticipantViewComponentProps, type ParticipantViewProps, } from '../../Participant/ParticipantView'; import type { CallContentProps } from '../CallContent'; import { useTheme } from '../../../contexts'; import { calculateParticipantViewSize, DEFAULT_NUMBER_OF_COLUMNS, getAutoNumberOfColumns, } from './gridSizing'; type FlatListProps = React.ComponentProps< typeof FlatList >; const VIEWABILITY_CONFIG: FlatListProps['viewabilityConfig'] = { waitForInteraction: false, itemVisiblePercentThreshold: 60, }; export type CallParticipantsListComponentProps = ParticipantViewComponentProps & { /** * Component to customize the participant view. */ ParticipantView?: React.ComponentType | null; /** * Forces a participant's video to be mirrored or unmirrored. By default, the video track * from the local participant is mirrored, and all other videos are not mirrored. */ mirror?: boolean; }; /** * Props of the CallParticipantsList component */ export type CallParticipantsListProps = CallParticipantsListComponentProps & Pick & { /** * The list of participants to display in the list */ participants: StreamVideoParticipant[]; /** * The number of columns to display in the list of participants while in vertical or horizontal scrolling mode. This property is only used when there are more than 2 participants. * When omitted, vertical lists pick between 2 and 4 columns based on the size of the list's container (see `evenGridColumns`), * so wide containers (landscape, tablets, large foldable displays) don't stretch the tiles. Horizontal lists default to 2. */ numberOfColumns?: number; /** * If true, the automatically picked number of columns is always even (2 or 4), * so the grid splits down the middle, where foldable devices have their hinge. * Ignored when `numberOfColumns` is set or in horizontal mode. */ evenGridColumns?: boolean; /** * If true, the list will be displayed in horizontal scrolling mode */ horizontal?: boolean; /** * Check if phone is in landscape mode. * This will apply the landscape mode styles to the component. */ landscape?: boolean; }; /** * This component displays a list of participants in a FlatList. * You can use this component to display participants either in a vertical or horizontal scrolling mode. * NOTE: this component depends on a flex container to calculate the width and height of the participant view, * hence it should be used only in a flex parent container */ export const CallParticipantsList = ({ numberOfColumns: numberOfColumnsProp, evenGridColumns, horizontal, participants, ParticipantView = DefaultParticipantView, ParticipantLabel, ParticipantNetworkQualityIndicator, ParticipantReaction, ParticipantVideoFallback, VideoRenderer, supportedReactions, landscape, mirror, }: CallParticipantsListProps) => { const styles = useStyles(); const [containerLayout, setContainerLayout] = useState({ width: 0, height: 0, }); // we use a HashSet to track the currently viewable participants // and a separate force update state to rerender the component to inform that the HashSet has changed // NOTE: we use set instead of array or object for O(1) lookup, add and delete // Lazy ref init: avoids recreating instances on every render (useRef doesn't support initializer fns) const viewableParticipantSessionIds = useRef>(null!); if (!viewableParticipantSessionIds.current) { viewableParticipantSessionIds.current = new Set(); } // Debounced force re-render: coalesces rapid viewability changes into a single // re-render 500ms after the last change (drives the FlatList `extraData` below). const [forceUpdateValue, forceRender] = useReducer((v: number) => v + 1, 0); const forceUpdateTimeout = useRef>(undefined); const forceUpdate = useCallback(() => { clearTimeout(forceUpdateTimeout.current); forceUpdateTimeout.current = setTimeout(forceRender, 500); }, []); useEffect(() => () => clearTimeout(forceUpdateTimeout.current), []); // we use a ref to store the active call object // so that it can be used in the onViewableItemsChanged callback const activeCall = useCall(); const activeCallRef = useRef(activeCall); activeCallRef.current = activeCall; // This is the function that gets called when the user scrolls the list of participants. // It updates viewableParticipantSessionIds HashSet with the session IDs // of the participants that are currently visible. const onViewableItemsChanged = useCallback< NonNullable >( ({ viewableItems }) => { const participantPatches: StreamVideoParticipantPatches = {}; let mustUpdate = false; const newVisibleParticipantSessionIds = new Set( viewableItems.map((v) => v.key), ); const oldVisibleParticipantSessionIds = viewableParticipantSessionIds.current; const visibilityPatch = ( videoTrack: VisibilityState, ): StreamVideoParticipantPatches[string] => ({ viewportVisibilityState: { videoTrack, screenShareTrack: VisibilityState.UNKNOWN, }, }); newVisibleParticipantSessionIds.forEach((key) => { if (!oldVisibleParticipantSessionIds.has(key)) { mustUpdate = true; participantPatches[key] = visibilityPatch(VisibilityState.VISIBLE); } }); oldVisibleParticipantSessionIds.forEach((key) => { if (!newVisibleParticipantSessionIds.has(key)) { mustUpdate = true; participantPatches[key] = visibilityPatch(VisibilityState.INVISIBLE); } }); viewableParticipantSessionIds.current = newVisibleParticipantSessionIds; if (mustUpdate) { activeCallRef.current?.state.updateParticipants(participantPatches); forceUpdate(); } }, [forceUpdate], ); // NOTE: key must be sessionId always as it is used to track viewable participants const keyExtractor = useCallback>( (item) => item.sessionId, [], ); const onLayout = useCallback>( (event) => { const { height, width } = event.nativeEvent.layout; setContainerLayout((prev) => { if (prev.height === height && prev.width === width) { return prev; } return { height, width }; }); }, [], ); const numberOfColumns = numberOfColumnsProp ?? (horizontal ? DEFAULT_NUMBER_OF_COLUMNS : getAutoNumberOfColumns({ containerHeight: containerLayout.height, containerWidth: containerLayout.width, participantsLength: participants.length, evenGridColumns, })); const { itemHeight, itemWidth } = calculateParticipantViewSize({ containerHeight: containerLayout.height, containerWidth: containerLayout.width, participantsLength: participants.length, numberOfColumns, horizontal, margin: styles.participant.margin, horizontalMargin: styles.participantWrapperHorizontal.marginHorizontal, }); const itemContainerStyle = useMemo>(() => { const style = { width: itemWidth, height: itemHeight, margin: styles.participant.margin, }; if (horizontal) { return [styles.participantWrapperHorizontal, style]; } if (landscape) { return [styles.landScapeStyle, style]; } return style; }, [itemWidth, itemHeight, horizontal, landscape, styles]); const participantProps = useMemo( () => ({ ParticipantLabel, ParticipantNetworkQualityIndicator, ParticipantReaction, ParticipantVideoFallback, VideoRenderer, }), [ ParticipantLabel, ParticipantNetworkQualityIndicator, ParticipantReaction, ParticipantVideoFallback, VideoRenderer, ], ); const renderItem = useCallback>( ({ item: participant }) => { const isVisible = viewableParticipantSessionIds.current.has( participant.sessionId, ); return ( <> {ParticipantView && ( )} ); }, [ ParticipantView, itemContainerStyle, participantProps, supportedReactions, mirror, ], ); // in vertical mode, only when there are more than 2 participants in a call, the participants should be displayed in a grid // else we display them both in a stretched row on the screen const shouldWrapByColumns = !!horizontal || participants.length > 2; if (!shouldWrapByColumns) { return ( <> {participants.map((participant, index) => { return ( ParticipantView && ( ) ); })} ); } return ( ); }; const useStyles = () => { const { theme } = useTheme(); return useMemo( () => StyleSheet.create({ flexed: { flex: 1 }, participantWrapperHorizontal: { marginHorizontal: theme.variants.spacingSizes.sm, borderRadius: theme.variants.borderRadiusSizes.sm, }, landScapeStyle: { borderRadius: theme.variants.borderRadiusSizes.sm, }, participant: { margin: theme.variants.spacingSizes.xs, }, }), [theme], ); };