MediaWiki:Common.js

Матеріал з darnytsa_hero
Перейти до навігації Перейти до пошуку

Увага: Після публікування слід очистити кеш браузера, щоб побачити зміни.

  • Firefox / Safari: тримайте Shift, коли натискаєте Оновити, або натисніть Ctrl-F5 чи Ctrl-Shift-R (⌘-R на Apple Mac)
  • Google Chrome: натисніть Ctrl-Shift-R (⌘-Shift-R на Apple Mac)
  • Edge: тримайте Ctrl, коли натискаєте Оновити, або натисніть Ctrl-F5.
$(function () {
    // Теми
    var themes = {
        light: '/w/index.php?title=MediaWiki:Light.css&action=raw&ctype=text/css',
        dark: '/w/index.php?title=MediaWiki:Dark.css&action=raw&ctype=text/css'
    };

    var theme = localStorage.getItem('selectedTheme');
    if (!theme) {
        theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    if (themes[theme]) mw.loader.load(themes[theme], 'text/css');

    function createButton(text, bottom, onClick, title) {
        var $btn = $('<button>').text(text).attr('title', title).css({
            position: 'fixed',
            bottom: bottom + 'px',
            right: '10px',
            padding: '10px 16px',
            border: 'none',
            borderRadius: '25px',
            background: '#1a73e8',
            color: '#ffffff',
            fontWeight: 'bold',
            fontSize: '14px',
            cursor: 'pointer',
            zIndex: 9999,
            textAlign: 'center',
            boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
            whiteSpace: 'nowrap'
        }).click(onClick);
        $('body').append($btn);
        return $btn;
    }

    // Кнопка Темна/Світла тема
    var $themeBtn = createButton(
        theme === 'dark' ? 'Світла тема ☀️' : 'Темна тема 🌙',
        10,
        function () {
            var newTheme = theme === 'dark' ? 'light' : 'dark';
            localStorage.setItem('selectedTheme', newTheme);
            location.reload();
        },
        'Змінити тему'
    );

    // Змінна для зберігання розміру шрифту
    var fontSize = parseInt($('body').css('font-size'), 10) || 16;
    
    // Функція для застосування розміру шрифту
    function applyFontSize() {
        $('body').css('font-size', fontSize + 'px');
    }

    // Кнопка доступності
    var $accessBtn = createButton(
        'Доступність',
        70,
        function () {
            if (!$('body').hasClass('accessibility-mode')) {
                $('body').addClass('accessibility-mode');
                localStorage.setItem('accessibilityMode', 'on');
                $accessBtn.css('background', '#ff6600');
                $accessBtn.text('Доступність ON');
            } else {
                $('body').removeClass('accessibility-mode');
                localStorage.setItem('accessibilityMode', 'off');
                $accessBtn.css('background', '#1a73e8');
                $accessBtn.text('Доступність OFF');
            }
        },
        'Увімкнути/вимкнути режим доступності'
    );

    // Відновлення стану доступності
    if (localStorage.getItem('accessibilityMode') === 'on') {
        $('body').addClass('accessibility-mode');
        $accessBtn.css('background', '#ff6600');
        $accessBtn.text('Доступність ON');
    }

    // Лупа
    createButton('🔍 +', 130, function () {
        fontSize += 2;
        if (fontSize > 30) fontSize = 30;
        localStorage.setItem('fontSize', fontSize);
        applyFontSize();
    }, 'Збільшити шрифт');

    createButton('🔍 -', 170, function () {
        fontSize -= 2;
        if (fontSize < 12) fontSize = 12;
        localStorage.setItem('fontSize', fontSize);
        applyFontSize();
    }, 'Зменшити шрифт');

    // Відновлення розміру шрифту
    if (localStorage.getItem('fontSize')) {
        fontSize = parseInt(localStorage.getItem('fontSize'), 10);
    }
    applyFontSize();
});


//OVERLAY 
(function() {
    // ===== Отключаем MediaViewer =====
    if (window.mw && mw.config) mw.config.set('wgUseMediaViewer', false);

    // ===== CSS для overlay =====
    const style = document.createElement('style');
    style.innerHTML = `
    .custom-overlay {
        position: fixed;
        top:0; left:0;
        width:100%; height:100%;
        background: rgba(0,0,0,0.85);
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        z-index: 9999;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    .custom-overlay.show { opacity: 1; }
    .custom-overlay img {
        max-width: 90%;
        max-height: 90%;
        border-radius: 5px;
        box-shadow: 0 0 20px rgba(0,0,0,0.5);
    }
    .custom-overlay button {
        margin: 10px;
        padding: 8px 15px;
        font-size: 16px;
        cursor: pointer;
        background: #f44336;
        color: white;
        border: none;
        border-radius: 4px;
    }
    .nav-buttons { display: flex; justify-content: center; }
    `;
    document.head.appendChild(style);

    // ===== Переменные галереи =====
    let images = Array.from(document.querySelectorAll('img'));
    let overlay, imgElement, currentIndex = 0;

    // ===== Функция показа overlay =====
    function showOverlay(index) {
        currentIndex = index;
        const url = images[currentIndex].src;

        // Удаляем старый overlay
        if (overlay) { overlay.remove(); overlay = null; imgElement = null; }

        overlay = document.createElement('div');
        overlay.className = 'custom-overlay';

        imgElement = document.createElement('img');
        imgElement.src = url;
        overlay.appendChild(imgElement);

        // Кнопка Закрити
        const closeBtn = document.createElement('button');
        closeBtn.innerText = '✕ Закрити';
        closeBtn.addEventListener('click', () => overlay.remove());
        overlay.appendChild(closeBtn);

        // Кнопки навигации
        const navDiv = document.createElement('div');
        navDiv.className = 'nav-buttons';

        const prevBtn = document.createElement('button');
        prevBtn.innerText = '← Назад';
        prevBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            currentIndex = (currentIndex - 1 + images.length) % images.length;
            imgElement.src = images[currentIndex].src;
        });

        const nextBtn = document.createElement('button');
        nextBtn.innerText = 'Вперед →';
        nextBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            currentIndex = (currentIndex + 1) % images.length;
            imgElement.src = images[currentIndex].src;
        });

        navDiv.appendChild(prevBtn);
        navDiv.appendChild(nextBtn);
        overlay.appendChild(navDiv);

        // Закрытие кликом по фону
        overlay.addEventListener('click', e => {
            if (e.target === overlay) overlay.remove();
        });

        document.body.appendChild(overlay);
        setTimeout(() => overlay.classList.add('show'), 10);
    }

    // ===== Функция для открытия overlay по ссылке на страницу файла =====
    async function showFilePageOverlay(url) {
        try {
            const res = await fetch(url);
            const html = await res.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            const img = doc.querySelector('.fullMedia img');
            if (img && img.src) {
                // Добавляем изображение во временный массив для листания
                const tempIndex = images.length;
                images.push({src: img.src});
                showOverlay(tempIndex);
            } else {
                console.warn('Не удалось найти изображение на странице файла:', url);
            }
        } catch(err) {
            console.error('Ошибка при получении файла:', err);
        }
    }

    // ===== Перехват кликов =====
    document.body.addEventListener('click', e => {
        const target = e.target;

        // Прямое изображение
        if (target.tagName === 'IMG') {
            const parentLink = target.closest('a[href*="/w/images/"]');
            if (!parentLink) {
                e.preventDefault();
                showOverlay(images.indexOf(target));
            }
        }

        // Ссылка на страницу файла
        if (target.tagName === 'A' && target.href.includes('/w/index.php/File:')) {
            e.preventDefault();
            showFilePageOverlay(target.href);
        }
    });

})();