All files / Rindu/hooks usePictureInPicture.ts

29.41% Statements 5/17
80% Branches 4/5
50% Functions 2/4
29.41% Lines 5/17

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 5719x       41x                         41x 41x           41x                                                                
import { Dispatch, MutableRefObject, SetStateAction, useEffect } from "react";
 
import { ITrack } from "types/spotify";
 
export function usePictureInPicture({
  setIsPip,
  videoRef,
  pictureInPictureCanvas,
  currentlyPlaying,
  isPictureInPictureLyircsCanvas,
}: {
  setIsPip: Dispatch<SetStateAction<boolean>>;
  videoRef: MutableRefObject<HTMLVideoElement | undefined>;
  pictureInPictureCanvas: MutableRefObject<HTMLCanvasElement | undefined>;
  isPictureInPictureLyircsCanvas: boolean;
  currentlyPlaying: ITrack | undefined;
}): void {
  useEffect(() => {
    if (
      videoRef.current ||
      pictureInPictureCanvas.current ||
      !currentlyPlaying ||
      isPictureInPictureLyircsCanvas
    ) {
      return;
    }
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = 512;
    const video = document.createElement("video");
 
    function handleLeavePictureInPicture() {
      setIsPip(false);
    }
    function handlEnterPictureInPicture() {
      setIsPip(true);
    }
 
    video.addEventListener(
      "leavepictureinpicture",
      handleLeavePictureInPicture
    );
    video.addEventListener("enterpictureinpicture", handlEnterPictureInPicture);
 
    video.muted = true;
    canvas.getContext("2d");
    video.srcObject = canvas.captureStream();
    pictureInPictureCanvas.current = canvas;
    videoRef.current = video;
  }, [
    currentlyPlaying,
    isPictureInPictureLyircsCanvas,
    pictureInPictureCanvas,
    setIsPip,
    videoRef,
  ]);
}