User:Monster Domosed/common.js: Difference between revisions

No edit summary
No edit summary
 
(42 intermediate revisions by the same user not shown)
Line 2: Line 2:
     'use strict';
     'use strict';


     const LQ_ICON = '/images/6/65/2D_icon.png';
     const urlCache = new Map();
    const HQ_ICON = '/images/7/7e/3D_icon.png';


     function updateViewerSize(viewer, wrapper) {
     function getSize(element) {
         const match = wrapper.className.match(/model_size_(\d+)/);
         const match = element.className.match(/model_size_(\d+)/);
        return match ? parseInt(match[1], 10) : 500;
    }


         if (!match) {
    function getFileUrl(fileName) {
             return;
         if (urlCache.has(fileName)) {
             return urlCache.get(fileName);
         }
         }


        const size = parseInt(match[1], 10);
        viewer.style.width = size + 'px';
        viewer.style.height = size + 'px';
    }
    function getHQUrl(fileName) {
         const apiUrl =
         const apiUrl =
             mw.config.get('wgScriptPath') +
             mw.config.get('wgScriptPath') +
             '/api.php?action=query' +
             '/api.php?action=query' +
             '&titles=File:' + encodeURIComponent(fileName) +
             '&titles=File:' + encodeURIComponent(fileName) +
            '.glb' +
             '&prop=imageinfo' +
             '&prop=imageinfo' +
             '&iiprop=url' +
             '&iiprop=url' +
             '&format=json';
             '&format=json';


         return fetch(apiUrl)
         const promise = fetch(apiUrl)
             .then(function (response) {
             .then(function (response) {
                if (!response.ok) {
                    throw new Error('API request failed');
                }
                 return response.json();
                 return response.json();
             })
             })
             .then(function (data) {
             .then(function (data) {
                 const pages = data.query.pages;
                 const page = Object.values(data.query.pages)[0];
                 const page = Object.values(pages)[0];
                 return page && page.imageinfo ? page.imageinfo[0].url : null;
            })
            .catch(function () {
                return null;
            });


                if (!page.imageinfo) {
        urlCache.set(fileName, promise);
                    return null;
        return promise;
                }
    }
    function buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay) {
        const bar = document.createElement('div');
        bar.className = 'model-viewer-controls';


                return page.imageinfo[0].url;
        const playButton = document.createElement('button');
            });
        playButton.className = 'model-anim-button';
    }
        playButton.type = 'button';


        const select = document.createElement('select');
        select.className = 'model-anim-select';


function switchQuality(viewer, icon, lqUrl, hqUrl) {
        const slider = document.createElement('input');
    const isLQ = viewer.src === lqUrl;
        slider.className = 'model-anim-slider';
        slider.type = 'range';
    const oldTime = viewer.currentTime;
        slider.min = '0';
    const oldAnimation = viewer.animationName;
        slider.max = '1000';
        slider.value = '0';
    const oldOrbit = viewer.cameraOrbit;
        slider.step = '1';
    const oldTarget = viewer.cameraTarget;
    viewer.addEventListener('load', function restore() {
        viewer.removeEventListener('load', restore);
        if (oldOrbit) {
            viewer.cameraOrbit = oldOrbit;
        }
        if (oldTarget) {
            viewer.cameraTarget = oldTarget;
        }
        if (oldAnimation) {
            viewer.animationName = oldAnimation;
        }
        if (typeof oldTime === 'number') {
            viewer.currentTime = oldTime;
        }
        if (viewer.hasAttribute('autoplay')) {
            viewer.play();
        }
    }, { once: true });
    viewer.src = isLQ ? hqUrl : lqUrl;
    icon.src = isLQ ? HQ_ICON : LQ_ICON;
}


        let paused = !autoplay;
        let rafId = null;
        let duration = 0;


    function initViewer(viewer) {
        function updateSlider() {
        if (viewer.dataset.qualityButtonAdded) {
            if (duration > 0) {
             return;
                slider.value = String(Math.round((viewer.currentTime / duration) * 1000));
            }
             rafId = requestAnimationFrame(updateSlider);
         }
         }


         const wrapper = viewer.closest('[class*="model_size_"]');
         function startLoop() {
            cancelAnimationFrame(rafId);
            rafId = requestAnimationFrame(updateSlider);
        }


         if (!wrapper) {
         function setPlaying(playing) {
             return;
            paused = !playing;
            playButton.textContent = playing ? '❚❚' : '▶';
            if (playing) {
                viewer.play();
             } else {
                viewer.pause();
            }
         }
         }


         const src = viewer.getAttribute('src');
         playButton.addEventListener('click', function () {
            setPlaying(paused);
        });


         if (!src || !src.endsWith('-compressed.glb')) {
         slider.addEventListener('input', function () {
            return;
            if (duration > 0) {
        }
                viewer.currentTime = (parseFloat(slider.value) / 1000) * duration;
            }
        });
 
        viewer.addEventListener('load', function () {
            const animations = viewer.availableAnimations || [];
 
            if (animations.length) {
                animations.forEach(function (animName) {
                    const option = document.createElement('option');
                    option.value = animName;
                    option.textContent = animName;
                    select.appendChild(option);
                });
 
                if (defaultAnimation && animations.indexOf(defaultAnimation) !== -1) {
                    select.value = defaultAnimation;
                }
 
                viewer.animationName = select.value;
                duration = viewer.duration || 0;
 
                select.addEventListener('change', function () {
                    viewer.animationName = select.value;
                    duration = viewer.duration || 0;
                    viewer.currentTime = 0;
                    if (paused) {
                        setPlaying(true);
                    }
                });
 
                if (paused) {
                    setPlaying(false);
                }


        viewer.dataset.qualityButtonAdded = '1';
                startLoop();
                bar.classList.add('model-viewer-controls--visible');
            }
        });


         updateViewerSize(viewer, wrapper);
         bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
    }




        const fileMatch = src.match(/\/([^\/]+)-compressed\.glb$/);


         if (!fileMatch) {
    function loadModel(preview) {
         if (preview.dataset.loaded) {
             return;
             return;
         }
         }


         const baseName = fileMatch[1];
         preview.dataset.loaded = '1';


        const fileName = preview.dataset.model;
        const displayName = preview.dataset.name || fileName;
        const defaultAnimation = preview.dataset.animation || '';
        const autoplay = preview.dataset.autoplay === 'true';
        const size = getSize(preview);


         getHQUrl(baseName)
         getFileUrl(fileName + '.glb')
             .then(function (hqUrl) {
             .then(function (url) {
 
                 if (!url) {
                 if (!hqUrl) {
                     return;
                     return;
                 }
                 }


                const wrap = document.createElement('div');
                wrap.className = 'model-viewer-wrap';


                 const container = document.createElement('div');
                 const container = document.createElement('div');
                 container.className = 'mv-quality-container';
                 container.className = 'model-viewer-container';
                container.style.width = size + 'px';
                container.style.height = size + 'px';
 
                const viewer = document.createElement('model-viewer');
                viewer.src = url;
                viewer.setAttribute('camera-controls', '');
                viewer.setAttribute('touch-action', 'pan-y');
                if (preview.dataset.autoplay === 'true') {
                    viewer.setAttribute('autoplay', '');
                }


                viewer.parentNode.insertBefore(container, viewer);
                 container.appendChild(viewer);
                 container.appendChild(viewer);
                wrap.appendChild(container);


                buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay);


                 const button = document.createElement('button');
                 const name = document.createElement('div');
                 button.className = 'mv-quality-toggle';
                 name.className = 'model-name';
                 button.type = 'button';
                 name.textContent = displayName;


                wrap.appendChild(name);


                 const icon = document.createElement('img');
                 preview.replaceWith(wrap);
                icon.src = LQ_ICON;
            });
                icon.alt = '';
    }


    function initPreview(preview) {
        if (preview.dataset.initialized) {
            return;
        }


                button.appendChild(icon);
        preview.dataset.initialized = '1';
                container.appendChild(button);


        const button = document.createElement('button');
        button.className = 'model-load-button';
        button.type = 'button';
        button.addEventListener('click', function () {
            loadModel(preview);
        });


                button.addEventListener('click', function () {
        preview.appendChild(button);
                    switchQuality(
    }
                        viewer,
                        icon,
                        src,
                        hqUrl
                    );
                });


             });
    function scan() {
        document
             .querySelectorAll('.model-placeholder')
            .forEach(initPreview);
     }
     }


    let scanTimer = null;


     function scan() {
     function debouncedScan() {
         document.querySelectorAll('model-viewer').forEach(initViewer);
         clearTimeout(scanTimer);
        scanTimer = setTimeout(scan, 100);
     }
     }


     scan();
     scan();


 
     const observer = new MutationObserver(debouncedScan);
     const observer = new MutationObserver(function () {
        scan();
    });
 
 
     observer.observe(document.body, {
     observer.observe(document.body, {
         childList: true,
         childList: true,
         subtree: true
         subtree: true
    });
    window.addEventListener('resize', function () {
        document.querySelectorAll('model-viewer').forEach(function (viewer) {
            const wrapper = viewer.closest('[class*="model_size_"]');
            if (wrapper) {
                updateViewerSize(viewer, wrapper);
            }
        });
     });
     });


})();
})();