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

No edit summary
No edit summary
 
(46 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 size = parseInt(match[1], 10);
        const playButton = document.createElement('button');
        playButton.className = 'model-anim-button';
        playButton.type = 'button';


    el.style.width = `${size}px`;
        const select = document.createElement('select');
    el.style.height = `${size}px`;
        select.className = 'model-anim-select';
});


(function () {
        const slider = document.createElement('input');
    'use strict';
        slider.className = 'model-anim-slider';
        slider.type = 'range';
        slider.min = '0';
        slider.max = '1000';
        slider.value = '0';
        slider.step = '1';
 
        let paused = !autoplay;
        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);
            rafId = requestAnimationFrame(updateSlider);
        }


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


         const match = wrapper.className.match(/model_size_(\d+)/);
         playButton.addEventListener('click', function () {
            setPlaying(paused);
        });
 
        slider.addEventListener('input', function () {
            if (duration > 0) {
                viewer.currentTime = (parseFloat(slider.value) / 1000) * duration;
            }
        });


         if (!match) {
         viewer.addEventListener('load', function () {
            return;
            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);
                }


         const size = match[1];
                startLoop();
                bar.classList.add('model-viewer-controls--visible');
            }
         });


         viewer.style.width = size + 'px';
         bar.appendChild(playButton);
         viewer.style.height = size + 'px';
        bar.appendChild(select);
         bar.appendChild(slider);
        container.appendChild(bar);
     }
     }




     function addButton(viewer) {
 
         if (viewer.dataset.qualityButton) {
     function loadModel(preview) {
         if (preview.dataset.loaded) {
             return;
             return;
         }
         }


         viewer.dataset.qualityButton = '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 parent = viewer.parentElement;
         getFileUrl(fileName + '.glb')
            .then(function (url) {
                if (!url) {
                    return;
                }


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


        parent.insertBefore(container, viewer);
                const container = document.createElement('div');
        container.appendChild(viewer);
                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', '');
                }


        const button = document.createElement('button');
                container.appendChild(viewer);
        button.className = 'mv-quality-toggle';
                wrap.appendChild(container);
        button.type = 'button';


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


        const icon = document.createElement('img');
                const name = document.createElement('div');
        icon.src = LQ_ICON;
                name.className = 'model-name';
        icon.alt = 'LQ/HQ';
                name.textContent = displayName;


                wrap.appendChild(name);


        button.appendChild(icon);
                preview.replaceWith(wrap);
        container.appendChild(button);
            });
    }


    function initPreview(preview) {
        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 () {
         button.addEventListener('click', function () {
             console.log('quality button clicked');
             loadModel(preview);
            icon.src = icon.src.includes('2D_icon')
                ? HQ_ICON
                : LQ_ICON;
         });
         });


        preview.appendChild(button);
    }


         console.log('Added quality button', viewer);
    function scan() {
         document
            .querySelectorAll('.model-placeholder')
            .forEach(initPreview);
     }
     }


    let scanTimer = null;


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


     scan();
     scan();


     const observer = new MutationObserver(function () {
     const observer = new MutationObserver(debouncedScan);
        scan();
    });
 
     observer.observe(document.body, {
     observer.observe(document.body, {
         childList: true,
         childList: true,
Line 103: Line 228:


})();
})();