mirror of
https://github.com/suitenumerique/meet.git
synced 2026-08-21 07:36:43 +00:00
♻️(refactor) move pip feature into dedicated module
group pip components and hooks under features/pip for isolation
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useDocumentPiP } from '../hooks/useDocumentPiP'
|
||||
import { UNSAFE_PortalProvider } from '@react-aria/overlays'
|
||||
|
||||
// Minimal base styles so the PiP window renders correctly on first paint.
|
||||
const ensureBaseStyles = (target: Document) => {
|
||||
if (target.getElementById('pip-base-styles')) return
|
||||
const style = target.createElement('style')
|
||||
style.id = 'pip-base-styles'
|
||||
style.textContent = `
|
||||
html, body { margin: 0; padding: 0; height: 100%; background: #0b0f19; }
|
||||
body { overflow: hidden; }
|
||||
* { box-sizing: border-box; }
|
||||
`
|
||||
target.head.appendChild(style)
|
||||
}
|
||||
|
||||
// Clone existing styles to keep the PiP window visually consistent.
|
||||
const copyStyles = (source: Document, target: Document) => {
|
||||
if (target.getElementById('pip-style-clone')) return
|
||||
const marker = target.createElement('meta')
|
||||
marker.id = 'pip-style-clone'
|
||||
target.head.appendChild(marker)
|
||||
|
||||
source.querySelectorAll('style, link[rel="stylesheet"]').forEach((node) => {
|
||||
const cloned = node.cloneNode(true) as HTMLElement
|
||||
target.head.appendChild(cloned)
|
||||
})
|
||||
}
|
||||
|
||||
const syncThemeAttribute = (source: Document, target: Document) => {
|
||||
const theme = source.documentElement.getAttribute('data-lk-theme')
|
||||
if (theme) {
|
||||
target.documentElement.setAttribute('data-lk-theme', theme)
|
||||
}
|
||||
}
|
||||
|
||||
const cssVarNameCacheByElement = new WeakMap<HTMLElement, string[]>()
|
||||
const cssVarNameCacheByUri = new Map<string, string[]>()
|
||||
|
||||
const syncCssVariables = (source: Document, target: Document) => {
|
||||
const sourceView = source.defaultView
|
||||
if (!sourceView) return
|
||||
|
||||
const getCachedVarNames = () => {
|
||||
const docEl = source.documentElement
|
||||
if (!docEl) return []
|
||||
|
||||
const cachedByElement = cssVarNameCacheByElement.get(docEl)
|
||||
if (cachedByElement) return cachedByElement
|
||||
|
||||
const cachedByUri = source.baseURI
|
||||
? cssVarNameCacheByUri.get(source.baseURI)
|
||||
: undefined
|
||||
if (cachedByUri) return cachedByUri
|
||||
|
||||
const varNames = new Set<string>()
|
||||
const collectVarsFrom = (element: HTMLElement | null) => {
|
||||
if (!element) return
|
||||
const styles = sourceView.getComputedStyle(element)
|
||||
for (let i = 0; i < styles.length; i += 1) {
|
||||
const property = styles[i]
|
||||
if (property.startsWith('--')) {
|
||||
varNames.add(property)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collectVarsFrom(source.documentElement)
|
||||
collectVarsFrom(source.body)
|
||||
|
||||
const result = Array.from(varNames)
|
||||
cssVarNameCacheByElement.set(docEl, result)
|
||||
if (source.baseURI) {
|
||||
cssVarNameCacheByUri.set(source.baseURI, result)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const varNames = getCachedVarNames()
|
||||
if (!varNames.length) return
|
||||
|
||||
const rootStyles = sourceView.getComputedStyle(source.documentElement)
|
||||
const bodyStyles = source.body
|
||||
? sourceView.getComputedStyle(source.body)
|
||||
: null
|
||||
|
||||
varNames.forEach((property) => {
|
||||
const bodyValue = bodyStyles?.getPropertyValue(property)
|
||||
const value = bodyValue || rootStyles.getPropertyValue(property)
|
||||
if (value) {
|
||||
target.documentElement.style.setProperty(property, value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* React Portal that renders children into a Document Picture-in-Picture window.
|
||||
* Handles PiP window lifecycle, style injection, React root management, and uses UNSAFE_PortalProvider
|
||||
* to ensure React Aria overlays render correctly within the PiP window.
|
||||
* Creates a fresh React root on reopen to prevent black screen issues.
|
||||
*/
|
||||
export const DocumentPiPPortal = ({
|
||||
isOpen,
|
||||
width,
|
||||
height,
|
||||
children,
|
||||
onClose,
|
||||
}: {
|
||||
isOpen: boolean
|
||||
width?: number
|
||||
height?: number
|
||||
children: React.ReactNode
|
||||
onClose?: () => void
|
||||
}) => {
|
||||
const { openPiP, closePiP, pipWindow, isSupported } = useDocumentPiP({
|
||||
width,
|
||||
height,
|
||||
})
|
||||
const [container, setContainer] = useState<HTMLElement | null>(null)
|
||||
const containerRef = useRef<HTMLElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
closePiP()
|
||||
setContainer(null)
|
||||
containerRef.current = null
|
||||
return
|
||||
}
|
||||
|
||||
if (!isSupported) return
|
||||
|
||||
let cancelled = false
|
||||
openPiP().then((win) => {
|
||||
if (!win || cancelled) return
|
||||
const doc = win.document
|
||||
ensureBaseStyles(doc)
|
||||
copyStyles(document, doc)
|
||||
syncThemeAttribute(document, doc)
|
||||
syncCssVariables(document, doc)
|
||||
const existingContainer = containerRef.current
|
||||
if (!existingContainer || existingContainer.ownerDocument !== doc) {
|
||||
const nextContainer = doc.createElement('div')
|
||||
nextContainer.id = 'pip-root'
|
||||
nextContainer.style.width = '100%'
|
||||
nextContainer.style.height = '100%'
|
||||
nextContainer.style.display = 'flex'
|
||||
nextContainer.style.alignItems = 'stretch'
|
||||
nextContainer.style.justifyContent = 'center'
|
||||
doc.body.appendChild(nextContainer)
|
||||
containerRef.current = nextContainer
|
||||
setContainer(nextContainer)
|
||||
} else {
|
||||
setContainer(existingContainer)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [closePiP, isOpen, isSupported, openPiP])
|
||||
|
||||
useEffect(() => {
|
||||
if (!pipWindow) return
|
||||
const handleClose = () => {
|
||||
// Reset container so reopening PiP mounts a fresh root.
|
||||
containerRef.current = null
|
||||
setContainer(null)
|
||||
onClose?.()
|
||||
}
|
||||
pipWindow.addEventListener('pagehide', handleClose)
|
||||
pipWindow.addEventListener('beforeunload', handleClose)
|
||||
return () => {
|
||||
pipWindow.removeEventListener('pagehide', handleClose)
|
||||
pipWindow.removeEventListener('beforeunload', handleClose)
|
||||
}
|
||||
}, [onClose, pipWindow])
|
||||
|
||||
const portal = useMemo(() => {
|
||||
if (!container) return null
|
||||
return createPortal(
|
||||
// "UNSAFE" because it bypasses react-aria's default portal container.
|
||||
// We need it to target the PiP document; otherwise overlays render in the main window.
|
||||
<UNSAFE_PortalProvider getContainer={() => container}>
|
||||
{children}
|
||||
</UNSAFE_PortalProvider>,
|
||||
container
|
||||
)
|
||||
}, [children, container])
|
||||
|
||||
return portal
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { styled } from '@/styled-system/jsx'
|
||||
import { AudioDevicesControl } from '@/features/rooms/livekit/components/controls/Device/AudioDevicesControl'
|
||||
import { VideoDeviceControl } from '@/features/rooms/livekit/components/controls/Device/VideoDeviceControl'
|
||||
import { ScreenShareToggle } from '@/features/rooms/livekit/components/controls/ScreenShareToggle'
|
||||
import { LeaveButton } from '@/features/rooms/livekit/components/controls/LeaveButton'
|
||||
import { ReactionsToggle } from '@/features/rooms/livekit/components/controls/ReactionsToggle'
|
||||
import { SubtitlesToggle } from '@/features/rooms/livekit/components/controls/SubtitlesToggle'
|
||||
import { HandToggle } from '@/features/rooms/livekit/components/controls/HandToggle'
|
||||
import { OptionsButton } from '@/features/rooms/livekit/components/controls/Options/OptionsButton'
|
||||
import { StartMediaButton } from '@/features/rooms/livekit/components/controls/StartMediaButton'
|
||||
import { PipLateralMenu } from './controls/PipLateralMenu'
|
||||
|
||||
/**
|
||||
* Compact control bar for the Picture-in-Picture window.
|
||||
* Centralizes all PiP controls (devices, reactions, screen share, options, etc.) in one reusable component.
|
||||
*/
|
||||
export const PipControlBar = ({
|
||||
showScreenShare,
|
||||
}: {
|
||||
showScreenShare: boolean
|
||||
}) => (
|
||||
<PipControls>
|
||||
<PipControlsCenter>
|
||||
<AudioDevicesControl hideMenu />
|
||||
<VideoDeviceControl hideMenu />
|
||||
<ReactionsToggle />
|
||||
{showScreenShare && <ScreenShareToggle />}
|
||||
<SubtitlesToggle />
|
||||
<HandToggle />
|
||||
<OptionsButton />
|
||||
<LeaveButton />
|
||||
<StartMediaButton />
|
||||
</PipControlsCenter>
|
||||
<PipControlsRight>
|
||||
<PipLateralMenu />
|
||||
</PipControlsRight>
|
||||
</PipControls>
|
||||
)
|
||||
|
||||
const PipControls = styled('div', {
|
||||
base: {
|
||||
flex: '0 0 auto',
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
padding: '0.5rem 0.75rem',
|
||||
backgroundColor: 'primaryDark.50',
|
||||
width: '100%',
|
||||
position: 'relative',
|
||||
},
|
||||
})
|
||||
|
||||
const PipControlsCenter = styled('div', {
|
||||
base: {
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
gap: '0.4rem',
|
||||
flex: '1 1 auto',
|
||||
},
|
||||
})
|
||||
|
||||
const PipControlsRight = styled('div', {
|
||||
base: {
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
alignItems: 'center',
|
||||
position: 'absolute',
|
||||
right: '1.35rem',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { styled } from '@/styled-system/jsx'
|
||||
import { supportsScreenSharing } from '@livekit/components-core'
|
||||
import {
|
||||
isTrackReference,
|
||||
TrackReferenceOrPlaceholder,
|
||||
} from '@livekit/components-core'
|
||||
import { useTracks } from '@livekit/components-react'
|
||||
import { Track } from 'livekit-client'
|
||||
import { ParticipantTile } from '@/features/rooms/livekit/components/ParticipantTile'
|
||||
import { GridLayout } from '@/features/rooms/livekit/components/layout/GridLayout'
|
||||
import { SidePanel } from '@/features/rooms/livekit/components/SidePanel'
|
||||
import { PipControlBar } from './PipControlBar'
|
||||
|
||||
const pickTrackForPip = (
|
||||
tracks: TrackReferenceOrPlaceholder[]
|
||||
): TrackReferenceOrPlaceholder | undefined => {
|
||||
// Prefer screen share when present; otherwise fallback to first available track.
|
||||
const screenShareTrack = tracks
|
||||
.filter(isTrackReference)
|
||||
.find((track) => track.publication.source === Track.Source.ScreenShare)
|
||||
|
||||
if (screenShareTrack) return screenShareTrack
|
||||
return tracks[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* Main view component for the Picture-in-Picture window.
|
||||
* Handles track selection (prioritizes screen share), layout switching (grid for multiple participants),
|
||||
* and renders the control bar and side panel within the PiP window.
|
||||
*/
|
||||
export const PipView = () => {
|
||||
const tracks = useTracks(
|
||||
[
|
||||
{ source: Track.Source.Camera, withPlaceholder: true },
|
||||
{ source: Track.Source.ScreenShare, withPlaceholder: false },
|
||||
],
|
||||
{ onlySubscribed: false }
|
||||
)
|
||||
|
||||
const trackRef = pickTrackForPip(tracks)
|
||||
const browserSupportsScreenSharing = supportsScreenSharing()
|
||||
const hasMultipleTiles = tracks.length > 1
|
||||
|
||||
if (!trackRef && !hasMultipleTiles) return null
|
||||
|
||||
return (
|
||||
<PipContainer>
|
||||
{/* Keep stage height stable to avoid layout shifting on track changes. */}
|
||||
<PipStage>
|
||||
{hasMultipleTiles ? (
|
||||
<PipGridWrapper>
|
||||
<GridLayout tracks={tracks} style={{ height: '100%' }}>
|
||||
<ParticipantTile disableMetadata />
|
||||
</GridLayout>
|
||||
</PipGridWrapper>
|
||||
) : (
|
||||
<ParticipantTile trackRef={trackRef} disableMetadata />
|
||||
)}
|
||||
</PipStage>
|
||||
{/* Compact control bar for PiP; extend here when adding more actions. */}
|
||||
<PipControlBar showScreenShare={browserSupportsScreenSharing} />
|
||||
{/* Side panel (effects, settings, etc.) opens within PiP window. */}
|
||||
<SidePanel />
|
||||
</PipContainer>
|
||||
)
|
||||
}
|
||||
|
||||
const PipContainer = styled('div', {
|
||||
base: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'grid',
|
||||
gridTemplateRows: 'minmax(0, 1fr) auto',
|
||||
backgroundColor: 'primaryDark.50',
|
||||
'& .lk-participant-tile': {
|
||||
height: '100%',
|
||||
},
|
||||
'& .lk-participant-media': {
|
||||
height: '100%',
|
||||
},
|
||||
'& .lk-participant-media-video': {
|
||||
height: '100%',
|
||||
objectFit: 'cover',
|
||||
},
|
||||
'& .lk-grid-layout': {
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const PipStage = styled('div', {
|
||||
base: {
|
||||
position: 'relative',
|
||||
minHeight: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const PipGridWrapper = styled('div', {
|
||||
base: {
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { DocumentPiPPortal } from './DocumentPiPPortal'
|
||||
import { PipView } from './PipView'
|
||||
import { useRoomPiP } from '../hooks/useRoomPiP'
|
||||
|
||||
/**
|
||||
* Wrapper that mounts the PiP UI when room-level PiP state is enabled.
|
||||
* Bridges Valtio-backed PiP state with DocumentPiPPortal and PipView rendering.
|
||||
*/
|
||||
export const RoomPiP = () => {
|
||||
const { isOpen, close } = useRoomPiP()
|
||||
|
||||
return (
|
||||
<DocumentPiPPortal isOpen={isOpen} onClose={close}>
|
||||
<PipView />
|
||||
</DocumentPiPPortal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { css } from '@/styled-system/css'
|
||||
import { useState } from 'react'
|
||||
import { Dialog, DialogTrigger } from 'react-aria-components'
|
||||
import { Button } from '@/primitives'
|
||||
import { RiArrowDownSLine, RiArrowUpSLine } from '@remixicon/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { StyledPopover } from '@/primitives/Popover'
|
||||
import { useOverlayBoundaryElement } from '@/primitives/useOverlayPortalContainer'
|
||||
import { ChatToggle } from '@/features/rooms/livekit/components/controls/ChatToggle'
|
||||
import { ParticipantsToggle } from '@/features/rooms/livekit/components/controls/Participants/ParticipantsToggle'
|
||||
import { ToolsToggle } from '@/features/rooms/livekit/components/controls/ToolsToggle'
|
||||
import { InfoToggle } from '@/features/rooms/livekit/components/controls/InfoToggle'
|
||||
import { AdminToggle } from '@/features/rooms/livekit/components/AdminToggle'
|
||||
|
||||
const NavigationControls = ({ onPress }: { onPress?: () => void }) => (
|
||||
<>
|
||||
<InfoToggle onPress={onPress} tooltipType="delayed" />
|
||||
<ChatToggle onPress={onPress} tooltipType="delayed" />
|
||||
<ParticipantsToggle onPress={onPress} tooltipType="delayed" />
|
||||
<ToolsToggle onPress={onPress} tooltipType="delayed" />
|
||||
<AdminToggle onPress={onPress} tooltipType="delayed" />
|
||||
</>
|
||||
)
|
||||
|
||||
/**
|
||||
* PiP chevron menu that exposes Info/Chat/Participants/Tools/Admin.
|
||||
*/
|
||||
export const PipLateralMenu = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const boundaryElement = useOverlayBoundaryElement()
|
||||
|
||||
const handlePress = () => setIsOpen(!isOpen)
|
||||
const handleClose = () => setIsOpen(false)
|
||||
|
||||
return (
|
||||
<DialogTrigger isOpen={isOpen} onOpenChange={setIsOpen}>
|
||||
<Button
|
||||
id="pip-controlbar-more-options-trigger"
|
||||
square
|
||||
variant="secondaryDark"
|
||||
aria-label={t('controls.moreOptions')}
|
||||
tooltip={t('controls.moreOptions')}
|
||||
onPress={handlePress}
|
||||
>
|
||||
{isOpen ? <RiArrowDownSLine /> : <RiArrowUpSLine />}
|
||||
</Button>
|
||||
<StyledPopover placement="top" boundaryElement={boundaryElement}>
|
||||
<Dialog
|
||||
className={css({
|
||||
width: '65px',
|
||||
backgroundColor: 'primaryDark.50',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
borderRadius: '4px',
|
||||
paddingTop: '10px',
|
||||
gap: '0.5rem',
|
||||
})}
|
||||
>
|
||||
<NavigationControls onPress={handleClose} />
|
||||
</Dialog>
|
||||
</StyledPopover>
|
||||
</DialogTrigger>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import React, { useEffect } from 'react'
|
||||
import { RiMoreFill } from '@remixicon/react'
|
||||
import { Box, Button } from '@/primitives'
|
||||
import { css } from '@/styled-system/css'
|
||||
import { OptionsMenuItems } from '@/features/rooms/livekit/components/controls/Options/OptionsMenuItems'
|
||||
|
||||
type PipOptionsMenuProps = {
|
||||
wrapperRef: React.RefObject<HTMLDivElement>
|
||||
isOpen: boolean
|
||||
setIsOpen: (isOpen: boolean) => void
|
||||
label: string
|
||||
}
|
||||
|
||||
/**
|
||||
* PiP-specific options menu with absolute positioning for correct alignment in PiP window.
|
||||
* Renders locally (unlike standard Menu) and closes automatically on item click or outside click.
|
||||
*/
|
||||
export const PipOptionsMenu = ({
|
||||
wrapperRef,
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
label,
|
||||
}: PipOptionsMenuProps) => {
|
||||
// Close menu when a menu item action completes (e.g., transcription, effects, recording).
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const doc = wrapperRef.current?.ownerDocument ?? document
|
||||
|
||||
const handleMenuItemClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null
|
||||
const wrapper = wrapperRef.current
|
||||
if (!wrapper || !target) return
|
||||
|
||||
// Don't close if clicking the trigger button
|
||||
if (wrapper.querySelector('button')?.contains(target)) return
|
||||
|
||||
// Close if clicking a menu item (action will have fired)
|
||||
if (target.closest('[role="menuitem"]')) {
|
||||
// Use requestAnimationFrame to ensure action completes first, without visible delay
|
||||
requestAnimationFrame(() => {
|
||||
setIsOpen(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
doc.addEventListener('click', handleMenuItemClick, true)
|
||||
return () => {
|
||||
doc.removeEventListener('click', handleMenuItemClick, true)
|
||||
}
|
||||
}, [isOpen, setIsOpen, wrapperRef])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className={css({
|
||||
position: 'relative',
|
||||
})}
|
||||
>
|
||||
<Button
|
||||
id="room-options-trigger"
|
||||
square
|
||||
variant="primaryDark"
|
||||
aria-label={label}
|
||||
tooltip={label}
|
||||
onPress={() => setIsOpen(!isOpen)}
|
||||
>
|
||||
<RiMoreFill />
|
||||
</Button>
|
||||
{isOpen && (
|
||||
<div
|
||||
className={css({
|
||||
position: 'absolute',
|
||||
left: '50%',
|
||||
bottom: 'calc(100% + 0.85rem)',
|
||||
transform: 'translateX(-50%)',
|
||||
zIndex: 10,
|
||||
})}
|
||||
>
|
||||
<Box size="sm" type="popover" variant="dark">
|
||||
<OptionsMenuItems />
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
type DocumentPictureInPicture = {
|
||||
requestWindow: (options?: {
|
||||
width?: number
|
||||
height?: number
|
||||
}) => Promise<Window>
|
||||
}
|
||||
|
||||
type WindowWithDocumentPiP = Window & {
|
||||
documentPictureInPicture?: DocumentPictureInPicture
|
||||
}
|
||||
|
||||
export const useDocumentPiP = ({
|
||||
width = 480,
|
||||
height = 270,
|
||||
}: {
|
||||
width?: number
|
||||
height?: number
|
||||
} = {}) => {
|
||||
const [pipWindow, setPipWindow] = useState<Window | null>(null)
|
||||
const pipWindowRef = useRef<Window | null>(null)
|
||||
const pendingPiPRef = useRef<Promise<Window | null> | null>(null)
|
||||
|
||||
const [isSupported] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
return 'documentPictureInPicture' in window
|
||||
})
|
||||
|
||||
const openPiP = useCallback(async () => {
|
||||
if (!isSupported) return null
|
||||
const existingWindow = pipWindowRef.current
|
||||
if (existingWindow && !existingWindow.closed) return existingWindow
|
||||
|
||||
if (pendingPiPRef.current) return pendingPiPRef.current
|
||||
|
||||
// Request a new PiP window from the browser API.
|
||||
const pip = (window as WindowWithDocumentPiP).documentPictureInPicture
|
||||
if (!pip) return null
|
||||
|
||||
const requestPromise = (async () => {
|
||||
try {
|
||||
const win = await pip.requestWindow({ width, height })
|
||||
const currentWindow = pipWindowRef.current
|
||||
if (currentWindow && !currentWindow.closed) return currentWindow
|
||||
setPipWindow(win)
|
||||
return win
|
||||
} catch (error) {
|
||||
// Avoid unhandled rejections if the user blocks or closes the request.
|
||||
console.error('Failed to open Picture-in-Picture window', error)
|
||||
return null
|
||||
} finally {
|
||||
pendingPiPRef.current = null
|
||||
}
|
||||
})()
|
||||
|
||||
pendingPiPRef.current = requestPromise
|
||||
return requestPromise
|
||||
}, [height, isSupported, width])
|
||||
|
||||
const closePiP = useCallback(() => {
|
||||
if (!pipWindow) return
|
||||
if (!pipWindow.closed) {
|
||||
pipWindow.close()
|
||||
}
|
||||
setPipWindow(null)
|
||||
}, [pipWindow])
|
||||
|
||||
useEffect(() => {
|
||||
pipWindowRef.current = pipWindow
|
||||
}, [pipWindow])
|
||||
|
||||
useEffect(() => {
|
||||
if (!pipWindow) return
|
||||
|
||||
const handleClose = () => {
|
||||
setPipWindow(null)
|
||||
}
|
||||
|
||||
pipWindow.addEventListener('pagehide', handleClose)
|
||||
pipWindow.addEventListener('beforeunload', handleClose)
|
||||
|
||||
return () => {
|
||||
pipWindow.removeEventListener('pagehide', handleClose)
|
||||
pipWindow.removeEventListener('beforeunload', handleClose)
|
||||
}
|
||||
}, [pipWindow])
|
||||
|
||||
return {
|
||||
isSupported,
|
||||
isOpen: !!pipWindow && !pipWindow.closed,
|
||||
pipWindow,
|
||||
openPiP,
|
||||
closePiP,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useSnapshot } from 'valtio'
|
||||
import { roomPiPStore } from '@/stores/roomPiP'
|
||||
|
||||
export const useRoomPiP = () => {
|
||||
const { isOpen } = useSnapshot(roomPiPStore)
|
||||
const isSupported =
|
||||
typeof window !== 'undefined' && 'documentPictureInPicture' in window
|
||||
|
||||
const open = useCallback(() => {
|
||||
roomPiPStore.isOpen = true
|
||||
}, [])
|
||||
|
||||
const close = useCallback(() => {
|
||||
roomPiPStore.isOpen = false
|
||||
}, [])
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
roomPiPStore.isOpen = !roomPiPStore.isOpen
|
||||
}, [])
|
||||
|
||||
return {
|
||||
isSupported,
|
||||
isOpen,
|
||||
open,
|
||||
close,
|
||||
toggle,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user