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

попытка #2
Метка: отменено
Откат правки 362378 участника Тэйтанка-птекила (обс.)
Метка: отмена
 
(не показано 67 промежуточных версий этого же участника)
Строка 1: Строка 1:
/* Нигилистические фокусы (см. [[Шаблон:Нигилизм/doc]]) */
/* Нигилистические фокусы (см. шаблон {{tl|Нигилизм}}) */
$(function () {
$(function () {
     var nihilism = $('#nihilism');
     var nihilism = $('#nihilism');
Строка 20: Строка 20:
});
});


/* Стирание памяти для «Людей в чёрном» */
/* Стирание памяти для [[MIB]] («Людей в чёрном») */
$(function () {
$(function () {
     if ($("#erase_memory")[0])
     if ($("#erase_memory")[0])
Строка 50: Строка 50:
/* Вставка юзернейма с помощью <span class="insertusername"></span> */
/* Вставка юзернейма с помощью <span class="insertusername"></span> */
$(function () {
$(function () {
     if ((typeof (disableUsernameReplace) == "undefined" || !disableUsernameReplace) && mw.config.get("wgUserName") !== null)
     if ((typeof (disableUsernameReplace) == "undefined" || !disableUsernameReplace) && mw.config.get("wgUserName") !== null) {
         $("span.insertusername").html(mw.config.get("wgUserName"));
        var username = mw.config.get("wgUserName");
         $("span.insertusername").text(username);
    }
});
});


function defaultUploadInfo() {
    var rewrite = document.getElementById("wpForReUpload");
    if (!rewrite) return;
    if (rewrite.value == 1) return;
    var d = document.getElementById("wpUploadDescription");
    if (d) {
        if (!d.value.match(/\[\[(Категория|Category):/)) {
            d.value += "\n\n\n[[Категория:Некатегоризованные изображения]]";
        }
    }
}


/* Замена категорий для шаблона {{Cats}} */
/* Замена категорий для шаблона {{Cats}} */
Строка 77: Строка 67:




/* Функция для вставки VK-видео на страницу для шаблона VKVideo, простая версия */
/* Вставка VK-видео на страницу для шаблона {{VKVideo}} */
window.vkVideoInit = function() {
(function() {
     console.log('VK Video: Initializing...');
     'use strict';
   
    var containers = document.querySelectorAll('.vk-video-js');
    console.log('VK Video: Found ' + containers.length + ' containers');
      
      
     for (var i = 0; i < containers.length; i++) {
     function initVKVideo() {
         var container = containers[i];
         var containers = document.querySelectorAll('.vk-video-js');
        var oid = container.getAttribute('data-oid');
        var id = container.getAttribute('data-id');
        var width = container.getAttribute('data-width') || '640';
        var height = container.getAttribute('data-height') || '360';
          
          
         console.log('VK Video: Container ' + i + ' - oid:' + oid + ' id:' + id);
         for (var i = 0; i < containers.length; i++) {
       
            var container = containers[i];
        if (oid && id && oid !== 'null' && id !== 'null') {
             var oid = container.getAttribute('data-oid');
             var iframe = document.createElement('iframe');
             var id = container.getAttribute('data-id');
             iframe.src = 'https://vk.com/video_ext.php?oid=' + encodeURIComponent(oid) + '&id=' + encodeURIComponent(id);
             var width = container.getAttribute('data-width') || '560';
             iframe.width = width;
             var height = container.getAttribute('data-height') || '315';
            iframe.height = height;
            iframe.frameBorder = '0';
             iframe.allowFullscreen = true;
            iframe.style.border = 'none';
            iframe.style.borderRadius = '4px';
              
              
             container.innerHTML = '';
             width = parseInt(width) || 560;
            container.appendChild(iframe);
             height = parseInt(height) || 315;
             console.log('VK Video: Container ' + i + ' - SUCCESS');
             if (width > 1920) width = 1920;
        } else {
             if (height < 100) height = 100;
             console.error('VK Video: Container ' + i + ' - MISSING DATA');
             if (height > 1080) height = 1080;
             container.innerHTML = '<div style="color: red; padding: 10px; text-align: center; border: 1px solid red;">Ошибка: неверные параметры видео</div>';
        }
    }
};
 
/* Запускаем после загрузки ВК-видео DOM */
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', window.vkVideoInit);
} else {
    window.vkVideoInit();
}
 
 
/* Раскрытие картинок во всплывающем окне по клику на них (для удобства назову — FancyBoxAlternative), совместимо с расширением TimedMediaHandler */
 
/* Увеличение изображений по клику */
(function() {
/* Создаём модальное окно */
    if (!document.getElementById('imageModal')) {
        var modalHTML = '<div id="imageModal" class="image-modal">' +
            '<span class="modal-close">&times;</span>' +
            '<img class="modal-content" id="modalImage">' +
            '<div class="modal-caption" id="modalCaption"></div>' +
        '</div>';
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }
 
/* Инициализация после загрузки DOM */
    document.addEventListener('DOMContentLoaded', function() {
        var modal = document.getElementById('imageModal');
        var modalImg = document.getElementById('modalImage');
        var captionText = document.getElementById('modalCaption');
        var closeBtn = document.querySelector('.modal-close');
 
    /* Функция открытия модального окна */
        function openModal(imgElement) {
        /*Проверяем, не является ли изображение видео-плейсхолдером TimedMediaHandler */
             if (imgElement.closest('.video-js') || imgElement.closest('.mw-tmh-player')) {
                return; /* Прерываем выполнение для видео */
            }
              
              
             modal.style.display = 'block';
             if (oid && id && oid !== 'null' && id !== 'null' && /^[a-zA-Z0-9_-]{1,100}$/.test(oid) && /^[-_a-zA-Z0-9]+$/.test(id)) {
            modalImg.src = imgElement.src;
                var iframe = document.createElement('iframe');
           
                iframe.src = 'https://vk.com/video_ext.php?oid=' + encodeURIComponent(oid) + '&id=' + encodeURIComponent(id);
            /* Получаем описание */
                iframe.width = width;
            var caption = imgElement.alt || imgElement.title || 'Изображение';
                iframe.height = height;
            captionText.innerHTML = caption;
                iframe.frameBorder = '0';
           
                iframe.allowFullscreen = true;
            /* Блокируем прокрутку body */
               
            document.body.style.overflow = 'hidden';
                iframe.sandbox = 'allow-scripts allow-same-origin allow-presentation allow-fullscreen';
        }
                iframe.allow = 'fullscreen';
 
                iframe.referrerPolicy = 'no-referrer';
    /* Функция закрытия модального окна */
                iframe.loading = 'lazy';
        function closeModal() {
                iframe.style.border = 'none';
            modal.style.display = 'none';
               
            document.body.style.overflow = 'auto';
                while (container.firstChild) {
        }
                    container.removeChild(container.firstChild);
 
                }
    /* Обработчики закрытия */
                container.appendChild(iframe);
        closeBtn.onclick = closeModal;
            } else {
        modal.onclick = function(event) {
                var errorDiv = document.createElement('div');
            if (event.target === modal) closeModal();
               
        };
                errorDiv.style.color = 'red';
        document.addEventListener('keydown', function(event) {
                errorDiv.style.padding = '10px';
            if (event.key === 'Escape') closeModal();
                errorDiv.style.textAlign = 'center';
        });
                errorDiv.style.border = '1px solid';
 
                 errorDiv.style.backgroundColor = '#fff';
    /* Добавляем обработчики ко всем изображениям, кроме служебных */
                 errorDiv.style.fontFamily = 'Arial, sans-serif';
        function addClickHandlers() {
                 errorDiv.style.fontSize = '14px';
            var images = document.querySelectorAll(`
                 errorDiv.style.margin = '5px 0';
                 #content img,
                 .mw-body-content img,
                 .thumb img,
                 .image img,
                .gallery img
            `);


            images.forEach(function(img) {
                 errorDiv.textContent = 'Ошибка: неверные параметры видео';
          /* Пропускаем специзображения */
               
                 if (img.classList.contains('modal-content') ||
                while (container.firstChild) {
                    img.classList.contains('no-zoom') ||
                     container.removeChild(container.firstChild);
                    img.closest('.video-js') ||
                     img.closest('.mw-tmh-player') ||
                    img.parentNode.classList.contains('mw-tmh-player')) {
                    return;
                 }
                 }
 
                 container.appendChild(errorDiv);
      /* Добавляем курсор и обработчик */
             }
                 img.style.cursor = 'pointer';
                img.addEventListener('click', function() {
                    openModal(this);
                });
             });
         }
         }
 
    }
        /* Инициализация */
   
        addClickHandlers();
    if (document.readyState === 'loading') {
 
        document.addEventListener('DOMContentLoaded', initVKVideo);
        /* Обработка динамически загружаемого контента */
    } else {
        var observer = new MutationObserver(function(mutations) {
         initVKVideo();
            mutations.forEach(function(mutation) {
     }
                if (mutation.addedNodes.length) addClickHandlers();
            });
         });
        observer.observe(document.body, { childList: true, subtree: true });
     });
})();
})();