From bede0ba5abd9dd4306f7c70e4f924f7c1ec180d3 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Wed, 14 Sep 2022 01:35:48 +0200 Subject: [PATCH] [Perf] Avatar: Fix playing during heavy animation --- src/components/common/Avatar.tsx | 3 ++- .../middle/message/hooks/useVideoAutoPause.ts | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/components/common/Avatar.tsx b/src/components/common/Avatar.tsx index 39a46dbe..f6a42a93 100644 --- a/src/components/common/Avatar.tsx +++ b/src/components/common/Avatar.tsx @@ -114,7 +114,7 @@ const Avatar: FC = ({ const { transitionClassNames } = useShowTransition(hasBlobUrl, undefined, hasBlobUrl, 'slow'); - useVideoAutoPause(videoRef, shouldPlayVideo); + const { handlePlaying } = useVideoAutoPause(videoRef, shouldPlayVideo); useVideoCleanup(videoRef, [shouldPlayVideo]); useEffect(() => { @@ -170,6 +170,7 @@ const Avatar: FC = ({ autoPlay disablePictureInPicture playsInline + onPlaying={handlePlaying} /> )} diff --git a/src/components/middle/message/hooks/useVideoAutoPause.ts b/src/components/middle/message/hooks/useVideoAutoPause.ts index 00783501..ae3a0ccc 100644 --- a/src/components/middle/message/hooks/useVideoAutoPause.ts +++ b/src/components/middle/message/hooks/useVideoAutoPause.ts @@ -10,7 +10,11 @@ export default function useVideoAutoPause(playerRef: { current: HTMLVideoElement const canPlayRef = useRef(); canPlayRef.current = canPlay; + const isFrozenRef = useRef(); + const freezePlaying = useCallback(() => { + isFrozenRef.current = true; + if (!playerRef.current) { return; } @@ -23,6 +27,8 @@ export default function useVideoAutoPause(playerRef: { current: HTMLVideoElement }, [playerRef]); const unfreezePlaying = useCallback(() => { + isFrozenRef.current = false; + if ( playerRef.current && wasPlaying.current && canPlayRef.current // At this point HTMLVideoElement can be unmounted from the DOM @@ -38,4 +44,13 @@ export default function useVideoAutoPause(playerRef: { current: HTMLVideoElement useBackgroundMode(freezePlaying, unfreezePlayingOnRaf); useHeavyAnimationCheck(freezePlaying, unfreezePlaying); + + const handlePlaying = useCallback(() => { + if (isFrozenRef.current) { + wasPlaying.current = true; + playerRef.current!.pause(); + } + }, [playerRef]); + + return { handlePlaying }; }