import { useState, useEffect, useRef } from 'react'; import { useScreenVideoTrack } from '@daily-co/daily-react'; import { useParticipants } from './useParticipants'; /** * View modes for the demo experience */ export type ViewMode = 'discovery' | 'presentation'; /** * Custom hook for automatic view mode switching based on screenshare presence. * * Switches between: * - **Discovery Mode**: Avatar-focused (default, when no screenshare active) * - **Presentation Mode**: Slideshow-focused (when slideshow participant is screensharing) * * @param onModeChange - Optional callback fired when mode changes * @returns Current view mode * * @example * ```tsx * const viewMode = useViewMode((mode) => { * console.log('Switched to', mode); * }); * * return viewMode === 'presentation' ? : ; * ``` */ export const useViewMode = ( onModeChange?: (mode: ViewMode) => void ): ViewMode => { const { slideshow } = useParticipants(); const slideshowScreenTrack = useScreenVideoTrack(slideshow?.session_id || ''); const [viewMode, setViewMode] = useState('discovery'); // Store callback in ref to avoid effect re-runs when it changes const onModeChangeRef = useRef(onModeChange); useEffect(() => { onModeChangeRef.current = onModeChange; }, [onModeChange]); useEffect(() => { // Check if slideshow participant is actively sharing screen // Use Daily's useScreenVideoTrack hook which provides isOff state const isSlideshowActive = slideshow && !slideshowScreenTrack.isOff; const newMode: ViewMode = isSlideshowActive ? 'presentation' : 'discovery'; if (newMode !== viewMode) { // Add small debounce to prevent rapid switching const timeoutId = setTimeout(() => { setViewMode(newMode); onModeChangeRef.current?.(newMode); // Optional: Log for debugging if (process.env.NODE_ENV === 'development') { console.log('[useViewMode] Switched to:', newMode, { slideshowPresent: !!slideshow, screenshareActive: isSlideshowActive, }); } }, 100); // 100ms debounce return () => clearTimeout(timeoutId); } }, [slideshow, slideshowScreenTrack.isOff, viewMode]); return viewMode; };