Mediawiki:common.js

Вернуться

Строка 106: Строка 106:
     };
     };
      
      
var LawTooltipsModule = {
var LawTooltipsModule = {
    init: function() {
    init: function() {
        var tableCells = document.querySelectorAll('.law-tooltips td, .law-tooltips th');
        console.log('[LawTooltips] init()');
        if (tableCells.length === 0) return;
        var tableCells = document.querySelectorAll('.law-tooltips td, .law-tooltips th');
        console.log('[LawTooltips] .law-tooltips ячеек:', tableCells.length);
        function run() {
        if (tableCells.length === 0) {
            var lawData = LawTooltipsModule.extractLawData();
            console.warn('[LawTooltips] Нет ячеек .law-tooltips — выход');
            if (Object.keys(lawData).length > 0) {
            return;
                LawTooltipsModule.initCellTooltips(tableCells, lawData);
        }
                return true;
 
            }
        function run() {
            return false;
            console.log('[LawTooltips] run() — извлечение данных...');
        }
            var lawData = LawTooltipsModule.extractLawData();
            var count = Object.keys(lawData).length;
        MediaWikiTooltips.load(function() {
            console.log('[LawTooltips] Загружено записей законов:', count, count ? Object.keys(lawData).slice(0, 10).join(', ') + (count > 10 ? '...' : '') : '');
            if (run()) return;
            if (count > 0) {
            setTimeout(function() {
                LawTooltipsModule.initCellTooltips(tableCells, lawData);
                if (run()) return;
                return true;
                setTimeout(run, 500);
            }
            }, 300);
            return false;
        });
        }
    },
 
        if (typeof MediaWikiTooltips === 'undefined') {
    extractLawData: function() {
            console.error('[LawTooltips] MediaWikiTooltips не найден — тултипы не загрузятся');
        var lawData = {};
            run();
        var containers = document.querySelectorAll('.mw-collapsible');
            return;
        containers.forEach(function(block) {
        }
            var content = block.querySelector('.mw-collapsible-content');
        MediaWikiTooltips.load(function() {
            if (content && block.classList.contains('mw-collapsed')) {
            console.log('[LawTooltips] MediaWikiTooltips.load вызван');
                block.classList.remove('mw-collapsed');
            if (run()) {
                var toggle = content.querySelector('.mw-collapsible-toggle');
                console.log('[LawTooltips] Инициализация с первой попытки');
                if (toggle) toggle.setAttribute('aria-expanded', 'true');
                return;
            }
            }
        });
            setTimeout(function() {
                if (run()) {
        var detailTables = document.querySelectorAll('.mw-collapsible-content table');
                    console.log('[LawTooltips] Инициализация после 300ms');
        detailTables.forEach(function(table) {
                    return;
            if (table.classList.contains('law-tooltips')) return;
                }
            var rows = table.querySelectorAll('tr');
                setTimeout(function() {
                    if (run()) console.log('[LawTooltips] Инициализация после 800ms');
            rows.forEach(function(row) {
                    else console.warn('[LawTooltips] Данные законов не найдены после всех попыток');
                var cells = row.querySelectorAll('td');
                }, 500);
                if (cells.length < 3) return;
            }, 300);
        });
                var crimeCell = cells[0];
    },
                var descriptionCell = cells[1];
 
                var exampleCell = cells[2];
    extractLawData: function() {
        var lawData = {};
                var anchor = crimeCell.querySelector('[id]');
        var containers = document.querySelectorAll('.mw-collapsible');
                if (!anchor) return;
        console.log('[LawTooltips] extractLawData: коллапсибл-блоков:', containers.length);
        containers.forEach(function(block) {
                var lawCode = anchor.id;
            var content = block.querySelector('.mw-collapsible-content');
                var titleElement = crimeCell.querySelector('b');
            if (content && block.classList.contains('mw-collapsed')) {
                if (!titleElement || !lawCode.match(/^\d{3}$/)) return;
                block.classList.remove('mw-collapsed');
                var toggle = content.querySelector('.mw-collapsible-toggle');
                var titleText = titleElement.textContent.trim();
                if (toggle) toggle.setAttribute('aria-expanded', 'true');
                var lawTitle = titleText.replace(/^\d{3}\s*/, '').replace(/^\d{3}/, '').trim();
            }
                var description = descriptionCell.innerHTML.trim();
        });
 
                var examples = [];
        var detailTables = document.querySelectorAll('.mw-collapsible-content table');
                var exampleItems = exampleCell.querySelectorAll('li');
        console.log('[LawTooltips] extractLawData: таблиц в .mw-collapsible-content:', detailTables.length);
                exampleItems.forEach(function(item) {
        detailTables.forEach(function(table, tableIndex) {
                    var html = item.innerHTML.trim().replace(/<br\s*\/?>/gi, '');
            if (table.classList.contains('law-tooltips')) {
                    if (html) examples.push(html);
                console.log('[LawTooltips] extractLawData: таблица', tableIndex, '— пропуск (law-tooltips)');
                });
                return;
            }
                lawData[lawCode] = {
            var rows = table.querySelectorAll('tr');
                    title: lawTitle,
 
                    description: description,
            rows.forEach(function(row) {
                    examples: examples
                var cells = row.querySelectorAll('td');
                };
                if (cells.length < 3) return;
            });
 
        });
                var crimeCell = cells[0];
                var descriptionCell = cells[1];
        return lawData;
                var exampleCell = cells[2];
    },
 
                var anchor = crimeCell.querySelector('[id]');
    createTooltipContent: function(lawCode, lawData) {
                if (!anchor) return;
        var data = lawData[lawCode];
 
        if (!data) return null;
                var lawCode = anchor.id;
                var titleElement = crimeCell.querySelector('b');
        var html = '<div class="law-tooltip">';
                if (!titleElement || !lawCode.match(/^\d{3}$/)) return;
        html += '<h4 class="law-tooltip-title">' + lawCode + ' - ' + data.title + '</h4>';
 
        html += '<p class="law-tooltip-description">' + data.description + '</p>';
                var titleText = titleElement.textContent.trim();
                var lawTitle = titleText.replace(/^\d{3}\s*/, '').replace(/^\d{3}/, '').trim();
        if (data.examples && data.examples.length > 0) {
                var description = descriptionCell.innerHTML.trim();
            html += '<div class="law-tooltip-examples">';
 
            html += '<strong>Примеры:</strong><ul>';
                var examples = [];
            data.examples.slice(0, 5).forEach(function(example) {
                var exampleItems = exampleCell.querySelectorAll('li');
                html += '<li>' + example + '</li>';
                exampleItems.forEach(function(item) {
            });
                    var html = item.innerHTML.trim().replace(/<br\s*\/?>/gi, '');
            html += '</ul></div>';
                    if (html) examples.push(html);
        }
                });
        html += '</div>';
 
                lawData[lawCode] = {
        return html;
                    title: lawTitle,
    },
                    description: description,
                    examples: examples
    initCellTooltips: function(tableCells, lawData) {
                };
        tableCells.forEach(function(cell) {
            });
            var link = cell.querySelector('a[href*="#"]');
        });
            if (!link) return;
 
        console.log('[LawTooltips] extractLawData: итого кодов:', Object.keys(lawData).length);
            var href = link.getAttribute('href');
        return lawData;
            var match = href.match(/#(\d{3})/);
    },
            if (!match) return;
 
    createTooltipContent: function(lawCode, lawData) {
            var lawCode = match[1];
        var data = lawData[lawCode];
            var tooltipContent = LawTooltipsModule.createTooltipContent(lawCode, lawData);
        if (!data) return null;
            if (!tooltipContent) return;
 
        var html = '<div class="law-tooltip">';
            cell.classList.add('law-cell-with-tooltip');
        html += '<h4 class="law-tooltip-title">' + lawCode + ' - ' + data.title + '</h4>';
        html += '<p class="law-tooltip-description">' + data.description + '</p>';
            cell.addEventListener('click', function(e) {
 
                e.preventDefault();
        if (data.examples && data.examples.length > 0) {
                window.location.hash = lawCode;
            html += '<div class="law-tooltip-examples">';
            });
            html += '<strong>Примеры:</strong><ul>';
            data.examples.slice(0, 5).forEach(function(example) {
            tippy(cell, {
                html += '<li>' + example + '</li>';
                content: tooltipContent,
            });
                allowHTML: true,
            html += '</ul></div>';
                interactive: true,
        }
                placement: 'top',
        html += '</div>';
                maxWidth: 400,
 
                theme: 'law-theme',
        return html;
                arrow: true,
    },
                duration: [200, 150],
 
                delay: [0, 50],
    initCellTooltips: function(tableCells, lawData) {
                appendTo: document.body,
        var withLink = 0, withMatch = 0, withContent = 0, tooltipsCreated = 0;
                boundary: 'viewport',
        tableCells.forEach(function(cell) {
                popperOptions: {
            var link = cell.querySelector('a[href*="#"]');
                    strategy: 'fixed',
            if (!link) return;
                    modifiers: [
            withLink++;
                        {
 
                            name: 'preventOverflow',
            var href = link.getAttribute('href');
                            options: {
            var match = href.match(/#(\d{3})/);
                                boundary: 'viewport',
            if (!match) return;
                                padding: 20,
            withMatch++;
                                altAxis: true,
 
                                altBoundary: true
            var lawCode = match[1];
                            }
            var tooltipContent = LawTooltipsModule.createTooltipContent(lawCode, lawData);
                        },
            if (!tooltipContent) return;
                        {
            withContent++;
                            name: 'flip',
 
                            options: {
            cell.classList.add('law-cell-with-tooltip');
                                fallbackPlacements: ['bottom', 'left', 'right']
            tooltipsCreated++;
                            }
 
                        },
            cell.addEventListener('click', function(e) {
                        {
                e.preventDefault();
                            name: 'computeStyles',
                window.location.hash = lawCode;
                            options: { adaptive: false }
            });
                        }
 
                    ]
            if (typeof tippy === 'undefined') {
                },
                console.error('[LawTooltips] tippy не найден — подключи библиотеку Tippy.js');
                onShow: function(instance) {
                return;
                    document.querySelectorAll('[data-tippy-root]').forEach(function(tooltip) {
            }
                        if (tooltip._tippy && tooltip._tippy !== instance) {
            tippy(cell, {
                            tooltip._tippy.hide();
                content: tooltipContent,
                        }
                allowHTML: true,
                    });
                interactive: true,
                }
                placement: 'top',
            });
                maxWidth: 400,
        });
                theme: 'law-theme',
    }
                arrow: true,
};
                duration: [200, 150],
                delay: [0, 50],
                appendTo: document.body,
                boundary: 'viewport',
                popperOptions: {
                    strategy: 'fixed',
                    modifiers: [
                        {
                            name: 'preventOverflow',
                            options: {
                                boundary: 'viewport',
                                padding: 20,
                                altAxis: true,
                                altBoundary: true
                            }
                        },
                        {
                            name: 'flip',
                            options: {
                                fallbackPlacements: ['bottom', 'left', 'right']
                            }
                        },
                        {
                            name: 'computeStyles',
                            options: { adaptive: false }
                        }
                    ]
                },
                onShow: function(instance) {
                    document.querySelectorAll('[data-tippy-root]').forEach(function(tooltip) {
                        if (tooltip._tippy && tooltip._tippy !== instance) {
                            tooltip._tippy.hide();
                        }
                    });
                }
            });
        });
        console.log('[LawTooltips] initCellTooltips: ячеек с ссылкой', withLink, '| с #XXX', withMatch, '| с данными', withContent, '| тултипов создано', tooltipsCreated);
    }
};