Source: media/viewer/videoPlayer.js

import { UiVideoPlayer } from "../player/UiVideoPlayer.js";
export { initVideo }

// static video player instance
let videoInterval = null;
let videoTimeout = null;
let videoPlayer = null;

/**
 * Internal function to destroy the video player and stop all timers.
 * @private
 */
function _disposeVideo() {
    if (videoInterval) videoInterval = clearInterval(videoInterval);
    if (videoTimeout) videoTimeout = clearTimeout(videoTimeout);
    if (videoPlayer) videoPlayer = videoPlayer.dispose();
}

/**
 * Internal function to create a container for the player. The player will
 * be initialized when it was added to the dom.
 * @param {object} config 
 * @param {HTMLElement} container 
 * @returns {HTMLElement} - Video player inside a container.
 */
function initVideo(config, container) {
    // dispose old player
    _disposeVideo();

    container = container || document.createElement("div");

    // create the player instance and append it to the container
    const initPlayer = () => {
        if (videoInterval) clearInterval(videoInterval);

        videoPlayer = new UiVideoPlayer(container, config);

        // call initPlayer to dispose and re-initialize when content is drawn again
        videoInterval = setInterval(() => {
            if (container.offsetParent == null) initVideo(config, container);
        }, 200);
    }

    // timeout to allow fast switching of popup content
    videoTimeout = setTimeout(() => {
        // only init the player if it is visible (offsetParent == null when not displayed)
        if (container.offsetParent) {
            initPlayer();
        } else {
            if (videoInterval) clearInterval(videoInterval);
            videoInterval = setInterval(() => {
                if (container.offsetParent) initPlayer();
            }, 200);
        }
    }, 0);

    return container;
}