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

Нет описания правки
Нет описания правки
 
(не показано 14 промежуточных версий этого же участника)
Строка 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';
Строка 12: Строка 16:
     var ARROW_HIDE_DELAY = 2500; // мс бездействия до скрытия стрелок
     var ARROW_HIDE_DELAY = 2500; // мс бездействия до скрытия стрелок
     var MIN_IMAGE_SIZE = 100;    // px — минимальный размер картинки для лайтбокса
     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();


     // ---------- Утилиты ----------
     // ---------- Утилиты ----------
Строка 30: Строка 37:


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


Строка 44: Строка 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 );
             }
             }
         }
         }
Строка 51: Строка 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 );
             }
             }
         }
         }
Строка 69: Строка 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 ) {
Строка 97: Строка 122:
             } );
             } );
         } );
         } );
        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;
     }
     }


Строка 113: Строка 194:
     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() {
Строка 129: Строка 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' );
Строка 136: Строка 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' );
Строка 150: Строка 264:
         fileLink.setAttribute( 'rel', 'noopener noreferrer' );
         fileLink.setAttribute( 'rel', 'noopener noreferrer' );
         fileLink.addEventListener( 'click', function ( e ) {
         fileLink.addEventListener( 'click', function ( e ) {
            e.stopPropagation();
        } );
        fileLink.addEventListener( 'contextmenu', function ( e ) {
             e.stopPropagation();
             e.stopPropagation();
         } );
         } );
Строка 156: Строка 273:
         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' );
Строка 199: Строка 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 } );
Строка 208: Строка 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();
         } );
         } );


Строка 241: Строка 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';
         } );
         } );
     }
     }
Строка 264: Строка 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;


Строка 285: Строка 444:
             hideArrows();
             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;
Строка 309: Строка 473:
         currentIndex = 0;
         currentIndex = 0;
         document.body.style.overflow = '';
         document.body.style.overflow = '';
        restoreFocus();
     }
     }


Строка 326: Строка 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' ) { showArrowsTemporarily(); next(); }
         if ( e.key === 'Tab' ) {
         else if ( e.key === 'ArrowLeft' ) { showArrowsTemporarily(); prev(); }
            trapFocus( e );
        } else if ( e.key === 'Escape' ) {
            closeLightbox();
         } else if ( e.key === 'ArrowRight' ) {
            showArrowsTemporarily();
            next();
         } else if ( e.key === 'ArrowLeft' ) {
            showArrowsTemporarily();
            prev();
        }
     } );
     } );


Строка 359: Строка 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 } );


} )();
} )();