MediaWiki:Common.js: различия между версиями
Перейти к навигации
Перейти к поиску
Shihov (обсуждение | вклад) Полностью удалено содержимое страницы Метки: очистка ручная отмена |
Shihov (обсуждение | вклад) Нет описания правки Метка: отменено |
||
Строка 1: | Строка 1: | ||
$(document).ready(function() { | |||
console.log("Скрипт дерева категорий загружен."); | |||
function saveTreeHTML() { | |||
console.log("Сохраняем HTML дерева..."); | |||
var treeHTML = $('#p-categorytree-portlet .CategoryTreeTag').prop('outerHTML'); | |||
localStorage.setItem('categoryTreeHTML', treeHTML); | |||
var expandedCategories = []; | |||
$('#p-categorytree-portlet .CategoryTreeItem.expanded').each(function() { | |||
expandedCategories.push($(this).text().trim()); | |||
}); | |||
localStorage.setItem('expandedCategories', JSON.stringify(expandedCategories)); | |||
} | |||
function restoreTreeHTML() { | |||
console.log("Восстанавливаем HTML дерева..."); | |||
var treeHTML = localStorage.getItem('categoryTreeHTML'); | |||
if (treeHTML) { | |||
$('#p-categorytree-portlet .CategoryTreeTag').replaceWith(treeHTML); | |||
} | |||
// Восстанавливаем только верхние уровни категорий | |||
var expandedCategories = JSON.parse(localStorage.getItem('expandedCategories')) || []; | |||
$('#p-categorytree-portlet .CategoryTreeItem').each(function() { | |||
var categoryName = $(this).text().trim(); | |||
if (expandedCategories.includes(categoryName)) { | |||
$(this).find('.CategoryTreeToggle').first().click(); | |||
} | |||
}); | |||
// Повторно навешиваем обработчики событий | |||
attachCategoryEvents(); | |||
} | |||
function attachCategoryEvents() { | |||
console.log("Повторно навешиваем обработчики событий..."); | |||
$('body').off('click', '#p-categorytree-portlet .CategoryTreeItem').on('click', '#p-categorytree-portlet .CategoryTreeItem', function(event) { | |||
var $target = $(event.target); | |||
var $item = $(this); | |||
var $toggleButton = $item.find('.CategoryTreeToggle').first(); | |||
var isCategory = !$item.find('.CategoryTreePageBullet').length; | |||
if ($target.hasClass('CategoryTreeToggle')) return; | |||
if ($target.is('a') && isCategory) { | |||
event.preventDefault(); | |||
$toggleButton.click(); | |||
} else if (isCategory) { | |||
$toggleButton.click(); | |||
} else { | |||
var link = $item.find('a').attr('href'); | |||
if (link) { | |||
saveTreeHTML(); | |||
localStorage.setItem('lastOpenedPageTitle', $item.text().trim()); | |||
window.location.href = link; | |||
} | |||
} | |||
saveTreeHTML(); | |||
}); | |||
} | |||
restoreTreeHTML(); | |||
function scrollToCategory(categoryTitle, callback) { | |||
var $categoryItem = $('#p-categorytree-portlet .CategoryTreeItem').filter(function() { | |||
return $(this).text().trim() === categoryTitle; | |||
}); | |||
if ($categoryItem.length) { | |||
console.log("Категория найдена, перематываем..."); | |||
$('#p-categorytree-portlet').animate({ | |||
scrollTop: $categoryItem.position().top - 50 | |||
}, 500, function() { | |||
$('.CategoryTreeItem').removeClass('highlighted'); | |||
$categoryItem.addClass('highlighted'); | |||
if (callback) callback(true); | |||
}); | |||
localStorage.setItem('highlightedCategory', categoryTitle); | |||
return true; | |||
} | |||
if (callback) callback(false); | |||
return false; | |||
} | |||
function expandAndFindCategory($parent, callback) { | |||
var $toggleButton = $parent.find('.CategoryTreeToggle').first(); | |||
if ($toggleButton.length && !$parent.hasClass('expanded')) { | |||
console.log("Раскрываем:", $parent.text().trim()); | |||
$toggleButton.click(); | |||
setTimeout(function() { | |||
if (scrollToCategory(mw.config.get('wgTitle'))) { | |||
callback(true); | |||
} else { | |||
callback(false); | |||
} | |||
}, 1000); | |||
} else { | |||
callback(false); | |||
} | |||
} | |||
function resetCategoryTree() { | |||
console.log("Категория не найдена. Очищаем данные и сбрасываем дерево."); | |||
localStorage.removeItem('categoryTreeHTML'); | |||
localStorage.removeItem('lastOpenedPageTitle'); | |||
localStorage.removeItem('highlightedCategory'); | |||
localStorage.removeItem('expandedCategories'); | |||
// Оставляем верхний уровень категорий открытым | |||
$('#p-categorytree-portlet .CategoryTreeItem').each(function() { | |||
if ($(this).parents('.CategoryTreeChildren').length === 0) { | |||
$(this).find('.CategoryTreeToggle').first().click(); | |||
} | |||
}); | |||
// Повторно навешиваем обработчики событий | |||
attachCategoryEvents(); | |||
} | |||
function recursiveSearchForCategory() { | |||
console.log("Очищаем `localStorage` перед поиском..."); | |||
localStorage.removeItem('lastOpenedPageTitle'); | |||
localStorage.removeItem('highlightedCategory'); | |||
var currentPageTitle = mw.config.get('wgTitle'); | |||
if (!currentPageTitle) { | |||
console.log("Не удалось определить текущую страницу."); | |||
return; | |||
} | |||
console.log("Начинаем поиск категории для текущей страницы:", currentPageTitle); | |||
if (scrollToCategory(currentPageTitle)) { | |||
return; | |||
} | |||
var $categoryItems = $('#p-categorytree-portlet .CategoryTreeItem'); | |||
if ($categoryItems.length === 0) { | |||
resetCategoryTree(); | |||
return; | |||
} | |||
var index = 0; | |||
function processNext() { | |||
if (index >= $categoryItems.length) { | |||
console.log("Категория не найдена. Сбрасываем дерево."); | |||
resetCategoryTree(); | |||
return; | |||
} | |||
var $item = $($categoryItems[index]); | |||
expandAndFindCategory($item, function(found) { | |||
if (!found) { | |||
index++; | |||
processNext(); | |||
} | |||
}); | |||
} | |||
processNext(); | |||
} | |||
setTimeout(function() { | |||
recursiveSearchForCategory(); | |||
}, 500); | |||
$(window).on('beforeunload', saveTreeHTML); | |||
// Первичная инициализация обработчиков событий | |||
attachCategoryEvents(); | |||
}); |
Версия от 13:14, 27 февраля 2025
$(document).ready(function() {
console.log("Скрипт дерева категорий загружен.");
function saveTreeHTML() {
console.log("Сохраняем HTML дерева...");
var treeHTML = $('#p-categorytree-portlet .CategoryTreeTag').prop('outerHTML');
localStorage.setItem('categoryTreeHTML', treeHTML);
var expandedCategories = [];
$('#p-categorytree-portlet .CategoryTreeItem.expanded').each(function() {
expandedCategories.push($(this).text().trim());
});
localStorage.setItem('expandedCategories', JSON.stringify(expandedCategories));
}
function restoreTreeHTML() {
console.log("Восстанавливаем HTML дерева...");
var treeHTML = localStorage.getItem('categoryTreeHTML');
if (treeHTML) {
$('#p-categorytree-portlet .CategoryTreeTag').replaceWith(treeHTML);
}
// Восстанавливаем только верхние уровни категорий
var expandedCategories = JSON.parse(localStorage.getItem('expandedCategories')) || [];
$('#p-categorytree-portlet .CategoryTreeItem').each(function() {
var categoryName = $(this).text().trim();
if (expandedCategories.includes(categoryName)) {
$(this).find('.CategoryTreeToggle').first().click();
}
});
// Повторно навешиваем обработчики событий
attachCategoryEvents();
}
function attachCategoryEvents() {
console.log("Повторно навешиваем обработчики событий...");
$('body').off('click', '#p-categorytree-portlet .CategoryTreeItem').on('click', '#p-categorytree-portlet .CategoryTreeItem', function(event) {
var $target = $(event.target);
var $item = $(this);
var $toggleButton = $item.find('.CategoryTreeToggle').first();
var isCategory = !$item.find('.CategoryTreePageBullet').length;
if ($target.hasClass('CategoryTreeToggle')) return;
if ($target.is('a') && isCategory) {
event.preventDefault();
$toggleButton.click();
} else if (isCategory) {
$toggleButton.click();
} else {
var link = $item.find('a').attr('href');
if (link) {
saveTreeHTML();
localStorage.setItem('lastOpenedPageTitle', $item.text().trim());
window.location.href = link;
}
}
saveTreeHTML();
});
}
restoreTreeHTML();
function scrollToCategory(categoryTitle, callback) {
var $categoryItem = $('#p-categorytree-portlet .CategoryTreeItem').filter(function() {
return $(this).text().trim() === categoryTitle;
});
if ($categoryItem.length) {
console.log("Категория найдена, перематываем...");
$('#p-categorytree-portlet').animate({
scrollTop: $categoryItem.position().top - 50
}, 500, function() {
$('.CategoryTreeItem').removeClass('highlighted');
$categoryItem.addClass('highlighted');
if (callback) callback(true);
});
localStorage.setItem('highlightedCategory', categoryTitle);
return true;
}
if (callback) callback(false);
return false;
}
function expandAndFindCategory($parent, callback) {
var $toggleButton = $parent.find('.CategoryTreeToggle').first();
if ($toggleButton.length && !$parent.hasClass('expanded')) {
console.log("Раскрываем:", $parent.text().trim());
$toggleButton.click();
setTimeout(function() {
if (scrollToCategory(mw.config.get('wgTitle'))) {
callback(true);
} else {
callback(false);
}
}, 1000);
} else {
callback(false);
}
}
function resetCategoryTree() {
console.log("Категория не найдена. Очищаем данные и сбрасываем дерево.");
localStorage.removeItem('categoryTreeHTML');
localStorage.removeItem('lastOpenedPageTitle');
localStorage.removeItem('highlightedCategory');
localStorage.removeItem('expandedCategories');
// Оставляем верхний уровень категорий открытым
$('#p-categorytree-portlet .CategoryTreeItem').each(function() {
if ($(this).parents('.CategoryTreeChildren').length === 0) {
$(this).find('.CategoryTreeToggle').first().click();
}
});
// Повторно навешиваем обработчики событий
attachCategoryEvents();
}
function recursiveSearchForCategory() {
console.log("Очищаем `localStorage` перед поиском...");
localStorage.removeItem('lastOpenedPageTitle');
localStorage.removeItem('highlightedCategory');
var currentPageTitle = mw.config.get('wgTitle');
if (!currentPageTitle) {
console.log("Не удалось определить текущую страницу.");
return;
}
console.log("Начинаем поиск категории для текущей страницы:", currentPageTitle);
if (scrollToCategory(currentPageTitle)) {
return;
}
var $categoryItems = $('#p-categorytree-portlet .CategoryTreeItem');
if ($categoryItems.length === 0) {
resetCategoryTree();
return;
}
var index = 0;
function processNext() {
if (index >= $categoryItems.length) {
console.log("Категория не найдена. Сбрасываем дерево.");
resetCategoryTree();
return;
}
var $item = $($categoryItems[index]);
expandAndFindCategory($item, function(found) {
if (!found) {
index++;
processNext();
}
});
}
processNext();
}
setTimeout(function() {
recursiveSearchForCategory();
}, 500);
$(window).on('beforeunload', saveTreeHTML);
// Первичная инициализация обработчиков событий
attachCategoryEvents();
});