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

мНет описания правки
Нет описания правки
Метка: ручная отмена
Строка 339: Строка 339:
// Функция для подсветки ячеек в таблице при наведении
// Функция для подсветки ячеек в таблице при наведении
function applyHighlighting() {
function applyHighlighting() {
     // Проверка, является ли устройство мобильным
     // Проверка, является ли устройство мобильным, если да — функция не выполняется
     if (/Mobi|Android/i.test(navigator.userAgent)) {
     if (/Mobi|Android/i.test(navigator.userAgent)) {
         return;
         return;
Строка 353: Строка 353:
         var noHeader = table.classList.contains('no-header-table');
         var noHeader = table.classList.contains('no-header-table');


         if (!tbody) return;
        // Проверяем, что тело таблицы существует
         if (tbody) {
            // Получаем все строки <tr> внутри tbody, исключая строки, содержащие вложенные таблицы
            var rows = Array.prototype.slice.call(tbody.querySelectorAll('tr')).filter(function(row) {
                return !row.querySelector('table');
            });


        // Получаем все строки <tr> внутри tbody, исключая строки с вложенными таблицами
            // Пропускаем первую строку, если нет thead и нет класса 'no-header'
        var rows = Array.prototype.slice.call(tbody.querySelectorAll('tr')).filter(function(row) {
            var topLevelRows = (!thead && !noHeader) ? rows.slice(1) : rows;
            return !row.querySelector('table');
        });


        // Пропускаем первую строку, если нет thead и нет класса 'no-header'
            var hasInvalidRowspan = false;
        var topLevelRows = (!thead && !noHeader) ? rows.slice(1) : rows;
            var hasTooManyRowspan = false;


        // Объект для хранения оригинальных стилей
// Проходим по строкам первого уровня
        var originalStyles = {};
            topLevelRows.forEach(function(row) {
                // Получаем все ячейки строки, исключая те, что имеют класс 'mobile'
                var cells = Array.prototype.slice.call(row.querySelectorAll('td, th')).filter(function(cell) {
                return !cell.classList.contains('mobile');
                });
                var cellCount = cells.length;


        // Сохраняем исходные стили каждой ячейки
                // Проверяем, есть ли больше двух ячеек с атрибутом rowspan
        topLevelRows.forEach(function(row, rowIndex) {
                var rowspanCount = cells.filter(function(cell) {
            var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                    return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1';
                }).length;


            originalStyles[rowIndex] = {};
                // Если в строке больше двух ячеек с rowspan, функция не применяется
            cells.forEach(function(cell, cellIndex) {
                 if (rowspanCount > 2) {
                 originalStyles[rowIndex][cellIndex] = {
                     hasTooManyRowspan = true;
                    backgroundColor: getComputedStyle(cell).backgroundColor,
                    return;
                     color: getComputedStyle(cell).color
                }
                };
            });
        });


        // Объект для хранения подсвеченных ячеек
                // Если строка имеет 3 или меньше ячеек и больше одного rowspan, не применяем функцию
        var highlightedCells = {};
                if (cellCount <= 3 && rowspanCount > 1) {
                    hasTooManyRowspan = true;
                    return;
                }


        // Проходим по каждой строке для добавления событий подсветки
                // Проверяем, есть ли корректные ячейки с rowspan на краю строки (первый или последний элемент)
        topLevelRows.forEach(function(row, rowIndex) {
                var hasValidRowspanEdge = cells.some(function(cell, index) {
            var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                    return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && (index === 0 || index === cells.length - 1);
                });


            cells.forEach(function(cell, cellIndex) {
                // Если ячейки с rowspan находятся не на краю, устанавливаем флаг ошибки
                var rowspan = parseInt(cell.getAttribute('rowspan'), 10) || 1;
                if (!hasValidRowspanEdge && cells.some(function(cell, index) {
                 var cellId = 'row-' + rowIndex + '-cell-' + cellIndex;
                    return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && index > 0 && index < cells.length - 1;
                 })) {
                    hasInvalidRowspan = true;
                }
            });


                // Добавляем обработчик события при наведении мыши
            // Если есть некорректные строки с rowspan или слишком много rowspan, выходим
                cell.addEventListener('mouseover', function() {
            if (hasTooManyRowspan || hasInvalidRowspan) return;
                    if (highlightedCells[cellId]) return;
                    highlightedCells[cellId] = true;


                    // Подсвечиваем текущую ячейку
            // Проходим по каждой строке для добавления событий подсветки
                    cell.style.backgroundColor = brightenColor(getComputedStyle(cell).backgroundColor);
            topLevelRows.forEach(function(row) {
                    cell.style.color = brightenColor(getComputedStyle(cell).color);
                var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                var originalStyles = cells.map(function(cell) {
                    // Сохраняем оригинальные стили каждой ячейки
                    return {
                        backgroundColor: getComputedStyle(cell).backgroundColor,
                        color: getComputedStyle(cell).color
                    };
                });


                    // Подсвечиваем все строки, охватываемые rowspan
                // Добавляем события 'mouseover' и 'mouseout' для подсветки
                     for (var i = rowIndex; i < rowIndex + rowspan; i++) {
                cells.forEach(function(cell, index) {
                        var targetRow = topLevelRows[i];
                     if (cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1') return;
                        if (!targetRow) continue;


                        var targetCells = Array.prototype.slice.call(targetRow.querySelectorAll('td, th'));
                    // Добавляем обработчик события при наведении мыши
                         targetCells.forEach(function(targetCell, targetIndex) {
                    cell.addEventListener('mouseover', function() {
                             var targetCellId = 'row-' + i + '-cell-' + targetIndex;
                         cells.forEach(function(innerCell, innerIndex) {
                            if (!highlightedCells[targetCellId]) {
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
                                 targetCell.style.backgroundColor = brightenColor(getComputedStyle(targetCell).backgroundColor);
                                 // Увеличиваем яркость фона и текста ячейки при наведении
                                 targetCell.style.color = brightenColor(getComputedStyle(targetCell).color);
                                innerCell.style.backgroundColor = brightenColor(originalStyles[innerIndex].backgroundColor);
                                highlightedCells[targetCellId] = true;
                                 innerCell.style.color = brightenColor(originalStyles[innerIndex].color);
                             }
                             }
                         });
                         });
                    }
                    // Подсвечиваем все строки с rowspan в том же столбце
                    topLevelRows.forEach(function(checkRow, checkRowIndex) {
                        if (checkRowIndex === rowIndex) return;
                        var checkCells = Array.prototype.slice.call(checkRow.querySelectorAll('td, th'));
                        var targetCell = checkCells[cellIndex];
                        if (targetCell && targetCell.hasAttribute('rowspan')) {
                            var targetCellId = 'row-' + checkRowIndex + '-cell-' + cellIndex;
                            if (!highlightedCells[targetCellId]) {
                                targetCell.style.backgroundColor = brightenColor(getComputedStyle(targetCell).backgroundColor);
                                targetCell.style.color = brightenColor(getComputedStyle(targetCell).color);
                                highlightedCells[targetCellId] = true;
                            }
                        }
                     });
                     });
                });
                // Добавляем обработчик события, когда мышь уходит с ячейки
                cell.addEventListener('mouseout', function() {
                    if (!highlightedCells[cellId]) return;


                     // Восстанавливаем стили для всех строк, затронутых rowspan
                     // Добавляем обработчик события, когда мышь уходит с ячейки
                     for (var i = rowIndex; i < rowIndex + rowspan; i++) {
                     cell.addEventListener('mouseout', function() {
                        var targetRow = topLevelRows[i];
                         cells.forEach(function(innerCell, innerIndex) {
                        if (!targetRow) continue;
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
 
                                 // Восстанавливаем оригинальные стили после наведения
                        var targetCells = Array.prototype.slice.call(targetRow.querySelectorAll('td, th'));
                                innerCell.style.backgroundColor = originalStyles[innerIndex].backgroundColor;
                         targetCells.forEach(function(targetCell, targetIndex) {
                                 innerCell.style.color = originalStyles[innerIndex].color;
                             var targetCellId = 'row-' + i + '-cell-' + targetIndex;
                            if (highlightedCells[targetCellId]) {
                                 targetCell.style.backgroundColor = originalStyles[i][targetIndex].backgroundColor;
                                 targetCell.style.color = originalStyles[i][targetIndex].color;
                                delete highlightedCells[targetCellId];
                             }
                             }
                         });
                         });
                    }
                    // Восстанавливаем стили в текущем ряду
                    cells.forEach(function(innerCell, innerIndex) {
                        var innerCellId = 'row-' + rowIndex + '-cell-' + innerIndex;
                        if (highlightedCells[innerCellId]) {
                            innerCell.style.backgroundColor = originalStyles[rowIndex][innerIndex].backgroundColor;
                            innerCell.style.color = originalStyles[rowIndex][innerIndex].color;
                            delete highlightedCells[innerCellId];
                        }
                     });
                     });
                 });
                 });
             });
             });
         });
         }
     });
     });
}
}