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

Нет описания правки
Нет описания правки
 
(не показано 19 промежуточных версий этого же участника)
Строка 1: Строка 1:
/**
/**
  * Гаджет: AbsyFancyBoxy для Absurdopedia.wiki
  * Гаджет: AbsyFancyBoxy
* Версия 1.0
  * Локальный лайтбокс с листанием галереи и подписями.
  * Локальный лайтбокс с листанием галереи и подписями.
  * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
  * Без внешних библиотек. Не конфликтует с TimedMediaHandler.
* Идёт в связке с [[MediaWiki:Gadget-AbsyFancyBoxy.css]]
* Лицензия: MIT (opensource.org/license/mit) ==> 2026, absurdopedia.wiki
  */
  */
( function () {
( function () {
     'use strict';
     'use strict';
Строка 10: Строка 14:
     var MEDIA_EXT = /\.(webm|ogv|ogg|oga|mp4|mp3|flac|opus|wav)$/i;
     var MEDIA_EXT = /\.(webm|ogv|ogg|oga|mp4|mp3|flac|opus|wav)$/i;
     var SAFE_URL = /^(https?:)?\/\//i;
     var SAFE_URL = /^(https?:)?\/\//i;
     var CAN_HOVER = window.matchMedia && window.matchMedia( '(hover: hover)' ).matches;
     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();


     // ---------- Утилиты ----------
     // ---------- Утилиты ----------
Строка 26: Строка 34:
         pathSegments.pop();
         pathSegments.pop();
         return parts[ 0 ] + '/' + pathSegments.join( '/' );
         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();
     }
     }


Строка 33: Строка 64:
             var galleryText = galleryItem.querySelector( '.gallerytext' );
             var galleryText = galleryItem.querySelector( '.gallerytext' );
             if ( galleryText && galleryText.textContent.trim() ) {
             if ( galleryText && galleryText.textContent.trim() ) {
                 return galleryText.textContent.trim();
                 return getCaptionText( galleryText );
             }
             }
         }
         }
Строка 40: Строка 71:
             var thumbCaption = container.querySelector( '.thumbcaption, figcaption' );
             var thumbCaption = container.querySelector( '.thumbcaption, figcaption' );
             if ( thumbCaption && thumbCaption.textContent.trim() ) {
             if ( thumbCaption && thumbCaption.textContent.trim() ) {
                 return thumbCaption.textContent.trim();
                 return getCaptionText( thumbCaption );
             }
             }
         }
         }
Строка 58: Строка 89:
     // ---------- Сбор галереи ----------
     // ---------- Сбор галереи ----------
     function collectGallery( clickedLink ) {
     function collectGallery( clickedLink ) {
        var items = [];
         var gallery = clickedLink.closest( '.gallery, ul.gallery' );
         var gallery = clickedLink.closest( '.gallery, ul.gallery' );
         var root = gallery || clickedLink.closest( '.mw-parser-output' );
         var root = gallery || clickedLink.closest( '.mw-parser-output' );
         if ( !root ) return items;
         if ( !root ) return [];


        // Повторный клик в той же галерее — отдаём готовый массив
        if ( galleryCache.has( root ) ) {
            return galleryCache.get( root );
        }
        var items = [];
         var links = root.querySelectorAll( 'a.image, a.mw-file-description' );
         var links = root.querySelectorAll( 'a.image, a.mw-file-description' );
         links.forEach( function ( link ) {
         links.forEach( function ( link ) {
Строка 69: Строка 105:
             var img = link.querySelector( 'img' );
             var img = link.querySelector( 'img' );
             if ( !img ) return;
             if ( !img ) return;
            // Отсекаем слишком мелкие картинки
            if ( isImageTooSmall( img ) ) return;


             var thumbSrc = img.getAttribute( 'src' );
             var thumbSrc = img.getAttribute( 'src' );
Строка 79: Строка 118:
                 link: link,
                 link: link,
                 src: fullSrc,
                 src: fullSrc,
                 caption: getCaption( link, img )
                 caption: getCaption( link, img ),
                fileHref: link.getAttribute( 'href' ) || ''
             } );
             } );
         } );
         } );
        galleryCache.set( root, items );
         return 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;
     }
     }


Строка 93: Строка 189:
     var nextBtn = null;
     var nextBtn = null;
     var closeBtn = null;
     var closeBtn = null;
    var fileLink = null;
    var hideTimer = null;


     var gallery = [];
     var gallery = [];
     var currentIndex = 0;
     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() {
     function buildOverlay() {
Строка 112: Строка 234:
         stage.className = 'absyfancyboxy-stage';
         stage.className = 'absyfancyboxy-stage';
         overlay.appendChild( stage );
         overlay.appendChild( stage );
        // Обёртка вокруг картинки — чтобы крестик был строго в её углу
        var imageWrap = document.createElement( 'div' );
        imageWrap.className = 'absyfancyboxy-imagewrap';
        stage.appendChild( imageWrap );


         imgElement = document.createElement( 'img' );
         imgElement = document.createElement( 'img' );
Строка 119: Строка 246:
             captionElement.textContent = 'Не удалось загрузить изображение';
             captionElement.textContent = 'Не удалось загрузить изображение';
         } );
         } );
         stage.appendChild( imgElement );
         imgElement.addEventListener( 'load', function () {
            updateCounterPosition();
            updateClosePosition();
        } );
        imageWrap.appendChild( imgElement );


         captionElement = document.createElement( 'div' );
         captionElement = document.createElement( 'div' );
         captionElement.id = 'absyfancyboxy-caption';
         captionElement.id = 'absyfancyboxy-caption';
         stage.appendChild( captionElement );
         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 = document.createElement( 'div' );
         counterElement.id = 'absyfancyboxy-counter';
         counterElement.id = 'absyfancyboxy-counter';
         stage.appendChild( counterElement );
         overlay.appendChild( counterElement );


         closeBtn = document.createElement( 'div' );
         closeBtn = document.createElement( 'div' );
Строка 147: Строка 293:
         overlay.appendChild( closeBtn );
         overlay.appendChild( closeBtn );


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


         if ( CAN_HOVER ) {
         // Всегда скрыты до первого взаимодействия
            setArrowsVisible( false );
        setArrowsVisible( false );
            overlay.addEventListener( 'mouseenter', function () { setArrowsVisible( true ); } );
 
            overlay.addEventListener( 'mouseleave', function () { 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 ) {
         stage.addEventListener( 'click', function ( e ) {
Строка 164: Строка 316:
         var touchStartX = null;
         var touchStartX = null;
         overlay.addEventListener( 'touchstart', function ( e ) {
         overlay.addEventListener( 'touchstart', function ( e ) {
            // Касание над подписью — не считаем свайпом (даём прокрутить текст)
            if ( e.target.closest( '#absyfancyboxy-caption' ) ) {
                touchStartX = null;
                return;
            }
             if ( e.touches.length === 1 ) touchStartX = e.touches[ 0 ].clientX;
             if ( e.touches.length === 1 ) touchStartX = e.touches[ 0 ].clientX;
         }, { passive: true } );
         }, { passive: true } );
Строка 173: Строка 330:
             }
             }
             touchStartX = null;
             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();
         } );
         } );


Строка 188: Строка 369:
         btn.addEventListener( 'click', function ( e ) {
         btn.addEventListener( 'click', function ( e ) {
             e.stopPropagation();
             e.stopPropagation();
            showArrowsTemporarily();
             if ( dir === 'prev' ) prev(); else next();
             if ( dir === 'prev' ) prev(); else next();
         } );
         } );
Строка 193: Строка 375:
             if ( e.key === 'Enter' || e.key === ' ' ) {
             if ( e.key === 'Enter' || e.key === ' ' ) {
                 e.preventDefault();
                 e.preventDefault();
                showArrowsTemporarily();
                 if ( dir === 'prev' ) prev(); else next();
                 if ( dir === 'prev' ) prev(); else next();
             }
             }
Строка 204: Строка 387:
             btn.style.opacity = visible ? '0.85' : '0';
             btn.style.opacity = visible ? '0.85' : '0';
             btn.style.pointerEvents = visible ? 'auto' : 'none';
             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 );
     }
     }


Строка 213: Строка 412:
         imgElement.src = item.src;
         imgElement.src = item.src;
         imgElement.alt = item.caption || '';
         imgElement.alt = item.caption || '';
         captionElement.textContent = 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;
         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;
         var multiple = gallery.length > 1;
Строка 221: Строка 439:
         counterElement.style.display = multiple ? 'block' : 'none';
         counterElement.style.display = multiple ? 'block' : 'none';


         if ( CAN_HOVER && multiple ) setArrowsVisible( false );
         if ( multiple ) {
            showArrowsTemporarily();
        } else {
            hideArrows();
        }
 
        // Обновить позиции счётчика и крестика после рендера
        updateCounterPosition();
        updateClosePosition();
     }
     }


     function openLightbox( items, index ) {
     function openLightbox( items, index ) {
         if ( !overlay ) buildOverlay();
         if ( !overlay ) buildOverlay();
        saveFocus();
         gallery = items;
         gallery = items;
         currentIndex = index || 0;
         currentIndex = index || 0;
Строка 236: Строка 463:
     function closeLightbox() {
     function closeLightbox() {
         if ( !overlay ) return;
         if ( !overlay ) return;
        hideArrows();
         overlay.classList.remove( 'is-open' );
         overlay.classList.remove( 'is-open' );
         imgElement.src = '';
         imgElement.src = '';
Строка 241: Строка 469:
         captionElement.textContent = '';
         captionElement.textContent = '';
         counterElement.textContent = '';
         counterElement.textContent = '';
        fileLink.removeAttribute( 'href' );
         gallery = [];
         gallery = [];
         currentIndex = 0;
         currentIndex = 0;
         document.body.style.overflow = '';
         document.body.style.overflow = '';
        restoreFocus();
     }
     }


Строка 261: Строка 491:
     document.addEventListener( 'keydown', function ( e ) {
     document.addEventListener( 'keydown', function ( e ) {
         if ( !overlay || !overlay.classList.contains( 'is-open' ) ) return;
         if ( !overlay || !overlay.classList.contains( 'is-open' ) ) return;
         if ( e.key === 'Escape' ) closeLightbox();
 
         else if ( e.key === 'ArrowRight' ) next();
         if ( e.key === 'Tab' ) {
         else if ( e.key === 'ArrowLeft' ) prev();
            trapFocus( e );
        } else if ( e.key === 'Escape' ) {
            closeLightbox();
         } else if ( e.key === 'ArrowRight' ) {
            showArrowsTemporarily();
            next();
         } else if ( e.key === 'ArrowLeft' ) {
            showArrowsTemporarily();
            prev();
        }
     } );
     } );


Строка 272: Строка 511:
         if ( !link.closest( '.mw-parser-output' ) ) return;
         if ( !link.closest( '.mw-parser-output' ) ) return;
         if ( isMediaLink( link ) ) return;
         if ( isMediaLink( link ) ) return;
        // Если картинка мелкая — не перехватываем клик
        var img = link.querySelector( 'img' );
        if ( !img || isImageTooSmall( img ) ) return;


         var items = collectGallery( link );
         var items = collectGallery( link );
Строка 290: Строка 533:
     if ( window.mw && mw.hook ) {
     if ( window.mw && mw.hook ) {
         mw.hook( 'wikipage.content' ).add( function () {
         mw.hook( 'wikipage.content' ).add( function () {
            // Контент перерисован когда кеш галерей устарел
            galleryCache = new WeakMap();
             if ( overlay && overlay.classList.contains( 'is-open' ) ) closeLightbox();
             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 } );


} )();
} )();