All files / Rindu/utils callPictureInPicture.ts

85.71% Statements 18/21
75% Branches 3/4
50% Functions 1/2
84.21% Lines 16/19

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 376x       4x 3x             3x 3x 3x 3x 3x 2x 2x 1x 1x           1x 1x 1x         1x      
export async function callPictureInPicture(
  pictureInPictureCanvas: HTMLCanvasElement,
  video: HTMLVideoElement
): Promise<void> {
  if (!navigator.mediaSession?.metadata?.artwork) return;
  const artwork = navigator.mediaSession.metadata.artwork;
  function onLoadedData() {
    video.removeEventListener("loadedmetadata", onLoadedData);
 
    video.play().then(video.requestPictureInPicture).then(video.pause);
  }
 
  try {
    const image = new Image();
    image.crossOrigin = "Anonymous";
    const imgSrc = [...artwork].pop()?.src;
    if (!imgSrc) return;
    image.src = imgSrc;
    await image.decode();
    const ctx = pictureInPictureCanvas?.getContext("2d");
    ctx?.clearRect(
      0,
      0,
      pictureInPictureCanvas.width,
      pictureInPictureCanvas.height
    );
    ctx?.drawImage(image, 0, 0, 512, 512);
    if (video.readyState >= 2) {
      video.requestPictureInPicture();
    } else E{
      video.addEventListener("loadedmetadata", onLoadedData);
    }
  } catch (err) {
    console.error(err);
  }
}