WICG / document-picture-in-picture

https://wicg.github.io/document-picture-in-picture/
Other
56 stars 9 forks source link

How to share javascript logic & CSS from parent to children PiP windows? #84

Closed mmarzullotv closed 1 year ago

mmarzullotv commented 1 year ago

Hey, let's say I got many buttons, components and its functionality attached to them and this PiP window needs to inherit.

How can I properly pass it? Because I tried adding a console.log to the play button in a handler function but is not being triggered within the PiP window. It seems I can only share some of the CSS styles and inner DOM elements, but not actual Javascript and all the styling I added to custom buttons.

Here's the test code:


const VideoPlayer = (): JSX.Element => {
  // Handle to the picture-in-picture window.
  const pipWindow = useRef(null);
  const videoContainerRef = useRef(null);
  const playerRef = useRef(null);
  // const [isPip, setIsPip] = useState(false);

  const handlePlay = () => {
    console.log("playyyyy");
  };

  const enterPiP = async () => {
    const pipOptions = {
      width: playerRef.current.clientWidth,
      height: playerRef.current.clientHeight,
      copyStyleSheets: true,
    };

    // @ts-ignore
    pipWindow.current = await documentPictureInPicture.requestWindow(
      pipOptions
    );

    // Style remaining container to imply the player is in PiP.
    if (videoContainerRef.current) {
      // setIsPip(true);
      playerRef.current.classList.add("pip-mode");

      // Add player to the PiP window.
      pipWindow?.current?.document.body.append(playerRef.current);

      // Listen for the PiP closing event to put the video back.
      pipWindow?.current?.addEventListener(
        "pagehide",
        onLeavePiP.bind(pipWindow.current),
        {
          once: true,
        }
      );
    }
  };

  // Called when the PiP window has closed.
  const onLeavePiP = () => {
    // Remove PiP styling from the container.
    if (videoContainerRef.current) {
      // setIsPip(false);
      playerRef.current.classList.remove("pip-mode");

      // Add the player back to the main window.
      videoContainerRef.current.append(playerRef.current);

      pipWindow.current = null;
    }
  };

  return (
    <div ref={videoContainerRef} className="videoContainer">
      <div ref={playerRef} className="videoPlayer">
        <video
          id="video"
          autoPlay
          muted
          playsInline
          loop
          src="https://storage.googleapis.com/media-session/sintel/trailer.mp4"
        ></video>
        <div className="videoControls">
          <button className="videoControlButton" onClick={handlePlay}>
            Play
          </button>
          <button className="videoControlButton">CC</button>
          <button className="videoControlButton" onClick={enterPiP}>
            Open PiP
          </button>
        </div>
      </div>
    </div>
  );
};

export default VideoPlayer;