MediaWiki:Gadget-AbsyFancyBoxy.js: различия между версиями

Материал из Тестовая Абсурдопедии
Перейти к навигации Перейти к поиску
Нет описания правки
Нет описания правки
Строка 5: Строка 5:
  * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
  * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
  * Идёт в связке с [[MediaWiki:Gadget-AbsyFancyBoxy.css]]
  * Идёт в связке с [[MediaWiki:Gadget-AbsyFancyBoxy.css]]
  * Лицензия: CC BY-SA 4.0 (источник: absurdopedia.wiki)
  * Лицензия: MIT (opensource.org/license/mit); источник: absurdopedia.wiki
  */
  */



Версия от 19:54, 15 ноября 2026

/**
 * Гаджет: AbsyFancyBoxy
 * Версия 1.0
 * Локальный лайтбокс с листанием галереи и подписями.
 * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
 * Идёт в связке с [[MediaWiki:Gadget-AbsyFancyBoxy.css]]
 * Лицензия: MIT (opensource.org/license/mit); источник: absurdopedia.wiki
 */

( function () {
    'use strict';

    // ---------- Константы ----------
    var MEDIA_EXT = /\.(webm|ogv|ogg|oga|mp4|mp3|flac|opus|wav)$/i;
    var SAFE_URL = /^(https?:)?\/\//i;
    var ARROW_HIDE_DELAY = 2500; // мс бездействия до скрытия стрелок
    var MIN_IMAGE_SIZE = 100;    // px — минимальный размер картинки для лайтбокса
    var FOCUSABLE_SELECTOR = 'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])';

    var galleryCache = new WeakMap();

    // ---------- Утилиты ----------
    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( '/' );
    }

    // Отсекаем слишком мелкие картинки (иконки из подписей и т.п.)
    // не форсируем layout, цикл по сотням миниатюр становится дешевле.
    function isImageTooSmall( img ) {
        var w = img.width || img.naturalWidth || 0;
        var h = img.height || img.naturalHeight || 0;
        // Если размеры ещё не посчитаны (lazy loading) — не отсекаем
        if ( w === 0 && h === 0 ) return false;
        return w < MIN_IMAGE_SIZE && h < MIN_IMAGE_SIZE;
    }

    // Извлекаем текст подписи, сохраняя <br> и \n как маркеры переноса.
    function getCaptionText( el ) {
        var clone = el.cloneNode( true );
        // Заменяем <br> на текстовый маркер переноса
        clone.querySelectorAll( 'br' ).forEach( function ( br ) {
            br.replaceWith( document.createTextNode( '\n' ) );
        } );
        return clone.textContent
            .replace( /[^\S\n]+/g, ' ' )   // схлопываем пробелы, кроме \n
            .replace( /\s*\n\s*/g, '\n' )  // убираем пробелы вокруг \n
            .trim();
    }

    function getCaption( link, img ) {
        var galleryItem = link.closest( '.gallerybox, li.gallerybox' );
        if ( galleryItem ) {
            var galleryText = galleryItem.querySelector( '.gallerytext' );
            if ( galleryText && galleryText.textContent.trim() ) {
                return getCaptionText( galleryText );
            }
        }
        var container = link.closest( 'figure, .thumb' );
        if ( container ) {
            var thumbCaption = container.querySelector( '.thumbcaption, figcaption' );
            if ( thumbCaption && thumbCaption.textContent.trim() ) {
                return getCaptionText( thumbCaption );
            }
        }
        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 gallery = clickedLink.closest( '.gallery, ul.gallery' );
        var root = gallery || clickedLink.closest( '.mw-parser-output' );
        if ( !root ) return [];

        // Повторный клик в той же галерее — отдаём готовый массив
        if ( galleryCache.has( root ) ) {
            return galleryCache.get( root );
        }

        var 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;

            // Отсекаем слишком мелкие картинки
            if ( isImageTooSmall( 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 ),
                fileHref: link.getAttribute( 'href' ) || ''
            } );
        } );

        galleryCache.set( root, items );
        return items;
    }

    // ---------- Focus trap ----------
    function getFocusableElements() {
        if ( !overlay ) return [];
        var nodes = overlay.querySelectorAll( FOCUSABLE_SELECTOR );
        var result = [];
        nodes.forEach( function ( el ) {
            // Отсекаем скрытые (display:none и подобные)
            if ( el.offsetParent === null ) return;
            var style = window.getComputedStyle( el );
            if ( style.visibility === 'hidden' ) return;
            result.push( el );
        } );
        return result;
    }

    function trapFocus( e ) {
        if ( e.key !== 'Tab' ) return;
        var focusable = getFocusableElements();
        if ( !focusable.length ) {
            e.preventDefault();
            return;
        }
        var first = focusable[ 0 ];
        var last = focusable[ focusable.length - 1 ];
        var active = document.activeElement;

        if ( e.shiftKey ) {
            // Shift+Tab: если на первом или вне оверлея — уйти на последний
            if ( active === first || !overlay.contains( active ) ) {
                e.preventDefault();
                last.focus();
            }
        } else {
            // Tab: если на последнем или вне оверлея — уйти на первый
            if ( active === last || !overlay.contains( active ) ) {
                e.preventDefault();
                first.focus();
            }
        }
    }

    function saveFocus() {
        lastFocusedElement = document.activeElement;
    }

    function restoreFocus() {
        if ( lastFocusedElement && typeof lastFocusedElement.focus === 'function' ) {
            try {
                lastFocusedElement.focus();
            } catch ( err ) { /* элемент мог исчезнуть из DOM */ }
        }
        lastFocusedElement = null;
    }

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

    var gallery = [];
    var currentIndex = 0;
    var lastFocusedElement = null;

    // Позиция счётчика обновляется относительно картинки.
    function updateCounterPosition() {
        if ( !counterElement || !imgElement || !overlay ) return;
        if ( counterElement.style.display === 'none' ) return;
        var imgRect = imgElement.getBoundingClientRect();
        var overlayRect = overlay.getBoundingClientRect();
        var left = imgRect.left - overlayRect.left + imgRect.width / 2;
        var top = imgRect.top - overlayRect.top - 28;
        counterElement.style.left = left + 'px';
        counterElement.style.top = top + 'px';
    }

    // Крестик в overlay 
    function updateClosePosition() {
        if ( !closeBtn || !imgElement || !overlay ) return;
        var imgRect = imgElement.getBoundingClientRect();
        var overlayRect = overlay.getBoundingClientRect();
        var left = imgRect.right - overlayRect.left - 8;  // 8px от правого края картинки
        var top = imgRect.top - overlayRect.top - 12;      // 12px от верхнего края картинки
        closeBtn.style.left = left + 'px';
        closeBtn.style.top = top + 'px';
    }

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

        // Обёртка вокруг картинки — чтобы крестик был строго в её углу
        var imageWrap = document.createElement( 'div' );
        imageWrap.className = 'absyfancyboxy-imagewrap';
        stage.appendChild( imageWrap );

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

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

        fileLink = document.createElement( 'a' );
        fileLink.id = 'absyfancyboxy-filelink';
        fileLink.textContent = 'ФАЙЛ';
        fileLink.setAttribute( 'role', 'link' );
        fileLink.setAttribute( 'tabindex', '0' );
        fileLink.setAttribute( 'target', '_blank' );
        fileLink.setAttribute( 'rel', 'noopener noreferrer' );
        fileLink.addEventListener( 'click', function ( e ) {
            e.stopPropagation();
        } );
        fileLink.addEventListener( 'contextmenu', function ( e ) {
            e.stopPropagation();
        } );
        stage.appendChild( fileLink );

        counterElement = document.createElement( 'div' );
        counterElement.id = 'absyfancyboxy-counter';
        overlay.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', '‹' );
        nextBtn = makeArrow( 'next', '›' );
        stage.appendChild( prevBtn );
        stage.appendChild( nextBtn );

        // Всегда скрыты до первого взаимодействия
        setArrowsVisible( false );

        // Десктоп: мышь над оверлеем — показать, ушла — скрыть
        overlay.addEventListener( 'mouseenter', showArrowsTemporarily );
        overlay.addEventListener( 'mousemove', showArrowsTemporarily );
        overlay.addEventListener( 'mouseleave', hideArrows );

        // Мобильные: касание/свайп — показать на время
        overlay.addEventListener( 'touchstart', showArrowsTemporarily, { passive: true } );
        overlay.addEventListener( 'touchmove', showArrowsTemporarily, { passive: true } );

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

        var touchStartX = null;
        overlay.addEventListener( 'touchstart', function ( e ) {
            // Касание над подписью — не считаем свайпом (даём прокрутить текст)
            if ( e.target.closest( '#absyfancyboxy-caption' ) ) {
                touchStartX = null;
                return;
            }
            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;
        } );

        // Колёсико: вверх — предыдущая, вниз — следующая
        overlay.addEventListener( 'wheel', function ( e ) {
            // Над подписью — не листаем, даём прокрутить текст
            if ( e.target.closest( '#absyfancyboxy-caption' ) ) return;
            e.preventDefault();
            showArrowsTemporarily();
            if ( e.deltaY < 0 ) prev();
            else if ( e.deltaY > 0 ) next();
        }, { passive: false } );

        // Средняя кнопка мыши — закрыть
        overlay.addEventListener( 'mousedown', function ( e ) {
            if ( e.button === 1 ) {
                e.preventDefault();
                closeLightbox();
            }
        } );

        // Правая кнопка мыши — закрыть без контекстного меню
        overlay.addEventListener( 'contextmenu', function ( e ) {
            e.preventDefault();
            closeLightbox();
        } );

        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();
            showArrowsTemporarily();
            if ( dir === 'prev' ) prev(); else next();
        } );
        btn.addEventListener( 'keydown', function ( e ) {
            if ( e.key === 'Enter' || e.key === ' ' ) {
                e.preventDefault();
                showArrowsTemporarily();
                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';
            // Скрытые стрелки не должны получать фокус
            btn.style.visibility = visible ? 'visible' : 'hidden';
        } );
    }

    function showArrowsTemporarily() {
        setArrowsVisible( true );
        if ( hideTimer ) clearTimeout( hideTimer );
        hideTimer = setTimeout( hideArrows, ARROW_HIDE_DELAY );
    }

    function hideArrows() {
        if ( hideTimer ) {
            clearTimeout( hideTimer );
            hideTimer = null;
        }
        setArrowsVisible( false );
    }

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

        // Подпись: переносы \n превращаем в настоящие <br> (безопасно)
        captionElement.textContent = '';
        var captionText = item.caption || '';
        if ( captionText ) {
            var parts = captionText.split( '\n' );
            parts.forEach( function ( part, i ) {
                if ( i > 0 ) captionElement.appendChild( document.createElement( 'br' ) );
                captionElement.appendChild( document.createTextNode( part ) );
            } );
        }

        counterElement.textContent = ( currentIndex + 1 ) + ' / ' + gallery.length;

        if ( item.fileHref ) {
            fileLink.href = item.fileHref;
            fileLink.style.display = 'block';
        } else {
            fileLink.removeAttribute( 'href' );
            fileLink.style.display = 'none';
        }

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

        if ( multiple ) {
            showArrowsTemporarily();
        } else {
            hideArrows();
        }

        // Обновить позиции счётчика и крестика после рендера
        updateCounterPosition();
        updateClosePosition();
    }

    function openLightbox( items, index ) {
        if ( !overlay ) buildOverlay();
        saveFocus();
        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;
        hideArrows();
        overlay.classList.remove( 'is-open' );
        imgElement.src = '';
        imgElement.alt = '';
        captionElement.textContent = '';
        counterElement.textContent = '';
        fileLink.removeAttribute( 'href' );
        gallery = [];
        currentIndex = 0;
        document.body.style.overflow = '';
        restoreFocus();
    }

    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 === 'Tab' ) {
            trapFocus( e );
        } else if ( e.key === 'Escape' ) {
            closeLightbox();
        } else if ( e.key === 'ArrowRight' ) {
            showArrowsTemporarily();
            next();
        } else if ( e.key === 'ArrowLeft' ) {
            showArrowsTemporarily();
            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 img = link.querySelector( 'img' );
        if ( !img || isImageTooSmall( img ) ) 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 () {
            // Контент перерисован когда кеш галерей устарел
            galleryCache = new WeakMap();
            if ( overlay && overlay.classList.contains( 'is-open' ) ) closeLightbox();
        } );
    }

// ---------- Автоповорот экрана для ОС Android ----------
window.addEventListener( 'resize', function () {
    if ( !overlay || !overlay.classList.contains( 'is-open' ) ) return;

    requestAnimationFrame( function () {
        requestAnimationFrame( function () {
            if ( !overlay || !overlay.classList.contains( 'is-open' ) ) return;

            var stage = overlay.querySelector( '.absyfancyboxy-stage' );
            if ( stage ) void stage.offsetHeight;

            var caption = overlay.querySelector( '#absyfancyboxy-caption' );
            if ( caption ) caption.scrollTop = 0;

            updateCounterPosition();
            updateClosePosition();

            if ( prevBtn && nextBtn ) {
                showArrowsTemporarily();
            }
        } );
    } );
}, { passive: true } );

} )();