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

No edit summary
No edit summary
 
(48 intermediate revisions by the same user not shown)
Line 1: Line 1:
document.querySelectorAll('model-viewer').forEach(el => {
(function () {
     const wrapper = el.closest('[class*="model_size_"]');
    'use strict';
     if (!wrapper) {
 
         return;
     const urlCache = new Map();
 
     function getSize(element) {
        const match = element.className.match(/model_size_(\d+)/);
         return match ? parseInt(match[1], 10) : 500;
     }
     }


     const match = wrapper.className.match(/\bmodel_size_(\d+)\b/);
     function getFileUrl(fileName) {
    if (!match) {
        if (urlCache.has(fileName)) {
         return;
            return urlCache.get(fileName);
        }
 
        const apiUrl =
            mw.config.get('wgScriptPath') +
            '/api.php?action=query' +
            '&titles=File:' + encodeURIComponent(fileName) +
            '&prop=imageinfo' +
            '&iiprop=url' +
            '&format=json';
 
        const promise = fetch(apiUrl)
            .then(function (response) {
                if (!response.ok) {
                    throw new Error('API request failed');
                }
                return response.json();
            })
            .then(function (data) {
                const page = Object.values(data.query.pages)[0];
                return page && page.imageinfo ? page.imageinfo[0].url : null;
            })
            .catch(function () {
                return null;
            });
 
        urlCache.set(fileName, promise);
         return promise;
     }
     }
    function buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay) {
        const bar = document.createElement('div');
        bar.className = 'model-viewer-controls';
        const playButton = document.createElement('button');
        playButton.className = 'model-anim-button';
        playButton.type = 'button';


    const size = parseInt(match[1], 10);
        const select = document.createElement('select');
        select.className = 'model-anim-select';


    el.style.width = `${size}px`;
        const slider = document.createElement('input');
    el.style.height = `${size}px`;
        slider.className = 'model-anim-slider';
});
        slider.type = 'range';
        slider.min = '0';
        slider.max = '1000';
        slider.value = '0';
        slider.step = '1';


(function () {
        let paused = !autoplay;
    'use strict';
        let rafId = null;
        let duration = 0;


    const LQ_ICON = '/images/6/65/2D_icon.png';
        function updateSlider() {
    const HQ_ICON = '/images/7/7e/3D_icon.png';
            if (duration > 0) {
                slider.value = String(Math.round((viewer.currentTime / duration) * 1000));
            }
            rafId = requestAnimationFrame(updateSlider);
        }


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


         const match = wrapper.className.match(/\bmodel_size_(\d+)\b/);
         function setPlaying(playing) {
        if (!match) {
            paused = !playing;
             return;
            playButton.textContent = playing ? '❚❚' : '▶';
            if (playing) {
                viewer.play();
            } else {
                viewer.pause();
             }
         }
         }


         const size = parseInt(match[1], 10);
         playButton.addEventListener('click', function () {
            setPlaying(paused);
        });
 
        slider.addEventListener('input', function () {
            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);
                    }
                });


        viewer.style.width = size + 'px';
                if (paused) {
         viewer.style.height = size + 'px';
                    setPlaying(false);
                }
 
                startLoop();
                bar.classList.add('model-viewer-controls--visible');
            }
         });
 
        bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
     }
     }


    function switchModel(viewer, icon) {
const isHQ = !viewer.src.endsWith('-compressed.glb');
viewer.src = isHQ
    ? viewer.src.replace(/\.glb$/i, '-compressed.glb')
    : viewer.src.replace(/-compressed\.glb$/i, '.glb');
icon.src = isHQ ? LQ_ICON : HQ_ICON;


     function initViewer(viewer) {
 
         if (viewer.dataset.modelViewerEnhanced) {
     function loadModel(preview) {
         if (preview.dataset.loaded) {
             return;
             return;
         }
         }


         viewer.dataset.modelViewerEnhanced = '1';
         preview.dataset.loaded = '1';


         updateViewerSize(viewer);
         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);


         const wrapper = document.createElement('div');
         getFileUrl(fileName + '.glb')
        wrapper.className = 'mv-quality-container';
            .then(function (url) {
                if (!url) {
                    return;
                }


        viewer.parentNode.insertBefore(wrapper, viewer);
                const wrap = document.createElement('div');
        wrapper.appendChild(viewer);
                wrap.className = 'model-viewer-wrap';


        const button = document.createElement('button');
                const container = document.createElement('div');
        button.className = 'mv-quality-toggle';
                container.className = 'model-viewer-container';
        button.type = 'button';
                container.style.width = size + 'px';
        button.title = 'Switch quality';
                container.style.height = size + 'px';


        const icon = document.createElement('img');
                const viewer = document.createElement('model-viewer');
        icon.alt = '';
                viewer.src = url;
                viewer.setAttribute('camera-controls', '');
                viewer.setAttribute('touch-action', 'pan-y');
                if (preview.dataset.autoplay === 'true') {
                    viewer.setAttribute('autoplay', '');
                }


        const isHQ = !viewer.src.endsWith('-compressed.glb');
                container.appendChild(viewer);
        icon.src = isHQ ? HQ_ICON : LQ_ICON;
                wrap.appendChild(container);


        button.appendChild(icon);
                buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay);
        wrapper.appendChild(button);


        button.addEventListener('click', function () {
                const name = document.createElement('div');
            switchModel(viewer, icon);
                name.className = 'model-name';
        });
                name.textContent = displayName;
    }


    function init() {
                wrap.appendChild(name);
        document.querySelectorAll('model-viewer').forEach(initViewer);
    }


    if (document.readyState === 'loading') {
                preview.replaceWith(wrap);
        document.addEventListener('DOMContentLoaded', init);
            });
    } else {
        init();
     }
     }


     window.addEventListener('resize', function () {
     function initPreview(preview) {
         document.querySelectorAll('model-viewer').forEach(updateViewerSize);
         if (preview.dataset.initialized) {
    });
            return;
})();
        }
 
 


        preview.dataset.initialized = '1';


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


        preview.appendChild(button);
    }


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


    let scanTimer = null;


    function debouncedScan() {
        clearTimeout(scanTimer);
        scanTimer = setTimeout(scan, 100);
    }


    scan();


    const observer = new MutationObserver(debouncedScan);
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });


})();