MediaWiki:Gadget-blamefinder.js: различия между версиями
Перейти к навигации
Перейти к поиску
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| (не показано 16 промежуточных версий этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Gadget: Blame Finder | * Gadget: Blame Finder | ||
* Версия | * Версия 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 | // ===== ЭКРАНИРОВАНИЕ ===== | ||
function escapeText(text) { | |||
if (text === undefined || text === null) return ''; | if (text === undefined || text === null) return ''; | ||
return String(text) | return String(text) | ||
| Строка 46: | Строка 75: | ||
.replace(/>/g, '>') | .replace(/>/g, '>') | ||
.replace(/"/g, '"') | .replace(/"/g, '"') | ||
.replace(/'/g, '' | .replace(/'/g, '''); | ||
} | } | ||
function | function sanitizeUrl(url) { | ||
if ( | if (!url || typeof url !== 'string') return null; | ||
var trimmed = url.trim(); | |||
if (trimmed === '') return null; | |||
if (trimmed.charAt(0) === '#') return trimmed; | |||
if (trimmed.charAt(0) === '/' && trimmed.charAt(1) !== '/') return trimmed; | |||
if ( | 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) { | function createSafeElement(tag, options) { | ||
var element = document.createElement(tag); | var element = document.createElement(tag); | ||
if (!options) return element; | if (!options) return element; | ||
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; | |||
} | } | ||
| Строка 85: | Строка 111: | ||
Object.keys(options.attrs).forEach(function(key) { | Object.keys(options.attrs).forEach(function(key) { | ||
if (key === 'href' || key === 'src') { | if (key === 'href' || key === 'src') { | ||
var | var safe = sanitizeUrl(options.attrs[key]); | ||
if ( | if (safe !== null) element.setAttribute(key, safe); | ||
} else { | } else { | ||
element.setAttribute(key, options.attrs[key]); | element.setAttribute(key, String(options.attrs[key])); | ||
} | } | ||
}); | }); | ||
} | } | ||
return element; | return element; | ||
} | } | ||
function createSafeLink(url, text, title) { | function createSafeLink(url, text, title) { | ||
var safeUrl = | var safeUrl = sanitizeUrl(url) || '#'; | ||
return createSafeElement('a', { | |||
text: text, | text: text, | ||
attrs: { | attrs: { | ||
| Строка 120: | Строка 129: | ||
target: '_blank', | target: '_blank', | ||
rel: 'noopener noreferrer', | rel: 'noopener noreferrer', | ||
title: title | title: title || text | ||
} | } | ||
}); | }); | ||
} | } | ||
| Строка 133: | Строка 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; | ||
if (html.classList.contains('skin-theme-clientpref-night')) | var body = document.body; | ||
if (html.classList.contains('skin-theme-clientpref-os')) { | if (html.classList.contains('skin-theme-clientpref-night')) result = true; | ||
else if (html.classList.contains('skin-theme-clientpref-day')) result = false; | |||
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; | ||
var isSpecial = false; | var isSpecial = false; | ||
var pathname = window.location.pathname || ''; | var pathname = window.location.pathname || ''; | ||
var search = window.location.search || ''; | var search = window.location.search || ''; | ||
if ( | 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 { | try { | ||
var urlParams = new URLSearchParams(search); | 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) { | |||
if (pathname. | |||
var pathTitle = pathname.split('/wiki/')[1]; | var pathTitle = pathname.split('/wiki/')[1]; | ||
if (pathTitle) { | if (pathTitle) { | ||
try { | try { pathTitle = decodeURIComponent(pathTitle); } catch (e) {} | ||
pathTitle = pathTitle.split('?')[0].split('#')[0]; | |||
classifyTitle(pathTitle); | |||
title = validateTitle(pathTitle); | title = validateTitle(pathTitle); | ||
} | } | ||
} else { | } else { | ||
var | var segments = pathname.split('/').filter(function(s) { return s.length > 0; }); | ||
if ( | 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) { | } catch (e) { | ||
| Строка 217: | Строка 251: | ||
} | } | ||
return { | return { title: title || 'Main_Page', isArticle: namespace === 0 && !isSpecial }; | ||
} | } | ||
function | // ===== API ===== | ||
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('&'); | ||
| Строка 249: | Строка 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); | ||
xhr.setRequestHeader('Api-User-Agent', 'BlameFinder/ | xhr.setRequestHeader('Api-User-Agent', 'BlameFinder/2.0'); | ||
xhr.onreadystatechange = function() { | xhr.onreadystatechange = function() { | ||
if (completed) return; | if (completed) return; | ||
if (xhr.readyState === 4) { | if (xhr.readyState === 4) { | ||
if (xhr.status === 200) { | if (xhr.status === 200) { | ||
var contentType = xhr.getResponseHeader('Content-Type') || ''; | var contentType = xhr.getResponseHeader('Content-Type') || ''; | ||
if ( | if (contentType.indexOf('application/json') === -1 && | ||
contentType.indexOf('text/javascript') === -1) { | |||
clearTimeout(timeoutId); | clearTimeout(timeoutId); | ||
completed = true; | completed = true; | ||
| Строка 271: | Строка 294: | ||
return; | return; | ||
} | } | ||
try { | try { | ||
var data = JSON.parse(xhr.responseText); | var data = JSON.parse(xhr.responseText); | ||
if (!data || typeof data !== 'object') | if (!data || typeof data !== 'object') throw new Error('Invalid response'); | ||
clearTimeout(timeoutId); | clearTimeout(timeoutId); | ||
completed = true; | completed = true; | ||
| Строка 307: | Строка 327: | ||
} | } | ||
// ===== ЛОГ-ПАНЕЛЬ ===== | |||
var logPanel = null; | var logPanel = null; | ||
var logEntries = []; | var logEntries = []; | ||
var logVisible = false; | |||
function createLogPanel() { | function createLogPanel() { | ||
| Строка 316: | Строка 338: | ||
id: 'blame-log-panel', | id: 'blame-log-panel', | ||
css: { | css: { | ||
position: 'fixed', | position: 'fixed', bottom: '80px', right: '20px', | ||
width: LOG_WIDTH + 'px', | |||
maxHeight: LOG_MAX_HEIGHT_CSS, | |||
width: ' | |||
maxHeight: | |||
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' | ||
| Строка 337: | Строка 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 | |||
} | } | ||
}); | }); | ||
| Строка 347: | Строка 361: | ||
var titleSpan = createSafeElement('span', { | var titleSpan = createSafeElement('span', { | ||
text: 'Логи BlameFinder', | text: 'Логи BlameFinder', | ||
css: { | css: { color: COLORS.primary, fontWeight: 'bold' } | ||
}); | }); | ||
| Строка 356: | Строка 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'); | ||
| Строка 396: | Строка 397: | ||
var content = createSafeElement('div', { | var content = createSafeElement('div', { | ||
id: 'blame-log-content', | id: 'blame-log-content', | ||
css: { | css: { wordBreak: 'break-word' } | ||
}); | }); | ||
| Строка 411: | Строка 410: | ||
}; | }; | ||
toggleButton.onclick = function(e) { | toggleButton.onclick = function(e) { | ||
e.stopPropagation(); | e.stopPropagation(); | ||
logVisible = !logVisible; | logVisible = !logVisible; | ||
logPanel.style.display = logVisible ? 'block' : 'none'; | logPanel.style.display = logVisible ? 'block' : 'none'; | ||
syncLogToggleLabel(); | |||
}; | }; | ||
logPanel.style.display = 'none'; | |||
} | |||
function showLogPanel() { | |||
if (!logPanel || logVisible) return; | |||
logVisible = true; | |||
logPanel.style.display = 'block'; | logPanel.style.display = 'block'; | ||
syncLogToggleLabel(); | |||
positionLogPanelNearButton(); | |||
} | |||
function syncLogToggleLabel() { | |||
var toggle = document.getElementById('blame-toggle'); | |||
if (toggle) toggle.textContent = logVisible ? 'Скрыть' : 'Показать'; | |||
} | } | ||
function | function positionLogPanelNearButton() { | ||
var | if (!logPanel) return; | ||
var | var btn = document.getElementById('blame-finder-button'); | ||
if (!btn) return; | |||
if ( | |||
if ( | var r = btn.getBoundingClientRect(); | ||
var panelW = Math.min(LOG_WIDTH, window.innerWidth - 20); | |||
var panelH = Math.min(300, window.innerHeight * 0.5); | |||
var left = r.left; | |||
if (left + panelW > window.innerWidth - 10) { | |||
left = Math.max(10, window.innerWidth - panelW - 10); | |||
} | |||
var top = r.top - panelH - 10; | |||
if (top < 10) { | |||
top = Math.min(r.bottom + 10, window.innerHeight - panelH - 10); | |||
} | |||
logPanel.style.left = left + 'px'; | |||
logPanel.style.top = top + 'px'; | |||
logPanel.style.right = 'auto'; | |||
logPanel.style.bottom = 'auto'; | |||
logPanel.style.width = panelW + 'px'; | |||
} | |||
function addLog(message, type) { | |||
var timestamp = new Date().toLocaleTimeString('ru', { timeZoneName: 'short' }); | |||
var color = COLORS.success; | |||
if (type === 'error') color = COLORS.danger; | |||
else if (type === 'warning') color = COLORS.warning; | |||
if (logEntries.length > | logEntries.unshift({ time: timestamp, text: String(message), color: color }); | ||
if (logEntries.length > LOG_MAX_ENTRIES) logEntries.pop(); | |||
updateLogDisplay(); | updateLogDisplay(); | ||
} | } | ||
| Строка 444: | Строка 473: | ||
var content = document.getElementById('blame-log-content'); | var content = document.getElementById('blame-log-content'); | ||
if (!content) return; | if (!content) return; | ||
while (content.firstChild) content.removeChild(content.firstChild); | |||
while (content.firstChild) | |||
logEntries.forEach(function(entry) { | logEntries.forEach(function(entry) { | ||
var entryDiv = createSafeElement('div', { | var entryDiv = createSafeElement('div', { | ||
css: { | css: { color: entry.color, marginBottom: '3px' } | ||
}); | }); | ||
| Строка 460: | Строка 483: | ||
content.appendChild(entryDiv); | content.appendChild(entryDiv); | ||
}); | }); | ||
} | |||
// ===== КНОПКА + DRAG ===== | |||
function clamp(v, min, max) { | |||
return Math.max(min, Math.min(max, v)); | |||
} | } | ||
function addButton() { | function addButton() { | ||
addLog('Инициализация BlameFinder для | if (document.getElementById('blame-finder-button')) return; | ||
addLog('Инициализация BlameFinder для ' + window.location.host, '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', | ||
background: COLORS.primary, color: 'white', | |||
padding: '10px 20px', borderRadius: '5px', | |||
background: | cursor: 'grab', zIndex: '9999', | ||
fontFamily: 'sans-serif', fontSize: '14px', | |||
padding: '10px 20px', | boxShadow: '0 2px 10px rgba(0,0,0,0.3)', | ||
userSelect: 'none', webkitUserSelect: 'none', | |||
cursor: ' | touchAction: 'none', transition: 'background 0.15s' | ||
fontFamily: 'sans-serif', | |||
boxShadow: '0 2px 10px rgba(0,0,0,0.3)' | |||
} | } | ||
}); | }); | ||
button. | document.body.appendChild(button); | ||
createLogPanel(); | |||
}; | restoreButtonPosition(button); | ||
makeButtonDraggable(button); | |||
addLog('Кнопка добавлена', 'success'); | |||
} | |||
function restoreButtonPosition(button) { | |||
var saved = null; | |||
try { | |||
saved = JSON.parse(localStorage.getItem(BUTTON_STORAGE_KEY) || 'null'); | |||
} catch (e) { | |||
saved = null; | |||
} | |||
if (!saved || typeof saved.left !== 'number' || typeof saved.top !== 'number') return; | |||
var rect = button.getBoundingClientRect(); | |||
var w = rect.width || 120; | |||
var h = rect.height || 40; | |||
var left = clamp(saved.left, 0, window.innerWidth - w); | |||
var top = clamp(saved.top, 0, window.innerHeight - h); | |||
button.style.right = 'auto'; | |||
button.style.bottom = 'auto'; | |||
button.style.left = left + 'px'; | |||
button.style.top = top + 'px'; | |||
} | |||
function saveButtonPosition(button) { | |||
var rect = button.getBoundingClientRect(); | |||
try { | |||
localStorage.setItem(BUTTON_STORAGE_KEY, JSON.stringify({ | |||
left: Math.round(rect.left), | |||
top: Math.round(rect.top) | |||
})); | |||
} catch (e) {} | |||
} | |||
function makeButtonDraggable(button) { | |||
var startX = 0, startY = 0, startLeft = 0, startTop = 0; | |||
var pointerId = null; | |||
var moved = false; | |||
function onPointerDown(e) { | |||
if (e.pointerType === 'mouse' && e.button !== 0) return; | |||
pointerId = e.pointerId; | |||
moved = false; | |||
var rect = button.getBoundingClientRect(); | |||
startLeft = rect.left; | |||
startTop = rect.top; | |||
startX = e.clientX; | |||
startY = e.clientY; | |||
button.style.right = 'auto'; | |||
button.style.bottom = 'auto'; | |||
button.style.left = startLeft + 'px'; | |||
button.style.top = startTop + 'px'; | |||
button.style.cursor = 'grabbing'; | |||
button.dataset.dragging = '1'; | |||
try { button.setPointerCapture(pointerId); } catch (err) {} | |||
button.addEventListener('pointermove', onPointerMove); | |||
button.addEventListener('pointerup', onPointerUp); | |||
button.addEventListener('pointercancel', onPointerUp); | |||
} | |||
function onPointerMove(e) { | |||
if (e.pointerId !== pointerId) return; | |||
var dx = e.clientX - startX; | |||
var dy = e.clientY - startY; | |||
if (!moved && (Math.abs(dx) > DRAG_MOVE_THRESHOLD || Math.abs(dy) > DRAG_MOVE_THRESHOLD)) { | |||
moved = true; | |||
} | |||
if (!moved) return; | |||
var rect = button.getBoundingClientRect(); | |||
var newLeft = clamp(startLeft + dx, 0, window.innerWidth - rect.width); | |||
var newTop = clamp(startTop + dy, 0, window.innerHeight - rect.height); | |||
button.style.left = newLeft + 'px'; | |||
button.style.top = newTop + 'px'; | |||
if (logVisible) positionLogPanelNearButton(); | |||
e.preventDefault(); | e.preventDefault(); | ||
} | |||
function onPointerUp(e) { | |||
if (e.pointerId !== pointerId) return; | |||
try { button.releasePointerCapture(pointerId); } catch (err) {} | |||
button.removeEventListener('pointermove', onPointerMove); | |||
button.removeEventListener('pointerup', onPointerUp); | |||
button.removeEventListener('pointercancel', onPointerUp); | |||
button.style.cursor = 'grab'; | |||
delete button.dataset.dragging; | |||
if (moved) saveButtonPosition(button); | |||
pointerId = null; | |||
} | |||
button.addEventListener('pointerdown', onPointerDown); | |||
button.addEventListener('mouseenter', function() { | |||
if (!button.dataset.dragging) button.style.background = COLORS.primaryHover; | |||
}); | |||
button.addEventListener('mouseleave', function() { | |||
if (!button.dataset.dragging) button.style.background = COLORS.primary; | |||
}); | |||
function handleActivate(e) { | |||
if (moved) { | |||
moved = false; | |||
if (e) { e.preventDefault(); e.stopPropagation(); } | |||
return; | |||
} | |||
if (e) { e.preventDefault(); e.stopPropagation(); } | |||
showLogPanel(); | |||
activateSelectionMode(); | activateSelectionMode(); | ||
} | |||
button.addEventListener('click', handleActivate); | |||
button.addEventListener('keydown', function(e) { | |||
if (e.key === 'Enter' || e.key === ' ') handleActivate(e); | |||
}); | }); | ||
button.addEventListener('dblclick', function(e) { | |||
e.preventDefault(); | |||
e.stopPropagation(); | |||
try { localStorage.removeItem(BUTTON_STORAGE_KEY); } catch (err) {} | |||
button.style.left = 'auto'; | |||
button.style.top = 'auto'; | |||
button.style.right = '20px'; | |||
button.style.bottom = '20px'; | |||
if (logVisible) positionLogPanelNearButton(); | |||
}); | |||
window.addEventListener('resize', function() { | |||
var rect = button.getBoundingClientRect(); | |||
if (rect.left + rect.width > window.innerWidth || | |||
rect.top + rect.height > window.innerHeight) { | |||
button.style.left = clamp(rect.left, 0, window.innerWidth - rect.width) + 'px'; | |||
button.style.top = clamp(rect.top, 0, window.innerHeight - rect.height) + 'px'; | |||
} | |||
if (logVisible) positionLogPanelNearButton(); | |||
}); | |||
} | } | ||
// ===== РЕЖИМ ВЫДЕЛЕНИЯ ===== | |||
var selectionActive = false; | var selectionActive = false; | ||
var selectionTimer = null; | var selectionTimer = null; | ||
var | var selectionCountdown = null; | ||
function activateSelectionMode() { | function activateSelectionMode() { | ||
| Строка 519: | Строка 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)' | ||
} | } | ||
}); | }); | ||
tooltip.appendChild(document.createTextNode('Выделите текст')); | |||
tooltip.appendChild( | tooltip.appendChild(document.createElement('br')); | ||
var small = createSafeElement('small', { css: { color: COLORS.warning } }); | |||
small.appendChild(document.createTextNode('осталось ')); | |||
var small = createSafeElement('small', { | |||
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: { | |||
}); | }); | ||
small.appendChild(timerSpan); | small.appendChild(timerSpan); | ||
small.appendChild(document.createTextNode(' секунд')); | |||
tooltip.appendChild(small); | tooltip.appendChild(small); | ||
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); | ||
function cleanup() { | |||
if (!selectionActive) return; | |||
selectionActive = false; | |||
document.removeEventListener('mouseup', mouseHandler); | |||
document.removeEventListener('touchend', touchHandler); | |||
if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; } | |||
if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; } | |||
var tip = document.getElementById('blame-tooltip'); | |||
if (tip && tip.parentNode) tip.parentNode.removeChild(tip); | |||
addLog('Режим выделения отключён', 'info'); | |||
} | |||
function mouseHandler() { | function mouseHandler() { | ||
| Строка 577: | Строка 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); | |||
} | } | ||
function handleSelection() { | function handleSelection() { | ||
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) + | ||
(selectedText.length > 50 ? '..."' : '"'); | (selectedText.length > 50 ? '..."' : '"'); | ||
addLog(logText, 'success'); | addLog(logText, 'success'); | ||
cleanup(); | |||
findAuthor(selectedText); | findAuthor(selectedText); | ||
} else if (selectedText.length > 0) { | } else if (selectedText.length > 0) { | ||
addLog('Слишком короткий текст (' + selectedText.length + ' символов, нужно минимум | addLog('Слишком короткий текст (' + selectedText.length + | ||
' символов, нужно минимум ' + SELECTION_MIN_LENGTH + ')', 'warning'); | |||
} | } | ||
} | } | ||
document.addEventListener('mouseup', mouseHandler); | document.addEventListener('mouseup', mouseHandler); | ||
document.addEventListener('touchend', touchHandler); | document.addEventListener('touchend', touchHandler); | ||
selectionTimer = setTimeout(function() { | |||
if (selectionActive) { | if (selectionActive) { | ||
addLog('Время вышло', 'warning'); | addLog('Время вышло', 'warning'); | ||
cleanup(); | |||
} | } | ||
}, | }, SELECTION_TIMEOUT_MS); | ||
} | } | ||
// ===== ПОИСК АВТОРА ===== | |||
function findAuthor(text) { | function findAuthor(text) { | ||
var pageInfo = getPageInfo(); | var pageInfo = getPageInfo(); | ||
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 { | ||
| Строка 682: | Строка 822: | ||
}, function(error) { | }, function(error) { | ||
clearTimeout(globalTimeout); | clearTimeout(globalTimeout); | ||
finish(); | |||
addLog('Ошибка при запросе к API: ' + error, 'error'); | addLog('Ошибка при запросе к API: ' + error, 'error'); | ||
}); | }); | ||
| Строка 689: | Строка 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() { | ||
| Строка 699: | Строка 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) { | |||
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; | ||
} | } | ||
if (!data.query || !data.query.pages || !data.query.pages[0]) { | if (!data.query || !data.query.pages || !data.query.pages[0]) { | ||
addLog('Странный ответ от API', 'error'); | addLog('Странный ответ от API', 'error'); | ||
| Строка 725: | Строка 860: | ||
var page = data.query.pages[0]; | var page = data.query.pages[0]; | ||
if (page.missing) { | if (page.missing) { | ||
addLog('Страница не найдена в API', 'error'); | addLog('Страница не найдена в API', 'error'); | ||
| Строка 739: | Строка 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'); | ||
| Строка 752: | Строка 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); | ||
| Строка 770: | Строка 902: | ||
function findTextAppearance(revisions, text, title, callback) { | function findTextAppearance(revisions, text, title, callback) { | ||
var | var count = revisions.length; | ||
addLog('Анализируем ' + | addLog('Анализируем ' + count + ' ревизий от старых к новым', 'info'); | ||
var rejectedRevisions = new Set(); | |||
var lastCandidate = null; | |||
var retries = 0; | |||
var | var i = count - 1; | ||
while (i >= 0 && retries <= MAX_VERIFICATION_RETRIES) { | |||
var rev = | 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) { | |||
i--; | |||
continue; | |||
} | } | ||
addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info'); | |||
if (i === count - 1) { | |||
addLog('Текст есть в самой первой ревизии страницы', 'info'); | |||
callback({ rev: rev, title: title }); | |||
return; | |||
} | } | ||
var previousContent = (revisions[i + 1] && revisions[i + 1].content) || ''; | |||
var appearsInCurrent = content.indexOf(text) !== -1; | |||
var appearsInPrevious = previousContent.indexOf(text) !== -1; | |||
if (appearsInCurrent && !appearsInPrevious) { | |||
addLog('Верификация пройдена: текст появился именно в этой правке', 'success'); | |||
callback({ rev: rev, title: title }); | |||
return; | |||
} | |||
lastCandidate = rev; | |||
rejectedRevisions.add(rev.revid); | |||
retries++; | |||
addLog( | |||
'Верификация не пройдена (текст был и в предыдущей правке). ' + | |||
'Попытка ' + retries + '/' + MAX_VERIFICATION_RETRIES + ', продолжаем поиск...', | |||
'warning' | |||
); | |||
i--; | |||
} | |||
if (lastCandidate) { | |||
addLog( | |||
'Достигнут лимит попыток верификации. Возвращаю последнего кандидата: ' + | |||
lastCandidate.revid, | |||
'warning' | |||
); | |||
callback({ rev: lastCandidate, title: title }); | |||
return; | |||
callback({ rev: | |||
} | } | ||
addLog('Текст не найден ни в одной ревизии', 'error'); | |||
callback(null); | |||
} | } | ||
| Строка 851: | Строка 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('Результат: автор ' + rev.user + ', дата ' + formattedDate, 'success'); | |||
var dark = isDarkTheme(); | var dark = isDarkTheme(); | ||
var colors = dark ? { | var colors = dark ? { | ||
bg: '# | bg: '#3a3d42', fg: '#ffffff', border: '#72777d', | ||
accent: '#8fb3ff', subtle: '#54595d', btnText: '#1a1a1a' | |||
accent: '# | |||
} : { | } : { | ||
bg: '#ffffff', | bg: '#ffffff', fg: '#202122', border: '#a2a9b1', | ||
accent: '#3366cc', subtle: '#eaecf0', btnText: '#ffffff' | |||
accent: '#3366cc', | |||
}; | }; | ||
| Строка 885: | Строка 999: | ||
id: 'blame-overlay', | id: 'blame-overlay', | ||
css: { | css: { | ||
position: 'fixed', | position: 'fixed', top: '0', left: '0', right: '0', bottom: '0', | ||
background: 'rgba(0,0,0,0.5)', zIndex: '9999' | |||
background: 'rgba(0,0,0,0.5)', | |||
} | } | ||
}); | }); | ||
| Строка 897: | Строка 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', | position: 'fixed', top: '50%', left: '50%', | ||
transform: 'translate(-50%, -50%)', | transform: 'translate(-50%, -50%)', | ||
background: colors.bg, | background: colors.bg, color: colors.fg, | ||
border: '2px solid ' + colors.border, | border: '2px solid ' + colors.border, | ||
borderRadius: '8px', | borderRadius: '8px', padding: '20px', | ||
zIndex: '10000', maxWidth: '500px', | |||
zIndex: '10000', | |||
boxShadow: '0 5px 20px rgba(0,0,0,0.3)', | boxShadow: '0 5px 20px rgba(0,0,0,0.3)', | ||
fontFamily: 'sans-serif' | fontFamily: 'sans-serif' | ||
| Строка 914: | Строка 1019: | ||
}); | }); | ||
var | var h3 = createSafeElement('h3', { | ||
text: 'Найден автор текста', | text: 'Найден автор текста', | ||
css: { | css: { marginTop: '0', color: colors.fg } | ||
}); | }); | ||
modal.appendChild( | h3.id = 'blame-modal-title'; | ||
modal.appendChild(h3); | |||
var userP = createSafeElement('p'); | var userP = createSafeElement('p'); | ||
userP.appendChild(createSafeElement('strong', { text: 'Участник:' })); | |||
userP.appendChild(document.createTextNode(' ' + rev.user)); | |||
userP.appendChild(document.createTextNode(' ' + | |||
modal.appendChild(userP); | modal.appendChild(userP); | ||
var dateP = createSafeElement('p'); | var dateP = createSafeElement('p'); | ||
dateP.appendChild(createSafeElement('strong', { text: 'Дата правки:' })); | |||
dateP.appendChild(document.createTextNode(' ' + formattedDate)); | dateP.appendChild(document.createTextNode(' ' + formattedDate)); | ||
modal.appendChild(dateP); | modal.appendChild(dateP); | ||
var commentP = createSafeElement('p'); | var commentP = createSafeElement('p'); | ||
commentP.appendChild(createSafeElement('strong', { text: 'Комментарий:' })); | |||
commentP.appendChild(document.createTextNode(' "' + rev.comment + '"')); | |||
commentP.appendChild(document.createTextNode(' "' + | |||
modal.appendChild(commentP); | modal.appendChild(commentP); | ||
var versionP = createSafeElement('p'); | var versionP = createSafeElement('p'); | ||
versionP.appendChild(createSafeElement('strong', { text: 'Версия:' })); | |||
versionP.appendChild(document.createTextNode(' ')); | versionP.appendChild(document.createTextNode(' ')); | ||
var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + | |||
var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&oldid=' + rev.revid; | '&oldid=' + encodeURIComponent(rev.revid); | ||
var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию'); | var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию'); | ||
versionLink.style.color | versionLink.style.setProperty('color', colors.accent, 'important'); | ||
versionLink.style. | versionLink.style.setProperty('text-decoration', 'underline', 'important'); | ||
versionP.appendChild(versionLink); | versionP.appendChild(versionLink); | ||
modal.appendChild(versionP); | modal.appendChild(versionP); | ||
var diffP = createSafeElement('p'); | var diffP = createSafeElement('p'); | ||
diffP.appendChild(createSafeElement('strong', { text: 'Дифф:' })); | |||
diffP.appendChild(document.createTextNode(' ')); | diffP.appendChild(document.createTextNode(' ')); | ||
var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + | |||
var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&diff=prev&oldid=' + rev.revid; | '&diff=prev&oldid=' + encodeURIComponent(rev.revid); | ||
var diffLink = createSafeLink(diffUrl, 'посмотреть изменения'); | var diffLink = createSafeLink(diffUrl, 'посмотреть изменения'); | ||
diffLink.style.color | diffLink.style.setProperty('color', colors.accent, 'important'); | ||
diffLink.style. | diffLink.style.setProperty('text-decoration', 'underline', 'important'); | ||
diffP.appendChild(diffLink); | diffP.appendChild(diffLink); | ||
modal.appendChild(diffP); | modal.appendChild(diffP); | ||
modal.appendChild(createSafeElement('hr', { | |||
css: { | css: { border: 'none', borderTop: '1px solid ' + colors.subtle } | ||
})); | |||
}) | |||
var closeButton = createSafeElement('button', { | var closeButton = createSafeElement('button', { | ||
id: 'blame-close', | id: 'blame-close', text: 'Закрыть', | ||
css: { | css: { | ||
background: colors.accent, | background: colors.accent, color: colors.btnText, | ||
border: 'none', padding: '8px 16px', | |||
border: 'none', | borderRadius: '4px', cursor: 'pointer' | ||
borderRadius: '4px', | |||
} | } | ||
}); | }); | ||
| Строка 993: | Строка 1083: | ||
var m = document.getElementById('blame-result-modal'); | var m = document.getElementById('blame-result-modal'); | ||
var o = document.getElementById('blame-overlay'); | var o = document.getElementById('blame-overlay'); | ||
if (m && m.parentNode) m.parentNode.removeChild(m); | |||
if (o && o.parentNode) o.parentNode.removeChild(o); | |||
document.removeEventListener('keydown', escHandler); | |||
} | |||
function escHandler(e) { | |||
if (e.key === 'Escape') closeModal(); | |||
if ( | |||
} | } | ||
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 ? '# | var bg = dark ? '#3a3d42' : '#f8f9fa'; | ||
var fg = dark ? '# | var fg = dark ? '#ffffff' : '#202122'; | ||
var border = dark ? '# | var border = dark ? '#72777d' : '#a2a9b1'; | ||
var div = createSafeElement('div', { | var div = createSafeElement('div', { | ||
id: 'blame-loading', | id: 'blame-loading', text: message || 'Загрузка...', | ||
css: { | css: { | ||
position: 'fixed', | position: 'fixed', top: '20px', right: '20px', | ||
background: bg, color: fg, | |||
background: bg, | |||
border: '1px solid ' + border, | border: '1px solid ' + border, | ||
padding: '10px 20px', | padding: '10px 20px', borderRadius: '4px', | ||
zIndex: '10000', fontFamily: 'sans-serif', | |||
zIndex: '10000', | |||
boxShadow: '0 2px 10px rgba(0,0,0,0.1)' | boxShadow: '0 2px 10px rgba(0,0,0,0.1)' | ||
} | } | ||
}); | }); | ||
document.body.appendChild(div); | document.body.appendChild(div); | ||
return div; | return div; | ||
| Строка 1035: | Строка 1123: | ||
function hideLoading(div) { | function hideLoading(div) { | ||
if (div && div.parentNode) | if (div && div.parentNode) div.parentNode.removeChild(div); | ||
} | } | ||
// ===== ЗАПУСК ===== | |||
var pageInfo = getPageInfo(); | var pageInfo = getPageInfo(); | ||
if (pageInfo.isArticle) { | if (pageInfo.isArticle) { | ||
if (document.readyState === 'complete') { | if (document.readyState === 'complete') { | ||
Текущая версия от 20:24, 15 ноября 2026
/**
* Gadget: Blame Finder
* Версия 2.0 с поддержкой ночного режима и перетаскиванием кнопки
* Назначение: поиск автора любого текста в статье
* Универсальный вики-портируемый код.
* Лицензия: MIT (opensource.org/license/mit ==> 2026, absurdopedia.wiki
* Использование:
1. Нажимаете кнопку «Кто автор?» (изначально она — в правом нижнем углу)
2. Выделяете любой текст на странице (минимум 20 символов)
3.1. В скинах Monobook и Vector-10:
· кликайте по появившейся в центре кнопке таймера (20 секунд на всё)
3.2 В скине Vector-22:
· кликайте по кнопке «Кто автор?» (20 секунд на всё)
4. Гаджет анализирует последние 1000 правок страницы
5. Находит первое появление этого текста в истории
6. Показывает:
· Имя автора
· Дату правки
· Комментарий к правке
· Ссылки на версию и diff
* Что может:
· Искать авторов фрагментов текста в статьях
· Расчитан на работу в пространствах статей и форума
· Поддерживает мышь и сенсорный экран
· Показывает панель логов с отладкой
*/
(function() {
'use strict';
if (window.self !== window.top) {
console.log('BlameFinder: не запускаемся в iframe по соображениям безопасности');
return;
}
// ===== КОНСТАНТЫ =====
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 {
if (typeof mw !== 'undefined' && mw.config && mw.config.get) {
scriptPath = mw.config.get('wgScriptPath') || SCRIPT_PATH_FALLBACK;
}
} catch (e) {
scriptPath = SCRIPT_PATH_FALLBACK;
}
// ===== ЭКРАНИРОВАНИЕ =====
function escapeText(text) {
if (text === undefined || text === null) return '';
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function sanitizeUrl(url) {
if (!url || typeof url !== 'string') return null;
var trimmed = url.trim();
if (trimmed === '') return null;
if (trimmed.charAt(0) === '#') return trimmed;
if (trimmed.charAt(0) === '/' && trimmed.charAt(1) !== '/') 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 !== undefined && options.text !== null) {
element.textContent = options.text;
}
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, String(options.attrs[key]));
}
});
}
return element;
}
function createSafeLink(url, text, title) {
var safeUrl = sanitizeUrl(url) || '#';
return createSafeElement('a', {
text: text,
attrs: {
href: safeUrl,
target: '_blank',
rel: 'noopener noreferrer',
title: title || text
}
});
}
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;
}
// ===== ТЕМА =====
var cachedDarkTheme = null;
function isDarkTheme() {
if (cachedDarkTheme !== null) return cachedDarkTheme;
var result = false;
try {
var html = document.documentElement;
var body = document.body;
if (html.classList.contains('skin-theme-clientpref-night')) result = true;
else if (html.classList.contains('skin-theme-clientpref-day')) result = false;
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) {}
cachedDarkTheme = result;
return result;
}
// ===== ИНФОРМАЦИЯ О СТРАНИЦЕ =====
var cachedPageInfo = null;
function getPageInfo() {
if (cachedPageInfo) return cachedPageInfo;
cachedPageInfo = computePageInfo();
return cachedPageInfo;
}
function computePageInfo() {
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 };
}
// ===== API =====
function absApiRequest(params, callback, errorCallback) {
var apiUrl = scriptPath + '/api.php';
params.format = 'json';
var queryString = Object.keys(params).map(function(key) {
var value = params[key];
return encodeURIComponent(key) + '=' + encodeURIComponent(value === undefined ? '' : value);
}).join('&');
var url = apiUrl + '?' + queryString;
var xhr = new XMLHttpRequest();
var timeoutId = null;
var completed = false;
timeoutId = setTimeout(function() {
if (!completed) {
completed = true;
try { xhr.abort(); } catch (e) {}
addLog('Таймаут API: сервер не отвечает', 'error');
if (errorCallback) errorCallback('timeout');
}
}, API_REQUEST_TIMEOUT_MS);
xhr.open('GET', url, true);
xhr.setRequestHeader('Api-User-Agent', 'BlameFinder/2.0');
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');
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 = [];
var logVisible = false;
function createLogPanel() {
if (logPanel) return;
logPanel = createSafeElement('div', {
id: 'blame-log-panel',
css: {
position: 'fixed', bottom: '80px', right: '20px',
width: LOG_WIDTH + 'px',
maxHeight: LOG_MAX_HEIGHT_CSS,
overflowY: 'auto',
background: COLORS.logBg, color: COLORS.success,
fontFamily: 'monospace', fontSize: '12px',
padding: '10px', borderRadius: '5px', zIndex: '9999',
border: '2px solid ' + COLORS.primary,
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 ' + COLORS.primary
}
});
var titleSpan = createSafeElement('span', {
text: 'Логи BlameFinder',
css: { color: COLORS.primary, fontWeight: 'bold' }
});
var buttonContainer = createSafeElement('div');
var clearButton = createSafeElement('button', {
id: 'blame-clear', text: 'Очистить',
css: {
background: 'none', border: '1px solid ' + COLORS.primary,
color: COLORS.primary, marginRight: '5px',
cursor: 'pointer', padding: '5px'
}
});
var toggleButton = createSafeElement('button', {
id: 'blame-toggle', text: 'Скрыть',
css: {
background: 'none', border: '1px solid ' + COLORS.primary,
color: COLORS.primary, cursor: 'pointer', padding: '5px'
}
});
['color', 'border-color'].forEach(function(prop) {
clearButton.style.setProperty(prop, COLORS.primary, 'important');
toggleButton.style.setProperty(prop, COLORS.primary, '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();
};
toggleButton.onclick = function(e) {
e.stopPropagation();
logVisible = !logVisible;
logPanel.style.display = logVisible ? 'block' : 'none';
syncLogToggleLabel();
};
logPanel.style.display = 'none';
}
function showLogPanel() {
if (!logPanel || logVisible) return;
logVisible = true;
logPanel.style.display = 'block';
syncLogToggleLabel();
positionLogPanelNearButton();
}
function syncLogToggleLabel() {
var toggle = document.getElementById('blame-toggle');
if (toggle) toggle.textContent = logVisible ? 'Скрыть' : 'Показать';
}
function positionLogPanelNearButton() {
if (!logPanel) return;
var btn = document.getElementById('blame-finder-button');
if (!btn) return;
var r = btn.getBoundingClientRect();
var panelW = Math.min(LOG_WIDTH, window.innerWidth - 20);
var panelH = Math.min(300, window.innerHeight * 0.5);
var left = r.left;
if (left + panelW > window.innerWidth - 10) {
left = Math.max(10, window.innerWidth - panelW - 10);
}
var top = r.top - panelH - 10;
if (top < 10) {
top = Math.min(r.bottom + 10, window.innerHeight - panelH - 10);
}
logPanel.style.left = left + 'px';
logPanel.style.top = top + 'px';
logPanel.style.right = 'auto';
logPanel.style.bottom = 'auto';
logPanel.style.width = panelW + 'px';
}
function addLog(message, type) {
var timestamp = new Date().toLocaleTimeString('ru', { timeZoneName: 'short' });
var color = COLORS.success;
if (type === 'error') color = COLORS.danger;
else if (type === 'warning') color = COLORS.warning;
logEntries.unshift({ time: timestamp, text: String(message), color: color });
if (logEntries.length > LOG_MAX_ENTRIES) 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);
});
}
// ===== КНОПКА + DRAG =====
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
function addButton() {
if (document.getElementById('blame-finder-button')) return;
addLog('Инициализация BlameFinder для ' + window.location.host, 'info');
var button = createSafeElement('div', {
id: 'blame-finder-button',
text: 'Кто автор?',
attrs: { role: 'button', tabindex: '0', 'aria-label': 'Найти автора выделенного текста' },
css: {
position: 'fixed', right: '20px', bottom: '20px',
background: COLORS.primary, color: 'white',
padding: '10px 20px', borderRadius: '5px',
cursor: 'grab', zIndex: '9999',
fontFamily: 'sans-serif', fontSize: '14px',
boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
userSelect: 'none', webkitUserSelect: 'none',
touchAction: 'none', transition: 'background 0.15s'
}
});
document.body.appendChild(button);
createLogPanel();
restoreButtonPosition(button);
makeButtonDraggable(button);
addLog('Кнопка добавлена', 'success');
}
function restoreButtonPosition(button) {
var saved = null;
try {
saved = JSON.parse(localStorage.getItem(BUTTON_STORAGE_KEY) || 'null');
} catch (e) {
saved = null;
}
if (!saved || typeof saved.left !== 'number' || typeof saved.top !== 'number') return;
var rect = button.getBoundingClientRect();
var w = rect.width || 120;
var h = rect.height || 40;
var left = clamp(saved.left, 0, window.innerWidth - w);
var top = clamp(saved.top, 0, window.innerHeight - h);
button.style.right = 'auto';
button.style.bottom = 'auto';
button.style.left = left + 'px';
button.style.top = top + 'px';
}
function saveButtonPosition(button) {
var rect = button.getBoundingClientRect();
try {
localStorage.setItem(BUTTON_STORAGE_KEY, JSON.stringify({
left: Math.round(rect.left),
top: Math.round(rect.top)
}));
} catch (e) {}
}
function makeButtonDraggable(button) {
var startX = 0, startY = 0, startLeft = 0, startTop = 0;
var pointerId = null;
var moved = false;
function onPointerDown(e) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
pointerId = e.pointerId;
moved = false;
var rect = button.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
startX = e.clientX;
startY = e.clientY;
button.style.right = 'auto';
button.style.bottom = 'auto';
button.style.left = startLeft + 'px';
button.style.top = startTop + 'px';
button.style.cursor = 'grabbing';
button.dataset.dragging = '1';
try { button.setPointerCapture(pointerId); } catch (err) {}
button.addEventListener('pointermove', onPointerMove);
button.addEventListener('pointerup', onPointerUp);
button.addEventListener('pointercancel', onPointerUp);
}
function onPointerMove(e) {
if (e.pointerId !== pointerId) return;
var dx = e.clientX - startX;
var dy = e.clientY - startY;
if (!moved && (Math.abs(dx) > DRAG_MOVE_THRESHOLD || Math.abs(dy) > DRAG_MOVE_THRESHOLD)) {
moved = true;
}
if (!moved) return;
var rect = button.getBoundingClientRect();
var newLeft = clamp(startLeft + dx, 0, window.innerWidth - rect.width);
var newTop = clamp(startTop + dy, 0, window.innerHeight - rect.height);
button.style.left = newLeft + 'px';
button.style.top = newTop + 'px';
if (logVisible) positionLogPanelNearButton();
e.preventDefault();
}
function onPointerUp(e) {
if (e.pointerId !== pointerId) return;
try { button.releasePointerCapture(pointerId); } catch (err) {}
button.removeEventListener('pointermove', onPointerMove);
button.removeEventListener('pointerup', onPointerUp);
button.removeEventListener('pointercancel', onPointerUp);
button.style.cursor = 'grab';
delete button.dataset.dragging;
if (moved) saveButtonPosition(button);
pointerId = null;
}
button.addEventListener('pointerdown', onPointerDown);
button.addEventListener('mouseenter', function() {
if (!button.dataset.dragging) button.style.background = COLORS.primaryHover;
});
button.addEventListener('mouseleave', function() {
if (!button.dataset.dragging) button.style.background = COLORS.primary;
});
function handleActivate(e) {
if (moved) {
moved = false;
if (e) { e.preventDefault(); e.stopPropagation(); }
return;
}
if (e) { e.preventDefault(); e.stopPropagation(); }
showLogPanel();
activateSelectionMode();
}
button.addEventListener('click', handleActivate);
button.addEventListener('keydown', function(e) {
if (e.key === 'Enter' || e.key === ' ') handleActivate(e);
});
button.addEventListener('dblclick', function(e) {
e.preventDefault();
e.stopPropagation();
try { localStorage.removeItem(BUTTON_STORAGE_KEY); } catch (err) {}
button.style.left = 'auto';
button.style.top = 'auto';
button.style.right = '20px';
button.style.bottom = '20px';
if (logVisible) positionLogPanelNearButton();
});
window.addEventListener('resize', function() {
var rect = button.getBoundingClientRect();
if (rect.left + rect.width > window.innerWidth ||
rect.top + rect.height > window.innerHeight) {
button.style.left = clamp(rect.left, 0, window.innerWidth - rect.width) + 'px';
button.style.top = clamp(rect.top, 0, window.innerHeight - rect.height) + 'px';
}
if (logVisible) positionLogPanelNearButton();
});
}
// ===== РЕЖИМ ВЫДЕЛЕНИЯ =====
var selectionActive = false;
var selectionTimer = null;
var selectionCountdown = 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: COLORS.primary, 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: COLORS.warning } });
small.appendChild(document.createTextNode('осталось '));
var timerSpan = createSafeElement('span', {
id: 'blame-timer', text: String(SELECTION_TIMEOUT_MS / 1000),
css: { color: COLORS.warning }
});
small.appendChild(timerSpan);
small.appendChild(document.createTextNode(' секунд'));
tooltip.appendChild(small);
document.body.appendChild(tooltip);
var secondsLeft = SELECTION_TIMEOUT_MS / 1000;
selectionCountdown = setInterval(function() {
secondsLeft--;
var timerSpanEl = document.getElementById('blame-timer');
if (timerSpanEl) timerSpanEl.textContent = String(secondsLeft);
if (secondsLeft <= 0) {
if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; }
}
}, 1000);
function cleanup() {
if (!selectionActive) return;
selectionActive = false;
document.removeEventListener('mouseup', mouseHandler);
document.removeEventListener('touchend', touchHandler);
if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; }
if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; }
var tip = document.getElementById('blame-tooltip');
if (tip && tip.parentNode) tip.parentNode.removeChild(tip);
addLog('Режим выделения отключён', 'info');
}
function mouseHandler() {
if (!selectionActive) return;
handleSelection();
}
var touchDebounceTimer = null;
function touchHandler() {
if (!selectionActive) return;
if (touchDebounceTimer) clearTimeout(touchDebounceTimer);
touchDebounceTimer = setTimeout(function() {
touchDebounceTimer = null;
handleSelection();
}, 150);
}
function handleSelection() {
if (!selectionActive) return;
var selection = window.getSelection();
var selectedText = selection ? selection.toString().trim() : '';
if (selectedText.length >= SELECTION_MIN_LENGTH) {
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 +
' символов, нужно минимум ' + SELECTION_MIN_LENGTH + ')', 'warning');
}
}
document.addEventListener('mouseup', mouseHandler);
document.addEventListener('touchend', touchHandler);
selectionTimer = setTimeout(function() {
if (selectionActive) {
addLog('Время вышло', 'warning');
cleanup();
}
}, SELECTION_TIMEOUT_MS);
}
// ===== ПОИСК АВТОРА =====
function findAuthor(text) {
var pageInfo = getPageInfo();
var title = pageInfo.title;
addLog('Начинаем поиск для страницы: ' + title, 'info');
addLog('Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"'), 'info');
var loadingDiv = showLoading('Анализирую историю правок...');
addLog('Запрашиваем историю правок через API', 'info');
var finished = false;
function finish() {
if (finished) return;
finished = true;
hideLoading(loadingDiv);
}
var globalTimeout = setTimeout(function() {
if (finished) return;
addLog('Глобальный таймаут (' + (GLOBAL_TIMEOUT_MS / 1000) +
' с): сервер не отвечает или история слишком велика', 'error');
finish();
}, GLOBAL_TIMEOUT_MS);
getRevisions(title, function(revisions) {
if (finished) return;
addLog('Получено ревизий: ' + revisions.length, 'info');
if (revisions.length === 0) {
addLog('Не удалось загрузить историю правок', 'error');
clearTimeout(globalTimeout);
finish();
return;
}
addLog('Начинаем поиск первого появления текста...', 'info');
addLog('Верификация включена (макс. попыток: ' + MAX_VERIFICATION_RETRIES + ')', 'info');
findTextAppearance(revisions, text, title, function(result) {
clearTimeout(globalTimeout);
finish();
if (result) {
addLog('Текст найден! Автор: ' + result.rev.user, 'success');
showResult(result);
} else {
addLog('Текст не найден в истории', 'error');
}
});
}, function(error) {
clearTimeout(globalTimeout);
finish();
addLog('Ошибка при запросе к API: ' + error, 'error');
});
}
function getRevisions(title, callback, errorCallback) {
var revisions = [];
var continueParam = null;
var totalFetched = 0;
function fetchRevisions() {
var params = {
action: 'query',
prop: 'revisions',
titles: title,
rvprop: 'ids|timestamp|user|comment|content',
rvlimit: REVISIONS_PER_BATCH,
rvdir: 'older',
rvslots: 'main',
formatversion: 2
};
if (continueParam) {
params.rvcontinue = continueParam;
}
absApiRequest(params, function(data) {
if (data.error) {
addLog('Ошибка API: ' + 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 + '/' + MAX_REVISIONS, 'info');
} else {
addLog('У страницы нет истории правок', 'warning');
callback(revisions);
return;
}
if (data.continue && typeof data.continue.rvcontinue === 'string' &&
totalFetched < MAX_REVISIONS) {
continueParam = data.continue.rvcontinue;
fetchRevisions();
} else {
if (totalFetched >= MAX_REVISIONS) {
addLog('Достигнут лимит загрузки (' + MAX_REVISIONS + ' ревизий)', 'warning');
}
callback(revisions);
}
}, errorCallback);
}
fetchRevisions();
}
function findTextAppearance(revisions, text, title, callback) {
var count = revisions.length;
addLog('Анализируем ' + count + ' ревизий от старых к новым', 'info');
var rejectedRevisions = new Set();
var lastCandidate = null;
var retries = 0;
var i = count - 1;
while (i >= 0 && retries <= MAX_VERIFICATION_RETRIES) {
var rev = revisions[i];
var content = rev.content || '';
if (rejectedRevisions.has(rev.revid)) {
i--;
continue;
}
if (content.indexOf(text) === -1) {
i--;
continue;
}
addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info');
if (i === count - 1) {
addLog('Текст есть в самой первой ревизии страницы', 'info');
callback({ rev: rev, title: title });
return;
}
var previousContent = (revisions[i + 1] && revisions[i + 1].content) || '';
var appearsInCurrent = content.indexOf(text) !== -1;
var appearsInPrevious = previousContent.indexOf(text) !== -1;
if (appearsInCurrent && !appearsInPrevious) {
addLog('Верификация пройдена: текст появился именно в этой правке', 'success');
callback({ rev: rev, title: title });
return;
}
lastCandidate = rev;
rejectedRevisions.add(rev.revid);
retries++;
addLog(
'Верификация не пройдена (текст был и в предыдущей правке). ' +
'Попытка ' + retries + '/' + MAX_VERIFICATION_RETRIES + ', продолжаем поиск...',
'warning'
);
i--;
}
if (lastCandidate) {
addLog(
'Достигнут лимит попыток верификации. Возвращаю последнего кандидата: ' +
lastCandidate.revid,
'warning'
);
callback({ rev: lastCandidate, title: title });
return;
}
addLog('Текст не найден ни в одной ревизии', 'error');
callback(null);
}
function showResult(result) {
var rev = result.rev;
var title = result.title;
var date = new Date(rev.timestamp);
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('Результат: автор ' + rev.user + ', дата ' + formattedDate, 'success');
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',
attrs: { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'blame-modal-title' },
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 h3 = createSafeElement('h3', {
text: 'Найден автор текста',
css: { marginTop: '0', color: colors.fg }
});
h3.id = 'blame-modal-title';
modal.appendChild(h3);
var userP = createSafeElement('p');
userP.appendChild(createSafeElement('strong', { text: 'Участник:' }));
userP.appendChild(document.createTextNode(' ' + rev.user));
modal.appendChild(userP);
var dateP = createSafeElement('p');
dateP.appendChild(createSafeElement('strong', { text: 'Дата правки:' }));
dateP.appendChild(document.createTextNode(' ' + formattedDate));
modal.appendChild(dateP);
var commentP = createSafeElement('p');
commentP.appendChild(createSafeElement('strong', { text: 'Комментарий:' }));
commentP.appendChild(document.createTextNode(' "' + rev.comment + '"'));
modal.appendChild(commentP);
var versionP = createSafeElement('p');
versionP.appendChild(createSafeElement('strong', { text: 'Версия:' }));
versionP.appendChild(document.createTextNode(' '));
var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) +
'&oldid=' + encodeURIComponent(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');
diffP.appendChild(createSafeElement('strong', { text: 'Дифф:' }));
diffP.appendChild(document.createTextNode(' '));
var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) +
'&diff=prev&oldid=' + encodeURIComponent(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);
modal.appendChild(createSafeElement('hr', {
css: { border: 'none', borderTop: '1px solid ' + colors.subtle }
}));
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);
document.removeEventListener('keydown', escHandler);
}
function escHandler(e) {
if (e.key === 'Escape') closeModal();
}
document.addEventListener('keydown', escHandler);
closeButton.onclick = closeModal;
overlay.onclick = closeModal;
try { closeButton.focus(); } catch (e) {}
}
function showLoading(message) {
var existing = document.getElementById('blame-loading');
if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
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: не основное пространство имён, гаджет не активирован');
}
})();