Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Picture-in-Picture functionality to Player component #400

Merged
merged 1 commit into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/stories/player/_types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ export interface PlayerArgs extends HTMLAttributes<HTMLVideoElement> {
url: string;
start?: number;
end?: number;
enablePipOnScroll?: boolean;
pipMode?: "auto" | (() => boolean) | boolean;
onPipChange?: (isPip: boolean) => void;
onCutHandler?: (time: number) => void;
isCutting?: boolean;
bookmarks?: IBookmark[];
Expand Down
93 changes: 93 additions & 0 deletions src/stories/player/hooks/usePictureInPicture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { useEffect } from "react";
import { PlayerArgs } from "../_types";

type PictureInPictureHook = (
videoRef?: HTMLVideoElement | null,
pipMode?: PlayerArgs["pipMode"],
onPipChange?: PlayerArgs["onPipChange"]
) => void;

export const usePictureInPicture: PictureInPictureHook = (videoRef, pipMode, onPipChange) => {

const getObserver = (videoRef: HTMLVideoElement, isVideoPlaying: () => boolean) => {
return new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting && isVideoPlaying()) {
videoRef.requestPictureInPicture();
}
if (
document.pictureInPictureElement &&
entry.isIntersecting &&
!isVideoPlaying()
) {
document.exitPictureInPicture();
}
});
},
{ threshold: 0.5 }
);
};

const handleManualPipMode = (videoRef: HTMLVideoElement, pipMode: boolean) => {
if (pipMode) {
videoRef.requestPictureInPicture();
}
if (!pipMode && document.pictureInPictureElement) {
document.exitPictureInPicture();
}
}

useEffect(() => {
// bail out if pipMode is not defined or videoRef is not defined or pip is not supported
if (typeof pipMode === "undefined")
return;
if (!document.pictureInPictureEnabled) {
console.warn("Picture-in-Picture is not supported in this browser");
return;
}
if (!videoRef)
return;

// if pipMode is auto, we will enter picture in picture mode when the video is not in view
if (pipMode === "auto") {
const isVideoPlaying = () =>
videoRef.currentTime > 0 &&
!videoRef.paused &&
!videoRef.ended &&
videoRef.readyState > 2;

const observer = getObserver(videoRef, isVideoPlaying);
observer.observe(videoRef);

return () => {
observer.disconnect();
};
} else if (typeof pipMode === "boolean") {
handleManualPipMode(videoRef, pipMode);
} else {
handleManualPipMode(videoRef, pipMode());
}
}, [pipMode, videoRef]);

useEffect(() => {
if (!document.pictureInPictureEnabled) {
return;
}
document.addEventListener("enterpictureinpicture", () => {
onPipChange?.(true);
});
document.addEventListener("leavepictureinpicture", () => {
onPipChange?.(false);
});

return () => {
document.removeEventListener("enterpictureinpicture", () => {
onPipChange?.(true);
});
document.removeEventListener("leavepictureinpicture", () => {
onPipChange?.(false);
});
};
}, [onPipChange]);
}
57 changes: 56 additions & 1 deletion src/stories/player/index.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import { Player, PlayerProvider } from ".";
import { IBookmark, PlayerArgs } from "./_types";
import { theme } from "../theme";
import { Tag } from "@zendeskgarden/react-tags";
import { Button } from "../buttons/button";

const Container = styled.div`
height: 80vh;
`;

interface PlayerStoryArgs extends PlayerArgs {}
interface PlayerStoryArgs extends PlayerArgs { }

const defaultArgs: PlayerStoryArgs = {
url: "https://s3.eu-west-1.amazonaws.com/appq.static/demo/098648899205a00f8311d929d3073499ef9d664b_1715352138.mp4",
Expand Down Expand Up @@ -81,11 +82,65 @@ const TemplateWithCutter: StoryFn<PlayerStoryArgs> = ({
);
};

const TemplateWithParagraphs: StoryFn<PlayerStoryArgs> = (args) => (
<Container id="player.story.container">
<Player {...args} />
{Array.from({ length: 10 }).map((_, index) => (
<p key={index}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
))}
</Container>
);

const TemplateWithButtonForPip: StoryFn<PlayerStoryArgs> = (args) => {
const [isPip, setIsPip] = useState(false);
const handlePipChange = useCallback((isPipFromPlayer: boolean) => {
setIsPip(isPipFromPlayer);
}, [setIsPip]);
return (
<Container id="player.story.container">
<Player {...args} pipMode={isPip} onPipChange={handlePipChange} />
<Button onClick={() => setIsPip(!isPip)}>
{isPip ? "Exit" : "Enter"} Picture in Picture
</Button>
{Array.from({ length: 10 }).map((_, index) => (
<p key={index}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
))}
</Container>
)
};

export const Basic = Template.bind({});
Basic.args = {
...defaultArgs,
};

export const AutoPip = TemplateWithParagraphs.bind({});
AutoPip.args = {
...defaultArgs,
pipMode: "auto",
};

export const ButtonPip = TemplateWithButtonForPip.bind({});
ButtonPip.args = {
...defaultArgs
};

export const Streaming = Template.bind({});
Streaming.args = {
...defaultArgs,
Expand Down
5 changes: 4 additions & 1 deletion src/stories/player/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Controls } from "./parts/controls";
import { FloatingControls } from "./parts/floatingControls";
import { VideoSpinner } from "./parts/spinner";
import { ProgressContextProvider } from "./context/progressContext";
import { usePictureInPicture } from "./hooks/usePictureInPicture";

/**
* The Player is a styled media tag with custom controls
Expand All @@ -28,7 +29,7 @@ const Player = forwardRef<HTMLVideoElement, PlayerArgs>((props, forwardRef) => (
const PlayerCore = forwardRef<HTMLVideoElement, PlayerArgs>(
(props, forwardRef) => {
const { context, togglePlay, setIsPlaying } = useVideoContext();
const { onCutHandler, bookmarks, isCutting } = props;
const { onCutHandler, bookmarks, isCutting, pipMode, onPipChange } = props;
const videoRef = context.player?.ref.current;
const isLoaded = !!videoRef;
const containerRef = useRef<HTMLDivElement>(null);
Expand All @@ -37,6 +38,8 @@ const PlayerCore = forwardRef<HTMLVideoElement, PlayerArgs>(
videoRef,
]);

usePictureInPicture(videoRef, pipMode, onPipChange);

useEffect(() => {
if (videoRef) {
videoRef.addEventListener("pause", () => {
Expand Down
Loading