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

Undo
Tag: Undo
No edit summary
 
(240 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);
         }


         /* ---- config ---- */
         const apiUrl =
        var imageUrl    = el.dataset.image        || '',
             mw.config.get('wgScriptPath') +
             image2dUrl  = el.dataset.imageFlat    || '',
             '/api.php?action=query' +
             icon2dUrl  = el.dataset.iconFlat    || '',
             '&titles=File:' + encodeURIComponent(fileName) +
             icon3dUrl  = el.dataset.iconStereo  || '',
             '&prop=imageinfo' +
            iconRotUrl  = el.dataset.iconRotate  || '',
             '&iiprop=url' +
            fw          = +el.dataset.frameWidth  || 300,
             '&format=json';
            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 promise = fetch(apiUrl)
             load = el.querySelector('.rotatable-model-loading'),
            .then(function (response) {
             wrap = el.closest('.rotatable-model-wrapper');
                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;
            });


         if (!imageUrl) {
         urlCache.set(fileName, promise);
            if (load) load.textContent = 'Error: no image URL';
        return promise;
            return;
    }
        }
    function buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay) {
        const bar = document.createElement('div');
        bar.className = 'model-viewer-controls';


         /* ---- state ---- */
         const playButton = document.createElement('button');
         var cur    = startFrame,
        playButton.className = 'model-anim-button';
            is2D  = false,
         playButton.type = 'button';
            dragOK = true,
            ready  = false;   // true once the strip image has loaded


         /* ============================================================
         const select = document.createElement('select');
          3D SPRITE STRIP
         select.className = 'model-anim-select';
          ============================================================ */
         var img = makeImg(imageUrl, '', 'rm-strip');


         // Set explicit display dimensions
         const slider = document.createElement('input');
         // width = single frame width × number of frames
         slider.className = 'model-anim-slider';
         // height = frame height
         slider.type = 'range';
         img.style.height = fh + 'px';
         slider.min = '0';
         img.style.width  = (fw * count) + 'px';
        slider.max = '1000';
         slider.value = '0';
        slider.step = '1';


         img.addEventListener('load', function () {
         let paused = !autoplay;
            ready = true;
        let rafId = null;
            if (load) load.style.display = 'none';
         let duration = 0;
            show(startFrame);
         });
        img.addEventListener('error', function () {
            if (load) { load.textContent = 'Failed to load image'; load.style.color = '#d33'; }
        });


         el.insertBefore(img, el.firstChild);
         function updateSlider() {
            if (duration > 0) {
                slider.value = String(Math.round((viewer.currentTime / duration) * 1000));
            }
            rafId = requestAnimationFrame(updateSlider);
        }


         // Handle cached images
         function startLoop() {
        if (img.complete && img.naturalWidth > 0) {
             cancelAnimationFrame(rafId);
             ready = true;
             rafId = requestAnimationFrame(updateSlider);
            if (load) load.style.display = 'none';
             show(startFrame);
         }
         }


         /* ============================================================
         function setPlaying(playing) {
          2D STATIC IMAGE
            paused = !playing;
          ============================================================ */
            playButton.textContent = playing ? '❚❚' : '▶';
        var staticImg = null;
            if (playing) {
        if (image2dUrl) {
                viewer.play();
            staticImg = makeImg(image2dUrl, '', 'rm-static');
             } else {
             el.insertBefore(staticImg, el.firstChild);
                viewer.pause();
            }
         }
         }


         /* ============================================================
         playButton.addEventListener('click', function () {
          MODE TOGGLE — single button, swaps icon on click
             setPlaying(paused);
          ============================================================ */
        });
        var toggleBtn = null,
             iconImg2d = null,
            iconImg3d = null;


         if (image2dUrl) {
         slider.addEventListener('input', function () {
             toggleBtn = document.createElement('span');
             if (duration > 0) {
            toggleBtn.className = 'rm-mode-toggle';
                viewer.currentTime = (parseFloat(slider.value) / 1000) * duration;
            toggleBtn.setAttribute('role', 'button');
             }
             toggleBtn.setAttribute('tabindex', '0');
        });
            toggleBtn.title = 'Switch to 2D';


             if (icon2dUrl) {
        viewer.addEventListener('load', function () {
                 iconImg2d = makeImg(icon2dUrl, '2D', 'rm-mode-icon rm-icon-2d');
            const animations = viewer.availableAnimations || [];
            }
 
            if (icon3dUrl) {
             if (animations.length) {
                 iconImg3d = makeImg(icon3dUrl, '3D', 'rm-mode-icon rm-icon-3d');
                 animations.forEach(function (animName) {
                iconImg3d.style.display = 'none';
                    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 (iconImg2d) toggleBtn.appendChild(iconImg2d);
                if (paused) {
            if (iconImg3d) toggleBtn.appendChild(iconImg3d);
                    setPlaying(false);
                }


            if (!icon2dUrl && !icon3dUrl) {
                startLoop();
                 toggleBtn.textContent = '2D';
                 bar.classList.add('model-viewer-controls--visible');
             }
             }
        });


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


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


        /* ============================================================
          FRAME DISPLAY
          ============================================================ */
        function show(idx) {
            cur = ((idx % count) + count) % count;
            // Move the strip so that frame `cur` is visible in the viewport
            var offset = cur * fw;
            img.style.left = '-' + offset + 'px';
            img.style.top  = '0px';
        }


        function nudge(d) {
    function loadModel(preview) {
            if (!is2D && ready) {
        if (preview.dataset.loaded) {
                show(cur + d);
            return;
                hideHint();
            }
         }
         }


         function reset() { show(startFrame); }
         preview.dataset.loaded = '1';


         function hideHint() {
         const fileName = preview.dataset.model;
            if (hint) hint.classList.add('rm-hidden');
        const displayName = preview.dataset.name || fileName;
         }
        const defaultAnimation = preview.dataset.animation || '';
        const autoplay = preview.dataset.autoplay === 'true';
         const size = getSize(preview);


         /* ============================================================
         getFileUrl(fileName + '.glb')
          2D ↔ 3D SWITCHING
            .then(function (url) {
          ============================================================ */
                if (!url) {
        function setMode(mode) {
                    return;
            is2D = (mode === '2d');
                }


            if (is2D) {
                 const wrap = document.createElement('div');
                 el.classList.add('rm-is-2d');
                 wrap.className = 'model-viewer-wrap';
                 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;
            }


            if (iconImg2d && iconImg3d) {
                const container = document.createElement('div');
                 iconImg2d.style.display = is2D ? 'none' : '';
                container.className = 'model-viewer-container';
                 iconImg3d.style.display = is2D ? '' : 'none';
                 container.style.width = size + 'px';
            }
                 container.style.height = size + 'px';


            if (toggleBtn) {
                const viewer = document.createElement('model-viewer');
                 toggleBtn.title = is2D ? 'Switch to 3D' : 'Switch to 2D';
                 viewer.src = url;
                 if (!icon2dUrl && !icon3dUrl) {
                viewer.setAttribute('camera-controls', '');
                     toggleBtn.textContent = is2D ? '3D' : '2D';
                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);
          DRAG  (mouse + touch)
          One frame per `sensitivity` pixels of movement.
          Clamped to ±1 frame per event to prevent skipping.
          ============================================================ */
        function startDrag(x0) {
            if (!dragOK || !ready) return;
            var acc = 0;
            hideHint();


            function move(cx) {
                const name = document.createElement('div');
                 var dx = cx - x0;
                 name.className = 'model-name';
                x0 = cx;
                 name.textContent = displayName;
                 acc += dx;


                 // Convert accumulated pixels to frame steps
                 wrap.appendChild(name);
                while (acc >= sensitivity) {
                    acc -= sensitivity;
                    show(cur + 1);
                }
                while (acc <= -sensitivity) {
                    acc += sensitivity;
                    show(cur - 1);
                }
            }


            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: always ±1 frame per tick ---- */
         preview.appendChild(button);
        el.addEventListener('wheel', function (e) {
    }
            if (!dragOK || !ready) 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 || !ready) 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);
}