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

No edit summary
Tags: Manual revert Mobile edit Mobile web edit
Replaced content with " 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(te..."
Tag: Replaced
Line 27: Line 27:
personal.prepend(test2, test3, test4);
personal.prepend(test2, test3, test4);
}
}
/**
* Rotatable Model Viewer — with 2D / 3D toggle
* All <img> elements created in JS to bypass MediaWiki sanitizer.
*/
(function () {
    'use strict';
    function makeImg(src, alt, className) {
        var i = new Image();
        i.src = src;
        i.alt = alt || '';
        i.draggable = false;
        if (className) i.className = className;
        return i;
    }
    function boot(el) {
        if (el.dataset.rmReady) return;
        el.dataset.rmReady = '1';
        /* ---- config ---- */
        var imageUrl    = el.dataset.image        || '',
            image2dUrl  = el.dataset.imageFlat    || '',
            icon2dUrl  = el.dataset.iconFlat    || '',
            icon3dUrl  = el.dataset.iconStereo  || '',
            iconRotUrl  = el.dataset.iconRotate  || '',
            fw          = +el.dataset.frameWidth  || 300,
            fh          = +el.dataset.frameHeight || 400,
            count      = +el.dataset.frameCount  || 24,
            startFrame  = +el.dataset.startFrame  || 0,
            sensitivity = +el.dataset.sensitivity || 5;
        /* ---- 1:1 square for 3D strip ---- */
        var sq = Math.min(fw, fh);
        var hint = el.querySelector('.rotatable-model-hint'),
            load = el.querySelector('.rotatable-model-loading'),
            wrap = el.closest('.rotatable-model-wrapper');
        if (!imageUrl) {
            if (load) load.textContent = 'Error: no image URL';
            return;
        }
        /* ---- state ---- */
        var cur    = startFrame,
            is2D  = false,
            dragOK = true,
            ready  = false;
        /* ============================================================
          SQUARE VIEWPORT
          ============================================================ */
        var viewport = document.createElement('div');
        viewport.className = 'rm-square-viewport';
        viewport.style.position = 'absolute';
        viewport.style.width    = sq + 'px';
        viewport.style.height  = sq + 'px';
        viewport.style.left    = ((fw - sq) / 2) + 'px';
        viewport.style.top      = ((fh - sq) / 2) + 'px';
        viewport.style.overflow = 'hidden';
        el.insertBefore(viewport, el.firstChild);
        /* ============================================================
          3D SPRITE STRIP — each frame is sq × sq
          ============================================================ */
        var img = makeImg(imageUrl, '', 'rm-strip');
        img.style.position = 'absolute';
        img.style.height  = sq + 'px';
        img.style.width    = (sq * count) + 'px';
        img.style.top      = '0';
        img.style.left    = '0';
        img.addEventListener('load', function () {
            ready = true;
            if (load) load.style.display = 'none';
            show(startFrame);
        });
        img.addEventListener('error', function () {
            if (load) { load.textContent = 'Failed to load image'; load.style.color = '#d33'; }
        });
        viewport.appendChild(img);
        if (img.complete && img.naturalWidth > 0) {
            ready = true;
            if (load) load.style.display = 'none';
            show(startFrame);
        }
        /* ============================================================
          2D STATIC IMAGE — renders at full fw × fh
          ============================================================ */
        var staticImg = null;
        if (image2dUrl) {
            staticImg = makeImg(image2dUrl, '', 'rm-static');
            el.insertBefore(staticImg, el.firstChild);
        }
        /* ============================================================
          MODE TOGGLE — single button, swaps icon on click
          ============================================================ */
        var toggleBtn = null,
            iconImg2d = null,
            iconImg3d = null;
        if (image2dUrl) {
            toggleBtn = document.createElement('span');
            toggleBtn.className = 'rm-mode-toggle';
            toggleBtn.setAttribute('role', 'button');
            toggleBtn.setAttribute('tabindex', '0');
            toggleBtn.title = 'Switch to 2D';
            if (icon2dUrl) {
                iconImg2d = makeImg(icon2dUrl, '2D', 'rm-mode-icon rm-icon-2d');
            }
            if (icon3dUrl) {
                iconImg3d = makeImg(icon3dUrl, '3D', 'rm-mode-icon rm-icon-3d');
                iconImg3d.style.display = 'none';
            }
            if (iconImg2d) toggleBtn.appendChild(iconImg2d);
            if (iconImg3d) toggleBtn.appendChild(iconImg3d);
            if (!icon2dUrl && !icon3dUrl) {
                toggleBtn.textContent = '2D';
            }
            el.appendChild(toggleBtn);
        }
        /* ============================================================
          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;
            img.style.left = -(cur * sq) + 'px';
        }
        function nudge(d) {
            if (!is2D && ready) {
                show(cur + d);
                hideHint();
            }
        }
        function reset() { show(startFrame); }
        function hideHint() {
            if (hint) hint.classList.add('rm-hidden');
        }
        /* ============================================================
          2D ↔ 3D SWITCHING
          ============================================================ */
        function setMode(mode) {
            is2D = (mode === '2d');
            if (is2D) {
                el.classList.add('rm-is-2d');
                if (wrap) wrap.classList.add('rm-is-2d');
                dragOK = false;
                viewport.style.display = 'none';
            } else {
                el.classList.remove('rm-is-2d');
                if (wrap) wrap.classList.remove('rm-is-2d');
                dragOK = true;
                viewport.style.display = '';
            }
            if (iconImg2d && iconImg3d) {
                iconImg2d.style.display = is2D ? 'none' : '';
                iconImg3d.style.display = is2D ? '' : 'none';
            }
            if (toggleBtn) {
                toggleBtn.title = is2D ? 'Switch to 3D' : 'Switch to 2D';
                if (!icon2dUrl && !icon3dUrl) {
                    toggleBtn.textContent = is2D ? '3D' : '2D';
                }
            }
        }
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function () {
                setMode(is2D ? '3d' : '2d');
            });
        }
        /* ============================================================
          DRAG  (mouse + touch)
          ============================================================ */
        function startDrag(x0) {
            if (!dragOK || !ready) return;
            var acc = 0;
            hideHint();
            function move(cx) {
                var dx = cx - x0;
                x0 = cx;
                acc += dx;
                while (acc >= sensitivity) {
                    acc -= sensitivity;
                    show(cur + 1);
                }
                while (acc <= -sensitivity) {
                    acc += sensitivity;
                    show(cur - 1);
                }
            }
            function onMM(e) { move(e.clientX); e.preventDefault(); }
            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');
            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) {
            if (e.target.closest('.rm-mode-toggle')) return;
            if (e.button === 0 && dragOK) { startDrag(e.clientX); e.preventDefault(); }
        });
        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 ---- */
        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 ---- */
        el.setAttribute('tabindex', '0');
        el.addEventListener('keydown', function (e) {
            if (is2D || !ready) 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 ---- */
        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 ---- */
        show(startFrame);
    }
    /* ---- scan & init ---- */
    function initAll(root) {
        var els = (root || document).querySelectorAll('.rotatable-model');
        for (var i = 0; i < els.length; i++) boot(els[i]);
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { initAll(); });
    } else {
        initAll();
    }
    if (typeof mw !== 'undefined' && mw.hook) {
        mw.hook('wikipage.content').add(function ($c) { initAll($c[0]); });
    }
}());
/**
* Custom Tooltips — replaces Extension:Popups for .item-link-wrapper and .ability-link-wrapper links
*/
( function () {
    'use strict';
    var tooltipCache = {};
    var $tooltip = null;
    var currentTarget = null;
    var showTimer = null;
    var hideTimer = null;
    var SHOW_DELAY = 250;
    var HIDE_DELAY = 300;
    var EDGE_MARGIN = 10; // margin from viewport edges
    /* ─── Create tooltip DOM element ─── */
    function getTooltip() {
        if ( !$tooltip ) {
            $tooltip = $( '<div>' )
                .addClass( 'custom-item-tooltip' )
                .hide()
                .appendTo( document.body )
                .on( 'mouseenter', function () {
                    clearTimeout( hideTimer );
                } )
                .on( 'mouseleave', function () {
                    scheduleHide();
                } );
        }
        return $tooltip;
    }
    /* ─── Positioning ─── */
    function positionTooltip( anchor ) {
        var tt = getTooltip();
        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
        tt.css( { top: -9999, left: -9999, visibility: 'hidden' } ).show();
        var ttW = tt.outerWidth();
        var ttH = tt.outerHeight();
        tt.css( 'visibility', '' );
        // ─── Vertical positioning ───
        var top;
        var spaceBelow = vpH - rect.bottom - 8;
        var spaceAbove = rect.top - 8;
        if ( spaceBelow >= ttH + EDGE_MARGIN ) {
            // Fits below the anchor
            top = rect.bottom + scrollTop + 8;
        } else if ( spaceAbove >= ttH + EDGE_MARGIN ) {
            // Fits above the anchor
            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 {
                top = scrollTop + EDGE_MARGIN;
            }
        }
        // ─── Horizontal positioning ───
        var left = rect.left + scrollLeft;
        // Overflows right edge
        if ( left + ttW > scrollLeft + vpW - EDGE_MARGIN ) {
            left = scrollLeft + vpW - ttW - EDGE_MARGIN;
        }
        // Overflows left edge
        if ( left < scrollLeft + EDGE_MARGIN ) {
            left = scrollLeft + EDGE_MARGIN;
        }
        tt.css( { top: top, left: left } );
    }
/* ability upgrade gadget CURRENTLY DOESN'T WORK WITH TOOLTIP*/
    /* ─── Initialize ability upgrade gadget for tooltip content ─── */
    function initAbilityUpgrades( $container ) {
        // Check if the gadget exists
        if ( !window.abilityUpgradeGadget ) {
            return;
        }
        var abilityCards = $container.find( '.ability-card' );
        if ( !abilityCards.length ) {
            return;
        }
        // Re-run the gadget's initialization for ability cards
        abilityCards.each( function () {
            var container = this;
           
            // Add hover listeners
            $( container ).find( '.ability-upgrade' ).each( function () {
                var el = this;
                $( el ).off( 'mouseenter.abilityUpgrade mouseleave.abilityUpgrade' );
                $( el ).on( 'mouseenter.abilityUpgrade', function () {
                    window.abilityUpgradeGadget.onHover( container, el );
                } );
                $( el ).on( 'mouseleave.abilityUpgrade', function () {
                    window.abilityUpgradeGadget.onUnhover( container );
                } );
            } );
        } );
    }
    /* ─── Make ability name clickable ─── */
    function makeAbilityNameClickable( $container, abilityName ) {
        // Find the ability name text within the ability card
        $container.find( '.ability-card' ).each( function () {
            var $card = $( this );
           
            // Target the ability name span (based on your HTML structure)
            var $nameSpan = $card.find( 'span[style*="font-family"][style*="Valve Occult"]' );
           
            if ( $nameSpan.length ) {
                var nameText = $nameSpan.text().trim();
               
                // Create a link wrapping the ability name
                var $link = $( '<a>' )
                    .attr( 'href', mw.util.getUrl( abilityName ) )
                    .attr( 'title', 'Go to ' + abilityName + ' page' )
                    .css( {
                        'color': 'inherit',
                        'text-decoration': 'none'
                    } )
                    .on( 'mouseenter', function () {
                        $( this ).css( 'text-decoration', 'underline' );
                    } )
                    .on( 'mouseleave', function () {
                        $( this ).css( 'text-decoration', 'none' );
                    } )
                    .text( nameText );
               
                // Replace the text with the link
                $nameSpan.empty().append( $link );
            }
        } );
    }
/* ─── Show tooltip ─── */
function showTooltip( anchor, name, type ) {
    clearTimeout( hideTimer );
    clearTimeout( showTimer );
    showTimer = setTimeout( function () {
        var tt = getTooltip();
        currentTarget = anchor;
        var normalizedName = type === 'ability' ? toTitleCase( name ) : name;
        var cacheKey = type + ':' + normalizedName;
        tt.removeClass( 'ability-tooltip item-tooltip' );
        if ( type === 'ability' ) {
            tt.addClass( 'ability-tooltip' );
        } else if ( type === 'item' ) {
            tt.addClass( 'item-tooltip' );
        }
        if ( tooltipCache[ cacheKey ] ) {
            tt.html( tooltipCache[ cacheKey ] ).show();
            positionTooltip( anchor );
           
            if ( type === 'ability' ) {
                initAbilityUpgrades( tt );
            }
            return;
        }
        tt.html( '<div class="custom-item-tooltip__loading">Loading…</div>' ).css( { top: -9999, left: -9999 } ).show();
        positionTooltip( anchor );
        var templateText;
        if ( type === 'item' ) {
            templateText = '{{Infobox item/auto|default=true|' + normalizedName + '}}';
        } else if ( type === 'ability' ) {
            templateText = '{{Ability card v2' +
                '|hero_name={{#invoke:Abilities/utils|find_hero_by_ability|' + normalizedName + '}}' +
                '|ability_num={{#invoke:Abilities|get_ability_number|{{#invoke:Abilities/utils|find_hero_by_ability|' + normalizedName + '}}|' + normalizedName + '}}' +
                '}}';
        }
        // Fetch rendered template WITH styles
        new mw.Api().post( {
            action: 'parse',
            text: templateText,
            title: mw.config.get( 'wgPageName' ),
            prop: 'text|modules|modulestyles',  // Add modules and modulestyles
            disablelimitreport: true,
            disableeditsection: true,
            wrapoutputclass: '',
            format: 'json'
        } ).then( function ( data ) {
            var html = data.parse.text[ '*' ];
           
            // Load any required style modules
            if ( data.parse.modulestyles ) {
                mw.loader.load( data.parse.modulestyles );
            }
           
            tooltipCache[ cacheKey ] = html;
            if ( currentTarget === anchor ) {
                tt.html( html ).show();
                positionTooltip( anchor );
               
                if ( type === 'ability' ) {
                    mw.hook( 'wikipage.content' ).fire( tt );
                    initAbilityUpgrades( tt );
                }
            }
        } ).catch( function () {
            if ( currentTarget === anchor ) {
                tt.hide();
            }
        } );
    }, SHOW_DELAY );
}
    /* ─── Hide tooltip ─── */
    function scheduleHide() {
        clearTimeout( showTimer );
        hideTimer = setTimeout( function () {
            if ( $tooltip ) {
                $tooltip.hide();
            }
            currentTarget = null;
        }, HIDE_DELAY );
    }
    /* ─── Attach handlers to wrapper ─── */
    function attachTooltipHandlers( $wrapper, name, type ) {
        // All links inside the wrapper, not just the first one
        var $links = $wrapper.find( 'a[href]' );
       
        // If no links found, attach to the wrapper itself (for icon-only mode)
        if ( !$links.length ) {
            $links = $wrapper;
        }
        $links.each( function () {
            var $link = $( this );
            // Remove native title from each link
            $link.removeAttr( 'title' );
            $link.on( 'mouseenter.customTooltip', function () {
                showTooltip( this, name, type );
            } ).on( 'mouseleave.customTooltip', function () {
                scheduleHide();
            } );
        } );
    }
    /* ─── Initialization ─── */
    mw.hook( 'wikipage.content' ).add( function ( $content ) {
        // Item tooltips
        $content.find( '.item-link-wrapper' ).each( function () {
            var $wrapper = $( this );
            var itemName = $wrapper.attr( 'data-item-name' );
            if ( !itemName ) return;
            attachTooltipHandlers( $wrapper, itemName, 'item' );
        } );
        // Ability tooltips
        $content.find( '.ability-link-wrapper' ).each( function () {
            var $wrapper = $( this );
            var abilityName = $wrapper.attr( 'data-ability-name' );
            if ( !abilityName ) return;
            attachTooltipHandlers( $wrapper, abilityName, 'ability' );
        } );
    } );
} )();