MediaWiki:Common.js: различия между версиями
Перейти к навигации
Перейти к поиску
попытка #2 Метка: отменено |
Попытка #3 Метка: отменено |
||
| Строка 121: | Строка 121: | ||
/* Раскрытие картинок во всплывающем окне по клику на них (для удобства назову — FancyBoxAlternative) | /* Раскрытие картинок во всплывающем окне по клику на них (для удобства назову — FancyBoxAlternative) */ | ||
/* Увеличение изображений по клику */ | /* Увеличение изображений по клику (совместимость с TimedMediaHandler) */ | ||
(function() { | (function() { | ||
'use strict'; | |||
/* Создаем модальное окно, если нет */ | |||
if (!document.getElementById('imageModal')) { | if (!document.getElementById('imageModal')) { | ||
var modalHTML = '<div id="imageModal" class="image-modal">' | var modalHTML = [ | ||
'<span class="modal-close">×</span>' | '<div id="imageModal" class="image-modal">', | ||
'<img class="modal-content" id="modalImage">' | ' <span class="modal-close">×</span>', | ||
'<div class="modal-caption" id="modalCaption"></div>' | ' <img class="modal-content" id="modalImage">', | ||
' <div class="modal-caption" id="modalCaption"></div>', | |||
'</div>' | |||
].join(''); | |||
document.body.insertAdjacentHTML('beforeend', modalHTML); | document.body.insertAdjacentHTML('beforeend', modalHTML); | ||
} | } | ||
/* Инициализация после загрузки DOM */ | |||
document.addEventListener('DOMContentLoaded', function() { | document.addEventListener('DOMContentLoaded', function() { | ||
var modal = document.getElementById('imageModal'); | var modal = document.getElementById('imageModal'); | ||
| Строка 142: | Строка 146: | ||
var closeBtn = document.querySelector('.modal-close'); | var closeBtn = document.querySelector('.modal-close'); | ||
/* Функция открытия модального окна */ | |||
function openModal(imgElement) { | function openModal(imgElement) { | ||
/* Проверяем, не является ли пикча видео-плейсхолдером TimedMediaHandler */ | |||
if ( | if (isTimedMediaHandlerElement(imgElement)) { | ||
return; /* Прерываем выполнение для видео */ | return; /* Прерываем выполнение для видео */ | ||
} | } | ||
| Строка 166: | Строка 170: | ||
} | } | ||
/* Проверка элементов TimedMediaHandler */ | |||
function isTimedMediaHandlerElement(element) { | |||
return element.closest('.video-js') || | |||
element.closest('.mw-tmh-player') || | |||
element.classList.contains('mw-tmh-thumbnail') || | |||
element.parentNode.classList.contains('mw-tmh-player'); | |||
} | |||
/* Обработчики закрытия | |||
closeBtn.onclick = closeModal; | closeBtn.onclick = closeModal; | ||
modal.onclick = function(event) { | modal.onclick = function(event) { | ||
| Строка 175: | Строка 187: | ||
}); | }); | ||
/* Добавляем обработчики ко всем изображениям, кроме служебных */ | |||
function addClickHandlers() { | function addClickHandlers() { | ||
var images = document.querySelectorAll(` | var images = document.querySelectorAll(` | ||
| Строка 186: | Строка 198: | ||
images.forEach(function(img) { | images.forEach(function(img) { | ||
/* Пропускаем специзображения */ | |||
if (img.classList.contains('modal-content') || | if (img.classList.contains('modal-content') || | ||
img.classList.contains('no-zoom') || | img.classList.contains('no-zoom') || | ||
isTimedMediaHandlerElement(img)) { | |||
return; | return; | ||
} | } | ||
| Строка 203: | Строка 213: | ||
} | } | ||
/* Инициализация */ | |||
addClickHandlers(); | addClickHandlers(); | ||
/* Обработка динамически загружаемого контента */ | |||
var observer = new MutationObserver(function(mutations) { | var observer = new MutationObserver(function(mutations) { | ||
mutations.forEach(function(mutation) { | mutations.forEach(function(mutation) { | ||
Версия от 07:47, 27 октября 2025
/* Нигилистические фокусы (см. [[Шаблон:Нигилизм/doc]]) */
$(function () {
var nihilism = $('#nihilism');
if (nihilism[0] && !document.location.href.match("diff")) {
var msg = nihilism.html();
if (!nihilism.hasClass('nihilism-no-white')) {
$('body').css('background-color', 'white');
}
var scripts = $('script');
var bodyNihilism = $('body').html('');
var divNihilism = $('<div class="mw-parser-output"></div>').html(msg);
if (nihilism.css('top') == '0px') {
bodyNihilism.css('top', '0px').css('left', '0px');
}
bodyNihilism.append(divNihilism).append(scripts);
$(document).dblclick(function () {
window.location = mw.util.getUrl(null, {'action': 'edit'});
});
}
});
/* Стирание памяти для «Людей в чёрном» */
$(function () {
if ($("#erase_memory")[0])
setTimeout(function () { $("#erase_memory").hide(); }, 20000);
});
/* Ссылка «править» для нулевой секции */
$(function () {
var zeroSectionTip = "Править введение";
if (!mw.config.get("wgArticleId")) {
return;
}
var action = mw.config.get("wgAction");
if (action != "view" && action != "purge")
return;
mw.util.$content.find("h2").children(".mw-editsection:first").clone().prependTo("#bodyContent").css("float", "right").find("a").each(function (index) {
$(this).attr("title", zeroSectionTip);
if ($(this).attr("class") === "mw-editsection-visualeditor") {
$(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&veaction=edit&vesection=0&summary=/*%20Преамбула%20*/%20");
} else {
$(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&action=edit§ion=0&summary=/*%20Преамбула%20*/%20");
}
});
});
/* Вставка юзернейма с помощью <span class="insertusername"></span> */
$(function () {
if ((typeof (disableUsernameReplace) == "undefined" || !disableUsernameReplace) && mw.config.get("wgUserName") !== null)
$("span.insertusername").html(mw.config.get("wgUserName"));
});
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}} */
$(function () {
var categoriesAlternative = $("#categories_alternative");
if (categoriesAlternative[0]) {
$('#mw-normal-catlinks').html(categoriesAlternative.html());
categoriesAlternative.hide();
}
});
/* Функция для вставки VK-видео на страницу для шаблона VKVideo, простая версия */
window.vkVideoInit = function() {
console.log('VK Video: Initializing...');
var containers = document.querySelectorAll('.vk-video-js');
console.log('VK Video: Found ' + containers.length + ' containers');
for (var i = 0; i < containers.length; i++) {
var container = containers[i];
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);
if (oid && id && oid !== 'null' && id !== 'null') {
var iframe = document.createElement('iframe');
iframe.src = 'https://vk.com/video_ext.php?oid=' + encodeURIComponent(oid) + '&id=' + encodeURIComponent(id);
iframe.width = width;
iframe.height = height;
iframe.frameBorder = '0';
iframe.allowFullscreen = true;
iframe.style.border = 'none';
iframe.style.borderRadius = '4px';
container.innerHTML = '';
container.appendChild(iframe);
console.log('VK Video: Container ' + i + ' - SUCCESS');
} else {
console.error('VK Video: Container ' + i + ' - MISSING DATA');
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() {
'use strict';
/* Создаем модальное окно, если нет */
if (!document.getElementById('imageModal')) {
var modalHTML = [
'<div id="imageModal" class="image-modal">',
' <span class="modal-close">×</span>',
' <img class="modal-content" id="modalImage">',
' <div class="modal-caption" id="modalCaption"></div>',
'</div>'
].join('');
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 (isTimedMediaHandlerElement(imgElement)) {
return; /* Прерываем выполнение для видео */
}
modal.style.display = 'block';
modalImg.src = imgElement.src;
/* Получаем описание */
var caption = imgElement.alt || imgElement.title || 'Изображение';
captionText.innerHTML = caption;
/* Блокируем прокрутку body */
document.body.style.overflow = 'hidden';
}
/* Функция закрытия модального окна */
function closeModal() {
modal.style.display = 'none';
document.body.style.overflow = 'auto';
}
/* Проверка элементов TimedMediaHandler */
function isTimedMediaHandlerElement(element) {
return element.closest('.video-js') ||
element.closest('.mw-tmh-player') ||
element.classList.contains('mw-tmh-thumbnail') ||
element.parentNode.classList.contains('mw-tmh-player');
}
/* Обработчики закрытия
closeBtn.onclick = closeModal;
modal.onclick = function(event) {
if (event.target === modal) closeModal();
};
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') closeModal();
});
/* Добавляем обработчики ко всем изображениям, кроме служебных */
function addClickHandlers() {
var images = document.querySelectorAll(`
#content img,
.mw-body-content img,
.thumb img,
.image img,
.gallery img
`);
images.forEach(function(img) {
/* Пропускаем специзображения */
if (img.classList.contains('modal-content') ||
img.classList.contains('no-zoom') ||
isTimedMediaHandlerElement(img)) {
return;
}
/* Добавляем курсор и обработчик */
img.style.cursor = 'pointer';
img.addEventListener('click', function() {
openModal(this);
});
});
}
/* Инициализация */
addClickHandlers();
/* Обработка динамически загружаемого контента */
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) addClickHandlers();
});
});
observer.observe(document.body, { childList: true, subtree: true });
});
})();