Skip to content

Commit

Permalink
fix(client): fixed a bug causing videos to keep playing and overlap a…
Browse files Browse the repository at this point in the history
…udio in the background
  • Loading branch information
Will Moss committed Jul 18, 2024
1 parent fabff0b commit 68a560c
Showing 1 changed file with 24 additions and 21 deletions.
45 changes: 24 additions & 21 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Dependencies
import { useEffect, useState, useRef } from "react";
import { useEffect, useState, useRef, useCallback } from "react";

// Components
import VideoCard from "./components/VideoCard";
Expand Down Expand Up @@ -181,27 +181,30 @@ const App = () => {

// Listener called when scroll is performed
const handleIntersection = (entries) => {
let visibleIndex = false;

entries.forEach((entry) => {
const videoElement = entry.target;
const currentIndex = parseInt(videoElement.getAttribute("data-index"));

// Case when a video is scroll-snapped and occupies the screen
if (entry.isIntersecting) {
visibleIndex = currentIndex;
videoElement.play();
}
// Case when a video is off-screen or being scrolled in / out of the screen
else {
if (!visibleIndexes.includes(currentIndex)) return;
videoElement.pause();
}
// Trick to always retrieve fresh state, rather than closure-scoped one
setVisibleIndexes((_visibleIndexes) => {
let visibleIndex = false;

entries.forEach((entry) => {
const videoElement = entry.target;
const currentIndex = parseInt(videoElement.getAttribute("data-index"));

// Case when a video is scroll-snapped and occupies the screen
if (entry.isIntersecting) {
visibleIndex = currentIndex;
videoElement.play();
}
// Case when a video is off-screen or being scrolled in / out of the screen
else {
if (!_visibleIndexes.includes(currentIndex)) return;
videoElement.pause();
}
});

if (visibleIndex === false) return _visibleIndexes;

return [visibleIndex - 1, visibleIndex, visibleIndex + 1];
});

if (visibleIndex === false) return;

setVisibleIndexes([visibleIndex - 1, visibleIndex, visibleIndex + 1]);
};

// Set up the observer
Expand Down

0 comments on commit 68a560c

Please sign in to comment.