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

Материал из Тестовая Абсурдопедии
Перейти к навигации Перейти к поиску
Нет описания правки
Нет описания правки
Строка 116: Строка 116:


     function createSafeLink(url, text, title) {
     function createSafeLink(url, text, title) {
        // [FIX 4] Используем sanitizeUrl вместо проверки через includes().
         var safeUrl = sanitizeUrl(url) || '#';
         var safeUrl = sanitizeUrl(url) || '#';


Строка 617: Строка 616:
                 timer = null;
                 timer = null;
             }
             }
            // [FIX 6] очищаем и setTimeout
 
             if (selectionTimer) {
             if (selectionTimer) {
                 clearTimeout(selectionTimer);
                 clearTimeout(selectionTimer);
Строка 660: Строка 659:
         document.addEventListener('touchend', touchHandler);
         document.addEventListener('touchend', touchHandler);


        // [FIX 6] сохраняем id таймера в модульную переменную, cleanup его снимет
         selectionTimer = setTimeout(function() {
         selectionTimer = setTimeout(function() {
             if (selectionActive) {
             if (selectionActive) {

Версия от 22:05, 4 ноября 2026

/**
 * Gadget: Blame Finder
 * Версия 2.0 с поддержкой ночного режима
 * Назначение: поиск автора любого текста в статье
 * Локализация под wiki.peresvet.artushak.ru, лицензия: CC BY-SA 4.0
 * Использование:
  1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
  2. Выделяете любой текст на странице (минимум 20 символов)
  3. Кликайте по появившейся в центре кнопке таймера (20 секунд на всё)
  4. Гаджет анализирует последние 1000 правок страницы
  5. Находит первое появление этого текста в истории
  6. Показывает:
   · Имя автора
   · Дату правки
   · Комментарий к правке
   · Ссылки на версию и diff
 * Что может:
  · Искать авторов фрагментов текста в статьях
  · Расчитан на работу в пространствах статей и форума
  · Поддерживает мышь и сенсорный экран
  · Показывает панель логов с отладкой
 */

(function() {
    'use strict';

    if (window.self !== window.top) {
        console.log('BlameFinder: не запускаемся в iframe по соображениям безопасности');
        return;
    }

    var scriptPath = '/w';
    try {
        if (typeof mw !== 'undefined' && mw.config && mw.config.get) {
            scriptPath = mw.config.get('wgScriptPath') || '/w';
        }
    } catch (e) {
        scriptPath = '/w';
    }

    function escapeText(text, escapeSlash) {
        if (text === undefined || text === null) return '';
        var s = String(text)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
        if (escapeSlash) {
            s = s.replace(/\//g, '&#x2F;');
        }
        return s;
    }

    function escapeHtml(text) {
        return escapeText(text, true);
    }

    function escapeForLog(text) {
        return escapeText(text, false);
    }

    function sanitizeUrl(url) {
        if (!url || typeof url !== 'string') return null;
        var trimmed = url.trim();
        if (trimmed === '') return null;

        // Разрешаем только относительные пути, якоря и абсолютные http(s).
        if (trimmed.charAt(0) === '/' || trimmed.charAt(0) === '#') {
            return trimmed;
        }

        try {
            var parsed = new URL(trimmed, window.location.origin);
            if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
                return trimmed;
            }
        } catch (e) {
        }
        return null;
    }

    function createSafeElement(tag, options) {
        var element = document.createElement(tag);

        if (!options) return element;

        if (options.className) element.className = options.className;
        if (options.id) element.id = options.id;
        if (options.text) element.textContent = options.text;
        if (options.html) {
            element.textContent = options.html;
        }

        if (options.css) {
            Object.keys(options.css).forEach(function(prop) {
                element.style[prop] = options.css[prop];
            });
        }

        if (options.attrs) {
            Object.keys(options.attrs).forEach(function(key) {
                if (key === 'href' || key === 'src') {
                    var safe = sanitizeUrl(options.attrs[key]);
                    if (safe !== null) {
                        element.setAttribute(key, safe);
                    }
                } else {
                    element.setAttribute(key, options.attrs[key]);
                }
            });
        }

        return element;
    }

    function createSafeLink(url, text, title) {
        var safeUrl = sanitizeUrl(url) || '#';

        var link = createSafeElement('a', {
            text: text,
            attrs: {
                href: safeUrl,
                target: '_blank',
                rel: 'noopener noreferrer',
                title: title ? escapeHtml(title) : escapeHtml(text)
            }
        });

        return link;
    }

    function validateTitle(title) {
        if (!title || typeof title !== 'string') return null;
        var cleaned = title.replace(/[\x00-\x1F\x7F<>"']/g, '').trim();
        return cleaned.length > 0 ? cleaned : null;
    }

    function isDarkTheme() {
        try {
            var html = document.documentElement;
            var body = document.body;

            if (html.classList.contains('skin-theme-clientpref-night')) return true;
            if (html.classList.contains('skin-theme-clientpref-day')) return false;
            if (html.classList.contains('skin-theme-clientpref-os')) {
                return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            }

            var dataTheme = (html.getAttribute('data-theme') || '') + ' ' +
                            (body ? (body.getAttribute('data-theme') || '') : '');
            if (/dark|night/i.test(dataTheme)) return true;
            if (/light|day/i.test(dataTheme)) return false;

            if (body) {
                var bg = window.getComputedStyle(body).backgroundColor;
                var m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
                if (m) {
                    var r = parseInt(m[1], 10);
                    var g = parseInt(m[2], 10);
                    var b = parseInt(m[3], 10);
                    var luminance = (0.299 * r + 0.587 * g + 0.114 * b);
                    if (luminance < 128) return true;
                    if (luminance >= 128) return false;
                }
            }
        } catch (e) {}
        return false;
    }

    function getPageInfo() {
        var title = null;
        var namespace = 0;
        var isSpecial = false;

        var pathname = window.location.pathname || '';
        var search = window.location.search || '';

        var excludedNamespaces = [
            'обсуждение', 'talk', 'участник', 'user', 'user_talk',
            'обсуждение_участника', 'файл', 'file', 'file_talk',
            'обсуждение_файла', 'mediawiki', 'mediawiki_talk',
            'обсуждение_mediawiki', 'шаблон', 'template',
            'template_talk', 'обсуждение_шаблона', 'справка',
            'help', 'help_talk', 'обсуждение_справки', 'категория',
            'category', 'category_talk', 'обсуждение_категории',
            'портал', 'portal', 'portal_talk', 'обсуждение_портала',
            'special', 'служебная'
        ];

        function classifyTitle(candidate) {
            if (!candidate) return;
            if (candidate.indexOf(':') !== -1) {
                var prefix = candidate.split(':')[0].toLowerCase();
                if (excludedNamespaces.indexOf(prefix) !== -1) {
                    namespace = 1;
                }
                if (prefix === 'special' || prefix === 'служебная') {
                    isSpecial = true;
                }
            }
        }

        try {
            var urlParams = new URLSearchParams(search);
            var paramTitle = urlParams.get('title');

            if (paramTitle) {
                paramTitle = validateTitle(paramTitle);
                if (paramTitle) {
                    classifyTitle(paramTitle);
                    title = paramTitle;
                }
            }

            if (!title) {
                if (/special:|служебная:/i.test(pathname)) {
                    isSpecial = true;
                }

                if (pathname.indexOf('/wiki/') !== -1) {
                    var pathTitle = pathname.split('/wiki/')[1];
                    if (pathTitle) {
                        try {
                            pathTitle = decodeURIComponent(pathTitle);
                        } catch (e) {}

                        pathTitle = pathTitle.split('?')[0].split('#')[0];

                        classifyTitle(pathTitle);
                        title = validateTitle(pathTitle);
                    }
                } else {
                    var segments = pathname.split('/').filter(function(s) {
                        return s.length > 0;
                    });

                    if (segments.length > 0) {
                        var rootTitle = segments[segments.length - 1];
                        try {
                            rootTitle = decodeURIComponent(rootTitle);
                        } catch (e) {}

                        rootTitle = rootTitle.split('?')[0].split('#')[0];

                        classifyTitle(rootTitle);
                        title = validateTitle(rootTitle);
                    }
                }
            }

            if (!title) {
                var h1 = document.querySelector('h1.firstHeading, .firstHeading, #firstHeading');
                if (h1 && h1.textContent) {
                    title = validateTitle(h1.textContent.trim());
                }
            }
        } catch (e) {
            console.log('BlameFinder: ошибка получения информации о странице', e);
        }

        return {
            title: title || 'Main_Page',
            isArticle: namespace === 0 && !isSpecial
        };
    }

    function absApiRequest(params, callback, errorCallback) {
        var apiUrl = scriptPath + '/api.php';
        params.format = 'json';

        var safeParams = {};
        Object.keys(params).forEach(function(key) {
            var value = params[key];
            if (typeof value === 'string') {
                safeParams[key] = value.replace(/[<>"']/g, '');
            } else {
                safeParams[key] = value;
            }
        });

        var queryString = Object.keys(safeParams).map(function(key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(safeParams[key]);
        }).join('&');

        var url = apiUrl + '?' + queryString;
        var xhr = new XMLHttpRequest();
        var timeoutId = null;
        var completed = false;

        timeoutId = setTimeout(function() {
            if (!completed) {
                completed = true;
                xhr.abort();
                addLog('Таймаут API: сервер не отвечает', 'error');
                if (errorCallback) errorCallback('timeout');
            }
        }, 15000);

        xhr.open('GET', url, true);
        xhr.setRequestHeader('Api-User-Agent', 'BlameFinder/1.2');

        xhr.onreadystatechange = function() {
            if (completed) return;

            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var contentType = xhr.getResponseHeader('Content-Type') || '';
                    if (contentType.indexOf('application/json') === -1 &&
                        contentType.indexOf('text/javascript') === -1) {
                        clearTimeout(timeoutId);
                        completed = true;
                        addLog('Неверный Content-Type ответа API', 'error');
                        if (errorCallback) errorCallback('invalid_content_type');
                        return;
                    }

                    try {
                        var data = JSON.parse(xhr.responseText);
                        if (!data || typeof data !== 'object') {
                            throw new Error('Invalid response format');
                        }
                        clearTimeout(timeoutId);
                        completed = true;
                        callback(data);
                    } catch (e) {
                        clearTimeout(timeoutId);
                        completed = true;
                        addLog('Ошибка парсинга ответа API', 'error');
                        if (errorCallback) errorCallback('parse_error');
                    }
                } else {
                    clearTimeout(timeoutId);
                    completed = true;
                    addLog('Ошибка HTTP: ' + xhr.status, 'error');
                    if (errorCallback) errorCallback('http_' + xhr.status);
                }
            }
        };

        xhr.onerror = function() {
            if (!completed) {
                clearTimeout(timeoutId);
                completed = true;
                addLog('Ошибка сети при запросе к API', 'error');
                if (errorCallback) errorCallback('network_error');
            }
        };

        xhr.send();
    }

    var logPanel = null;
    var logEntries = [];

    function createLogPanel() {
        if (logPanel) return;

        logPanel = createSafeElement('div', {
            id: 'blame-log-panel',
            css: {
                position: 'fixed',
                bottom: '20px',
                left: '20px',
                width: '400px',
                maxHeight: '300px',
                overflowY: 'auto',
                background: 'rgba(0,0,0,0.9)',
                color: '#0f0',
                fontFamily: 'monospace',
                fontSize: '12px',
                padding: '10px',
                borderRadius: '5px',
                zIndex: '9999',
                border: '2px solid #36c',
                boxShadow: '0 0 20px rgba(0,0,0,0.5)',
                display: 'none'
            }
        });

        var header = createSafeElement('div', {
            css: {
                display: 'flex',
                justifyContent: 'space-between',
                marginBottom: '10px',
                paddingBottom: '5px',
                borderBottom: '2px solid #36c'
            }
        });

        var titleSpan = createSafeElement('span', {
            text: 'Логи BlameFinder',
            css: {
                color: '#36c',
                fontWeight: 'bold'
            }
        });

        var buttonContainer = createSafeElement('div');

        var clearButton = createSafeElement('button', {
            id: 'blame-clear',
            className: 'blame-log-btn',
            text: 'Очистить',
            css: {
                background: 'none',
                border: '1px solid #36c',
                color: '#36c',
                marginRight: '5px',
                cursor: 'pointer',
                padding: '5px'
            }
        });

        var toggleButton = createSafeElement('button', {
            id: 'blame-toggle',
            className: 'blame-log-btn',
            text: 'Скрыть',
            css: {
                background: 'none',
                border: '1px solid #36c',
                color: '#36c',
                cursor: 'pointer',
                padding: '5px'
            }
        });

        ['color', 'border-color'].forEach(function(prop) {
            clearButton.style.setProperty(prop, '#36c', 'important');
            toggleButton.style.setProperty(prop, '#36c', 'important');
        });
        clearButton.style.setProperty('background', 'none', 'important');
        toggleButton.style.setProperty('background', 'none', 'important');

        buttonContainer.appendChild(clearButton);
        buttonContainer.appendChild(toggleButton);
        header.appendChild(titleSpan);
        header.appendChild(buttonContainer);

        var content = createSafeElement('div', {
            id: 'blame-log-content',
            css: {
                wordBreak: 'break-word'
            }
        });

        logPanel.appendChild(header);
        logPanel.appendChild(content);
        document.body.appendChild(logPanel);

        clearButton.onclick = function(e) {
            e.stopPropagation();
            logEntries = [];
            updateLogDisplay();
        };

        var logVisible = true;
        toggleButton.onclick = function(e) {
            e.stopPropagation();
            logVisible = !logVisible;
            logPanel.style.display = logVisible ? 'block' : 'none';
            toggleButton.textContent = logVisible ? 'Скрыть' : 'Показать';
        };

        logPanel.style.display = 'block';
    }

    function addLog(message, type) {
        var timestamp = new Date().toLocaleTimeString('ru', {
            timeZoneName: 'short'
        });
        var color = '#0f0';
        if (type === 'error') color = '#f00';
        if (type === 'warning') color = '#ff0';
        if (type === 'success') color = '#0f0';

        var safeMessage = escapeForLog(String(message));

        logEntries.unshift({
            time: timestamp,
            text: safeMessage,
            color: color
        });

        if (logEntries.length > 30) logEntries.pop();
        updateLogDisplay();
    }

    function updateLogDisplay() {
        var content = document.getElementById('blame-log-content');
        if (!content) return;

        while (content.firstChild) {
            content.removeChild(content.firstChild);
        }

        logEntries.forEach(function(entry) {
            var entryDiv = createSafeElement('div', {
                css: {
                    color: entry.color,
                    marginBottom: '3px'
                }
            });

            entryDiv.textContent = '[' + entry.time + '] ' + entry.text;
            content.appendChild(entryDiv);
        });
    }

    function addButton() {
        addLog('Инициализация BlameFinder для wiki.peresvet.artushak.ru', 'info');

        var button = createSafeElement('div', {
            id: 'blame-finder-button',
            text: 'Кто автор?',
            css: {
                position: 'fixed',
                bottom: '20px',
                right: '20px',
                background: '#36c',
                color: 'white',
                padding: '10px 20px',
                borderRadius: '5px',
                cursor: 'pointer',
                zIndex: '9999',
                fontFamily: 'sans-serif',
                fontSize: '14px',
                boxShadow: '0 2px 10px rgba(0,0,0,0.3)'
            }
        });

        button.onmouseover = function() {
            this.style.background = '#447ff5';
        };

        button.onmouseout = function() {
            this.style.background = '#36c';
        };

        button.addEventListener('click', function(e) {
            e.preventDefault();
            activateSelectionMode();
        });

        document.body.appendChild(button);
        addLog('Кнопка добавлена в правый нижний угол', 'success');
        createLogPanel();
    }

    var selectionActive = false;
    var selectionTimer = null;

    function activateSelectionMode() {
        if (selectionActive) {
            addLog('Режим выделения уже активен', 'warning');
            return;
        }

        selectionActive = true;
        addLog('Режим выделения активирован', 'info');
        addLog('Выделите текст (мышью или касанием)', 'info');

        var tooltip = createSafeElement('div', {
            id: 'blame-tooltip',
            css: {
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                background: '#36c',
                color: 'white',
                padding: '20px 40px',
                borderRadius: '10px',
                zIndex: '10000',
                fontFamily: 'sans-serif',
                fontSize: '18px',
                textAlign: 'center',
                boxShadow: '0 0 30px rgba(0,0,0,0.5)'
            }
        });

        tooltip.appendChild(document.createTextNode('Выделите текст'));
        tooltip.appendChild(document.createElement('br'));

        var small = createSafeElement('small', {
            css: { color: '#ff0' }
        });
        small.appendChild(document.createTextNode('осталось '));

        var timerSpan = createSafeElement('span', {
            id: 'blame-timer',
            text: '20',
            css: { color: '#ff0' }
        });
        small.appendChild(timerSpan);
        small.appendChild(document.createTextNode(' секунд'));

        tooltip.appendChild(small);
        document.body.appendChild(tooltip);

        var seconds = 20;
        var timer = setInterval(function() {
            seconds--;
            var timerSpanEl = document.getElementById('blame-timer');
            if (timerSpanEl) timerSpanEl.textContent = seconds;
        }, 1000);

        function cleanup() {
            selectionActive = false;

            document.removeEventListener('mouseup', mouseHandler);
            document.removeEventListener('touchend', touchHandler);

            if (timer) {
                clearInterval(timer);
                timer = null;
            }

            if (selectionTimer) {
                clearTimeout(selectionTimer);
                selectionTimer = null;
            }

            var tip = document.getElementById('blame-tooltip');
            if (tip && tip.parentNode) {
                tip.parentNode.removeChild(tip);
            }
        }

        function mouseHandler() {
            if (!selectionActive) return;
            handleSelection();
        }

        function touchHandler() {
            if (!selectionActive) return;
            setTimeout(handleSelection, 100);
        }

        function handleSelection() {
            if (!selectionActive) return;

            var selection = window.getSelection();
            var selectedText = selection.toString().trim();

            if (selectedText.length >= 20) {
                var logText = 'Выделен текст (' + selectedText.length + ' символов): "' +
                             selectedText.substring(0, 50) +
                             (selectedText.length > 50 ? '..."' : '"');
                addLog(logText, 'success');
                cleanup();
                findAuthor(selectedText);
            } else if (selectedText.length > 0) {
                addLog('Слишком короткий текст (' + selectedText.length + ' символов, нужно минимум 20)', 'warning');
            }
        }

        document.addEventListener('mouseup', mouseHandler);
        document.addEventListener('touchend', touchHandler);

        selectionTimer = setTimeout(function() {
            if (selectionActive) {
                addLog('Время вышло', 'warning');
                cleanup();
                addLog('Режим выделения отключён', 'info');
            }
        }, 20000);

        var origCleanup = cleanup;
        cleanup = function() {
            origCleanup();
            addLog('Режим выделения отключён', 'info');
        };
    }

    function findAuthor(text) {
        var pageInfo = getPageInfo();
        var title = pageInfo.title;

        addLog('Начинаем поиск для страницы: ' + escapeForLog(title), 'info');

        var logText = 'Ищем текст: "' + text.substring(0, 100) +
                     (text.length > 100 ? '..."' : '"');
        addLog(logText, 'info');

        var loadingDiv = showLoading('Анализирую историю правок...');
        addLog('Запрашиваем историю правок через API', 'info');

        var globalTimeout = setTimeout(function() {
            hideLoading(loadingDiv);
            addLog('Глобальный таймаут: сервер не отвечает', 'error');
        }, 15000);

        getRevisions(title, function(revisions) {
            clearTimeout(globalTimeout);
            addLog('Получено ревизий: ' + revisions.length, 'info');

            if (revisions.length === 0) {
                addLog('Не удалось загрузить историю правок', 'error');
                hideLoading(loadingDiv);
                return;
            }

            addLog('Начинаем поиск первого появления текста...', 'info');

            findTextAppearance(revisions, text, title, function(result) {
                hideLoading(loadingDiv);

                if (result) {
                    addLog('Текст найден! Автор: ' + escapeForLog(result.rev.user), 'success');
                    showResult(result);
                } else {
                    addLog('Текст не найден в истории', 'error');
                }
            });
        }, function(error) {
            clearTimeout(globalTimeout);
            hideLoading(loadingDiv);
            addLog('Ошибка при запросе к API: ' + error, 'error');
        });
    }

    function getRevisions(title, callback, errorCallback) {
        var revisions = [];
        var continueParam = {};
        var totalFetched = 0;
        var maxRevisions = 1000;

        function fetchRevisions() {
            var params = {
                action: 'query',
                prop: 'revisions',
                titles: title,
                rvprop: 'ids|timestamp|user|comment|content',
                rvlimit: 50,
                rvdir: 'older',
                rvslots: 'main',
                formatversion: 2
            };

            if (continueParam.rvcontinue) {
                if (typeof continueParam.rvcontinue === 'string') {
                    params.rvcontinue = continueParam.rvcontinue.replace(/[<>"']/g, '');
                }
            }

            absApiRequest(params, function(data) {
                if (data.error) {
                    addLog('Ошибка API: ' + escapeForLog(data.error.info), 'error');
                    if (errorCallback) errorCallback(data.error.info);
                    return;
                }

                if (!data.query || !data.query.pages || !data.query.pages[0]) {
                    addLog('Странный ответ от API', 'error');
                    if (errorCallback) errorCallback('invalid_response');
                    return;
                }

                var page = data.query.pages[0];

                if (page.missing) {
                    addLog('Страница не найдена в API', 'error');
                    if (errorCallback) errorCallback('page_missing');
                    return;
                }

                if (page.revisions && page.revisions.length > 0) {
                    page.revisions.forEach(function(rev) {
                        revisions.push({
                            revid: rev.revid || 0,
                            timestamp: rev.timestamp || '',
                            user: (rev.user && typeof rev.user === 'string') ? rev.user : 'Аноним',
                            comment: (rev.comment && typeof rev.comment === 'string') ? rev.comment : '—',
                            content: (rev.slots && rev.slots.main && rev.slots.main.content) ?
                                    rev.slots.main.content : ''
                        });
                    });

                    totalFetched += page.revisions.length;
                    addLog('Загружено ревизий: ' + totalFetched + '/' + maxRevisions, 'info');
                } else {
                    addLog('У страницы нет истории правок', 'warning');
                    callback(revisions);
                    return;
                }

                if (data.continue && totalFetched < maxRevisions) {
                    continueParam = {
                        rvcontinue: data.continue.rvcontinue
                    };
                    fetchRevisions();
                } else {
                    if (totalFetched >= maxRevisions) {
                        addLog('Достигнут лимит загрузки (' + maxRevisions + ' ревизий)', 'warning');
                    }
                    callback(revisions);
                }
            }, errorCallback);
        }

        fetchRevisions();
    }

    function findTextAppearance(revisions, text, title, callback) {
        var oldestFirst = revisions.slice().reverse();
        addLog('Анализируем ' + oldestFirst.length + ' ревизий от старых к новым', 'info');

        var foundRev = null;
        var checkedCount = 0;

        for (var i = 0; i < oldestFirst.length; i++) {
            var rev = oldestFirst[i];
            var content = rev.content || '';
            checkedCount++;

            if (checkedCount % 50 === 0) {
                addLog('Проверено ' + checkedCount + '/' + oldestFirst.length + ' ревизий...', 'info');
            }

            if (content.indexOf(text) === -1) {
                continue;
            }

            addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info');

            if (i === 0) {
                // Текст есть в самой первой ревизии — автор первый.
                foundRev = rev;
                addLog('Текст есть в самой первой ревизии страницы', 'info');
                break;
            }

            var previousContent = oldestFirst[i - 1].content || '';
            if (previousContent.indexOf(text) === -1) {
                // Текст появился именно в этой правке.
                foundRev = rev;
                addLog('Найдено первое появление! Ревизия: ' + rev.revid, 'success');
                break;
            }

            addLog('Текст был и в предыдущей ревизии, продолжаем поиск...', 'info');
        }

        if (!foundRev) {
            addLog('Текст не найден ни в одной ревизии', 'error');
            callback(null);
            return;
        }

        callback({ rev: foundRev, title: title });
    }

    function showResult(result) {
        var rev = result.rev;
        var title = result.title;

        var date = new Date(rev.timestamp);
        var formattedDate = date.toLocaleString('ru', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'UTC'
        }) + ' (UTC)';

        addLog('Результат: автор ' + escapeForLog(rev.user) + ', дата ' + formattedDate, 'success');

        var safeUser = escapeHtml(rev.user);
        var safeComment = escapeHtml(rev.comment);

        var dark = isDarkTheme();

        var colors = dark ? {
            bg: '#3a3d42',
            fg: '#ffffff',
            border: '#72777d',
            accent: '#8fb3ff',
            subtle: '#54595d',
            btnText: '#1a1a1a'
        } : {
            bg: '#ffffff',
            fg: '#202122',
            border: '#a2a9b1',
            accent: '#3366cc',
            subtle: '#eaecf0',
            btnText: '#ffffff'
        };

        var overlay = createSafeElement('div', {
            id: 'blame-overlay',
            css: {
                position: 'fixed',
                top: '0',
                left: '0',
                right: '0',
                bottom: '0',
                background: 'rgba(0,0,0,0.5)',
                zIndex: '9999'
            }
        });

        var modal = createSafeElement('div', {
            id: 'blame-result-modal',
            css: {
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                background: colors.bg,
                color: colors.fg,
                border: '2px solid ' + colors.border,
                borderRadius: '8px',
                padding: '20px',
                zIndex: '10000',
                maxWidth: '500px',
                boxShadow: '0 5px 20px rgba(0,0,0,0.3)',
                fontFamily: 'sans-serif'
            }
        });

        var titleElement = createSafeElement('h3', {
            text: 'Найден автор текста',
            css: {
                marginTop: '0',
                color: colors.fg
            }
        });
        modal.appendChild(titleElement);

        var userP = createSafeElement('p');
        var userStrong = createSafeElement('strong', { text: 'Участник:' });
        userP.appendChild(userStrong);
        userP.appendChild(document.createTextNode(' ' + safeUser));
        modal.appendChild(userP);

        var dateP = createSafeElement('p');
        var dateStrong = createSafeElement('strong', { text: 'Дата правки:' });
        dateP.appendChild(dateStrong);
        dateP.appendChild(document.createTextNode(' ' + formattedDate));
        modal.appendChild(dateP);

        var commentP = createSafeElement('p');
        var commentStrong = createSafeElement('strong', { text: 'Комментарий:' });
        commentP.appendChild(commentStrong);
        commentP.appendChild(document.createTextNode(' "' + safeComment + '"'));
        modal.appendChild(commentP);

        var versionP = createSafeElement('p');
        var versionStrong = createSafeElement('strong', { text: 'Версия:' });
        versionP.appendChild(versionStrong);
        versionP.appendChild(document.createTextNode(' '));

        var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&oldid=' + rev.revid;
        var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию');
        versionLink.style.setProperty('color', colors.accent, 'important');
        versionLink.style.setProperty('text-decoration', 'underline', 'important');
        versionP.appendChild(versionLink);
        modal.appendChild(versionP);

        var diffP = createSafeElement('p');
        var diffStrong = createSafeElement('strong', { text: 'Дифф:' });
        diffP.appendChild(diffStrong);
        diffP.appendChild(document.createTextNode(' '));

        var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&diff=prev&oldid=' + rev.revid;
        var diffLink = createSafeLink(diffUrl, 'посмотреть изменения');
        diffLink.style.setProperty('color', colors.accent, 'important');
        diffLink.style.setProperty('text-decoration', 'underline', 'important');
        diffP.appendChild(diffLink);
        modal.appendChild(diffP);

        var hr = createSafeElement('hr', {
            css: {
                border: 'none',
                borderTop: '1px solid ' + colors.subtle
            }
        });
        modal.appendChild(hr);

        var closeButton = createSafeElement('button', {
            id: 'blame-close',
            text: 'Закрыть',
            css: {
                background: colors.accent,
                color: colors.btnText,
                border: 'none',
                padding: '8px 16px',
                borderRadius: '4px',
                cursor: 'pointer'
            }
        });
        modal.appendChild(closeButton);

        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        function closeModal() {
            var m = document.getElementById('blame-result-modal');
            var o = document.getElementById('blame-overlay');

            if (m && m.parentNode) {
                m.parentNode.removeChild(m);
            }
            if (o && o.parentNode) {
                o.parentNode.removeChild(o);
            }
        }

        closeButton.onclick = closeModal;
        overlay.onclick = closeModal;
    }

    function showLoading(message) {
        var dark = isDarkTheme();
        var bg = dark ? '#3a3d42' : '#f8f9fa';
        var fg = dark ? '#ffffff' : '#202122';
        var border = dark ? '#72777d' : '#a2a9b1';

        var div = createSafeElement('div', {
            id: 'blame-loading',
            text: message || 'Загрузка...',
            css: {
                position: 'fixed',
                top: '20px',
                right: '20px',
                background: bg,
                color: fg,
                border: '1px solid ' + border,
                padding: '10px 20px',
                borderRadius: '4px',
                zIndex: '10000',
                fontFamily: 'sans-serif',
                boxShadow: '0 2px 10px rgba(0,0,0,0.1)'
            }
        });

        document.body.appendChild(div);
        return div;
    }

    function hideLoading(div) {
        if (div && div.parentNode) {
            div.parentNode.removeChild(div);
        }
    }

    var pageInfo = getPageInfo();

    if (pageInfo.isArticle) {
        if (document.readyState === 'complete') {
            addButton();
        } else {
            window.addEventListener('load', addButton);
        }
    } else {
        console.log('BlameFinder: не основное пространство имён, гаджет не активирован');
    }
})();