From ab0da7c892ce7532840417b89a42302ab9db7018 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Fri, 9 Aug 2024 23:35:21 +0100 Subject: [PATCH] [Videos] handle app backgrounding (#4912) * play when returning from background * play when unfullscreening * play when entering fullscreen, just to be sure * state -> ref --------- Co-authored-by: Samuel Newman <10959775+mozzius@users.noreply.github.com> --- .../VideoEmbedInner/VideoEmbedInnerNative.tsx | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/src/view/com/util/post-embeds/VideoEmbedInner/VideoEmbedInnerNative.tsx b/src/view/com/util/post-embeds/VideoEmbedInner/VideoEmbedInnerNative.tsx index ae3a4a22..33148da0 100644 --- a/src/view/com/util/post-embeds/VideoEmbedInner/VideoEmbedInnerNative.tsx +++ b/src/view/com/util/post-embeds/VideoEmbedInner/VideoEmbedInnerNative.tsx @@ -7,6 +7,7 @@ import {useLingui} from '@lingui/react' import {useIsFocused} from '@react-navigation/native' import {HITSLOP_30} from '#/lib/constants' +import {useAppState} from '#/lib/hooks/useAppState' import {useVideoPlayer} from '#/view/com/util/post-embeds/VideoPlayerContext' import {android, atoms as a, useTheme} from '#/alf' import {Mute_Stroke2_Corner0_Rounded as MuteIcon} from '#/components/icons/Mute' @@ -21,6 +22,18 @@ export function VideoEmbedInnerNative() { const player = useVideoPlayer() const ref = useRef(null) const isScreenFocused = useIsFocused() + const isAppFocused = useAppState() + const prevFocusedRef = useRef(isAppFocused) + + // resume video when coming back from background + useEffect(() => { + if (isAppFocused !== prevFocusedRef.current) { + prevFocusedRef.current = isAppFocused + if (isAppFocused === 'active') { + player.play() + } + } + }, [isAppFocused, player]) // pause the video when the screen is not focused useEffect(() => { @@ -34,6 +47,10 @@ export function VideoEmbedInnerNative() { } }, [isScreenFocused, player]) + const enterFullscreen = useCallback(() => { + ref.current?.enterFullscreen() + }, []) + return ( - { - ref.current?.enterFullscreen() - }} - /> + ) } @@ -102,6 +115,22 @@ function Controls({ } }, [player]) + const onPressFullscreen = useCallback(() => { + switch (player.status) { + case 'idle': + case 'loading': + case 'readyToPlay': { + if (!player.playing) player.play() + enterFullscreen() + break + } + case 'error': { + player.replay() + break + } + } + }, [player, enterFullscreen]) + const toggleMuted = useCallback(() => { const muted = !player.muted // We want to set this to the _inverse_ of the new value, because we actually want for the audio to be mixed when @@ -150,7 +179,7 @@ function Controls({ )}