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

Нет описания правки
мНет описания правки
Строка 564: Строка 564:
// Функция для логики меню создаваемым модулем CategoryMenu
// Функция для логики меню создаваемым модулем CategoryMenu
function initCategorySwitcher() {
function initCategorySwitcher() {
var categories = document.querySelectorAll('.categories div');
    var categories = document.querySelectorAll('.categories div');
var menus = document.querySelectorAll('.menu');
    var menus = document.querySelectorAll('.menu');
var contentDivs = document.querySelectorAll('.content div');
    var contentDivs = document.querySelectorAll('.content div');
var menuItems = document.querySelectorAll('.menu div');
    var menuItems = document.querySelectorAll('.menu div');
var currentCategoryIndex = 0; // Индекс текущей активной категории
    var currentCategoryIndex = 0; // Индекс текущей активной категории


// Устанавливаем ID для категорий
    // Устанавливаем ID для категорий
categories.forEach(function(category, index) {
    categories.forEach(function(category, index) {
var categoryText = category.textContent.trim().toLowerCase().replace(/\s+/g, '-'); // Преобразуем текст в id
        var categoryText = category.textContent.trim().toLowerCase().replace(/\s+/g, '-'); // Преобразуем текст в id
category.id = categoryText || 'category-' + index; // Если текста нет, используем индекс
        category.id = categoryText || 'category-' + index; // Если текста нет, используем индекс
});
    });


// Устанавливаем ID для пунктов меню
    // Устанавливаем ID для пунктов меню
menuItems.forEach(function(menuItem, index) {
    menuItems.forEach(function(menuItem, index) {
var menuItemText = menuItem.textContent.trim().toLowerCase().replace(/\s+/g, '-'); // Преобразуем текст в id
        var menuItemText = menuItem.textContent.trim().toLowerCase().replace(/\s+/g, '-'); // Преобразуем текст в id
menuItem.id = menuItemText || 'menu-item-' + index; // Если текста нет, используем индекс
        menuItem.id = menuItemText || 'menu-item-' + index; // Если текста нет, используем индекс
});
    });


function clearActiveContent() {
    function clearActiveContent() {
for (var i = 0; i < contentDivs.length; i++) {
        for (var i = 0; i < contentDivs.length; i++) {
contentDivs[i].classList.remove('active');
            contentDivs[i].classList.remove('active');
}
        }
}
    }


function clearActiveMenu() {
    function clearActiveMenu() {
for (var i = 0; i < menus.length; i++) {
        for (var i = 0; i < menus.length; i++) {
menus[i].classList.remove('active');
            menus[i].classList.remove('active');
}
        }
}
    }


function clearActiveMenuItems() {
    function clearActiveMenuItems() {
for (var i = 0; i < menuItems.length; i++) {
        for (var i = 0; i < menuItems.length; i++) {
menuItems[i].classList.remove('active');
            menuItems[i].classList.remove('active');
}
        }
}
    }


function switchCategory(index) {
    function switchCategory(index) {
clearActiveMenu();
        if (categories.length === 0 || menus.length === 0) return; // Защита от пустых данных
clearActiveContent();


categories.forEach(function(category) {
        clearActiveMenu();
category.classList.remove('active');
        clearActiveContent();
});


var selectedCategory = categories[index];
        categories.forEach(function(category) {
if (selectedCategory) {
            category.classList.remove('active');
selectedCategory.classList.add('active');
        });
var categoryClass = selectedCategory.classList[0];
var selectedMenu = document.querySelector('.' + categoryClass + '-menu');
if (selectedMenu) {
selectedMenu.classList.add('active');
var firstParagraph = selectedMenu.querySelector('div');
if (firstParagraph) {
switchContent(firstParagraph);
}
}
}


currentCategoryIndex = index;
        var selectedCategory = categories[index];
updateArrowStates(); // Обновляем состояние стрелок
        if (selectedCategory) {
}
            selectedCategory.classList.add('active');
            var categoryClass = selectedCategory.classList[0];
            var selectedMenu = document.querySelector('.' + categoryClass + '-menu');
            if (selectedMenu) {
                selectedMenu.classList.add('active');
                var firstParagraph = selectedMenu.querySelector('div');
                if (firstParagraph) {
                    switchContent(firstParagraph);
                }
            }
        }


function switchContent(menuItem) {
        currentCategoryIndex = index;
clearActiveMenuItems();
        updateArrowStates(); // Обновляем состояние стрелок
clearActiveContent();
    }
var contentClass = menuItem.className + '-content';
var content = document.querySelector('.' + contentClass);
if (content) {
content.classList.add('active');
menuItem.classList.add('active');
}
}


// Обновляем состояние стрелок (активные/неактивные)
    function switchContent(menuItem) {
function updateArrowStates() {
        clearActiveMenuItems();
const prevArrow = document.getElementById('prev-category');
        clearActiveContent();
const nextArrow = document.getElementById('next-category');
        var contentClass = menuItem.className + '-content';
        var content = document.querySelector('.' + contentClass);
        if (content) {
            content.classList.add('active');
            menuItem.classList.add('active');
        }
    }


if (currentCategoryIndex === 0) {
    // Обновляем состояние стрелок (активные/неактивные)
prevArrow.classList.add('disabled');
    function updateArrowStates() {
prevArrow.style.pointerEvents = 'none'; // Отключаем клики
        const prevArrow = document.getElementById('prev-category');
} else {
        const nextArrow = document.getElementById('next-category');
prevArrow.classList.remove('disabled');
prevArrow.style.pointerEvents = 'auto'; // Включаем клики
}


if (currentCategoryIndex === categories.length - 1) {
        if (currentCategoryIndex === 0) {
nextArrow.classList.add('disabled');
            prevArrow.classList.add('disabled');
nextArrow.style.pointerEvents = 'none';
            prevArrow.style.pointerEvents = 'none'; // Отключаем клики
} else {
        } else {
nextArrow.classList.remove('disabled');
            prevArrow.classList.remove('disabled');
nextArrow.style.pointerEvents = 'auto';
            prevArrow.style.pointerEvents = 'auto'; // Включаем клики
}
        }
}


// Функция для обработки якорей
        if (currentCategoryIndex === categories.length - 1) {
function handleAnchorLink() {
            nextArrow.classList.add('disabled');
var hash = window.location.hash.substring(1); // Получаем якорь без '#'
            nextArrow.style.pointerEvents = 'none';
        } else {
if (hash) {
            nextArrow.classList.remove('disabled');
var categoryIndex = Array.from(categories).findIndex(category => category.id === hash);
            nextArrow.style.pointerEvents = 'auto';
if (categoryIndex !== -1) {
        }
switchCategory(categoryIndex);
    }
return;
}


var menuItem = document.querySelector('.menu div[id="' + hash + '"]');
    // Функция для обработки якорей
if (menuItem) {
    function handleAnchorLink() {
var categoryClass = menuItem.closest('.menu').classList[0].replace('-menu', '');
        var hash = window.location.hash.substring(1); // Получаем якорь без '#'
var categoryIndex = Array.from(categories).findIndex(category => category.classList.contains(categoryClass));
       
if (categoryIndex !== -1) {
        if (hash) {
switchCategory(categoryIndex);
            var categoryIndex = Array.from(categories).findIndex(category => category.id === hash);
switchContent(menuItem);
            if (categoryIndex !== -1) {
}
                switchCategory(categoryIndex);
}
                return;
}
            }
}


// Стрелки для переключения категорий
            var menuItem = document.querySelector('.menu div[id="' + hash + '"]');
document.getElementById('prev-category').addEventListener('click', function() {
            if (menuItem) {
if (currentCategoryIndex > 0) {
                var categoryClass = menuItem.closest('.menu').classList[0].replace('-menu', '');
currentCategoryIndex = currentCategoryIndex - 1;
                var categoryIndex = Array.from(categories).findIndex(category => category.classList.contains(categoryClass));
switchCategory(currentCategoryIndex); // Переключаем на новую категорию
                if (categoryIndex !== -1) {
}
                    switchCategory(categoryIndex);
});
                    switchContent(menuItem);
                }
            }
        }
    }


document.getElementById('next-category').addEventListener('click', function() {
    // Стрелки для переключения категорий
if (currentCategoryIndex < categories.length - 1) {
    document.getElementById('prev-category').addEventListener('click', function() {
currentCategoryIndex = currentCategoryIndex + 1;
        if (currentCategoryIndex > 0) {
switchCategory(currentCategoryIndex); // Переключаем на новую категорию
            currentCategoryIndex = currentCategoryIndex - 1;
}
            switchCategory(currentCategoryIndex); // Переключаем на новую категорию
});
        }
    });


// Инициализация: открываем первую категорию и первый пункт
    document.getElementById('next-category').addEventListener('click', function() {
if (categories.length > 0) {
        if (currentCategoryIndex < categories.length - 1) {
switchCategory(currentCategoryIndex); // Отображаем первую категорию
            currentCategoryIndex = currentCategoryIndex + 1;
updateArrowStates(); // Обновляем состояние стрелок
            switchCategory(currentCategoryIndex); // Переключаем на новую категорию
}
        }
    });


categories.forEach(function(category) {
    // Инициализация: открываем первую категорию и первый пункт
category.addEventListener('click', function(event) {
    if (categories.length > 0 && menus.length > 0) {
event.preventDefault(); // Предотвращаем любое действие при клике
        switchCategory(0); // Отображаем первую категорию и первый пункт
});
        updateArrowStates(); // Обновляем состояние стрелок
});
    }


for (var i = 0; i < menuItems.length; i++) {
    categories.forEach(function(category) {
menuItems[i].addEventListener('click', function() {
        category.addEventListener('click', function(event) {
switchContent(this);
            event.preventDefault(); // Предотвращаем любое действие при клике
});
        });
}
    });


document.querySelector('.menu-toggle').addEventListener('click', function() {
    for (var i = 0; i < menuItems.length; i++) {
var menu = document.querySelector('.menu-container');
        menuItems[i].addEventListener('click', function() {
menu.classList.toggle('active');
            switchContent(this);
var toggleButton = document.querySelector('.menu-toggle');
        });
toggleButton.classList.toggle('active');
    }
});


handleAnchorLink();
    document.querySelector('.menu-toggle').addEventListener('click', function() {
        var menu = document.querySelector('.menu-container');
        menu.classList.toggle('active');
        var toggleButton = document.querySelector('.menu-toggle');
        toggleButton.classList.toggle('active');
    });


window.addEventListener('hashchange', handleAnchorLink);
    handleAnchorLink();
 
    window.addEventListener('hashchange', handleAnchorLink);
}
}
const currentPageTitle = document.title;
const currentPageTitle = document.title;