Skip to content

Commit

Permalink
⚡️ : throttle the video playback
Browse files Browse the repository at this point in the history
  • Loading branch information
hsunpei committed Oct 16, 2024
1 parent 206b651 commit 07c71d8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 17 deletions.
2 changes: 1 addition & 1 deletion apps/docs/components/video/StickyVideo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const StickyVideo = ({ src }: StickyVideoProps) => {
width={width}
height={height}
src={src}
ratio={Math.round(scrolledRatio * 100) / 100}
ratio={scrolledRatio}
/>
</div>
</StickyContainer>
Expand Down
50 changes: 34 additions & 16 deletions packages/video/src/components/Video.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import React, { useEffect, useImperativeHandle, useRef } from 'react';
import React, { useEffect, useImperativeHandle, useCallback, useRef } from 'react';

import { useRafThrottle } from '@react-scrollytelling/core';

export interface VideoProps {
src: string;
Expand All @@ -18,11 +20,10 @@ export const Video = ({ src, width, height, ratio = 0, className }: VideoProps)
const videoRef = useRef<VideoRef>(null);

useEffect(() => {
// update currentTime when the percentage prop changes
// update currentTime when the ratio prop changes
if (!videoRef.current) {
return;
}

videoRef.current.setRatio(ratio);
}, [ratio]);

Expand All @@ -45,28 +46,45 @@ export const VideoWithImperativeHandle = React.memo(
React.forwardRef<VideoRef, VideoProps>(({ src, width, height, className }, ref) => {
const videoRef = useRef<HTMLVideoElement>(null);

const setVideoRatio = useCallback((ratio: number) => {
const videoElement = videoRef.current;
if (!videoElement) {
return;
}

const duration = videoElement.duration;
if (!isNaN(duration)) {
requestAnimationFrame(() => {
videoElement.currentTime = Math.round(ratio * duration * 100) / 100;
console.log('setRatio', ratio, Math.round(ratio * duration * 100) / 100);
});
}
}, []);
const setVideoRatioThrottled = useRafThrottle(setVideoRatio);

useImperativeHandle(
ref,
() => {
return {
setRatio: (ratio: number) => {
const videoElement = videoRef.current;
if (!videoElement) {
return;
}

const duration = videoElement.duration;
if (!isNaN(duration)) {
videoElement.currentTime = ratio * duration;
}
},
setRatio: setVideoRatioThrottled,
};
},
[]
[setVideoRatioThrottled]
);

return (
<video ref={videoRef} width={width} height={height} src={src} className={className}></video>
<video
ref={videoRef}
width={width}
height={height}
src={src}
className={className}
muted
disablePictureInPicture
disableRemotePlayback
playsInline
controls={false}
></video>
);
})
);

0 comments on commit 07c71d8

Please sign in to comment.