Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
blacksky.community src components Post Embed VideoEmbed VideoEmbedInner web-controls VideoControls.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445import {useCallback, useEffect, useRef, useState} from 'react'import {Pressable, View} from 'react-native'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {Trans} from '@lingui/react/macro'
import {formatTime} from '#/lib/media/video/formatTime'import {clamp} from '#/lib/numbers'import { useAutoplayDisabled, useSetSubtitlesEnabled, useSubtitlesEnabled,} from '#/state/preferences'import {atoms as a, useTheme, web} from '#/alf'import {useIsWithinMessage} from '#/components/dms/MessageContext'import {useFullscreen} from '#/components/hooks/useFullscreen'import {useInteractionState} from '#/components/hooks/useInteractionState'import { ArrowsDiagonalIn_Stroke2_Corner0_Rounded as ArrowsInIcon, ArrowsDiagonalOut_Stroke2_Corner0_Rounded as ArrowsOutIcon,} from '#/components/icons/ArrowsDiagonal'import { CC_Filled_Corner0_Rounded as CCActiveIcon, CC_Stroke2_Corner0_Rounded as CCInactiveIcon,} from '#/components/icons/CC'import {Pause_Filled_Corner0_Rounded as PauseIcon} from '#/components/icons/Pause'import {Play_Filled_Corner0_Rounded as PlayIcon} from '#/components/icons/Play'import {Loader} from '#/components/Loader'import {Text} from '#/components/Typography'import {IS_WEB_FIREFOX, IS_WEB_MOBILE_IOS, IS_WEB_TOUCH_DEVICE} from '#/env'import {GifPresentationControls} from '../../GifPresentationControls'import {TimeIndicator} from '../TimeIndicator'import {ControlButton} from './ControlButton'import {Scrubber} from './Scrubber'import {useVideoElement} from './utils'import {type ControlsProps} from './VideoControls.shared'import {VolumeControl} from './VolumeControl'
export function Controls({ videoRef, hlsRef, active, setActive, focused, setFocused, onScreen, fullscreenRef, hlsLoading, hasSubtitleTrack, isGif, altText, updateCuePositions,}: ControlsProps) { const { play, pause, playing, muted, changeMuted, togglePlayPause, currentTime, duration, buffering, error, canPlay, } = useVideoElement(videoRef) const t = useTheme() const {_} = useLingui() const subtitlesEnabled = useSubtitlesEnabled() const setSubtitlesEnabled = useSetSubtitlesEnabled() const { state: hovered, onIn: onHover, onOut: onEndHover, } = useInteractionState() const [isFullscreen, toggleFullscreen] = useFullscreen(fullscreenRef) const {state: hasFocus, onIn: onFocus, onOut: onBlur} = useInteractionState() const [interactingViaKeypress, setInteractingViaKeypress] = useState(false) const showSpinner = hlsLoading || buffering const { state: volumeHovered, onIn: onVolumeHover, onOut: onVolumeEndHover, } = useInteractionState()
const onKeyDown = useCallback(() => { setInteractingViaKeypress(true) }, [])
useEffect(() => { if (interactingViaKeypress) { document.addEventListener('click', () => setInteractingViaKeypress(false)) return () => { document.removeEventListener('click', () => setInteractingViaKeypress(false), ) } } }, [interactingViaKeypress])
useEffect(() => { if (isFullscreen) { document.documentElement.style.scrollbarGutter = 'unset' return () => { document.documentElement.style.removeProperty('scrollbar-gutter') } } }, [isFullscreen])
// pause + unfocus when another video is active useEffect(() => { if (!active) { pause() setFocused(false) } }, [active, pause, setFocused])
// autoplay/pause based on visibility const isWithinMessage = useIsWithinMessage() const autoplayDisabled = useAutoplayDisabled() || isWithinMessage useEffect(() => { if (active) { // GIFs play immediately, videos wait until onScreen if (onScreen || isGif) { if (!autoplayDisabled) play() } else { pause() } } }, [onScreen, pause, active, play, autoplayDisabled, isGif])
// use minimal quality when not focused useEffect(() => { if (!hlsRef.current) return if (focused) { // allow 30s of buffering hlsRef.current.config.maxMaxBufferLength = 30 } else { // back to what we initially set hlsRef.current.config.maxMaxBufferLength = 10 } }, [hlsRef, focused])
useEffect(() => { if (!hlsRef.current) return if (hasSubtitleTrack && subtitlesEnabled && canPlay) { hlsRef.current.subtitleTrack = 0 } else { hlsRef.current.subtitleTrack = -1 } }, [hasSubtitleTrack, subtitlesEnabled, hlsRef, canPlay])
// clicking on any button should focus the player, if it's not already focused const drawFocus = useCallback(() => { if (!active) { setActive() } setFocused(true) }, [active, setActive, setFocused])
const onPressEmptySpace = useCallback(() => { if (!focused) { drawFocus() if (autoplayDisabled) play() } else { togglePlayPause() } }, [togglePlayPause, drawFocus, focused, autoplayDisabled, play])
const onPressPlayPause = useCallback(() => { drawFocus() togglePlayPause() }, [drawFocus, togglePlayPause])
const onPressSubtitles = useCallback(() => { drawFocus() setSubtitlesEnabled(!subtitlesEnabled) }, [drawFocus, setSubtitlesEnabled, subtitlesEnabled])
const onPressFullscreen = useCallback(() => { drawFocus() toggleFullscreen() }, [drawFocus, toggleFullscreen])
const onSeek = useCallback( (time: number) => { if (!videoRef.current) return // Avoid fastSeek on Firefox - it seeks video to the nearest keyframe // but keeps audio at the precise time, causing audio/video desync if (videoRef.current.fastSeek && !IS_WEB_FIREFOX) { videoRef.current.fastSeek(time) } else { videoRef.current.currentTime = time } }, [videoRef], )
const playStateBeforeSeekRef = useRef(false)
const onSeekStart = useCallback(() => { drawFocus() playStateBeforeSeekRef.current = playing pause() }, [playing, pause, drawFocus])
const onSeekEnd = useCallback(() => { if (playStateBeforeSeekRef.current) { play() } }, [play])
const seekLeft = useCallback(() => { if (!videoRef.current) return
const currentTime = videoRef.current.currentTime
const duration = videoRef.current.duration || 0 onSeek(clamp(currentTime - 5, 0, duration)) }, [onSeek, videoRef])
const seekRight = useCallback(() => { if (!videoRef.current) return
const currentTime = videoRef.current.currentTime
const duration = videoRef.current.duration || 0 onSeek(clamp(currentTime + 5, 0, duration)) }, [onSeek, videoRef])
const [showCursor, setShowCursor] = useState(true) const cursorTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined) const onPointerMoveEmptySpace = useCallback(() => { setShowCursor(true) if (cursorTimeoutRef.current) { clearTimeout(cursorTimeoutRef.current) } cursorTimeoutRef.current = setTimeout(() => { setShowCursor(false) onEndHover() }, 2000) }, [onEndHover]) const onPointerLeaveEmptySpace = useCallback(() => { setShowCursor(false) if (cursorTimeoutRef.current) { clearTimeout(cursorTimeoutRef.current) } }, [])
// these are used to trigger the hover state. on mobile, the hover state // should stick around for a bit after they tap, and if the controls aren't // present this initial tab should *only* show the controls and not activate anything
const onPointerDown = useCallback( (evt: React.PointerEvent<HTMLDivElement>) => { if (evt.pointerType !== 'mouse' && !hovered) { evt.preventDefault() } clearTimeout(timeoutRef.current) }, [hovered], )
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined)
const onHoverWithTimeout = useCallback(() => { onHover() clearTimeout(timeoutRef.current) }, [onHover])
const onEndHoverWithTimeout = useCallback( (evt: React.PointerEvent<HTMLDivElement>) => { // if touch, end after 3s // if mouse, end immediately if (evt.pointerType !== 'mouse') { setTimeout(onEndHover, 3000) } else { onEndHover() } }, [onEndHover], )
const showControls = ((focused || autoplayDisabled) && !playing) || (interactingViaKeypress ? hasFocus : hovered)
// adjust subtitle cue positioning to avoid occlusion by controls // uses percentage-based positioning (snapToLines=false) so wrapped // multi-line cues grow upward instead of extending offscreen useEffect(() => { updateCuePositions(showControls) }, [showControls, updateCuePositions])
if (isGif) { return ( <GifPresentationControls isPlaying={playing} isLoading={showSpinner} onPress={onPressPlayPause} altText={altText} /> ) }
return ( <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column', }} onClick={evt => { evt.stopPropagation() setInteractingViaKeypress(false) }} onPointerEnter={onHoverWithTimeout} onPointerMove={onHoverWithTimeout} onPointerLeave={onEndHoverWithTimeout} onPointerDown={onPointerDown} onFocus={onFocus} onBlur={onBlur} onKeyDown={onKeyDown}> <Pressable accessibilityRole="button" onPointerEnter={onPointerMoveEmptySpace} onPointerMove={onPointerMoveEmptySpace} onPointerLeave={onPointerLeaveEmptySpace} accessibilityLabel={ !focused ? _(msg`Unmute video`) : playing ? _(msg`Pause video`) : _(msg`Play video`) } accessibilityHint="" style={[ a.flex_1, web({cursor: showCursor || !playing ? 'pointer' : 'none'}), ]} onPress={onPressEmptySpace} /> {!showControls && !focused && duration > 0 && ( <TimeIndicator time={Math.floor(duration - currentTime)} /> )} <View style={[ a.flex_shrink_0, a.w_full, a.px_xs, web({ background: 'linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.7))', }), {opacity: showControls ? 1 : 0}, {transition: 'opacity 0.2s ease-in-out'}, ]}> {(!volumeHovered || IS_WEB_TOUCH_DEVICE) && ( <Scrubber duration={duration} currentTime={currentTime} onSeek={onSeek} onSeekStart={onSeekStart} onSeekEnd={onSeekEnd} seekLeft={seekLeft} seekRight={seekRight} togglePlayPause={togglePlayPause} drawFocus={drawFocus} /> )} <View style={[ a.flex_1, a.px_xs, a.pb_sm, a.gap_sm, a.flex_row, a.align_center, ]}> <ControlButton active={playing} activeLabel={_(msg`Pause`)} inactiveLabel={_(msg`Play`)} activeIcon={PauseIcon} inactiveIcon={PlayIcon} onPress={onPressPlayPause} /> <View style={a.flex_1} /> {Math.round(duration) > 0 && ( <Text style={[ a.px_xs, {color: t.palette.white, fontVariant: ['tabular-nums']}, ]}> {formatTime(currentTime)} / {formatTime(duration)} </Text> )} {hasSubtitleTrack && ( <ControlButton active={subtitlesEnabled} activeLabel={_(msg`Disable captions`)} inactiveLabel={_(msg`Enable captions`)} activeIcon={CCActiveIcon} inactiveIcon={CCInactiveIcon} onPress={onPressSubtitles} /> )} <VolumeControl muted={muted} changeMuted={changeMuted} hovered={volumeHovered} onHover={onVolumeHover} onEndHover={onVolumeEndHover} drawFocus={drawFocus} /> {!IS_WEB_MOBILE_IOS && ( <ControlButton active={isFullscreen} activeLabel={_(msg`Exit fullscreen`)} inactiveLabel={_(msg`Enter fullscreen`)} activeIcon={ArrowsInIcon} inactiveIcon={ArrowsOutIcon} onPress={onPressFullscreen} /> )} </View> </View> {(showSpinner || error) && ( <View pointerEvents="none" style={[a.absolute, a.inset_0, a.justify_center, a.align_center]}> {showSpinner && <Loader fill={t.palette.white} size="lg" />} {error && ( <Text style={{color: t.palette.white}}> <Trans>An error occurred</Trans> </Text> )} </View> )} </div> )}