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

From The Deadlock Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(251 intermediate revisions by the same user not shown)
Line 1: Line 1:
( function () {
(function () {
     'use strict';
     'use strict';


     /* ---- bootstrap one viewer element ---- */
     const urlCache = new Map();
    function boot( el ) {


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


        /* --- config --- */
    function getFileUrl(fileName) {
         var imageUrl    = el.dataset.image,
         if (urlCache.has(fileName)) {
             fw          = +el.dataset.frameWidth  || 300,
             return urlCache.get(fileName);
            fh          = +el.dataset.frameHeight || 400,
        }
            count      = +el.dataset.frameCount  || 24,
            startFrame  = +el.dataset.startFrame  || 0,
            sensitivity = +el.dataset.sensitivity || 5;


         if ( !imageUrl ) return;
         const apiUrl =
            mw.config.get('wgScriptPath') +
            '/api.php?action=query' +
            '&titles=File:' + encodeURIComponent(fileName) +
            '&prop=imageinfo' +
            '&iiprop=url' +
            '&format=json';


         var cur  = startFrame,
         const promise = fetch(apiUrl)
             hint = el.querySelector( '.rotatable-model-hint' ),
             .then(function (response) {
             load = el.querySelector( '.rotatable-model-loading' );
                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;
            });


         /* --- build the <img> strip --- */
         urlCache.set(fileName, promise);
        var img  = document.createElement( 'img' );
         return promise;
         img.className = 'rm-strip';
    }
        img.alt      = '';
    function buildAnimationControls(wrap, container, viewer, defaultAnimation, autoplay) {
         img.draggable = false;
         const bar = document.createElement('div');
        img.style.height = fh + 'px';
         bar.className = 'model-viewer-controls';
         img.style.width  = ( fw * count ) + 'px';


         img.onload = function () {
         const playButton = document.createElement('button');
            if ( load ) load.style.display = 'none';
        playButton.className = 'model-anim-button';
         };
         playButton.type = 'button';
        img.onerror = function () {
            if ( load ) load.textContent = 'Image failed to load';
        };


         img.src = imageUrl;
         const select = document.createElement('select');
         el.insertBefore( img, el.firstChild );
         select.className = 'model-anim-select';


         /* --- helpers --- */
         const slider = document.createElement('input');
         function show( idx ) {
        slider.className = 'model-anim-slider';
             cur = ( ( idx % count ) + count ) % count;
        slider.type = 'range';
             img.style.left = -( cur * fw ) + 'px';
        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 nudge( d ) { show( cur + d ); hideHint(); }
         function startLoop() {
            cancelAnimationFrame(rafId);
            rafId = requestAnimationFrame(updateSlider);
        }


         function reset() { show( startFrame ); }
         function setPlaying(playing) {
 
            paused = !playing;
        function hideHint() {
            playButton.textContent = playing ? '❚❚' : '▶';
            if ( hint ) hint.classList.add( 'rm-hidden' );
            if (playing) {
                viewer.play();
            } else {
                viewer.pause();
            }
         }
         }


         /* --- drag (mouse + touch) --- */
         playButton.addEventListener('click', function () {
        function startDrag( x0 ) {
             setPlaying(paused);
             var acc = 0;
        });
            hideHint();


            function move( cx ) {
        slider.addEventListener('input', function () {
                acc += cx - x0;
            if (duration > 0) {
                 x0  = cx;
                 viewer.currentTime = (parseFloat(slider.value) / 1000) * duration;
                var fd = ( acc / sensitivity ) | 0;      // truncate → 0
                if ( fd ) {
                    acc -= fd * sensitivity;
                    show( cur + fd );
                }
             }
             }
        });


             function onMM( e ) { move( e.clientX ); e.preventDefault(); }
        viewer.addEventListener('load', function () {
            function onTM( e ) {
             const animations = viewer.availableAnimations || [];
                 if ( e.touches.length === 1 ) {
 
                     move( e.touches[0].clientX );
            if (animations.length) {
                    e.preventDefault();
                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;
                 }
                 }
            }
            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' );
                viewer.animationName = select.value;
            document.addEventListener( 'mousemove', onMM );
                duration = viewer.duration || 0;
            document.addEventListener( 'mouseup',  stop );
            document.addEventListener( 'touchmove', onTM, { passive: false } );
            document.addEventListener( 'touchend',  stop );
            document.addEventListener( 'touchcancel', stop );
        }


        el.addEventListener( 'mousedown', function ( e ) {
                select.addEventListener('change', function () {
            if ( e.button === 0 ) { startDrag( e.clientX ); e.preventDefault(); }
                    viewer.animationName = select.value;
        });
                    duration = viewer.duration || 0;
        el.addEventListener( 'touchstart', function ( e ) {
                    viewer.currentTime = 0;
            if ( e.touches.length === 1 ) { startDrag( e.touches[0].clientX ); e.preventDefault(); }
                    if (paused) {
        }, { passive: false } );
                        setPlaying(true);
                    }
                });


        /* --- mouse-wheel --- */
                if (paused) {
        el.addEventListener( 'wheel', function ( e ) {
                    setPlaying(false);
            var d = e.deltaY > 0 ? 1 : e.deltaY < 0 ? -1 : 0;
                }
            if ( d ) { nudge( d ); e.preventDefault(); }
        }, { passive: false } );


        /* --- keyboard (element must be focusable) --- */
                startLoop();
        el.setAttribute( 'tabindex', '0' );
                 bar.classList.add('model-viewer-controls--visible');
        el.addEventListener( 'keydown', function ( e ) {
            switch ( e.key ) {
                 case 'ArrowLeft':  nudge( -1 ); e.preventDefault(); break;
                case 'ArrowRight': nudge(  1 ); e.preventDefault(); break;
                case 'Home':      reset();    e.preventDefault(); break;
             }
             }
         });
         });


         /* --- nav buttons (outside .rotatable-model, inside wrapper) --- */
         bar.appendChild(playButton);
         var wrap = el.closest( '.rotatable-model-wrapper' );
         bar.appendChild(select);
         if ( wrap ) {
         bar.appendChild(slider);
            var bL = wrap.querySelector( '.rm-btn-left' ),
        container.appendChild(bar);
                bR = wrap.querySelector( '.rm-btn-right' ),
    }
                bO = wrap.querySelector( '.rm-btn-reset' );
 
 


            if ( bL ) bL.addEventListener( 'click', function () { nudge( -1 ); } );
    function loadModel(preview) {
            if ( bR ) bR.addEventListener( 'click', function () { nudge(  1 ); } );
        if (preview.dataset.loaded) {
             if ( bO ) bO.addEventListener( 'click', reset );
             return;
         }
         }


         /* --- initial frame --- */
         preview.dataset.loaded = '1';
        show( startFrame );
 
        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);
            });
     }
     }


     /* ---- scan & initialise ---- */
     function initPreview(preview) {
    function initAll( root ) {
        if (preview.dataset.initialized) {
         var els = ( root || document ).querySelectorAll(
            return;
                '.rotatable-model:not([data-rm-ready])' );
         }
         for ( var i = 0; i < els.length; i++ ) boot( els[i] );
 
        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);
     }
     }


     if ( document.readyState === 'loading' ) {
     function scan() {
         document.addEventListener( 'DOMContentLoaded', function () { initAll(); } );
         document
    } else {
            .querySelectorAll('.model-placeholder')
        initAll();
            .forEach(initPreview);
     }
     }


     // re-scan when MediaWiki injects content (VE save, live-preview, etc.)
     let scanTimer = null;
     if ( typeof mw !== 'undefined' && mw.hook ) {
 
         mw.hook( 'wikipage.content' ).add( function ( $c ) { initAll( $c[0] ); } );
     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);
}

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