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

From The Deadlock Wiki
Jump to navigation Jump to search
Hydrate .model-fallback into the interactive model viewer (via update-page on Domosed MCP)
No edit summary
 
(7 intermediate revisions by the same user not shown)
Line 5: Line 5:


     function getSize(element) {
     function getSize(element) {
         const className = typeof element.className === 'string'
         const match = element.className.match(/model_size_(\d+)/);
            ? element.className
            : '';
 
        const match = className.match(/model_size_(\d+)/);
 
         return match ? parseInt(match[1], 10) : 500;
         return match ? parseInt(match[1], 10) : 500;
     }
     }
Line 32: Line 27:
                     throw new Error('API request failed');
                     throw new Error('API request failed');
                 }
                 }
                 return response.json();
                 return response.json();
             })
             })
             .then(function (data) {
             .then(function (data) {
                 const pages = data.query && data.query.pages;
                 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 (!pages) {
                 if (defaultAnimation && animations.indexOf(defaultAnimation) !== -1) {
                     return null;
                     select.value = defaultAnimation;
                 }
                 }


                 const page = Object.values(pages)[0];
                 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 (!page || !page.imageinfo || !page.imageinfo[0]) {
                 if (paused) {
                     return null;
                     setPlaying(false);
                 }
                 }


                 return page.imageinfo[0].url;
                 startLoop();
             })
                bar.classList.add('model-viewer-controls--visible');
            .catch(function () {
             }
                return null;
        });
            });
 
        bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
    }


        urlCache.set(fileName, promise);


        return promise;
    }


     function loadModel(preview) {
     function loadModel(preview) {
Line 67: Line 147:


         const fileName = preview.dataset.model;
         const fileName = preview.dataset.model;
        if (!fileName) {
            return;
        }
         const displayName = preview.dataset.name || fileName;
         const displayName = preview.dataset.name || fileName;
        const defaultAnimation = preview.dataset.animation || '';
        const autoplay = preview.dataset.autoplay === 'true';
         const size = getSize(preview);
         const size = getSize(preview);


         getFileUrl(fileName + '.glb')
         getFileUrl(fileName + '.glb')
             .then(function (url) {
             .then(function (url) {
                 if (!url || !preview.isConnected) {
                 if (!url) {
                     return;
                     return;
                 }
                 }
Line 90: Line 167:


                 const viewer = document.createElement('model-viewer');
                 const viewer = document.createElement('model-viewer');
                 viewer.src = url;
                 viewer.src = url;
                 viewer.setAttribute('camera-controls', '');
                 viewer.setAttribute('camera-controls', '');
                 viewer.setAttribute('touch-action', 'pan-y');
                 viewer.setAttribute('touch-action', 'pan-y');
                if (preview.dataset.autoplay === 'true') {
                    viewer.setAttribute('autoplay', '');
                }


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


                 const name = document.createElement('div');
                 const name = document.createElement('div');
Line 109: Line 190:


     function initPreview(preview) {
     function initPreview(preview) {
         if (
         if (preview.dataset.initialized) {
            !preview ||
            preview.dataset.initialized
        ) {
             return;
             return;
         }
         }
Line 119: Line 197:


         const button = document.createElement('button');
         const button = document.createElement('button');
         button.className = 'model-load-button';
         button.className = 'model-load-button';
         button.type = 'button';
         button.type = 'button';
         button.addEventListener('click', function () {
         button.addEventListener('click', function () {
             loadModel(preview);
             loadModel(preview);
Line 130: Line 206:
     }
     }


    /**
     function scan() {
    * Builds the interactive .model-placeholder markup (preview <img>, hint,
         document
    * name) from the data attributes carried by a no-JS .model-fallback block.
             .querySelectorAll('.model-placeholder')
    * The preview image URL is fetched from the wiki API asynchronously.
             .forEach(initPreview);
    */
     function buildPlaceholder(data) {
         const model = data.model;
        const name = data.name || model;
        const altImage = data.altImage || model;
 
        const sizeMatch = String(data.modelsize || '').match(/(\d+)/);
        const size = sizeMatch ? parseInt(sizeMatch[1], 10) : 300;
 
        const el = document.createElement('div');
        el.className = 'model-placeholder model_size_' + size + 'px';
        el.dataset.model = model;
        el.dataset.name = name;
 
        const preview = document.createElement('div');
        preview.className = 'model-preview';
 
        const img = document.createElement('img');
        img.className = 'model-preview-img';
        img.alt = name;
 
        preview.appendChild(img);
        el.appendChild(preview);
 
        const hint = document.createElement('div');
        hint.className = 'model-hint';
        hint.textContent = 'Click to view';
        preview.appendChild(hint);
 
        const nameEl = document.createElement('div');
        nameEl.className = 'model-name';
        nameEl.textContent = name;
        el.appendChild(nameEl);
 
        if (altImage) {
             getFileUrl(altImage + '.png').then(function (url) {
                if (url && img.isConnected) {
                    img.src = url;
                }
            });
        }
 
        return el;
    }
 
    /**
    * Upgrades a no-JS .model-fallback block into the interactive placeholder,
    * preserving every data attribute the template supplied.
    */
    function hydrateFallback(fallback) {
        if (
            !fallback ||
            fallback.dataset.hydrated ||
            fallback.dataset.model === undefined
        ) {
            return;
        }
 
        fallback.dataset.hydrated = '1';
 
        const placeholder = buildPlaceholder({
            model: fallback.dataset.model,
            name: fallback.dataset.name,
            altImage: fallback.dataset.altImage,
            modelsize: fallback.dataset.modelsize
        });
 
        initPreview(placeholder);
 
        fallback.replaceWith(placeholder);
    }
 
    function scan(root) {
        if (!root) {
            return;
        }
 
        if (
            root.nodeType === Node.ELEMENT_NODE &&
            root.matches('.model-placeholder')
        ) {
            initPreview(root);
        }
 
        if (
            root.nodeType === Node.ELEMENT_NODE &&
            root.matches('.model-fallback')
        ) {
             hydrateFallback(root);
        }
 
        if (root.querySelectorAll) {
            root
                .querySelectorAll('.model-placeholder')
                .forEach(initPreview);
            root
                .querySelectorAll('.model-fallback')
                .forEach(hydrateFallback);
        }
     }
     }


     function startObserver() {
     let scanTimer = null;
        if (!document.body) {
            return;
        }
 
        const observer = new MutationObserver(function (mutations) {
            for (const mutation of mutations) {
                for (const node of mutation.addedNodes) {
                    if (node.nodeType === Node.ELEMENT_NODE) {
                        scan(node);
                    }
                }
            }
        });


        observer.observe(document.body, {
    function debouncedScan() {
            childList: true,
        clearTimeout(scanTimer);
            subtree: true
         scanTimer = setTimeout(scan, 100);
         });
     }
     }


     function init() {
     scan();
        scan(document);
        startObserver();
    }


     mw.hook('wikipage.content').add(function ($content) {
     const observer = new MutationObserver(debouncedScan);
         scan($content[0]);
    observer.observe(document.body, {
         childList: true,
        subtree: true
     });
     });


    if (document.readyState === 'loading') {
})();
        document.addEventListener('DOMContentLoaded', init, {
            once: true
        });
    } else {
        init();
    }


})();





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