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

Нет описания правки
Нет описания правки
Строка 1: Строка 1:
/**
/**
  * Gadget: Blame Finder
  * Gadget: Blame Finder
  * Версия 2.0 с поддержкой ночного режима и петаскиванием кнопки
  * Версия 2.0 с поддержкой ночного режима и перетаскиванием кнопки
  * Назначение: поиск автора любого текста в статье
  * Назначение: поиск автора любого текста в статье
  * Локализация под wiki.peresvet.artushak.ru, лицензия: CC BY-SA 4.0
  * Локализация под Абсурдопедию, лицензия: CC BY-SA 4.0
  * Использование:
  * Использование:
   1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
   1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
Строка 30: Строка 30:
     }
     }


     var scriptPath = '/w';
    // ===== КОНСТАНТЫ =====
     var SCRIPT_PATH_FALLBACK = '/w';
    var BUTTON_STORAGE_KEY = 'blameFinderButtonPos';
    var LOG_WIDTH = 380;
    var LOG_MAX_HEIGHT_CSS = 'min(300px, 50vh)';
    var LOG_MAX_ENTRIES = 30;
    var SELECTION_MIN_LENGTH = 20;
    var SELECTION_TIMEOUT_MS = 20000;
    var DRAG_MOVE_THRESHOLD = 5;
    var API_REQUEST_TIMEOUT_MS = 20000;
    var GLOBAL_TIMEOUT_MS = 120000;
    var MAX_REVISIONS = 500;
    var REVISIONS_PER_BATCH = 50;
 
    var COLORS = {
        primary: '#36c',
        primaryHover: '#447ff5',
        danger: '#f00',
        warning: '#ff0',
        success: '#0f0',
        logBg: 'rgba(0,0,0,0.9)'
    };
 
    var scriptPath = SCRIPT_PATH_FALLBACK;
     try {
     try {
         if (typeof mw !== 'undefined' && mw.config && mw.config.get) {
         if (typeof mw !== 'undefined' && mw.config && mw.config.get) {
             scriptPath = mw.config.get('wgScriptPath') || '/w';
             scriptPath = mw.config.get('wgScriptPath') || SCRIPT_PATH_FALLBACK;
         }
         }
     } catch (e) {
     } catch (e) {
         scriptPath = '/w';
         scriptPath = SCRIPT_PATH_FALLBACK;
     }
     }


     var BUTTON_STORAGE_KEY = 'blameFinderButtonPos';
     // ===== ЭКРАНИРОВАНИЕ =====
    var LOG_WIDTH = 380;
     function escapeText(text) {
    var LOG_MAX_HEIGHT_CSS = 'min(300px, 50vh)';
 
     function escapeText(text, escapeSlash) {
         if (text === undefined || text === null) return '';
         if (text === undefined || text === null) return '';
         var s = String(text)
         return String(text)
             .replace(/&/g, '&')
             .replace(/&/g, '&')
             .replace(/</g, '&lt;')
             .replace(/</g, '&lt;')
Строка 51: Строка 71:
             .replace(/"/g, '&quot;')
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&#039;');
             .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);
     }
     }


Строка 69: Строка 77:
         var trimmed = url.trim();
         var trimmed = url.trim();
         if (trimmed === '') return null;
         if (trimmed === '') return null;
         if (trimmed.charAt(0) === '/' || trimmed.charAt(0) === '#') {
         if (trimmed.charAt(0) === '#') return trimmed;
            return trimmed;
        if (trimmed.charAt(0) === '/' && trimmed.charAt(1) !== '/') return trimmed;
        }
         try {
         try {
             var parsed = new URL(trimmed, window.location.origin);
             var parsed = new URL(trimmed, window.location.origin);
Строка 86: Строка 93:
         if (options.className) element.className = options.className;
         if (options.className) element.className = options.className;
         if (options.id) element.id = options.id;
         if (options.id) element.id = options.id;
         if (options.text) element.textContent = options.text;
         if (options.text !== undefined && options.text !== null) {
        if (options.html) element.textContent = options.html;
            element.textContent = options.text;
        }


         if (options.css) {
         if (options.css) {
Строка 101: Строка 109:
                     if (safe !== null) element.setAttribute(key, safe);
                     if (safe !== null) element.setAttribute(key, safe);
                 } else {
                 } else {
                     element.setAttribute(key, options.attrs[key]);
                     element.setAttribute(key, String(options.attrs[key]));
                 }
                 }
             });
             });
Строка 116: Строка 124:
                 target: '_blank',
                 target: '_blank',
                 rel: 'noopener noreferrer',
                 rel: 'noopener noreferrer',
                 title: title ? escapeHtml(title) : escapeHtml(text)
                 title: title || text
             }
             }
         });
         });
Строка 127: Строка 135:
     }
     }


    // ===== ТЕМА =====
    var cachedDarkTheme = null;
     function isDarkTheme() {
     function isDarkTheme() {
        if (cachedDarkTheme !== null) return cachedDarkTheme;
        var result = false;
         try {
         try {
             var html = document.documentElement;
             var html = document.documentElement;
             var body = document.body;
             var body = document.body;
             if (html.classList.contains('skin-theme-clientpref-night')) return true;
             if (html.classList.contains('skin-theme-clientpref-night')) result = true;
             if (html.classList.contains('skin-theme-clientpref-day')) return false;
             else if (html.classList.contains('skin-theme-clientpref-day')) result = false;
             if (html.classList.contains('skin-theme-clientpref-os')) {
             else if (html.classList.contains('skin-theme-clientpref-os')) {
                 return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
                 result = !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
             }
             } else {
            var dataTheme = (html.getAttribute('data-theme') || '') + ' ' +
                var dataTheme = (html.getAttribute('data-theme') || '') + ' ' +
                            (body ? (body.getAttribute('data-theme') || '') : '');
                                (body ? (body.getAttribute('data-theme') || '') : '');
            if (/dark|night/i.test(dataTheme)) return true;
                if (/dark|night/i.test(dataTheme)) result = true;
            if (/light|day/i.test(dataTheme)) return false;
                else if (/light|day/i.test(dataTheme)) result = false;
            if (body) {
                else if (body) {
                var bg = window.getComputedStyle(body).backgroundColor;
                    var bg = window.getComputedStyle(body).backgroundColor;
                var m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
                    var m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
                if (m) {
                    if (m) {
                    var r = parseInt(m[1], 10);
                        var r = parseInt(m[1], 10);
                    var g = parseInt(m[2], 10);
                        var g = parseInt(m[2], 10);
                    var b = parseInt(m[3], 10);
                        var b = parseInt(m[3], 10);
                    var luminance = (0.299 * r + 0.587 * g + 0.114 * b);
                        result = (0.299 * r + 0.587 * g + 0.114 * b) < 128;
                    if (luminance < 128) return true;
                     }
                     if (luminance >= 128) return false;
                 }
                 }
             }
             }
         } catch (e) {}
         } catch (e) {}
         return false;
        cachedDarkTheme = result;
         return result;
     }
     }


    // ===== ИНФОРМАЦИЯ О СТРАНИЦЕ =====
    var cachedPageInfo = null;
     function getPageInfo() {
     function getPageInfo() {
        if (cachedPageInfo) return cachedPageInfo;
        cachedPageInfo = computePageInfo();
        return cachedPageInfo;
    }
    function computePageInfo() {
         var title = null;
         var title = null;
         var namespace = 0;
         var namespace = 0;
Строка 229: Строка 249:
     }
     }


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


         var safeParams = {};
         var queryString = Object.keys(params).map(function(key) {
        Object.keys(params).forEach(function(key) {
             var value = params[key];
             var value = params[key];
            if (typeof value === 'string') {
             return encodeURIComponent(key) + '=' + encodeURIComponent(value === undefined ? '' : value);
                safeParams[key] = value.replace(/[<>"']/g, '');
            } else {
                safeParams[key] = value;
            }
        });
 
        var queryString = Object.keys(safeParams).map(function(key) {
             return encodeURIComponent(key) + '=' + encodeURIComponent(safeParams[key]);
         }).join('&');
         }).join('&');


Строка 255: Строка 267:
             if (!completed) {
             if (!completed) {
                 completed = true;
                 completed = true;
                 xhr.abort();
                 try { xhr.abort(); } catch (e) {}
                 addLog('Таймаут API: сервер не отвечает', 'error');
                 addLog('Таймаут API: сервер не отвечает', 'error');
                 if (errorCallback) errorCallback('timeout');
                 if (errorCallback) errorCallback('timeout');
             }
             }
         }, 15000);
         }, API_REQUEST_TIMEOUT_MS);


         xhr.open('GET', url, true);
         xhr.open('GET', url, true);
Строка 279: Строка 291:
                     try {
                     try {
                         var data = JSON.parse(xhr.responseText);
                         var data = JSON.parse(xhr.responseText);
                         if (!data || typeof data !== 'object') throw new Error('Invalid response format');
                         if (!data || typeof data !== 'object') throw new Error('Invalid response');
                         clearTimeout(timeoutId);
                         clearTimeout(timeoutId);
                         completed = true;
                         completed = true;
Строка 321: Строка 333:
             id: 'blame-log-panel',
             id: 'blame-log-panel',
             css: {
             css: {
                 position: 'fixed',
                 position: 'fixed', bottom: '80px', right: '20px',
                bottom: '80px',
                right: '20px',
                 width: LOG_WIDTH + 'px',
                 width: LOG_WIDTH + 'px',
                 maxHeight: LOG_MAX_HEIGHT_CSS,
                 maxHeight: LOG_MAX_HEIGHT_CSS,
                 overflowY: 'auto',
                 overflowY: 'auto',
                 background: 'rgba(0,0,0,0.9)',
                 background: COLORS.logBg, color: COLORS.success,
                color: '#0f0',
                 fontFamily: 'monospace', fontSize: '12px',
                 fontFamily: 'monospace',
                 padding: '10px', borderRadius: '5px', zIndex: '9999',
                fontSize: '12px',
                 border: '2px solid ' + COLORS.primary,
                 padding: '10px',
                borderRadius: '5px',
                zIndex: '9999',
                 border: '2px solid #36c',
                 boxShadow: '0 0 20px rgba(0,0,0,0.5)',
                 boxShadow: '0 0 20px rgba(0,0,0,0.5)',
                 display: 'none'
                 display: 'none'
Строка 342: Строка 348:
         var header = createSafeElement('div', {
         var header = createSafeElement('div', {
             css: {
             css: {
                 display: 'flex',
                 display: 'flex', justifyContent: 'space-between',
                justifyContent: 'space-between',
                 marginBottom: '10px', paddingBottom: '5px',
                 marginBottom: '10px',
                 borderBottom: '2px solid ' + COLORS.primary
                paddingBottom: '5px',
                 borderBottom: '2px solid #36c'
             }
             }
         });
         });
Строка 352: Строка 356:
         var titleSpan = createSafeElement('span', {
         var titleSpan = createSafeElement('span', {
             text: 'Логи BlameFinder',
             text: 'Логи BlameFinder',
             css: { color: '#36c', fontWeight: 'bold' }
             css: { color: COLORS.primary, fontWeight: 'bold' }
         });
         });


Строка 358: Строка 362:


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


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


         ['color', 'border-color'].forEach(function(prop) {
         ['color', 'border-color'].forEach(function(prop) {
             clearButton.style.setProperty(prop, '#36c', 'important');
             clearButton.style.setProperty(prop, COLORS.primary, 'important');
             toggleButton.style.setProperty(prop, '#36c', 'important');
             toggleButton.style.setProperty(prop, COLORS.primary, 'important');
         });
         });
         clearButton.style.setProperty('background', 'none', 'important');
         clearButton.style.setProperty('background', 'none', 'important');
Строка 415: Строка 409:
             logVisible = !logVisible;
             logVisible = !logVisible;
             logPanel.style.display = logVisible ? 'block' : 'none';
             logPanel.style.display = logVisible ? 'block' : 'none';
            toggleButton.textContent = logVisible ? 'Скрыть' : 'Показать';
             syncLogToggleLabel();
             syncLogToggleLabel();
         };
         };
Строка 423: Строка 416:


     function showLogPanel() {
     function showLogPanel() {
         if (!logPanel) return;
         if (!logPanel || logVisible) return;
        if (logVisible) return;
         logVisible = true;
         logVisible = true;
         logPanel.style.display = 'block';
         logPanel.style.display = 'block';
Строка 464: Строка 456:
     function addLog(message, type) {
     function addLog(message, type) {
         var timestamp = new Date().toLocaleTimeString('ru', { timeZoneName: 'short' });
         var timestamp = new Date().toLocaleTimeString('ru', { timeZoneName: 'short' });
         var color = '#0f0';
         var color = COLORS.success;
         if (type === 'error') color = '#f00';
         if (type === 'error') color = COLORS.danger;
         if (type === 'warning') color = '#ff0';
         else if (type === 'warning') color = COLORS.warning;
        if (type === 'success') color = '#0f0';


        var safeMessage = escapeForLog(String(message));
         logEntries.unshift({ time: timestamp, text: String(message), color: color });
         logEntries.unshift({ time: timestamp, text: safeMessage, color: color });
         if (logEntries.length > LOG_MAX_ENTRIES) logEntries.pop();
         if (logEntries.length > 30) logEntries.pop();
         updateLogDisplay();
         updateLogDisplay();
     }
     }
Строка 484: Строка 474:
                 css: { color: entry.color, marginBottom: '3px' }
                 css: { color: entry.color, marginBottom: '3px' }
             });
             });
             entryDiv.textContent = '[' + entry.time + '] ' + entry.text;
             entryDiv.textContent = '[' + entry.time + '] ' + entry.text;
             content.appendChild(entryDiv);
             content.appendChild(entryDiv);
Строка 496: Строка 487:
     function addButton() {
     function addButton() {
         if (document.getElementById('blame-finder-button')) return;
         if (document.getElementById('blame-finder-button')) return;
 
         addLog('Инициализация BlameFinder для ' + window.location.host, 'info');
         addLog('Инициализация BlameFinder для absurdopedia.wiki', 'info');


         var button = createSafeElement('div', {
         var button = createSafeElement('div', {
             id: 'blame-finder-button',
             id: 'blame-finder-button',
             text: 'Кто автор?',
             text: 'Кто автор?',
            attrs: { role: 'button', tabindex: '0', 'aria-label': 'Найти автора выделенного текста' },
             css: {
             css: {
                 position: 'fixed',
                 position: 'fixed', right: '20px', bottom: '20px',
                right: '20px',
                 background: COLORS.primary, color: 'white',
                bottom: '20px',
                 padding: '10px 20px', borderRadius: '5px',
                 background: '#36c',
                 cursor: 'grab', zIndex: '9999',
                color: 'white',
                 fontFamily: 'sans-serif', fontSize: '14px',
                 padding: '10px 20px',
                borderRadius: '5px',
                 cursor: 'grab',
                zIndex: '9999',
                 fontFamily: 'sans-serif',
                fontSize: '14px',
                 boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
                 boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
                 userSelect: 'none',
                 userSelect: 'none', webkitUserSelect: 'none',
                webkitUserSelect: 'none',
                 touchAction: 'none', transition: 'background 0.15s'
                 touchAction: 'none',
                transition: 'background 0.15s'
             }
             }
         });
         });
Строка 565: Строка 548:
         var pointerId = null;
         var pointerId = null;
         var moved = false;
         var moved = false;
        var MOVE_THRESHOLD = 5;


         function onPointerDown(e) {
         function onPointerDown(e) {
             if (e.button !== undefined && e.button !== 0) return;
             if (e.pointerType === 'mouse' && e.button !== 0) return;
 
             pointerId = e.pointerId;
             pointerId = e.pointerId;
             moved = false;
             moved = false;
Строка 596: Строка 579:
             var dx = e.clientX - startX;
             var dx = e.clientX - startX;
             var dy = e.clientY - startY;
             var dy = e.clientY - startY;
             if (!moved && (Math.abs(dx) > MOVE_THRESHOLD || Math.abs(dy) > MOVE_THRESHOLD)) {
             if (!moved && (Math.abs(dx) > DRAG_MOVE_THRESHOLD || Math.abs(dy) > DRAG_MOVE_THRESHOLD)) {
                 moved = true;
                 moved = true;
             }
             }
Строка 602: Строка 585:


             var rect = button.getBoundingClientRect();
             var rect = button.getBoundingClientRect();
            var w = rect.width, h = rect.height;
             var newLeft = clamp(startLeft + dx, 0, window.innerWidth - rect.width);
             var newLeft = clamp(startLeft + dx, 0, window.innerWidth - w);
             var newTop  = clamp(startTop + dy, 0, window.innerHeight - rect.height);
             var newTop  = clamp(startTop + dy, 0, window.innerHeight - h);
             button.style.left = newLeft + 'px';
             button.style.left = newLeft + 'px';
             button.style.top = newTop + 'px';
             button.style.top = newTop + 'px';
Строка 627: Строка 609:


         button.addEventListener('mouseenter', function() {
         button.addEventListener('mouseenter', function() {
             if (!button.dataset.dragging) button.style.background = '#447ff5';
             if (!button.dataset.dragging) button.style.background = COLORS.primaryHover;
         });
         });
         button.addEventListener('mouseleave', function() {
         button.addEventListener('mouseleave', function() {
             if (!button.dataset.dragging) button.style.background = '#36c';
             if (!button.dataset.dragging) button.style.background = COLORS.primary;
         });
         });


         button.addEventListener('click', function(e) {
         function handleActivate(e) {
             if (moved) {
             if (moved) {
                 moved = false;
                 moved = false;
                 e.preventDefault();
                 if (e) { e.preventDefault(); e.stopPropagation(); }
                e.stopPropagation();
                 return;
                 return;
             }
             }
             e.preventDefault();
             if (e) { e.preventDefault(); e.stopPropagation(); }
             showLogPanel();
             showLogPanel();
             activateSelectionMode();
             activateSelectionMode();
        }
        button.addEventListener('click', handleActivate);
        button.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') handleActivate(e);
         });
         });


Строка 670: Строка 656:
     var selectionActive = false;
     var selectionActive = false;
     var selectionTimer = null;
     var selectionTimer = null;
    var selectionCountdown = null;


     function activateSelectionMode() {
     function activateSelectionMode() {
Строка 684: Строка 671:
             id: 'blame-tooltip',
             id: 'blame-tooltip',
             css: {
             css: {
                 position: 'fixed',
                 position: 'fixed', top: '50%', left: '50%',
                top: '50%',
                left: '50%',
                 transform: 'translate(-50%, -50%)',
                 transform: 'translate(-50%, -50%)',
                 background: '#36c',
                 background: COLORS.primary, color: 'white',
                color: 'white',
                 padding: '20px 40px', borderRadius: '10px',
                 padding: '20px 40px',
                 zIndex: '10000', fontFamily: 'sans-serif',
                borderRadius: '10px',
                 fontSize: '18px', textAlign: 'center',
                 zIndex: '10000',
                fontFamily: 'sans-serif',
                 fontSize: '18px',
                textAlign: 'center',
                 boxShadow: '0 0 30px rgba(0,0,0,0.5)'
                 boxShadow: '0 0 30px rgba(0,0,0,0.5)'
             }
             }
Строка 703: Строка 684:
         tooltip.appendChild(document.createElement('br'));
         tooltip.appendChild(document.createElement('br'));


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


         var timerSpan = createSafeElement('span', {
         var timerSpan = createSafeElement('span', {
             id: 'blame-timer',
             id: 'blame-timer', text: String(SELECTION_TIMEOUT_MS / 1000),
            text: '20',
             css: { color: COLORS.warning }
             css: { color: '#ff0' }
         });
         });
         small.appendChild(timerSpan);
         small.appendChild(timerSpan);
Строка 716: Строка 696:
         document.body.appendChild(tooltip);
         document.body.appendChild(tooltip);


         var seconds = 20;
         var secondsLeft = SELECTION_TIMEOUT_MS / 1000;
         var timer = setInterval(function() {
         selectionCountdown = setInterval(function() {
             seconds--;
             secondsLeft--;
             var timerSpanEl = document.getElementById('blame-timer');
             var timerSpanEl = document.getElementById('blame-timer');
             if (timerSpanEl) timerSpanEl.textContent = seconds;
             if (timerSpanEl) timerSpanEl.textContent = String(secondsLeft);
            if (secondsLeft <= 0) {
                if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; }
            }
         }, 1000);
         }, 1000);


Строка 730: Строка 713:
             document.removeEventListener('touchend', touchHandler);
             document.removeEventListener('touchend', touchHandler);


             if (timer) { clearInterval(timer); timer = null; }
             if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; }
             if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; }
             if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; }


Строка 744: Строка 727:
         }
         }


        var touchDebounceTimer = null;
         function touchHandler() {
         function touchHandler() {
             if (!selectionActive) return;
             if (!selectionActive) return;
             setTimeout(handleSelection, 100);
             if (touchDebounceTimer) clearTimeout(touchDebounceTimer);
            touchDebounceTimer = setTimeout(function() {
                touchDebounceTimer = null;
                handleSelection();
            }, 150);
         }
         }


Строка 752: Строка 740:
             if (!selectionActive) return;
             if (!selectionActive) return;
             var selection = window.getSelection();
             var selection = window.getSelection();
             var selectedText = selection.toString().trim();
             var selectedText = selection ? selection.toString().trim() : '';


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


Строка 782: Строка 771:
         var title = pageInfo.title;
         var title = pageInfo.title;


         addLog('Начинаем поиск для страницы: ' + escapeForLog(title), 'info');
         addLog('Начинаем поиск для страницы: ' + title, 'info');
 
         addLog('Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"'), 'info');
         var logText = 'Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"');
        addLog(logText, 'info');


         var loadingDiv = showLoading('Анализирую историю правок...');
         var loadingDiv = showLoading('Анализирую историю правок...');
         addLog('Запрашиваем историю правок через API', 'info');
         addLog('Запрашиваем историю правок через API', 'info');
        var finished = false;
        function finish() {
            if (finished) return;
            finished = true;
            hideLoading(loadingDiv);
        }


         var globalTimeout = setTimeout(function() {
         var globalTimeout = setTimeout(function() {
             hideLoading(loadingDiv);
             if (finished) return;
             addLog('Глобальный таймаут: сервер не отвечает', 'error');
             addLog('Глобальный таймаут (' + (GLOBAL_TIMEOUT_MS / 1000) +
         }, 15000);
                  ' с): сервер не отвечает или история слишком велика', 'error');
            finish();
         }, GLOBAL_TIMEOUT_MS);


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


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


             findTextAppearance(revisions, text, title, function(result) {
             findTextAppearance(revisions, text, title, function(result) {
                 hideLoading(loadingDiv);
                 clearTimeout(globalTimeout);
                finish();
                 if (result) {
                 if (result) {
                     addLog('Текст найден! Автор: ' + escapeForLog(result.rev.user), 'success');
                     addLog('Текст найден! Автор: ' + result.rev.user, 'success');
                     showResult(result);
                     showResult(result);
                 } else {
                 } else {
Строка 818: Строка 816:
         }, function(error) {
         }, function(error) {
             clearTimeout(globalTimeout);
             clearTimeout(globalTimeout);
             hideLoading(loadingDiv);
             finish();
             addLog('Ошибка при запросе к API: ' + error, 'error');
             addLog('Ошибка при запросе к API: ' + error, 'error');
         });
         });
Строка 825: Строка 823:
     function getRevisions(title, callback, errorCallback) {
     function getRevisions(title, callback, errorCallback) {
         var revisions = [];
         var revisions = [];
         var continueParam = {};
         var continueParam = null;
         var totalFetched = 0;
         var totalFetched = 0;
        var maxRevisions = 1000;


         function fetchRevisions() {
         function fetchRevisions() {
Строка 835: Строка 832:
                 titles: title,
                 titles: title,
                 rvprop: 'ids|timestamp|user|comment|content',
                 rvprop: 'ids|timestamp|user|comment|content',
                 rvlimit: 50,
                 rvlimit: REVISIONS_PER_BATCH,
                 rvdir: 'older',
                 rvdir: 'older',
                 rvslots: 'main',
                 rvslots: 'main',
Строка 841: Строка 838:
             };
             };


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


             absApiRequest(params, function(data) {
             absApiRequest(params, function(data) {
                 if (data.error) {
                 if (data.error) {
                     addLog('Ошибка API: ' + escapeForLog(data.error.info), 'error');
                     addLog('Ошибка API: ' + data.error.info, 'error');
                     if (errorCallback) errorCallback(data.error.info);
                     if (errorCallback) errorCallback(data.error.info);
                     return;
                     return;
Строка 878: Строка 873:
                     });
                     });
                     totalFetched += page.revisions.length;
                     totalFetched += page.revisions.length;
                     addLog('Загружено ревизий: ' + totalFetched + '/' + maxRevisions, 'info');
                     addLog('Загружено ревизий: ' + totalFetched + '/' + MAX_REVISIONS, 'info');
                 } else {
                 } else {
                     addLog('У страницы нет истории правок', 'warning');
                     addLog('У страницы нет истории правок', 'warning');
Строка 885: Строка 880:
                 }
                 }


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


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


         var foundRev = null;
         var foundRev = null;
         var checkedCount = 0;
         var checkedCount = 0;


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


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


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


             if (i === 0) {
             if (i === count - 1) {
                 foundRev = rev;
                 foundRev = rev;
                 addLog('Текст есть в самой первой ревизии страницы', 'info');
                 addLog('Текст есть в самой первой ревизии страницы', 'info');
Строка 926: Строка 922:
             }
             }


             var previousContent = oldestFirst[i - 1].content || '';
             var previousContent = (revisions[i + 1] && revisions[i + 1].content) || '';
             if (previousContent.indexOf(text) === -1) {
             if (previousContent.indexOf(text) === -1) {
                 foundRev = rev;
                 foundRev = rev;
Строка 950: Строка 946:


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


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


        var safeUser = escapeHtml(rev.user);
        var safeComment = escapeHtml(rev.comment);
         var dark = isDarkTheme();
         var dark = isDarkTheme();
         var colors = dark ? {
         var colors = dark ? {
             bg: '#3a3d42', fg: '#ffffff', border: '#72777d',
             bg: '#3a3d42', fg: '#ffffff', border: '#72777d',
Строка 983: Строка 977:
         var modal = createSafeElement('div', {
         var modal = createSafeElement('div', {
             id: 'blame-result-modal',
             id: 'blame-result-modal',
            attrs: { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'blame-modal-title' },
             css: {
             css: {
                 position: 'fixed', top: '50%', left: '50%',
                 position: 'fixed', top: '50%', left: '50%',
Строка 995: Строка 990:
         });
         });


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


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


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


Строка 1018: Строка 1015:
         versionP.appendChild(createSafeElement('strong', { text: 'Версия:' }));
         versionP.appendChild(createSafeElement('strong', { text: 'Версия:' }));
         versionP.appendChild(document.createTextNode(' '));
         versionP.appendChild(document.createTextNode(' '));
         var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&oldid=' + rev.revid;
         var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) +
                        '&oldid=' + encodeURIComponent(rev.revid);
         var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию');
         var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию');
         versionLink.style.setProperty('color', colors.accent, 'important');
         versionLink.style.setProperty('color', colors.accent, 'important');
Строка 1028: Строка 1026:
         diffP.appendChild(createSafeElement('strong', { text: 'Дифф:' }));
         diffP.appendChild(createSafeElement('strong', { text: 'Дифф:' }));
         diffP.appendChild(document.createTextNode(' '));
         diffP.appendChild(document.createTextNode(' '));
         var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&diff=prev&oldid=' + rev.revid;
         var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) +
                      '&diff=prev&oldid=' + encodeURIComponent(rev.revid);
         var diffLink = createSafeLink(diffUrl, 'посмотреть изменения');
         var diffLink = createSafeLink(diffUrl, 'посмотреть изменения');
         diffLink.style.setProperty('color', colors.accent, 'important');
         diffLink.style.setProperty('color', colors.accent, 'important');
Строка 1040: Строка 1039:


         var closeButton = createSafeElement('button', {
         var closeButton = createSafeElement('button', {
             id: 'blame-close',
             id: 'blame-close', text: 'Закрыть',
            text: 'Закрыть',
             css: {
             css: {
                 background: colors.accent, color: colors.btnText,
                 background: colors.accent, color: colors.btnText,
Строка 1058: Строка 1056:
             if (m && m.parentNode) m.parentNode.removeChild(m);
             if (m && m.parentNode) m.parentNode.removeChild(m);
             if (o && o.parentNode) o.parentNode.removeChild(o);
             if (o && o.parentNode) o.parentNode.removeChild(o);
            document.removeEventListener('keydown', escHandler);
        }
        function escHandler(e) {
            if (e.key === 'Escape') closeModal();
         }
         }
        document.addEventListener('keydown', escHandler);


         closeButton.onclick = closeModal;
         closeButton.onclick = closeModal;
         overlay.onclick = closeModal;
         overlay.onclick = closeModal;
        try { closeButton.focus(); } catch (e) {}
     }
     }


     function showLoading(message) {
     function showLoading(message) {
        var existing = document.getElementById('blame-loading');
        if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
         var dark = isDarkTheme();
         var dark = isDarkTheme();
         var bg = dark ? '#3a3d42' : '#f8f9fa';
         var bg = dark ? '#3a3d42' : '#f8f9fa';
Строка 1071: Строка 1079:


         var div = createSafeElement('div', {
         var div = createSafeElement('div', {
             id: 'blame-loading',
             id: 'blame-loading', text: message || 'Загрузка...',
            text: message || 'Загрузка...',
             css: {
             css: {
                 position: 'fixed', top: '20px', right: '20px',
                 position: 'fixed', top: '20px', right: '20px',