MediaWiki:Gadget-blamefinder.js: различия между версиями
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| (не показано 8 промежуточных версий этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Gadget: Blame Finder | * Gadget: Blame Finder | ||
* Версия 2.0 с поддержкой ночного режима и | * Версия 2.0 с поддержкой ночного режима и перетаскиванием кнопки | ||
* Назначение: поиск автора любого текста в статье | * Назначение: поиск автора любого текста в статье | ||
* | * Универсальный вики-портируемый код. | ||
* Лицензия: MIT (opensource.org/license/mit ==> 2026, absurdopedia.wiki | |||
* Использование: | * Использование: | ||
1. Нажимаете кнопку «Кто автор?» в правом нижнем углу | 1. Нажимаете кнопку «Кто автор?» (изначально она — в правом нижнем углу) | ||
2. Выделяете любой текст на странице (минимум 20 символов) | 2. Выделяете любой текст на странице (минимум 20 символов) | ||
3. | 3.1. В скинах Monobook и Vector-10: | ||
4. Гаджет анализирует последние 1000 правок страницы | · кликайте по появившейся в центре кнопке таймера (20 секунд на всё) | ||
5. Находит первое появление этого текста в истории | 3.2 В скине Vector-22: | ||
6. Показывает: | · кликайте по кнопке «Кто автор?» (20 секунд на всё) | ||
4. Гаджет анализирует последние 1000 правок страницы | |||
5. Находит первое появление этого текста в истории | |||
6. Показывает: | |||
· Имя автора | |||
· Дату правки | |||
· Комментарий к правке | |||
· Ссылки на версию и diff | |||
* Что может: | * Что может: | ||
· Искать авторов фрагментов текста в статьях | · Искать авторов фрагментов текста в статьях | ||
| Строка 30: | Строка 34: | ||
} | } | ||
var | // ===== КОНСТАНТЫ ===== | ||
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 = 1000; | |||
var REVISIONS_PER_BATCH = 50; | |||
var MAX_VERIFICATION_RETRIES = 5; | |||
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') || | scriptPath = mw.config.get('wgScriptPath') || SCRIPT_PATH_FALLBACK; | ||
} | } | ||
} catch (e) { | } catch (e) { | ||
scriptPath = | scriptPath = SCRIPT_PATH_FALLBACK; | ||
} | } | ||
// ===== ЭКРАНИРОВАНИЕ ===== | |||
function escapeText(text) { | |||
function escapeText(text | |||
if (text === undefined || text === null) return ''; | if (text === undefined || text === null) return ''; | ||
return String(text) | |||
.replace(/&/g, '&') | .replace(/&/g, '&') | ||
.replace(/</g, '<') | .replace(/</g, '<') | ||
| Строка 51: | Строка 76: | ||
.replace(/"/g, '"') | .replace(/"/g, '"') | ||
.replace(/'/g, '''); | .replace(/'/g, '''); | ||
} | } | ||
| Строка 69: | Строка 82: | ||
var trimmed = url.trim(); | var trimmed = url.trim(); | ||
if (trimmed === '') return null; | if (trimmed === '') return null; | ||
if (trimmed.charAt(0) === ' | if (trimmed.charAt(0) === '#') 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: | Строка 98: | ||
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 | if (options.text !== undefined && options.text !== null) { | ||
element.textContent = options.text; | |||
} | |||
if (options.css) { | if (options.css) { | ||
| Строка 101: | Строка 114: | ||
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: | Строка 129: | ||
target: '_blank', | target: '_blank', | ||
rel: 'noopener noreferrer', | rel: 'noopener noreferrer', | ||
title: title | title: title || text | ||
} | } | ||
}); | }); | ||
| Строка 127: | Строка 140: | ||
} | } | ||
// ===== ТЕМА ===== | |||
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')) | if (html.classList.contains('skin-theme-clientpref-night')) result = true; | ||
if (html.classList.contains('skin-theme-clientpref-day')) | 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')) { | ||
result = !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); | |||
} | } else { | ||
var dataTheme = (html.getAttribute('data-theme') || '') + ' ' + | |||
(body ? (body.getAttribute('data-theme') || '') : ''); | |||
if (/dark|night/i.test(dataTheme)) result = true; | |||
else if (/light|day/i.test(dataTheme)) result = false; | |||
else 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); | |||
result = (0.299 * r + 0.587 * g + 0.114 * b) < 128; | |||
} | |||
} | } | ||
} | } | ||
} catch (e) {} | } catch (e) {} | ||
return | 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: | Строка 254: | ||
} | } | ||
// ===== 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 | var queryString = Object.keys(params).map(function(key) { | ||
var value = params[key]; | var value = params[key]; | ||
return encodeURIComponent(key) + '=' + encodeURIComponent(value === undefined ? '' : value); | |||
return encodeURIComponent(key) + '=' + encodeURIComponent( | |||
}).join('&'); | }).join('&'); | ||
| Строка 255: | Строка 272: | ||
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'); | ||
} | } | ||
}, | }, API_REQUEST_TIMEOUT_MS); | ||
xhr.open('GET', url, true); | xhr.open('GET', url, true); | ||
| Строка 279: | Строка 296: | ||
try { | try { | ||
var data = JSON.parse(xhr.responseText); | var data = JSON.parse(xhr.responseText); | ||
if (!data || typeof data !== 'object') throw new Error('Invalid response | if (!data || typeof data !== 'object') throw new Error('Invalid response'); | ||
clearTimeout(timeoutId); | clearTimeout(timeoutId); | ||
completed = true; | completed = true; | ||
| Строка 321: | Строка 338: | ||
id: 'blame-log-panel', | id: 'blame-log-panel', | ||
css: { | css: { | ||
position: 'fixed', | position: 'fixed', 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: | background: COLORS.logBg, color: COLORS.success, | ||
fontFamily: 'monospace', fontSize: '12px', | |||
fontFamily: 'monospace', | padding: '10px', borderRadius: '5px', zIndex: '9999', | ||
border: '2px solid ' + COLORS.primary, | |||
padding: '10px', | |||
border: '2px solid | |||
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: | Строка 353: | ||
var header = createSafeElement('div', { | var header = createSafeElement('div', { | ||
css: { | css: { | ||
display: 'flex', | display: 'flex', justifyContent: 'space-between', | ||
marginBottom: '10px', paddingBottom: '5px', | |||
marginBottom: '10px', | borderBottom: '2px solid ' + COLORS.primary | ||
borderBottom: '2px solid | |||
} | } | ||
}); | }); | ||
| Строка 352: | Строка 361: | ||
var titleSpan = createSafeElement('span', { | var titleSpan = createSafeElement('span', { | ||
text: 'Логи BlameFinder', | text: 'Логи BlameFinder', | ||
css: { color: | css: { color: COLORS.primary, fontWeight: 'bold' } | ||
}); | }); | ||
| Строка 358: | Строка 367: | ||
var clearButton = createSafeElement('button', { | var clearButton = createSafeElement('button', { | ||
id: 'blame-clear', | id: 'blame-clear', text: 'Очистить', | ||
css: { | css: { | ||
background: 'none', | background: 'none', border: '1px solid ' + COLORS.primary, | ||
color: COLORS.primary, marginRight: '5px', | |||
color: | cursor: 'pointer', padding: '5px' | ||
cursor: 'pointer', | |||
} | } | ||
}); | }); | ||
var toggleButton = createSafeElement('button', { | var toggleButton = createSafeElement('button', { | ||
id: 'blame-toggle', | id: 'blame-toggle', text: 'Скрыть', | ||
css: { | css: { | ||
background: 'none', | background: 'none', border: '1px solid ' + COLORS.primary, | ||
color: COLORS.primary, cursor: 'pointer', padding: '5px' | |||
color: | |||
} | } | ||
}); | }); | ||
['color', 'border-color'].forEach(function(prop) { | ['color', 'border-color'].forEach(function(prop) { | ||
clearButton.style.setProperty(prop, | clearButton.style.setProperty(prop, COLORS.primary, 'important'); | ||
toggleButton.style.setProperty(prop, | toggleButton.style.setProperty(prop, COLORS.primary, 'important'); | ||
}); | }); | ||
clearButton.style.setProperty('background', 'none', 'important'); | clearButton.style.setProperty('background', 'none', 'important'); | ||
| Строка 415: | Строка 414: | ||
logVisible = !logVisible; | logVisible = !logVisible; | ||
logPanel.style.display = logVisible ? 'block' : 'none'; | logPanel.style.display = logVisible ? 'block' : 'none'; | ||
syncLogToggleLabel(); | syncLogToggleLabel(); | ||
}; | }; | ||
| Строка 423: | Строка 421: | ||
function showLogPanel() { | function showLogPanel() { | ||
if (!logPanel | if (!logPanel || logVisible) return; | ||
logVisible = true; | logVisible = true; | ||
logPanel.style.display = 'block'; | logPanel.style.display = 'block'; | ||
| Строка 464: | Строка 461: | ||
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 = | var color = COLORS.success; | ||
if (type === 'error') color = | if (type === 'error') color = COLORS.danger; | ||
if (type === 'warning') color = | else if (type === 'warning') color = COLORS.warning; | ||
logEntries.unshift({ time: timestamp, text: String(message), color: color }); | |||
logEntries.unshift({ time: timestamp, text: | if (logEntries.length > LOG_MAX_ENTRIES) logEntries.pop(); | ||
if (logEntries.length > | |||
updateLogDisplay(); | updateLogDisplay(); | ||
} | } | ||
| Строка 484: | Строка 479: | ||
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: | Строка 492: | ||
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 для | |||
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', | ||
background: COLORS.primary, color: 'white', | |||
padding: '10px 20px', borderRadius: '5px', | |||
background: | cursor: 'grab', zIndex: '9999', | ||
fontFamily: 'sans-serif', fontSize: '14px', | |||
padding: '10px 20px', | |||
cursor: 'grab', | |||
fontFamily: 'sans-serif', | |||
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', | ||
touchAction: 'none', transition: 'background 0.15s' | |||
touchAction: 'none', | |||
} | } | ||
}); | }); | ||
| Строка 565: | Строка 553: | ||
var pointerId = null; | var pointerId = null; | ||
var moved = false; | var moved = false; | ||
function onPointerDown(e) { | function onPointerDown(e) { | ||
if (e. | if (e.pointerType === 'mouse' && e.button !== 0) return; | ||
pointerId = e.pointerId; | pointerId = e.pointerId; | ||
moved = false; | moved = false; | ||
| Строка 596: | Строка 584: | ||
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) > | if (!moved && (Math.abs(dx) > DRAG_MOVE_THRESHOLD || Math.abs(dy) > DRAG_MOVE_THRESHOLD)) { | ||
moved = true; | moved = true; | ||
} | } | ||
| Строка 602: | Строка 590: | ||
var rect = button.getBoundingClientRect(); | var rect = button.getBoundingClientRect(); | ||
var newLeft = clamp(startLeft + dx, 0, window.innerWidth - rect.width); | |||
var newLeft = clamp(startLeft + dx, 0, window.innerWidth - | var newTop = clamp(startTop + dy, 0, window.innerHeight - rect.height); | ||
var newTop = clamp(startTop + dy, 0, window.innerHeight - | |||
button.style.left = newLeft + 'px'; | button.style.left = newLeft + 'px'; | ||
button.style.top = newTop + 'px'; | button.style.top = newTop + 'px'; | ||
| Строка 627: | Строка 614: | ||
button.addEventListener('mouseenter', function() { | button.addEventListener('mouseenter', function() { | ||
if (!button.dataset.dragging) button.style.background = | if (!button.dataset.dragging) button.style.background = COLORS.primaryHover; | ||
}); | }); | ||
button.addEventListener('mouseleave', function() { | button.addEventListener('mouseleave', function() { | ||
if (!button.dataset.dragging) button.style.background = | if (!button.dataset.dragging) button.style.background = COLORS.primary; | ||
}); | }); | ||
function handleActivate(e) { | |||
if (moved) { | if (moved) { | ||
moved = false; | moved = false; | ||
e.preventDefault(); | if (e) { e.preventDefault(); 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: | Строка 661: | ||
var selectionActive = false; | var selectionActive = false; | ||
var selectionTimer = null; | var selectionTimer = null; | ||
var selectionCountdown = null; | |||
function activateSelectionMode() { | function activateSelectionMode() { | ||
| Строка 684: | Строка 676: | ||
id: 'blame-tooltip', | id: 'blame-tooltip', | ||
css: { | css: { | ||
position: 'fixed', | position: 'fixed', top: '50%', left: '50%', | ||
transform: 'translate(-50%, -50%)', | transform: 'translate(-50%, -50%)', | ||
background: | background: COLORS.primary, color: 'white', | ||
padding: '20px 40px', borderRadius: '10px', | |||
padding: '20px 40px', | zIndex: '10000', fontFamily: 'sans-serif', | ||
fontSize: '18px', textAlign: 'center', | |||
zIndex: '10000', | |||
fontSize: '18px', | |||
boxShadow: '0 0 30px rgba(0,0,0,0.5)' | boxShadow: '0 0 30px rgba(0,0,0,0.5)' | ||
} | } | ||
| Строка 703: | Строка 689: | ||
tooltip.appendChild(document.createElement('br')); | tooltip.appendChild(document.createElement('br')); | ||
var small = createSafeElement('small', { css: { color: | 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), | ||
css: { color: COLORS.warning } | |||
css: { color: | |||
}); | }); | ||
small.appendChild(timerSpan); | small.appendChild(timerSpan); | ||
| Строка 716: | Строка 701: | ||
document.body.appendChild(tooltip); | document.body.appendChild(tooltip); | ||
var | var secondsLeft = SELECTION_TIMEOUT_MS / 1000; | ||
selectionCountdown = setInterval(function() { | |||
secondsLeft--; | |||
var timerSpanEl = document.getElementById('blame-timer'); | var timerSpanEl = document.getElementById('blame-timer'); | ||
if (timerSpanEl) timerSpanEl.textContent = | if (timerSpanEl) timerSpanEl.textContent = String(secondsLeft); | ||
if (secondsLeft <= 0) { | |||
if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; } | |||
} | |||
}, 1000); | }, 1000); | ||
| Строка 730: | Строка 718: | ||
document.removeEventListener('touchend', touchHandler); | document.removeEventListener('touchend', touchHandler); | ||
if ( | if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; } | ||
if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; } | if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; } | ||
| Строка 744: | Строка 732: | ||
} | } | ||
var touchDebounceTimer = null; | |||
function touchHandler() { | function touchHandler() { | ||
if (!selectionActive) return; | if (!selectionActive) return; | ||
setTimeout(handleSelection, | if (touchDebounceTimer) clearTimeout(touchDebounceTimer); | ||
touchDebounceTimer = setTimeout(function() { | |||
touchDebounceTimer = null; | |||
handleSelection(); | |||
}, 150); | |||
} | } | ||
| Строка 752: | Строка 745: | ||
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 >= | if (selectedText.length >= SELECTION_MIN_LENGTH) { | ||
var logText = 'Выделен текст (' + selectedText.length + ' символов): "' + | var logText = 'Выделен текст (' + selectedText.length + ' символов): "' + | ||
selectedText.substring(0, 50) + | selectedText.substring(0, 50) + | ||
| Строка 762: | Строка 755: | ||
findAuthor(selectedText); | findAuthor(selectedText); | ||
} else if (selectedText.length > 0) { | } else if (selectedText.length > 0) { | ||
addLog('Слишком короткий текст (' + selectedText.length + ' символов, нужно минимум | addLog('Слишком короткий текст (' + selectedText.length + | ||
' символов, нужно минимум ' + SELECTION_MIN_LENGTH + ')', 'warning'); | |||
} | } | ||
} | } | ||
| Строка 774: | Строка 768: | ||
cleanup(); | cleanup(); | ||
} | } | ||
}, | }, SELECTION_TIMEOUT_MS); | ||
} | } | ||
| Строка 782: | Строка 776: | ||
var title = pageInfo.title; | var title = pageInfo.title; | ||
addLog('Начинаем поиск для страницы: ' + | addLog('Начинаем поиск для страницы: ' + title, 'info'); | ||
addLog('Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"'), '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() { | ||
if (finished) return; | |||
addLog('Глобальный таймаут: сервер не отвечает', 'error'); | addLog('Глобальный таймаут (' + (GLOBAL_TIMEOUT_MS / 1000) + | ||
}, | ' с): сервер не отвечает или история слишком велика', 'error'); | ||
finish(); | |||
}, GLOBAL_TIMEOUT_MS); | |||
getRevisions(title, function(revisions) { | getRevisions(title, function(revisions) { | ||
if (finished) return; | |||
addLog('Получено ревизий: ' + revisions.length, 'info'); | addLog('Получено ревизий: ' + revisions.length, 'info'); | ||
if (revisions.length === 0) { | if (revisions.length === 0) { | ||
addLog('Не удалось загрузить историю правок', 'error'); | addLog('Не удалось загрузить историю правок', 'error'); | ||
clearTimeout(globalTimeout); | |||
finish(); | |||
return; | return; | ||
} | } | ||
addLog('Начинаем поиск первого появления текста...', 'info'); | addLog('Начинаем поиск первого появления текста...', 'info'); | ||
addLog('Верификация включена (макс. попыток: ' + MAX_VERIFICATION_RETRIES + ')', 'info'); | |||
findTextAppearance(revisions, text, title, function(result) { | findTextAppearance(revisions, text, title, function(result) { | ||
clearTimeout(globalTimeout); | |||
finish(); | |||
if (result) { | if (result) { | ||
addLog('Текст найден! Автор: ' + | addLog('Текст найден! Автор: ' + result.rev.user, 'success'); | ||
showResult(result); | showResult(result); | ||
} else { | } else { | ||
| Строка 818: | Строка 822: | ||
}, function(error) { | }, function(error) { | ||
clearTimeout(globalTimeout); | clearTimeout(globalTimeout); | ||
finish(); | |||
addLog('Ошибка при запросе к API: ' + error, 'error'); | addLog('Ошибка при запросе к API: ' + error, 'error'); | ||
}); | }); | ||
| Строка 825: | Строка 829: | ||
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; | ||
function fetchRevisions() { | function fetchRevisions() { | ||
| Строка 835: | Строка 838: | ||
titles: title, | titles: title, | ||
rvprop: 'ids|timestamp|user|comment|content', | rvprop: 'ids|timestamp|user|comment|content', | ||
rvlimit: | rvlimit: REVISIONS_PER_BATCH, | ||
rvdir: 'older', | rvdir: 'older', | ||
rvslots: 'main', | rvslots: 'main', | ||
formatversion: 2 | formatversion: 2 | ||
}; | }; | ||
if (continueParam) { | |||
if (continueParam | params.rvcontinue = continueParam; | ||
} | } | ||
absApiRequest(params, function(data) { | absApiRequest(params, function(data) { | ||
if (data.error) { | if (data.error) { | ||
addLog('Ошибка API: ' + | addLog('Ошибка API: ' + data.error.info, 'error'); | ||
if (errorCallback) errorCallback(data.error.info); | if (errorCallback) errorCallback(data.error.info); | ||
return; | return; | ||
| Строка 873: | Строка 873: | ||
user: (rev.user && typeof rev.user === 'string') ? rev.user : 'Аноним', | user: (rev.user && typeof rev.user === 'string') ? rev.user : 'Аноним', | ||
comment: (rev.comment && typeof rev.comment === 'string') ? rev.comment : '—', | comment: (rev.comment && typeof rev.comment === 'string') ? rev.comment : '—', | ||
content: (rev.slots && rev.slots.main && rev.slots.main.content) ? | content: (rev.slots && rev.slots.main && rev.slots.main.content) | ||
? rev.slots.main.content : '' | |||
}); | }); | ||
}); | }); | ||
totalFetched += page.revisions.length; | totalFetched += page.revisions.length; | ||
addLog('Загружено ревизий: ' + totalFetched + '/' + | addLog('Загружено ревизий: ' + totalFetched + '/' + MAX_REVISIONS, 'info'); | ||
} else { | } else { | ||
addLog('У страницы нет истории правок', 'warning'); | addLog('У страницы нет истории правок', 'warning'); | ||
| Строка 885: | Строка 885: | ||
} | } | ||
if (data.continue && totalFetched < | if (data.continue && typeof data.continue.rvcontinue === 'string' && | ||
continueParam = | totalFetched < MAX_REVISIONS) { | ||
continueParam = data.continue.rvcontinue; | |||
fetchRevisions(); | fetchRevisions(); | ||
} else { | } else { | ||
if (totalFetched >= | if (totalFetched >= MAX_REVISIONS) { | ||
addLog('Достигнут лимит загрузки (' + | addLog('Достигнут лимит загрузки (' + MAX_REVISIONS + ' ревизий)', 'warning'); | ||
} | } | ||
callback(revisions); | callback(revisions); | ||
| Строка 901: | Строка 902: | ||
function findTextAppearance(revisions, text, title, callback) { | function findTextAppearance(revisions, text, title, callback) { | ||
var | var count = revisions.length; | ||
addLog('Анализируем ' + | addLog('Анализируем ' + count + ' ревизий от старых к новым', 'info'); | ||
var | var rejectedRevisions = new Set(); | ||
var | var lastCandidate = null; | ||
var retries = 0; | |||
var i = count - 1; | |||
var rev = | |||
while (i >= 0 && retries <= MAX_VERIFICATION_RETRIES) { | |||
var rev = revisions[i]; | |||
var content = rev.content || ''; | var content = rev.content || ''; | ||
if ( | if (rejectedRevisions.has(rev.revid)) { | ||
i--; | |||
continue; | |||
} | } | ||
if (content.indexOf(text) === -1) continue; | if (content.indexOf(text) === -1) { | ||
i--; | |||
continue; | |||
} | |||
addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info'); | addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info'); | ||
if (i === | if (i === count - 1) { | ||
addLog('Текст есть в самой первой ревизии страницы', 'info'); | addLog('Текст есть в самой первой ревизии страницы', 'info'); | ||
callback({ rev: rev, title: title }); | |||
return; | |||
} | } | ||
var previousContent = | var previousContent = (revisions[i + 1] && revisions[i + 1].content) || ''; | ||
var appearsInCurrent = content.indexOf(text) !== -1; | |||
var appearsInPrevious = previousContent.indexOf(text) !== -1; | |||
addLog(' | |||
if (appearsInCurrent && !appearsInPrevious) { | |||
addLog('Верификация пройдена: текст появился именно в этой правке', 'success'); | |||
callback({ rev: rev, title: title }); | |||
return; | |||
} | } | ||
addLog(' | lastCandidate = rev; | ||
rejectedRevisions.add(rev.revid); | |||
retries++; | |||
addLog( | |||
'Верификация не пройдена (текст был и в предыдущей правке). ' + | |||
'Попытка ' + retries + '/' + MAX_VERIFICATION_RETRIES + ', продолжаем поиск...', | |||
'warning' | |||
); | |||
i--; | |||
} | } | ||
if ( | if (lastCandidate) { | ||
addLog(' | addLog( | ||
callback( | 'Достигнут лимит попыток верификации. Возвращаю последнего кандидата: ' + | ||
lastCandidate.revid, | |||
'warning' | |||
); | |||
callback({ rev: lastCandidate, title: title }); | |||
return; | return; | ||
} | } | ||
callback( | addLog('Текст не найден ни в одной ревизии', 'error'); | ||
callback(null); | |||
} | } | ||
| Строка 950: | Строка 975: | ||
var date = new Date(rev.timestamp); | var date = new Date(rev.timestamp); | ||
var formattedDate = date.toLocaleString('ru', { | var formattedDate; | ||
try { | |||
formattedDate = date.toLocaleString('ru', { | |||
year: 'numeric', month: 'long', day: 'numeric', | |||
hour: '2-digit', minute: '2-digit', timeZone: 'UTC' | |||
}) + ' (UTC)'; | |||
} catch (e) { | |||
formattedDate = rev.timestamp; | |||
} | |||
addLog('Результат: автор ' + | addLog('Результат: автор ' + rev.user + ', дата ' + formattedDate, 'success'); | ||
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: | Строка 1006: | ||
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: | Строка 1019: | ||
}); | }); | ||
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(' ' + | userP.appendChild(document.createTextNode(' ' + rev.user)); | ||
modal.appendChild(userP); | modal.appendChild(userP); | ||
| Строка 1012: | Строка 1038: | ||
var commentP = createSafeElement('p'); | var commentP = createSafeElement('p'); | ||
commentP.appendChild(createSafeElement('strong', { text: 'Комментарий:' })); | commentP.appendChild(createSafeElement('strong', { text: 'Комментарий:' })); | ||
commentP.appendChild(document.createTextNode(' "' + | commentP.appendChild(document.createTextNode(' "' + rev.comment + '"')); | ||
modal.appendChild(commentP); | modal.appendChild(commentP); | ||
| Строка 1018: | Строка 1044: | ||
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: | Строка 1055: | ||
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: | Строка 1068: | ||
var closeButton = createSafeElement('button', { | var closeButton = createSafeElement('button', { | ||
id: 'blame-close', | id: 'blame-close', text: 'Закрыть', | ||
css: { | css: { | ||
background: colors.accent, color: colors.btnText, | background: colors.accent, color: colors.btnText, | ||
| Строка 1058: | Строка 1085: | ||
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: | Строка 1108: | ||
var div = createSafeElement('div', { | var div = createSafeElement('div', { | ||
id: 'blame-loading', | id: 'blame-loading', text: message || 'Загрузка...', | ||
css: { | css: { | ||
position: 'fixed', top: '20px', right: '20px', | position: 'fixed', top: '20px', right: '20px', | ||