MediaWiki:Gadget-AbsyFancyBoxy.js

Материал из Тестовая Абсурдопедии
Перейти к навигации Перейти к поиску

Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
/**
 * Гаджет: AbsyFancyBoxy для Absurdopedia.wiki
 * Локальный лайтбокс с листанием галереи и подписями.
 * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
 */
( function () {
    'use strict';

    // ---------- Константы ----------
    var MEDIA_EXT = /\.(webm|ogv|ogg|oga|mp4|mp3|flac|opus|wav)$/i;
    var SAFE_URL = /^(https?:)?\/\//i;
    var CAN_HOVER = window.matchMedia && window.matchMedia( '(hover: hover)' ).matches;

    // ---------- Утилиты ----------
    function isSafeUrl( url ) {
        return url && ( SAFE_URL.test( url ) || url.charAt( 0 ) === '/' );
    }

    function getFullImageUrl( thumbSrc ) {
        if ( !thumbSrc || thumbSrc.indexOf( '/thumb/' ) === -1 ) {
            return thumbSrc;
        }
        var parts = thumbSrc.split( '/thumb/' );
        if ( parts.length !== 2 ) return thumbSrc;
        var pathSegments = parts[ 1 ].split( '/' );
        pathSegments.pop();
        return parts[ 0 ] + '/' + pathSegments.join( '/' );
    }

    function getCaption( link, img ) {
        var galleryItem = link.closest( '.gallerybox, li.gallerybox' );
        if ( galleryItem ) {
            var galleryText = galleryItem.querySelector( '.gallerytext' );
            if ( galleryText && galleryText.textContent.trim() ) {
                return galleryText.textContent.trim();
            }
        }
        var container = link.closest( 'figure, .thumb' );
        if ( container ) {
            var thumbCaption = container.querySelector( '.thumbcaption, figcaption' );
            if ( thumbCaption && thumbCaption.textContent.trim() ) {
                return thumbCaption.textContent.trim();
            }
        }
        return img.getAttribute( 'alt' ) || img.getAttribute( 'title' ) || '';
    }

    function isMediaLink( link ) {
        var href = link.getAttribute( 'href' ) || '';
        if ( MEDIA_EXT.test( href ) ) return true;
        if ( link.querySelector( 'video, audio, .mw-tmh-player, .oo-ui-widget' ) ) return true;
        if ( link.closest( '.mw-tmh-player' ) ) return true;
        var container = link.closest( 'figure, .thumb, .mw-halign-left, .mw-halign-right, .mw-halign-center, .mw-halign-none' );
        if ( container && container.querySelector( '.mw-tmh-player, video, audio' ) ) return true;
        return false;
    }

    // ---------- Сбор галереи ----------
    function collectGallery( clickedLink ) {
        var items = [];
        var gallery = clickedLink.closest( '.gallery, ul.gallery' );
        var root = gallery || clickedLink.closest( '.mw-parser-output' );
        if ( !root ) return items;

        var links = root.querySelectorAll( 'a.image, a.mw-file-description' );
        links.forEach( function ( link ) {
            if ( isMediaLink( link ) ) return;

            var img = link.querySelector( 'img' );
            if ( !img ) return;

            var thumbSrc = img.getAttribute( 'src' );
            if ( !isSafeUrl( thumbSrc ) ) return;

            var fullSrc = getFullImageUrl( thumbSrc );
            if ( !isSafeUrl( fullSrc ) ) return;

            items.push( {
                link: link,
                src: fullSrc,
                caption: getCaption( link, img )
            } );
        } );
        return items;
    }

    // ---------- Ленивое создание оверлея ----------
    var overlay = null;
    var imgElement = null;
    var captionElement = null;
    var counterElement = null;
    var prevBtn = null;
    var nextBtn = null;
    var closeBtn = null;

    var gallery = [];
    var currentIndex = 0;

    function buildOverlay() {
        overlay = document.createElement( 'div' );
        overlay.id = 'absyfancyboxy-overlay';
        overlay.setAttribute( 'role', 'dialog' );
        overlay.setAttribute( 'aria-modal', 'true' );
        overlay.setAttribute( 'aria-label', 'Просмотр изображения' );

        var backdrop = document.createElement( 'div' );
        backdrop.className = 'absyfancyboxy-backdrop';
        backdrop.addEventListener( 'click', closeLightbox );
        overlay.appendChild( backdrop );

        var stage = document.createElement( 'div' );
        stage.className = 'absyfancyboxy-stage';
        overlay.appendChild( stage );

        imgElement = document.createElement( 'img' );
        imgElement.id = 'absyfancyboxy-image';
        imgElement.alt = '';
        imgElement.addEventListener( 'error', function () {
            captionElement.textContent = 'Не удалось загрузить изображение';
        } );
        stage.appendChild( imgElement );

        captionElement = document.createElement( 'div' );
        captionElement.id = 'absyfancyboxy-caption';
        stage.appendChild( captionElement );

        counterElement = document.createElement( 'div' );
        counterElement.id = 'absyfancyboxy-counter';
        stage.appendChild( counterElement );

        closeBtn = document.createElement( 'div' );
        closeBtn.id = 'absyfancyboxy-close';
        closeBtn.textContent = '×';
        closeBtn.setAttribute( 'role', 'button' );
        closeBtn.setAttribute( 'tabindex', '0' );
        closeBtn.setAttribute( 'aria-label', 'Закрыть' );
        closeBtn.addEventListener( 'click', function ( e ) {
            e.stopPropagation();
            closeLightbox();
        } );
        closeBtn.addEventListener( 'keydown', function ( e ) {
            if ( e.key === 'Enter' || e.key === ' ' ) {
                e.preventDefault();
                closeLightbox();
            }
        } );
        overlay.appendChild( closeBtn );

        prevBtn = makeArrow( 'prev', '‹', 'left' );
        nextBtn = makeArrow( 'next', '›', 'right' );
        stage.appendChild( prevBtn );
        stage.appendChild( nextBtn );

        if ( CAN_HOVER ) {
            setArrowsVisible( false );
            overlay.addEventListener( 'mouseenter', function () { setArrowsVisible( true ); } );
            overlay.addEventListener( 'mouseleave', function () { setArrowsVisible( false ); } );
        }

        stage.addEventListener( 'click', function ( e ) {
            if ( e.target === stage ) closeLightbox();
        } );

        var touchStartX = null;
        overlay.addEventListener( 'touchstart', function ( e ) {
            if ( e.touches.length === 1 ) touchStartX = e.touches[ 0 ].clientX;
        }, { passive: true } );
        overlay.addEventListener( 'touchend', function ( e ) {
            if ( touchStartX === null || !e.changedTouches.length ) return;
            var dx = e.changedTouches[ 0 ].clientX - touchStartX;
            if ( Math.abs( dx ) > 50 ) {
                if ( dx < 0 ) next(); else prev();
            }
            touchStartX = null;
        } );

        document.body.appendChild( overlay );
    }

    function makeArrow( dir, symbol ) {
        var btn = document.createElement( 'div' );
        btn.className = 'absyfancyboxy-arrow';
        btn.dataset.dir = dir;
        btn.textContent = symbol;
        btn.setAttribute( 'role', 'button' );
        btn.setAttribute( 'tabindex', '0' );
        btn.setAttribute( 'aria-label', dir === 'prev' ? 'Предыдущее' : 'Следующее' );
        btn.addEventListener( 'click', function ( e ) {
            e.stopPropagation();
            if ( dir === 'prev' ) prev(); else next();
        } );
        btn.addEventListener( 'keydown', function ( e ) {
            if ( e.key === 'Enter' || e.key === ' ' ) {
                e.preventDefault();
                if ( dir === 'prev' ) prev(); else next();
            }
        } );
        return btn;
    }

    function setArrowsVisible( visible ) {
        if ( !prevBtn || !nextBtn ) return;
        [ prevBtn, nextBtn ].forEach( function ( btn ) {
            btn.style.opacity = visible ? '0.85' : '0';
            btn.style.pointerEvents = visible ? 'auto' : 'none';
        } );
    }

    // ---------- Рендер и управление ----------
    function render() {
        if ( !gallery.length ) return;
        var item = gallery[ currentIndex ];
        imgElement.src = item.src;
        imgElement.alt = item.caption || '';
        captionElement.textContent = item.caption || '';
        counterElement.textContent = ( currentIndex + 1 ) + ' / ' + gallery.length;

        var multiple = gallery.length > 1;
        prevBtn.style.display = multiple ? 'block' : 'none';
        nextBtn.style.display = multiple ? 'block' : 'none';
        counterElement.style.display = multiple ? 'block' : 'none';

        if ( CAN_HOVER && multiple ) setArrowsVisible( false );
    }

    function openLightbox( items, index ) {
        if ( !overlay ) buildOverlay();
        gallery = items;
        currentIndex = index || 0;
        overlay.classList.add( 'is-open' );
        document.body.style.overflow = 'hidden';
        render();
        if ( closeBtn ) closeBtn.focus();
    }

    function closeLightbox() {
        if ( !overlay ) return;
        overlay.classList.remove( 'is-open' );
        imgElement.src = '';
        imgElement.alt = '';
        captionElement.textContent = '';
        counterElement.textContent = '';
        gallery = [];
        currentIndex = 0;
        document.body.style.overflow = '';
    }

    function next() {
        if ( gallery.length < 2 ) return;
        currentIndex = ( currentIndex + 1 ) % gallery.length;
        render();
    }

    function prev() {
        if ( gallery.length < 2 ) return;
        currentIndex = ( currentIndex - 1 + gallery.length ) % gallery.length;
        render();
    }

    // ---------- Клавиатура ----------
    document.addEventListener( 'keydown', function ( e ) {
        if ( !overlay || !overlay.classList.contains( 'is-open' ) ) return;
        if ( e.key === 'Escape' ) closeLightbox();
        else if ( e.key === 'ArrowRight' ) next();
        else if ( e.key === 'ArrowLeft' ) prev();
    } );

    // ---------- Перехват клика ----------
    document.addEventListener( 'click', function ( e ) {
        var link = e.target.closest( 'a.image, a.mw-file-description' );
        if ( !link ) return;
        if ( !link.closest( '.mw-parser-output' ) ) return;
        if ( isMediaLink( link ) ) return;

        var items = collectGallery( link );
        if ( !items.length ) return;

        var idx = 0;
        for ( var i = 0; i < items.length; i++ ) {
            if ( items[ i ].link === link ) { idx = i; break; }
        }

        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        openLightbox( items, idx );
    }, true );

    // ---------- Сброс при AJAX-навигации ----------
    if ( window.mw && mw.hook ) {
        mw.hook( 'wikipage.content' ).add( function () {
            if ( overlay && overlay.classList.contains( 'is-open' ) ) closeLightbox();
        } );
    }

} )();