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

From The Deadlock Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(246 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';


         /* ---- config ---- */
         const promise = fetch(apiUrl)
        var imageUrl    = el.dataset.image        || '',
            .then(function (response) {
            image2dUrl  = el.dataset.imageFlat    || '',  // data-image-flat
                if (!response.ok) {
             icon2dUrl  = el.dataset.iconFlat    || '',  // data-icon-flat
                    throw new Error('API request failed');
             icon3dUrl  = el.dataset.iconStereo  || '',  // data-icon-stereo
                }
            iconRotUrl  = el.dataset.iconRotate  || '',  // data-icon-rotate
                return response.json();
            fw          = +el.dataset.frameWidth  || 300,
             })
            fh          = +el.dataset.frameHeight || 400,
             .then(function (data) {
             count      = +el.dataset.frameCount  || 24,
                const page = Object.values(data.query.pages)[0];
             startFrame  = +el.dataset.startFrame  || 0,
                return page && page.imageinfo ? page.imageinfo[0].url : null;
             sensitivity = +el.dataset.sensitivity || 5;
             })
             .catch(function () {
                return null;
             });


         var hint = el.querySelector('.rotatable-model-hint'),
         urlCache.set(fileName, promise);
            load = el.querySelector('.rotatable-model-loading'),
        return promise;
            wrap = el.closest('.rotatable-model-wrapper');
    }
    function buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay) {
        const bar = document.createElement('div');
        bar.className = 'model-viewer-controls';


         if (!imageUrl) {
         const playButton = document.createElement('button');
             if (load) load.textContent = 'Error: no image URL';
        playButton.className = 'model-anim-button';
             return;
        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';
 
        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 (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) {
                    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  (top-right, built entirely in JS)
                    viewer.animationName = select.value;
          ============================================================ */
                    duration = viewer.duration || 0;
        var btn2d = null, btn3d = null;
                    viewer.currentTime = 0;
                    if (paused) {
                        setPlaying(true);
                    }
                });


        if (image2dUrl) {
                if (paused) {
            var toggle = document.createElement('div');
                    setPlaying(false);
            toggle.className = 'rm-mode-toggle';
                }


            // 2D button
                startLoop();
            btn2d = document.createElement('span');
                bar.classList.add('model-viewer-controls--visible');
            btn2d.className = 'rm-mode-btn rm-mode-2d';
            btn2d.setAttribute('role', 'button');
            btn2d.setAttribute('tabindex', '0');
            btn2d.title = '2D View';
            if (icon2dUrl) {
                btn2d.appendChild(makeImg(icon2dUrl, '2D', 'rm-mode-icon'));
            } else {
                btn2d.textContent = '2D';
             }
             }
        });


            // 3D button (active by default)
        bar.appendChild(playButton);
            btn3d = document.createElement('span');
        bar.appendChild(select);
            btn3d.className = 'rm-mode-btn rm-mode-3d rm-active';
        bar.appendChild(slider);
            btn3d.setAttribute('role', 'button');
        container.appendChild(bar);
            btn3d.setAttribute('tabindex', '0');
    }
            btn3d.title = '3D View';
            if (icon3dUrl) {
                btn3d.appendChild(makeImg(icon3dUrl, '3D', 'rm-mode-icon'));
            } else {
                btn3d.textContent = '3D';
            }


            toggle.appendChild(btn2d);
            toggle.appendChild(btn3d);
            el.appendChild(toggle);
        }


        /* ============================================================
          ROTATION ICON  (bottom-right, built in JS)
          ============================================================ */
        if (iconRotUrl) {
            var rotDiv = document.createElement('div');
            rotDiv.className = 'rm-rotate-icon';
            rotDiv.appendChild(makeImg(iconRotUrl, 'Drag to rotate', ''));
            el.appendChild(rotDiv);
        }


        /* ============================================================
    function loadModel(preview) {
          FRAME DISPLAY
        if (preview.dataset.loaded) {
          ============================================================ */
             return;
        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'); }


         /* ============================================================
         preview.dataset.loaded = '1';
          2D ↔ 3D SWITCHING
          ============================================================ */
        function setMode(mode) {
            is2D = (mode === '2d');


            if (is2D) {
        const fileName = preview.dataset.model;
                el.classList.add('rm-is-2d');
        const displayName = preview.dataset.name || fileName;
                if (wrap) wrap.classList.add('rm-is-2d');
        const defaultAnimation = preview.dataset.animation || '';
                dragOK = false;
        const autoplay = preview.dataset.autoplay === 'true';
            } else {
        const size = getSize(preview);
                el.classList.remove('rm-is-2d');
                if (wrap) wrap.classList.remove('rm-is-2d');
                dragOK = true;
            }


            if (btn2d && btn3d) {
        getFileUrl(fileName + '.glb')
                btn2d.classList.toggle('rm-active', is2D);
            .then(function (url) {
                 btn3d.classList.toggle('rm-active', !is2D);
                 if (!url) {
            }
                    return;
        }
                }


        if (btn2d) btn2d.addEventListener('click', function () { setMode('2d'); });
                const wrap = document.createElement('div');
        if (btn3d) btn3d.addEventListener('click', function () { setMode('3d'); });
                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');
            if (e.target.closest('.rm-mode-toggle')) return;
                name.className = 'model-name';
            if (e.button === 0 && dragOK) { startDrag(e.clientX); e.preventDefault(); }
                name.textContent = displayName;
        });
        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 & init ---- */
     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);
}

Latest revision as of 00:56, 15 September 2026

(function () {
    'use strict';

    const urlCache = new Map();

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

    function getFileUrl(fileName) {
        if (urlCache.has(fileName)) {
            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';

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

        function startLoop() {
            cancelAnimationFrame(rafId);
            rafId = requestAnimationFrame(updateSlider);
        }

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

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

                if (paused) {
                    setPlaying(false);
                }

                startLoop();
                bar.classList.add('model-viewer-controls--visible');
            }
        });

        bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
    }



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

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

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

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

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

                container.appendChild(viewer);
                wrap.appendChild(container);

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

                const name = document.createElement('div');
                name.className = 'model-name';
                name.textContent = displayName;

                wrap.appendChild(name);

                preview.replaceWith(wrap);
            });
    }

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

})();





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