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

No edit summary
No edit summary
 
(245 intermediate revisions by the same user not shown)
Line 1: Line 1:
/**
* Rotatable Model Viewer — with 2D / 3D toggle
* All <img> elements created in JS to bypass MediaWiki sanitizer.
*/
(function () {
(function () {
     'use strict';
     'use strict';


     function makeImg(src, alt, className) {
     const urlCache = new Map();
        var i = new Image();
 
         i.src = src;
    function getSize(element) {
        i.alt = alt || '';
         const match = element.className.match(/model_size_(\d+)/);
        i.draggable = false;
         return match ? parseInt(match[1], 10) : 500;
        if (className) i.className = className;
         return i;
     }
     }


     function boot(el) {
     function getFileUrl(fileName) {
         if (el.dataset.rmReady) return;
         if (urlCache.has(fileName)) {
         el.dataset.rmReady = '1';
            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';


         /* ---- config ---- */
         const playButton = document.createElement('button');
        var imageUrl    = el.dataset.image        || '',
        playButton.className = 'model-anim-button';
            image2dUrl  = el.dataset.imageFlat    || '',
        playButton.type = 'button';
            icon2dUrl  = el.dataset.iconFlat    || '',
            icon3dUrl  = el.dataset.iconStereo  || '',
            iconRotUrl  = el.dataset.iconRotate  || '',
            fw          = +el.dataset.frameWidth  || 300,
            fh          = +el.dataset.frameHeight || 400,
            count      = +el.dataset.frameCount  || 24,
            startFrame  = +el.dataset.startFrame  || 0,
            sensitivity = +el.dataset.sensitivity || 5;


         var hint = el.querySelector('.rotatable-model-hint'),
         const select = document.createElement('select');
            load = el.querySelector('.rotatable-model-loading'),
        select.className = 'model-anim-select';
            wrap = el.closest('.rotatable-model-wrapper');


         if (!imageUrl) {
         const slider = document.createElement('input');
             if (load) load.textContent = 'Error: no image URL';
        slider.className = 'model-anim-slider';
             return;
        slider.type = 'range';
        slider.min = '0';
        slider.max = '1000';
        slider.value = '0';
        slider.step = '1';
 
        let paused = !autoplay;
        let rafId = null;
        let duration = 0;
 
        function updateSlider() {
             if (duration > 0) {
                slider.value = String(Math.round((viewer.currentTime / duration) * 1000));
             }
            rafId = requestAnimationFrame(updateSlider);
         }
         }


         /* ---- state ---- */
         function startLoop() {
        var cur    = startFrame,
             cancelAnimationFrame(rafId);
             is2D  = false,
             rafId = requestAnimationFrame(updateSlider);
             dragOK = true;
        }


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


         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;
            }
         });
         });


         el.insertBefore(img, el.firstChild);
         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 (img.complete && img.naturalWidth > 0) {
                if (defaultAnimation && animations.indexOf(defaultAnimation) !== -1) {
            if (load) load.style.display = 'none';
                    select.value = defaultAnimation;
        }
                }


        /* ============================================================
                viewer.animationName = select.value;
          2D STATIC IMAGE
                duration = viewer.duration || 0;
          ============================================================ */
        var staticImg = null;
        if (image2dUrl) {
            staticImg = makeImg(image2dUrl, '', 'rm-static');
            el.insertBefore(staticImg, el.firstChild);
        }


        /* ============================================================
                select.addEventListener('change', function () {
          MODE TOGGLE — single button, swaps icon on click
                    viewer.animationName = select.value;
          ============================================================ */
                    duration = viewer.duration || 0;
        var toggleBtn = null,
                    viewer.currentTime = 0;
            iconImg2d = null,
                    if (paused) {
            iconImg3d = null;
                        setPlaying(true);
                    }
                });


        if (image2dUrl) {
                if (paused) {
            toggleBtn = document.createElement('span');
                    setPlaying(false);
            toggleBtn.className = 'rm-mode-toggle';
                }
            toggleBtn.setAttribute('role', 'button');
            toggleBtn.setAttribute('tabindex', '0');
            toggleBtn.title = 'Switch to 2D';


            // Create both icon images, show only one at a time
                 startLoop();
            if (icon2dUrl) {
                 bar.classList.add('model-viewer-controls--visible');
                 iconImg2d = makeImg(icon2dUrl, '2D', 'rm-mode-icon rm-icon-2d');
            }
            if (icon3dUrl) {
                 iconImg3d = makeImg(icon3dUrl, '3D', 'rm-mode-icon rm-icon-3d');
                iconImg3d.style.display = 'none'; // hidden initially (3D is active, show 2D icon)
             }
             }
        });


            // In 3D mode → show 2D icon (to switch TO 2D)
        bar.appendChild(playButton);
            // In 2D mode → show 3D icon (to switch TO 3D)
        bar.appendChild(select);
            if (iconImg2d) toggleBtn.appendChild(iconImg2d);
        bar.appendChild(slider);
            if (iconImg3d) toggleBtn.appendChild(iconImg3d);
        container.appendChild(bar);
    }


            // Text fallback if no icons
            if (!icon2dUrl && !icon3dUrl) {
                toggleBtn.textContent = '2D';
            }


            el.appendChild(toggleBtn);
        }


        /* ============================================================
    function loadModel(preview) {
          ROTATION ICON  (bottom-right)
         if (preview.dataset.loaded) {
          ============================================================ */
             return;
         if (iconRotUrl) {
            var rotDiv = document.createElement('div');
            rotDiv.className = 'rm-rotate-icon';
            rotDiv.appendChild(makeImg(iconRotUrl, 'Drag to rotate', ''));
             el.appendChild(rotDiv);
         }
         }


         /* ============================================================
         preview.dataset.loaded = '1';
          FRAME DISPLAY
          ============================================================ */
        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'); }


         /* ============================================================
         const fileName = preview.dataset.model;
          2D ↔ 3D SWITCHING
        const displayName = preview.dataset.name || fileName;
          ============================================================ */
        const defaultAnimation = preview.dataset.animation || '';
         function setMode(mode) {
        const autoplay = preview.dataset.autoplay === 'true';
            is2D = (mode === '2d');
         const size = getSize(preview);


            if (is2D) {
        getFileUrl(fileName + '.glb')
                el.classList.add('rm-is-2d');
             .then(function (url) {
                if (wrap) wrap.classList.add('rm-is-2d');
                 if (!url) {
                dragOK = false;
                    return;
             } else {
                 }
                el.classList.remove('rm-is-2d');
                 if (wrap) wrap.classList.remove('rm-is-2d');
                 dragOK = true;
            }


            // Swap the visible icon
                 const wrap = document.createElement('div');
            if (iconImg2d && iconImg3d) {
                 wrap.className = 'model-viewer-wrap';
                 // 2D mode active → show 3D icon (to switch back)
                // 3D mode active → show 2D icon (to switch to 2D)
                iconImg2d.style.display = is2D ? 'none' : '';
                 iconImg3d.style.display = is2D ? '' : 'none';
            }


            // Update title
                const container = document.createElement('div');
            if (toggleBtn) {
                container.className = 'model-viewer-container';
                 toggleBtn.title = is2D ? 'Switch to 3D' : 'Switch to 2D';
                 container.style.width = size + 'px';
                container.style.height = size + 'px';


                 // Text fallback
                 const viewer = document.createElement('model-viewer');
                 if (!icon2dUrl && !icon3dUrl) {
                viewer.src = url;
                     toggleBtn.textContent = is2D ? '3D' : '2D';
                viewer.setAttribute('camera-controls', '');
                viewer.setAttribute('touch-action', 'pan-y');
                 if (preview.dataset.autoplay === 'true') {
                     viewer.setAttribute('autoplay', '');
                 }
                 }
            }
        }


        if (toggleBtn) {
                container.appendChild(viewer);
            toggleBtn.addEventListener('click', function () {
                wrap.appendChild(container);
                 setMode(is2D ? '3d' : '2d');
 
            });
                 buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay);
        }


        /* ============================================================
                const name = document.createElement('div');
          DRAG  (mouse + touch)
                name.className = 'model-name';
          ============================================================ */
                name.textContent = displayName;
        function startDrag(x0) {
            if (!dragOK) return;
            var acc = 0;
            hideHint();


            function move(cx) {
                 wrap.appendChild(name);
                acc += cx - x0;
                 x0 = cx;
                var fd = (acc / sensitivity) | 0;
                if (fd) { acc -= fd * sensitivity; show(cur + fd); }
            }


            function onMM(e) { move(e.clientX); e.preventDefault(); }
                 preview.replaceWith(wrap);
            function onTM(e) {
             });
                 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');
    function initPreview(preview) {
            document.addEventListener('mousemove',  onMM);
        if (preview.dataset.initialized) {
            document.addEventListener('mouseup',    stop);
             return;
            document.addEventListener('touchmove',  onTM, { passive: false });
             document.addEventListener('touchend',    stop);
            document.addEventListener('touchcancel', stop);
         }
         }


         el.addEventListener('mousedown', function (e) {
         preview.dataset.initialized = '1';
            if (e.target.closest('.rm-mode-toggle')) return;
 
            if (e.button === 0 && dragOK) { startDrag(e.clientX); e.preventDefault(); }
        const button = document.createElement('button');
        button.className = 'model-load-button';
        button.type = 'button';
        button.addEventListener('click', function () {
            loadModel(preview);
         });
         });
        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 ---- */
         preview.appendChild(button);
        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 ---- */
    function scan() {
        el.setAttribute('tabindex', '0');
        document
        el.addEventListener('keydown', function (e) {
             .querySelectorAll('.model-placeholder')
            if (is2D) return;
             .forEach(initPreview);
             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 ---- */
    let scanTimer = null;
        if (wrap) {
            var bL = wrap.querySelector('.rm-btn-left'),
                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 ---- */
    function debouncedScan() {
         show(startFrame);
         clearTimeout(scanTimer);
         scanTimer = setTimeout(scan, 100);
     }
     }


     /* ---- scan & init ---- */
     scan();
    function initAll(root) {
 
        var els = (root || document).querySelectorAll('.rotatable-model');
    const observer = new MutationObserver(debouncedScan);
        for (var i = 0; i < els.length; i++) boot(els[i]);
    observer.observe(document.body, {
    }
        childList: true,
        subtree: true
    });
 
})();
 
 
 


    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { initAll(); });
    } else {
        initAll();
    }


    if (typeof mw !== 'undefined' && mw.hook) {
const personal = document.querySelector(".vector-menu-content-list");
        mw.hook('wikipage.content').add(function ($c) { initAll($c[0]); });
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);
}