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

No edit summary
No edit summary
 
(255 intermediate revisions by the same user not shown)
Line 1: Line 1:
/**
(function () {
* Custom Item Tooltips — replaces Extension:Popups for .item-link-wrapper links
*/
( function () {
     'use strict';
     'use strict';


     var tooltipCache = {};
     const urlCache = new Map();
    var $tooltip = null;
    var currentTarget = null;
    var showTimer = null;
    var hideTimer = null;


     var SHOW_DELAY = 250;
     function getSize(element) {
    var HIDE_DELAY = 300;
        const match = element.className.match(/model_size_(\d+)/);
     var EDGE_MARGIN = 10; // margin from viewport edges
        return match ? parseInt(match[1], 10) : 500;
     }


    /* ─── Create tooltip DOM element ─── */
     function getFileUrl(fileName) {
     function getTooltip() {
         if (urlCache.has(fileName)) {
         if ( !$tooltip ) {
            return urlCache.get(fileName);
            $tooltip = $( '<div>' )
                .addClass( 'custom-item-tooltip' )
                .hide()
                .appendTo( document.body )
                .on( 'mouseenter', function () {
                    clearTimeout( hideTimer );
                } )
                .on( 'mouseleave', function () {
                    scheduleHide();
                } );
         }
         }
         return $tooltip;
 
        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';


    /* ─── Positioning ─── */
         const playButton = document.createElement('button');
    function positionTooltip( anchor ) {
         playButton.className = 'model-anim-button';
         var tt = getTooltip();
         playButton.type = 'button';
        var rect = anchor.getBoundingClientRect();
         var scrollTop = window.scrollY || document.documentElement.scrollTop;
        var scrollLeft = window.scrollX || document.documentElement.scrollLeft;
         var vpW = window.innerWidth;
        var vpH = window.innerHeight;


         // Render offscreen to measure actual dimensions
         const select = document.createElement('select');
        tt.css( { top: -9999, left: -9999, visibility: 'hidden' } ).show();
         select.className = 'model-anim-select';
         var ttW = tt.outerWidth();
        var ttH = tt.outerHeight();
        tt.css( 'visibility', '' );


         // ─── Vertical positioning ───
         const slider = document.createElement('input');
         var top;
        slider.className = 'model-anim-slider';
         var spaceBelow = vpH - rect.bottom - 8;
        slider.type = 'range';
         var spaceAbove = rect.top - 8;
        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);
        }


         if ( spaceBelow >= ttH + EDGE_MARGIN ) {
         function setPlaying(playing) {
             // Fits below the anchor
             paused = !playing;
            top = rect.bottom + scrollTop + 8;
             playButton.textContent = playing ? '❚❚' : '▶';
        } else if ( spaceAbove >= ttH + EDGE_MARGIN ) {
             if (playing) {
             // Fits above the anchor
                 viewer.play();
            top = rect.top + scrollTop - ttH - 8;
        } else {
            // Doesn't fit above or below — pin to the edge with more space
             if ( spaceBelow >= spaceAbove ) {
                 top = scrollTop + vpH - ttH - EDGE_MARGIN;
             } else {
             } else {
                 top = scrollTop + EDGE_MARGIN;
                 viewer.pause();
             }
             }
         }
         }


         // ─── Horizontal positioning ───
         playButton.addEventListener('click', function () {
         var left = rect.left + scrollLeft;
            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);
                });


        // Overflows right edge
                if (defaultAnimation && animations.indexOf(defaultAnimation) !== -1) {
        if ( left + ttW > scrollLeft + vpW - EDGE_MARGIN ) {
                    select.value = defaultAnimation;
            left = scrollLeft + vpW - ttW - EDGE_MARGIN;
                }
        }
 
                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);
                }


        // Overflows left edge
                startLoop();
        if ( left < scrollLeft + EDGE_MARGIN ) {
                bar.classList.add('model-viewer-controls--visible');
             left = scrollLeft + EDGE_MARGIN;
             }
         }
         });


         tt.css( { top: top, left: left } );
         bar.appendChild(playButton);
        bar.appendChild(select);
        bar.appendChild(slider);
        container.appendChild(bar);
     }
     }


    /* ─── Show tooltip ─── */
    function showTooltip( anchor, itemName ) {
        clearTimeout( hideTimer );
        clearTimeout( showTimer );


        showTimer = setTimeout( function () {
            var tt = getTooltip();
            currentTarget = anchor;


            // Already cached — show immediately
    function loadModel(preview) {
            if ( tooltipCache[ itemName ] ) {
        if (preview.dataset.loaded) {
                tt.html( tooltipCache[ itemName ] ).show();
            return;
                positionTooltip( anchor );
        }
                return;
            }


            // Loading indicator
        preview.dataset.loaded = '1';
            tt.html( '<div class="custom-item-tooltip__loading">Loading…</div>' ).show();
            positionTooltip( anchor );


            // Fetch rendered template
        const fileName = preview.dataset.model;
            new mw.Api().post( {
        const displayName = preview.dataset.name || fileName;
                action: 'parse',
        const defaultAnimation = preview.dataset.animation || '';
                text: '{{Infobox item/auto|' + itemName + '}}',
        const autoplay = preview.dataset.autoplay === 'true';
                title: mw.config.get( 'wgPageName' ),
        const size = getSize(preview);
                prop: 'text',
                disablelimitreport: true,
                disableeditsection: true,
                wrapoutputclass: '',
                format: 'json'
            } ).then( function ( data ) {
                var html = data.parse.text[ '*' ];
                tooltipCache[ itemName ] = html;


                // Only show if the mouse is still on this element
        getFileUrl(fileName + '.glb')
                if ( currentTarget === anchor ) {
            .then(function (url) {
                    tt.html( html ).show();
                if (!url) {
                     positionTooltip( anchor );
                     return;
                 }
                 }
            } ).catch( function () {
 
                 if ( currentTarget === anchor ) {
                const wrap = document.createElement('div');
                     tt.hide();
                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', '');
                 }
                 }
            } );


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


    /* ─── Hide tooltip ─── */
     function scan() {
     function scheduleHide() {
         document
         clearTimeout( showTimer );
            .querySelectorAll('.model-placeholder')
        hideTimer = setTimeout( function () {
             .forEach(initPreview);
             if ( $tooltip ) {
    }
                $tooltip.hide();
 
            }
    let scanTimer = null;
            currentTarget = null;
 
         }, HIDE_DELAY );
    function debouncedScan() {
        clearTimeout(scanTimer);
         scanTimer = setTimeout(scan, 100);
     }
     }


     /* ─── Initialization ─── */
     scan();
     mw.hook( 'wikipage.content' ).add( function ( $content ) {
 
         $content.find( '.item-link-wrapper' ).each( function () {
     const observer = new MutationObserver(debouncedScan);
            var $wrapper = $( this );
    observer.observe(document.body, {
            var itemName = $wrapper.attr( 'data-item-name' );
         childList: true,
            if ( !itemName ) return;
        subtree: true
    });
 
})();


            // All links inside the wrapper, not just the first one
            var $links = $wrapper.find( 'a[href]' );
            if ( !$links.length ) return;


            $links.each( function () {
                var $link = $( this );


                // Remove native title from each link
                $link.removeAttr( 'title' );


                $link.on( 'mouseenter.itemTooltip', function () {
                    showTooltip( this, itemName );
                } ).on( 'mouseleave.itemTooltip', function () {
                    scheduleHide();
                } );
            } );
        } );
    } );


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