All files / Rindu/hooks usePictureInPicture.ts

18.51% Statements 5/27
100% Branches 4/4
40% Functions 2/5
18.51% Lines 5/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 7219x       41x                       41x 41x 41x                                                                                                          
import { Dispatch, RefObject, SetStateAction, useEffect } from "react";
 
import { AudioPlayer, IUseToggleHandlers } from "hooks";
 
export function usePictureInPicture({
  setIsPip,
  videoRef,
  pictureInPictureCanvas,
  player,
}: {
  setIsPip: Dispatch<SetStateAction<boolean>>;
  videoRef: RefObject<HTMLVideoElement | null>;
  pictureInPictureCanvas: RefObject<HTMLCanvasElement | null>;
  player?: AudioPlayer | Spotify.Player;
  setIsPictureInPictureLyircsCanvas: IUseToggleHandlers;
}): void {
  useEffect(() => {
    if (videoRef.current || pictureInPictureCanvas.current || !player) {
      return;
    }
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = 512;
    const video = document.createElement("video");
 
    function handleLeavePictureInPicture() {
      setIsPip(false);
    }
    function handleEnterPictureInPicture() {
      setIsPip(true);
    }
 
    video.muted = true;
    const ctx = canvas.getContext("2d");
    video.srcObject = canvas.captureStream();
    pictureInPictureCanvas.current = canvas;
    document.body.appendChild(video);
    videoRef.current = video;
 
    ctx?.fillRect(
      0,
      0,
      pictureInPictureCanvas.current.width,
      pictureInPictureCanvas.current.height
    );
 
    video.style.width = "1px";
    video.style.height = "1px";
    video.style.position = "absolute";
    video.style.top = "0px";
    videoRef.current.play();
    videoRef.current?.addEventListener(
      "leavepictureinpicture",
      handleLeavePictureInPicture
    );
    videoRef?.current.addEventListener(
      "enterpictureinpicture",
      handleEnterPictureInPicture
    );
 
    return () => {
      videoRef.current?.removeEventListener(
        "leavepictureinpicture",
        handleLeavePictureInPicture
      );
      videoRef.current?.removeEventListener(
        "enterpictureinpicture",
        handleEnterPictureInPicture
      );
    };
  }, [player, pictureInPictureCanvas, setIsPip, videoRef]);
}