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

No edit summary
No edit summary
 
(248 intermediate revisions by the same user not shown)
Line 1: Line 1:
/**
* Rotatable Model Viewer — with 2D / 3D toggle
*/
(function () {
(function () {
     'use strict';
     'use strict';


     function boot(el) {
     const urlCache = new Map();
        if (el.dataset.rmReady) return;
        el.dataset.rmReady = '1';


         /* ---- config from data-attributes ---- */
    function getSize(element) {
         var imageUrl    = el.dataset.image        || '',
         const match = element.className.match(/model_size_(\d+)/);
             image2dUrl  = el.dataset.image2d      || '',
         return match ? parseInt(match[1], 10) : 500;
             fw          = +el.dataset.frameWidth  || 300,
    }
            fh          = +el.dataset.frameHeight || 400,
 
            count      = +el.dataset.frameCount  || 24,
    function getFileUrl(fileName) {
            startFrame  = +el.dataset.startFrame  || 0,
        if (urlCache.has(fileName)) {
            sensitivity = +el.dataset.sensitivity || 5;
            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 select = document.createElement('select');
        select.className = 'model-anim-select';
 
        const slider = document.createElement('input');
        slider.className = 'model-anim-slider';
        slider.type = 'range';
        slider.min = '0';
        slider.max = '1000';
        slider.value = '0';
        slider.step = '1';


         var hint  = el.querySelector('.rotatable-model-hint'),
         let paused = !autoplay;
            load  = el.querySelector('.rotatable-model-loading'),
        let rafId = null;
            wrap  = el.closest('.rotatable-model-wrapper');
        let duration = 0;


         if (!imageUrl) {
         function updateSlider() {
             if (load) load.textContent = 'Error: no image URL';
             if (duration > 0) {
             return;
                slider.value = String(Math.round((viewer.currentTime / duration) * 1000));
             }
            rafId = requestAnimationFrame(updateSlider);
         }
         }


         /* ============================================================
         function startLoop() {
          STATE
             cancelAnimationFrame(rafId);
          ============================================================ */
             rafId = requestAnimationFrame(updateSlider);
        var cur    = startFrame,
        }
             is2D    = false,          // current mode
             dragOK  = true;           // allow drag interaction


         /* ============================================================
         function setPlaying(playing) {
          3D SPRITE STRIP
            paused = !playing;
          ============================================================ */
            playButton.textContent = playing ? '❚❚' : '';
        var img      = new Image();
            if (playing) {
        img.className = 'rm-strip';
                viewer.play();
        img.alt      = '';
            } else {
        img.draggable = false;
                viewer.pause();
        img.style.height = fh + 'px';
            }
        img.style.width  = (fw * count) + 'px';
        }


         img.addEventListener('load', function () {
         playButton.addEventListener('click', function () {
             var detected = Math.round(img.naturalWidth / fw);
             setPlaying(paused);
            if (detected > 0 && detected !== count) count = detected;
            if (load) load.style.display = 'none';
            show(startFrame);
         });
         });
         img.addEventListener('error', function () {
 
             if (load) { load.textContent = 'Failed to load image'; load.style.color = '#d33'; }
         slider.addEventListener('input', function () {
             if (duration > 0) {
                viewer.currentTime = (parseFloat(slider.value) / 1000) * duration;
            }
         });
         });


         img.src = imageUrl;
         viewer.addEventListener('load', function () {
        el.insertBefore(img, el.firstChild);
            const animations = viewer.availableAnimations || [];


        if (img.complete && img.naturalWidth > 0) {
            if (animations.length) {
            if (load) load.style.display = 'none';
                animations.forEach(function (animName) {
        }
                    const option = document.createElement('option');
                    option.value = animName;
                    option.textContent = animName;
                    select.appendChild(option);
                });


        /* ============================================================
                if (defaultAnimation && animations.indexOf(defaultAnimation) !== -1) {
          2D STATIC IMAGE  (created only if URL provided)
                    select.value = defaultAnimation;
          ============================================================ */
                }
        var staticImg = null;
        if (image2dUrl) {
            staticImg = new Image();
            staticImg.className = 'rm-static';
            staticImg.alt      = '';
            staticImg.draggable = false;
            staticImg.src      = image2dUrl;
            el.insertBefore(staticImg, el.firstChild);
        }


        /* ============================================================
                viewer.animationName = select.value;
          FRAME DISPLAY
                duration = viewer.duration || 0;
          ============================================================ */
        function show(idx) {
            cur = ((idx % count) + count) % count;
            img.style.left = -(cur * fw) + 'px';
        }
        function nudge(d) { if (!is2D) { show(cur - d); hideHint(); } }
        function reset()  { show(startFrame); }
        function hideHint() { if (hint) hint.classList.add('rm-hidden'); }


        /* ============================================================
                select.addEventListener('change', function () {
          2D ↔ 3D MODE SWITCHING
                    viewer.animationName = select.value;
          ============================================================ */
                    duration = viewer.duration || 0;
        var btn2d = el.querySelector('.rm-mode-2d'),
                    viewer.currentTime = 0;
            btn3d = el.querySelector('.rm-mode-3d');
                    if (paused) {
                        setPlaying(true);
                    }
                });


        function setMode(mode) {
                if (paused) {
            is2D = (mode === '2d');
                    setPlaying(false);
                }


            if (is2D) {
                 startLoop();
                 el.classList.add('rm-is-2d');
                 bar.classList.add('model-viewer-controls--visible');
                 if (wrap) wrap.classList.add('rm-is-2d');
                dragOK = false;
            } else {
                el.classList.remove('rm-is-2d');
                if (wrap) wrap.classList.remove('rm-is-2d');
                dragOK = true;
             }
             }
        });
        bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
    }


            // Toggle active button
 
            if (btn2d && btn3d) {
 
                btn2d.classList.toggle('rm-active', is2D);
    function loadModel(preview) {
                btn3d.classList.toggle('rm-active', !is2D);
        if (preview.dataset.loaded) {
             }
             return;
         }
         }


         if (btn2d) {
         preview.dataset.loaded = '1';
            btn2d.addEventListener('click', function () { setMode('2d'); });
 
        }
        const fileName = preview.dataset.model;
         if (btn3d) {
        const displayName = preview.dataset.name || fileName;
             btn3d.addEventListener('click', function () { setMode('3d'); });
        const defaultAnimation = preview.dataset.animation || '';
        }
        const autoplay = preview.dataset.autoplay === 'true';
        const size = getSize(preview);
 
         getFileUrl(fileName + '.glb')
             .then(function (url) {
                if (!url) {
                    return;
                }
 
                const wrap = document.createElement('div');
                wrap.className = 'model-viewer-wrap';


        /* ============================================================
                const container = document.createElement('div');
          DRAG  (mouse + touch)
                container.className = 'model-viewer-container';
          ============================================================ */
                container.style.width = size + 'px';
        function startDrag(x0) {
                container.style.height = size + 'px';
            if (!dragOK) return;
            var acc = 0;
            hideHint();


            function move(cx) {
                const viewer = document.createElement('model-viewer');
                 acc += cx - x0;
                 viewer.src = url;
                 x0 = cx;
                 viewer.setAttribute('camera-controls', '');
                 var fd = (acc / sensitivity) | 0;
                 viewer.setAttribute('touch-action', 'pan-y');
                 if (fd) { acc -= fd * sensitivity; show(cur + fd); }
                 if (preview.dataset.autoplay === 'true') {
            }
                    viewer.setAttribute('autoplay', '');
                }


            function onMM(e) { move(e.clientX); e.preventDefault(); }
                 container.appendChild(viewer);
            function onTM(e) {
                 wrap.appendChild(container);
                 if (e.touches.length === 1) { move(e.touches[0].clientX); e.preventDefault(); }
            }
            function stop() {
                 el.classList.remove('rm-dragging');
                document.removeEventListener('mousemove',  onMM);
                document.removeEventListener('mouseup',    stop);
                document.removeEventListener('touchmove',  onTM);
                document.removeEventListener('touchend',    stop);
                document.removeEventListener('touchcancel', stop);
            }


            el.classList.add('rm-dragging');
                buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay);
            document.addEventListener('mousemove',   onMM);
            document.addEventListener('mouseup',     stop);
            document.addEventListener('touchmove',   onTM, { passive: false });
            document.addEventListener('touchend',    stop);
            document.addEventListener('touchcancel', stop);
        }


        el.addEventListener('mousedown', function (e) {
                const name = document.createElement('div');
            // Don't drag if clicking a mode button
                name.className = 'model-name';
            if (e.target.closest('.rm-mode-toggle')) return;
                name.textContent = displayName;
            if (e.button === 0 && dragOK) { startDrag(e.clientX); e.preventDefault(); }
        });
        el.addEventListener('touchstart', function (e) {
            if (e.target.closest('.rm-mode-toggle')) return;
            if (e.touches.length === 1 && dragOK) {
                startDrag(e.touches[0].clientX); e.preventDefault();
            }
        }, { passive: false });


        /* ---- wheel ---- */
                wrap.appendChild(name);
        el.addEventListener('wheel', function (e) {
            if (!dragOK) return;
            var d = e.deltaY > 0 ? 1 : e.deltaY < 0 ? -1 : 0;
            if (d) { nudge(d); e.preventDefault(); }
        }, { passive: false });


        /* ---- keyboard ---- */
                preview.replaceWith(wrap);
        el.setAttribute('tabindex', '0');
             });
        el.addEventListener('keydown', function (e) {
    }
            if (is2D) return;
             if (e.key === 'ArrowLeft')  { nudge(1); e.preventDefault(); }
            if (e.key === 'ArrowRight') { nudge(1); e.preventDefault(); }
            if (e.key === 'Home')      { reset();  e.preventDefault(); }
        });


        /* ---- nav buttons ---- */
    function initPreview(preview) {
        if (wrap) {
        if (preview.dataset.initialized) {
            var bL = wrap.querySelector('.rm-btn-left'),
             return;
                bR = wrap.querySelector('.rm-btn-right'),
                bO = wrap.querySelector('.rm-btn-reset');
            if (bL) bL.addEventListener('click', function () { nudge(-1); });
            if (bR) bR.addEventListener('click', function () { nudge( 1); });
             if (bO) bO.addEventListener('click', reset);
         }
         }


         /* ---- initial frame ---- */
         preview.dataset.initialized = '1';
         show(startFrame);
 
        const button = document.createElement('button');
        button.className = 'model-load-button';
        button.type = 'button';
        button.addEventListener('click', function () {
            loadModel(preview);
        });
 
         preview.appendChild(button);
     }
     }


     /* ---- scan & initialise ---- */
     function scan() {
    function initAll(root) {
         document
         var els = (root || document).querySelectorAll('.rotatable-model');
            .querySelectorAll('.model-placeholder')
        for (var i = 0; i < els.length; i++) boot(els[i]);
            .forEach(initPreview);
     }
     }


     if (document.readyState === 'loading') {
     let scanTimer = null;
        document.addEventListener('DOMContentLoaded', function () { initAll(); });
 
    } else {
    function debouncedScan() {
         initAll();
        clearTimeout(scanTimer);
         scanTimer = setTimeout(scan, 100);
     }
     }


     if (typeof mw !== 'undefined' && mw.hook) {
     scan();
         mw.hook('wikipage.content').add(function ($c) { initAll($c[0]); });
 
    }
    const observer = new MutationObserver(debouncedScan);
}());
    observer.observe(document.body, {
         childList: true,
        subtree: true
    });
 
})();
 
 
 
 
 
const personal = document.querySelector(".vector-menu-content-list");
if (personal){
const test2 = document.createElement("li");
const test3 = document.createElement("li");
const test4 = document.createElement("li");
test2.innerHTML = `<a href="/User:Monster_Domosed/common.js">JS</a>`;
test3.innerHTML = `<a href="/User:Monster_Domosed/common.css">CSS</a>`;
test4.innerHTML = `<a href="/User:Monster_Domosed/Sandbox">SB</a>`;
personal.prepend(test2, test3, test4);
}