Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265import {useCallback, useEffect, useMemo, useState} from 'react'import { type GestureResponderEvent, Pressable, useWindowDimensions, View,} from 'react-native'import Animated, { measure, runOnJS, useAnimatedRef, useFrameCallback,} from 'react-native-reanimated'import {useSafeAreaInsets} from 'react-native-safe-area-context'import {WebView} from 'react-native-webview'import {Image} from 'expo-image'import {type AppBskyEmbedExternal} from '@atproto/api'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {useNavigation} from '@react-navigation/native'
import {type NavigationProp} from '#/lib/routes/types'import { type EmbedPlayerParams, getPlayerAspect,} from '#/lib/strings/embed-player'import {useExternalEmbedsPrefs} from '#/state/preferences'import {EventStopper} from '#/view/com/util/EventStopper'import {atoms as a, useTheme} from '#/alf'import {CustomActivityIndicator} from '#/components/CustomActivityIndicator.tsx'import {useDialogControl} from '#/components/Dialog'import {EmbedConsentDialog} from '#/components/dialogs/EmbedConsent'import {Fill} from '#/components/Fill'import {KeepAwake} from '#/components/KeepAwake'import {PlayButtonIcon} from '#/components/video/PlayButtonIcon'import {IS_NATIVE} from '#/env'
interface ShouldStartLoadRequest { url: string}
// This renders the overlay when the player is either inactive or loading as a separate layerfunction PlaceholderOverlay({ isLoading, isPlayerActive, onPress,}: { isLoading: boolean isPlayerActive: boolean onPress: (event: GestureResponderEvent) => void}) { const {_} = useLingui()
// If the player is active and not loading, we don't want to show the overlay. if (isPlayerActive && !isLoading) return null
return ( <View style={[a.absolute, a.inset_0, {zIndex: 2}]}> <Pressable accessibilityRole="button" accessibilityLabel={_(msg`Play Video`)} accessibilityHint={_(msg`Plays the video`)} onPress={onPress} style={[a.flex_1, a.justify_center, a.align_center]}> {!isPlayerActive ? ( <PlayButtonIcon /> ) : ( <CustomActivityIndicator size="large" color="white" /> )} </Pressable> </View> )}
// This renders the webview/youtube player as a separate layerfunction Player({ params, onLoad, isPlayerActive,}: { isPlayerActive: boolean params: EmbedPlayerParams onLoad: () => void}) { // ensures we only load what's requested // when it's a youtube video, we need to allow both bsky.app and youtube.com const onShouldStartLoadWithRequest = useCallback( (event: ShouldStartLoadRequest) => event.url === params.playerUri || (params.source.startsWith('youtube') && event.url.includes('www.youtube.com')), [params.playerUri, params.source], )
// Don't show the player until it is active if (!isPlayerActive) return null
return ( <> <EventStopper style={[a.absolute, a.inset_0, {zIndex: 3}]}> <WebView javaScriptEnabled={true} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} mediaPlaybackRequiresUserAction={false} allowsInlineMediaPlayback bounces={false} allowsFullscreenVideo nestedScrollEnabled source={{uri: params.playerUri}} onLoad={onLoad} style={a.bg_transparent} setSupportMultipleWindows={false} // Prevent any redirects from opening a new window (ads) /> </EventStopper> <KeepAwake /> </> )}
// This renders the player area and handles the logic for when to show the player and when to show the overlayexport function ExternalPlayer({ link, params,}: { link: AppBskyEmbedExternal.ViewExternal params: EmbedPlayerParams}) { const t = useTheme() const navigation = useNavigation<NavigationProp>() const insets = useSafeAreaInsets() const windowDims = useWindowDimensions() const externalEmbedsPrefs = useExternalEmbedsPrefs() const consentDialogControl = useDialogControl()
const [isPlayerActive, setIsPlayerActive] = useState(false) const [isLoading, setIsLoading] = useState(true)
const aspect = useMemo(() => { return getPlayerAspect({ type: params.type, width: windowDims.width, hasThumb: !!link.thumb, }) }, [params.type, windowDims.width, link.thumb])
const viewRef = useAnimatedRef() const frameCallback = useFrameCallback(() => { const measurement = measure(viewRef) if (!measurement) return
const {height: winHeight, width: winWidth} = windowDims
// Get the proper screen height depending on what is going on const realWinHeight = IS_NATIVE // If it is native, we always want the larger number ? winHeight > winWidth ? winHeight : winWidth : winHeight // On web, we always want the actual screen height
const top = measurement.pageY const bot = measurement.pageY + measurement.height
// We can use the same logic on all platforms against the screenHeight that we get above const isVisible = top <= realWinHeight - insets.bottom && bot >= insets.top
if (!isVisible) { runOnJS(setIsPlayerActive)(false) } }, false) // False here disables autostarting the callback
// watch for leaving the viewport due to scrolling useEffect(() => { // We don't want to do anything if the player isn't active if (!isPlayerActive) return
// Interval for scrolling works in most cases, However, for twitch embeds, if we navigate away from the screen the webview will // continue playing. We need to watch for the blur event const unsubscribe = navigation.addListener('blur', () => { setIsPlayerActive(false) })
// Start watching for changes frameCallback.setActive(true)
return () => { unsubscribe() frameCallback.setActive(false) } }, [navigation, isPlayerActive, frameCallback])
const onLoad = useCallback(() => { setIsLoading(false) }, [])
const onPlayPress = useCallback( (event: GestureResponderEvent) => { // Prevent this from propagating upward on web event.preventDefault()
if (externalEmbedsPrefs?.[params.source] === undefined) { consentDialogControl.open() return }
setIsPlayerActive(true) }, [externalEmbedsPrefs, consentDialogControl, params.source], )
const onAcceptConsent = useCallback(() => { setIsPlayerActive(true) }, [])
return ( <> <EmbedConsentDialog control={consentDialogControl} source={params.source} onAccept={onAcceptConsent} />
<Animated.View ref={viewRef} collapsable={false} style={[aspect, a.overflow_hidden]}> {link.thumb && (!isPlayerActive || isLoading) ? ( <> <Image style={[a.flex_1]} source={{uri: link.thumb}} accessibilityIgnoresInvertColors /> <Fill style={[ t.name === 'light' ? t.atoms.bg_contrast_975 : t.atoms.bg, {opacity: 0.3}, ]} /> </> ) : ( <Fill style={[ { backgroundColor: t.name === 'light' ? t.palette.contrast_975 : 'black', opacity: 0.3, }, ]} /> )} <PlaceholderOverlay isLoading={isLoading} isPlayerActive={isPlayerActive} onPress={onPlayPress} /> <Player isPlayerActive={isPlayerActive} params={params} onLoad={onLoad} /> </Animated.View> </> )}