From 7d69e9077fc5508418b33dab3d3a3b7cd1ae9916 Mon Sep 17 00:00:00 2001 From: Bishal Pahari Date: Mon, 22 Apr 2024 20:36:11 +0545 Subject: [PATCH] perf: add ref callback and function to handle end of video --- src/components/VideoCarousel.jsx | 64 ++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/src/components/VideoCarousel.jsx b/src/components/VideoCarousel.jsx index 69aa7a4..314855a 100644 --- a/src/components/VideoCarousel.jsx +++ b/src/components/VideoCarousel.jsx @@ -2,15 +2,38 @@ import gsap from "gsap"; import { useGSAP } from "@gsap/react"; import { ScrollTrigger } from "gsap/all"; gsap.registerPlugin(ScrollTrigger); -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { hightlightsSlides } from "../constants"; import { pauseImg, playImg, replayImg } from "../utils"; const VideoCarousel = () => { - const videoRef = useRef([]); - const videoSpanRef = useRef([]); - const videoDivRef = useRef([]); + // ref to keep track + const videoRef = useRef([]); // track video playing + const videoSpanRef = useRef([]); // track the no of dots for video + const videoDivRef = useRef([]); // track progress animation in each dot + + // function to handle end of the video in the carousel + const handleVideoEnd = (index) => { + if (index !== 3) { + handleProcess("video-end", index); + } else { + handleProcess("video-last"); + } + }; + + // Define the ref callbacks + const setVideoRef = useCallback((el, i) => { + videoRef.current[i] = el; + }, []); + + const setVideoDivRef = useCallback((el, i) => { + videoDivRef.current[i] = el; + }, []); + + const setVideoSpanRef = useCallback((el, i) => { + videoSpanRef.current[i] = el; + }, []); // video and indicator const [video, setVideo] = useState({ @@ -29,7 +52,7 @@ const VideoCarousel = () => { gsap.to("#slider", { transform: `translateX(${-100 * videoId}%)`, duration: 2, - ease: "power2.inOut", // show visualizer https://gsap.com/docs/v3/Eases + ease: "power4.inOut", }); // video animation to play the video when it is in the view @@ -141,11 +164,13 @@ const VideoCarousel = () => { break; case "pause": - setVideo((pre) => ({ ...pre, isPlaying: !pre.isPlaying })); + videoRef.current[videoId].pause(); + setVideo((pre) => ({ ...pre, isPlaying: false })); break; case "play": - setVideo((pre) => ({ ...pre, isPlaying: !pre.isPlaying })); + videoRef.current[videoId].play(); + setVideo((pre) => ({ ...pre, isPlaying: true })); break; default: @@ -153,8 +178,9 @@ const VideoCarousel = () => { } }; - const handleLoadedMetaData = (i, e) => setLoadedData((pre) => [...pre, e]); - + const handleLoadedMetaData = useCallback((i, e) => { + setLoadedData((pre) => [...pre, e]); + }, []); return ( <>
@@ -162,6 +188,7 @@ const VideoCarousel = () => {
+ {/* Use the memoized callbacks in your JSX */}