MediaWiki:Common.js: различия между версиями
Страница интерфейса MediaWiki
Дополнительные действия
Defer (обсуждение | вклад) Нет описания правки |
Defer (обсуждение | вклад) Нет описания правки |
||
| Строка 324: | Строка 324: | ||
/* Каталог страниц Marine Corps ----------------------------------------------------------------- */ | /* Каталог страниц Marine Corps ----------------------------------------------------------------- */ | ||
(function () { | (function () { | ||
var catalog = document.querySelector('.scmc-catalog'); | |||
if (!catalog) return; | |||
var | var STATUSES = [ | ||
{ value: 'green', label: '🟢 Готово' }, | |||
{ value: 'yellow', label: '🟡 Нужно обновить' }, | |||
{ value: 'red', label: '🔴 Нет страницы' }, | |||
{ value: 'blue', label: '🔵 Заморожено' } | |||
]; | |||
function | function normalizeText(value) { | ||
return String(value || '').replace(/\s+/g, ' ').trim(); | |||
} | } | ||
function pageKey(value) { | |||
return normalizeText(value).replace(/_/g, ' ').toLowerCase(); | |||
} | |||
function encodeAttr(value) { | |||
return String(value || '') | |||
.replace(/&/g, '&') | |||
.replace(/"/g, '"') | |||
.replace(/</g, '<') | |||
.replace(/>/g, '>'); | |||
} | |||
function decodeAttr(value) { | |||
var textarea = document.createElement('textarea'); | |||
textarea.innerHTML = String(value || ''); | |||
return textarea.value; | |||
} | |||
var | function makeEl(tag, className, text) { | ||
var el = document.createElement(tag); | |||
if (className) el.className = className; | |||
if (text !== undefined) el.textContent = text; | |||
return el; | |||
} | |||
function makeButton(text, className) { | |||
var btn = document.createElement('button'); | |||
btn.type = 'button'; | |||
btn.className = className || 'scmc-catalog-btn'; | |||
btn.textContent = text; | |||
return btn; | |||
} | |||
function getApi() { | |||
return new mw.Api(); | |||
} | |||
function getCurrentPageName() { | |||
return mw.config.get('wgPageName').replace(/_/g, ' '); | |||
} | |||
function getPageWikitext() { | |||
return getApi().get({ | |||
action: 'query', | |||
prop: 'revisions', | |||
titles: getCurrentPageName(), | |||
rvprop: 'content', | |||
rvslots: 'main', | |||
formatversion: 2 | |||
}).then(function (data) { | |||
var page = data.query.pages[0]; | |||
var rev = page.revisions && page.revisions[0]; | |||
if (!rev) { | |||
} | throw new Error('Не удалось прочитать код страницы.'); | ||
} | |||
if (rev.slots && rev.slots.main && typeof rev.slots.main.content === 'string') { | |||
return rev.slots.main.content; | |||
} | |||
if ( | if (typeof rev.content === 'string') { | ||
return rev.content; | |||
} | } | ||
throw new Error('Не удалось получить wikitext.'); | |||
}); | |||
} | |||
function savePageWikitext(text, summary) { | |||
return getApi().postWithToken('csrf', { | |||
action: 'edit', | |||
title: getCurrentPageName(), | |||
text: text, | |||
summary: summary || 'Обновление каталога Marine Corps', | |||
formatversion: 2 | |||
}); | }); | ||
} | |||
function extractAttr(tag, names) { | |||
for (var i = 0; i < names.length; i++) { | |||
var name = names[i]; | |||
var re = new RegExp(name + '\\s*=\\s*(["\\\'])(.*?)\\1', 'i'); | |||
var match = tag.match(re); | |||
if (match) { | |||
return decodeAttr(match[2]); | |||
} | |||
} | |||
return ''; | |||
} | |||
function getRowDataFromTag(tag) { | |||
return { | |||
className: extractAttr(tag, ['class']) || 'scmc-catalog-row', | |||
section: extractAttr(tag, ['data-section', 'data_section']), | |||
page: extractAttr(tag, ['data-page', 'data_page']), | |||
title: extractAttr(tag, ['data-title', 'data_title']), | |||
scan: extractAttr(tag, ['data-scan', 'data_scan']), | |||
status: extractAttr(tag, ['data-status', 'data_status']), | |||
note: extractAttr(tag, ['data-note', 'data_note']) | |||
}; | |||
} | |||
function buildOpeningTag(data) { | |||
var className = normalizeText(data.className || 'scmc-catalog-row'); | |||
var section = normalizeText(data.section); | |||
var page = normalizeText(data.page); | |||
var title = normalizeText(data.title || data.page); | |||
var scan = normalizeText(data.scan); | |||
var status = normalizeText(data.status || 'yellow'); | |||
var note = normalizeText(data.note); | |||
var out = '<div class="' + encodeAttr(className) + '"'; | |||
out += ' data-section="' + encodeAttr(section) + '"'; | |||
out += ' data-page="' + encodeAttr(page) + '"'; | |||
out += ' data-title="' + encodeAttr(title) + '"'; | |||
if (scan) { | |||
out += ' data-scan="' + encodeAttr(scan) + '"'; | |||
} | } | ||
out += ' data-status="' + encodeAttr(status) + '"'; | |||
if (note) { | |||
if (note | out += ' data-note="' + encodeAttr(note) + '"'; | ||
} | } | ||
out += '>'; | |||
return out; | |||
} | |||
} | |||
function getCatalogRowsFromText(text) { | |||
var rows = []; | |||
var re = /<div\b[^>]*\bscmc-catalog-row\b[^>]*>[\s\S]*?<\/div>/gi; | |||
var match; | |||
while ((match = re.exec(text)) !== null) { | |||
var full = match[0]; | |||
var openingMatch = full.match(/^<div\b[^>]*>/i); | |||
if (!openingMatch) continue; | |||
var opening = openingMatch[0]; | |||
var data = getRowDataFromTag(opening); | |||
if (!data.page) continue; | |||
rows.push({ | |||
start: match.index, | |||
end: match.index + full.length, | |||
full: full, | |||
opening: opening, | |||
}); | inner: full.slice(opening.length, full.length - 6), | ||
data: data | |||
}); | |||
} | |||
return rows; | |||
} | |||
function findSingleRow(rows, page) { | |||
var key = pageKey(page); | |||
var matches = rows.filter(function (row) { | |||
return pageKey(row.data.page) === key; | |||
}); | |||
if (!matches.length) { | |||
throw new Error('Строка каталога не найдена: ' + page); | |||
} | |||
if (matches.length > 1) { | |||
throw new Error('В каталоге несколько строк с data-page="' + page + '". Сначала убери дубликат.'); | |||
} | } | ||
return matches[0]; | |||
} | |||
function setBusy(state) { | |||
Array.prototype.forEach.call(document.querySelectorAll('.scmc-catalog-btn, .scmc-catalog-section-select, .scmc-catalog-status-select, .scmc-catalog-index'), function (el) { | |||
el.disabled = !!state; | |||
}); | |||
} | |||
function updateSingleRow(page, updater, summary) { | |||
setBusy(true); | |||
return getPageWikitext().then(function (text) { | |||
var rows = getCatalogRowsFromText(text); | |||
var row = findSingleRow(rows, page); | |||
var data = Object.assign({}, row.data); | |||
updater(data); | |||
if (!data.title) data.title = data.page; | |||
var newOpening = buildOpeningTag(data); | |||
var newFull = newOpening + row.inner + '</div>'; | |||
var newText = text.slice(0, row.start) + newFull + text.slice(row.end); | |||
return savePageWikitext(newText, summary); | |||
}).then(function () { | |||
location.reload(); | |||
}).catch(function (error) { | |||
} | alert(error.message || 'Не удалось сохранить изменение.'); | ||
setBusy(false); | |||
}); | |||
} | |||
function moveRowToPosition(page, targetPosition) { | |||
setBusy(true); | |||
return getPageWikitext().then(function (text) { | |||
var rows = getCatalogRowsFromText(text); | |||
var row = findSingleRow(rows, page); | |||
var oldIndex = rows.indexOf(row); | |||
var targetIndex = Math.max(0, Math.min(rows.length - 1, targetPosition - 1)); | |||
if (oldIndex === targetIndex) { | |||
setBusy(false); | |||
return; | |||
} | |||
var ordered = rows.map(function (item) { | |||
return item.full; | |||
}); | |||
var moved = ordered.splice(oldIndex, 1)[0]; | |||
ordered.splice(targetIndex, 0, moved); | |||
var first = rows[0]; | |||
var last = rows[rows.length - 1]; | |||
var newText = text.slice(0, first.start) + ordered.join('\n') + text.slice(last.end); | |||
return savePageWikitext(newText, 'Изменение порядка страниц в каталоге Marine Corps').then(function () { | |||
location.reload(); | |||
}); | }); | ||
}).catch(function (error) { | |||
alert(error.message || 'Не удалось изменить позицию.'); | |||
setBusy(false); | |||
}); | |||
} | |||
function getRowDataFromElement(row) { | |||
return { | |||
section: normalizeText(row.getAttribute('data-section')), | |||
page: normalizeText(row.getAttribute('data-page')), | |||
title: normalizeText(row.getAttribute('data-title') || row.textContent), | |||
scan: normalizeText(row.getAttribute('data-scan')), | |||
status: normalizeText(row.getAttribute('data-status') || 'yellow'), | |||
note: normalizeText(row.getAttribute('data-note')) | |||
}; | |||
} | |||
function getAllSections() { | |||
var sections = {}; | |||
Array.prototype.forEach.call(catalog.querySelectorAll('.scmc-catalog-row'), function (row) { | |||
var section = normalizeText(row.getAttribute('data-section')); | |||
if (section) sections[section] = true; | |||
}); | |||
return Object.keys(sections).sort(function (a, b) { | |||
return a.localeCompare(b, 'ru'); | |||
}); | |||
} | |||
function renderNoteText(data) { | |||
var parts = []; | |||
if (data.scan === 'stop') { | |||
parts.push('Из основного проекта.'); | |||
} | |||
if (data.note) { | |||
parts.push(data.note); | |||
} | } | ||
function | return parts.join(' '); | ||
var | } | ||
function createStatusSelect(value, page) { | |||
var select = document.createElement('select'); | |||
select.className = 'scmc-catalog-status-select'; | |||
select.setAttribute('data-status', value); | |||
STATUSES.forEach(function (status) { | |||
var option = document.createElement('option'); | |||
option.value = status.value; | |||
option.textContent = status.label; | |||
if (status.value === value) { | |||
option.selected = true; | |||
} | } | ||
select.appendChild(option); | |||
return | }); | ||
select.addEventListener('change', function () { | |||
var newStatus = select.value; | |||
updateSingleRow(page, function (data) { | |||
data.status = newStatus; | |||
}, 'Изменение статуса страницы в каталоге Marine Corps'); | |||
}); | |||
return select; | |||
} | |||
function createSectionSelect(value, page, sections) { | |||
var select = document.createElement('select'); | |||
select.className = 'scmc-catalog-section-select'; | |||
sections.forEach(function (section) { | |||
var option = document.createElement('option'); | |||
option.value = section; | |||
option.textContent = section; | |||
if (section === value) { | |||
option.selected = true; | |||
} | } | ||
select.appendChild(option); | |||
return { | }); | ||
select.addEventListener('change', function () { | |||
var newSection = select.value; | |||
updateSingleRow(page, function (data) { | |||
data.section = newSection; | |||
}, 'Изменение раздела страницы в каталоге Marine Corps'); | |||
}); | |||
return select; | |||
} | |||
function enhanceRow(row, index, total, sections) { | |||
if (row.getAttribute('data-scmc-enhanced') === 'true') return; | |||
var data = getRowDataFromElement(row); | |||
var page = data.page; | |||
var title = data.title || page; | |||
var isStop = data.scan === 'stop'; | |||
row.setAttribute('data-scmc-enhanced', 'true'); | |||
row.innerHTML = ''; | |||
var indexButton = makeButton(String(index + 1), 'scmc-catalog-index'); | |||
indexButton.title = 'Изменить позицию'; | |||
indexButton.addEventListener('click', function () { | |||
var answer = prompt('На какое место переместить страницу? Сейчас: ' + (index + 1) + '. Всего: ' + total + '.', String(index + 1)); | |||
if (answer === null) return; | |||
var target = parseInt(answer, 10); | |||
if (!target || target < 1 || target > total) { | |||
alert('Нужно число от 1 до ' + total + '.'); | |||
return; | |||
} | } | ||
var | moveRowToPosition(page, target); | ||
}); | |||
var mainBox = makeEl('div', 'scmc-catalog-main'); | |||
var titleBox = makeEl('div', 'scmc-catalog-title'); | |||
var link = document.createElement('a'); | |||
link.href = mw.util.getUrl(page); | |||
link.textContent = title; | |||
titleBox.appendChild(link); | |||
if (page && page !== title) { | |||
titleBox.appendChild(makeEl('span', 'scmc-catalog-page', page)); | |||
} | } | ||
mainBox.appendChild(titleBox); | |||
var noteText = renderNoteText(data); | |||
if (noteText) { | |||
mainBox.appendChild(makeEl('div', 'scmc-catalog-note', noteText)); | |||
} | } | ||
function | var noteButton = makeButton('✎', 'scmc-catalog-btn scmc-catalog-note-btn'); | ||
noteButton.title = 'Изменить заметку'; | |||
} | |||
noteButton.addEventListener('click', function () { | |||
var answer = prompt('Заметка для страницы "' + title + '". Оставь пустым, чтобы удалить заметку.', data.note || ''); | |||
if (answer === null) return; | |||
updateSingleRow(page, function (newData) { | |||
newData.note = normalizeText(answer); | |||
}, 'Изменение заметки страницы в каталоге Marine Corps'); | |||
}); | |||
var stopButton = makeButton(isStop ? 'Основной' : 'Наш', 'scmc-catalog-btn scmc-catalog-stop-btn'); | |||
stopButton.setAttribute('data-active', isStop ? 'true' : 'false'); | |||
stopButton.title = isStop ? 'Страница из основного проекта. Нажми, чтобы убрать stop.' : 'Нажми, чтобы пометить как страницу из основного проекта.'; | |||
stopButton.addEventListener('click', function () { | |||
updateSingleRow(page, function (newData) { | |||
if (newData.scan === 'stop') { | |||
newData.scan = ''; | |||
} else { | |||
newData.scan = 'stop'; | |||
} | |||
}, 'Изменение режима сканирования страницы в каталоге Marine Corps'); | |||
}); | |||
var sectionBox = makeEl('div', 'scmc-catalog-section'); | |||
sectionBox.appendChild(createSectionSelect(data.section, page, sections)); | |||
var statusBox = makeEl('div', 'scmc-catalog-status'); | |||
statusBox.appendChild(createStatusSelect(data.status, page)); | |||
row.appendChild(indexButton); | |||
row.appendChild(mainBox); | |||
row.appendChild(noteButton); | |||
row.appendChild(stopButton); | |||
row.appendChild(sectionBox); | |||
row.appendChild(statusBox); | |||
} | |||
function buildTools(rows) { | |||
if (document.querySelector('.scmc-catalog-tools')) return; | |||
var tools = makeEl('div', 'scmc-catalog-tools'); | |||
var toolsRow = makeEl('div', 'scmc-catalog-tools-row'); | |||
var search = document.createElement('input'); | |||
search.className = 'scmc-catalog-search'; | |||
search.type = 'search'; | |||
search.placeholder = 'Поиск по названию, странице, разделу, статусу или заметке'; | |||
var filter = document.createElement('select'); | |||
filter.className = 'scmc-catalog-filter'; | |||
[ | |||
['all', 'Все страницы'], | |||
['problem', 'Все проблемные'], | |||
['green', 'Готово'], | |||
['yellow', 'Нужно обновить'], | |||
['red', 'Нет страницы'], | |||
['blue', 'Заморожено'], | |||
['stop', 'Из основного проекта'], | |||
['note', 'С заметками'] | |||
].forEach(function (item) { | |||
var option = document.createElement('option'); | |||
option.value = item[0]; | |||
option.textContent = item[1]; | |||
filter.appendChild(option); | |||
}); | |||
var counter = makeEl('div', 'scmc-catalog-counter'); | |||
toolsRow.appendChild(search); | |||
toolsRow.appendChild(filter); | |||
toolsRow.appendChild(counter); | |||
tools.appendChild(toolsRow); | |||
catalog.parentNode.insertBefore(tools, catalog); | |||
function | function applyFilter() { | ||
var | var q = normalizeText(search.value).toLowerCase(); | ||
var | var mode = filter.value; | ||
var visible = 0; | var visible = 0; | ||
rows.forEach(function ( | rows.forEach(function (item) { | ||
var | var rowEl = item.row; | ||
var | var data = getRowDataFromElement(rowEl); | ||
var | var haystack = [ | ||
data.title, | |||
data.page, | |||
data.section, | |||
data.status, | |||
data.note, | |||
data.scan === 'stop' ? 'из основного проекта основной stop' : '' | |||
].join(' ').toLowerCase(); | |||
var | var okSearch = !q || haystack.indexOf(q) !== -1; | ||
var okMode = true; | |||
if (mode === 'problem') okMode = data.status !== 'green'; | |||
if (mode === 'green') okMode = data.status === 'green'; | |||
if (mode === 'yellow') okMode = data.status === 'yellow'; | |||
if (mode === 'red') okMode = data.status === 'red'; | |||
if (mode === 'blue') okMode = data.status === 'blue'; | |||
if (mode === 'stop') okMode = data.scan === 'stop'; | |||
if (mode === 'note') okMode = !!data.note; | |||
if ( | if (okSearch && okMode) { | ||
rowEl.classList.remove('scmc-catalog-hidden'); | |||
visible++; | |||
} else { | |||
rowEl.classList.add('scmc-catalog-hidden'); | |||
} | |||
}); | }); | ||
counter.textContent = 'Показано: ' + visible + ' | counter.textContent = 'Показано: ' + visible + ' / ' + rows.length; | ||
} | } | ||
search.addEventListener('input', applyFilter); | |||
filter.addEventListener('change', applyFilter); | |||
applyFilter(); | |||
} | |||
function initCatalog() { | |||
var rowElements = Array.prototype.slice.call(catalog.querySelectorAll('.scmc-catalog-row')); | |||
var sections = getAllSections(); | |||
var rows = rowElements.map(function (row) { | |||
return { row: row }; | |||
}); | |||
rowElements.forEach(function (row, index) { | |||
enhanceRow(row, index, rowElements.length, sections); | |||
}); | |||
buildTools(rows); | |||
} | |||
mw.hook('wikipage.content').add(function () { | |||
initCatalog(); | |||
}); | |||
initCatalog(); | |||
})(); | })(); | ||
Версия от 09:46, 15 июня 2026
/* Загрузка лого морпехов */
$(document).ready(function() {
var secondUrl = "https://spacestories.club/Marine_Corps";
var secondLogoImgUrl = "https://spacestories.club/images/0/0d/CMlog.png";
if ($('.second-mw-logo').length === 0) {
var $secondLogo = $('<a>', {
href: secondUrl,
class: 'second-mw-logo citizen-cdx-button--size-large cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--icon-only cdx-button--weight-quiet',
title: 'Перейти на заглавную страницу Marines Corps',
}).append(
$('<img>', {
class: 'mw-logo-icon',
src: secondLogoImgUrl,
alt: 'Второе лого',
'aria-hidden': 'true',
height: '32',
width: '32'
})
);
$('.mw-logo').after($secondLogo);
}
});
/* Аудиоплееры */
(function(){
var players = document.getElementsByClassName('audio-player');
for(var i=0;i<players.length;i++){
(function(p){
var src = p.getAttribute('data-src');
if(src){
var audio = document.createElement('audio');
audio.setAttribute('controls','controls');
audio.setAttribute('preload','none');
var source = document.createElement('source');
source.setAttribute('src',src);
source.setAttribute('type','audio/mpeg');
audio.appendChild(source);
p.appendChild(audio);
}
})(players[i]);
}
})();
/* Подгрузка внешних CSS/JS */
(function(){
if(typeof mw === 'undefined') return;
function getFilesFromUrl(param){
if(!param) return [];
return param.split('|').map(function(file){ return file.trim(); });
}
function getBaseUrl(){
var server = mw.config.get('wgServer').replace(/^http:/,'https:');
var script = mw.config.get('wgScript');
return server + script + '?action=raw&ctype=text/';
}
function isValidExtension(ext){ return ext === 'js' || ext === 'css'; }
function getFileUrl(file){
var prefix = file.indexOf('MediaWiki:') === 0 ? 'MediaWiki:' : 'User:' + (mw.config.get('wgUserName') || '') + '/';
var fullName = file.indexOf(':') > -1 ? file : prefix + file;
var ext = file.split('.').pop().toLowerCase();
if(!isValidExtension(ext)){
console.error('Недопустимое расширение файла:', file);
return null;
}
var timestamp = new Date().getTime();
return getBaseUrl() + (ext==='js' ? 'javascript' : 'css') + '&title=' + encodeURIComponent(fullName) + '&_=' + timestamp;
}
function loadFiles(files){
for(var i=0;i<files.length;i++){
var url = getFileUrl(files[i]);
if(url){
var ext = files[i].split('.').pop().toLowerCase();
mw.loader.load(url,'text/' + (ext==='js' ? 'javascript' : 'css'));
}
}
}
mw.loader.using('mediawiki.util', function(){
var params = mw.util.getParamValue('use');
var files = getFilesFromUrl(params);
loadFiles(files);
});
})();
/* Перенос page-info и цвет заголовков */
(function(){
var footerPlaces = document.getElementById('footer-places');
var pageInfo = document.querySelector('.page-info');
if(footerPlaces && pageInfo){
footerPlaces.insertAdjacentElement('afterend', pageInfo.cloneNode(true));
pageInfo.parentNode.removeChild(pageInfo);
}
var headerColorElement = document.querySelector('.headerColor');
if(headerColorElement){
var content = headerColorElement.textContent.split('|');
if(content.length === 2){
var headers = document.querySelectorAll('.citizen-section-heading, .citizen-section-heading--collapsed');
for(var hi=0; hi<headers.length; hi++){
var header = headers[hi],
indicator = header.querySelector('.citizen-section-indicator'),
headline = header.querySelector('.mw-headline');
if(!indicator || !headline) continue;
if(header.classList.contains('citizen-section-heading--collapsed')){
indicator.style.cssText = 'background: black; box-shadow: unset;';
} else {
indicator.style.cssText = 'background: ' + content[1] + '; box-shadow: 0 0 20px 0px ' + content[1] + 'cc;';
headline.style.cssText = 'border-image: linear-gradient(to right top,' + content[0] + ', black); border-image-slice:1;';
}
}
}
}
})();
/* Sidebar для ролей */
(function(){
var jobsContainer = document.querySelector('.JobsTableContainer');
if(jobsContainer && jobsContainer.innerHTML.trim()){
var bodyContent = document.getElementById('bodyContent');
if(bodyContent){
bodyContent.insertAdjacentHTML('beforebegin', jobsContainer.innerHTML);
var jobTable = document.getElementById('IdJobsTableContainer1');
if(jobTable) jobTable.id = 'IdJobsTableContainer2';
}
}
})();
/* Хронология */
(function(){
if(!window.jQuery) return;
jQuery(function($){
$('.timeline-header').on('click', function(){
$(this).next('.timeline-content').slideToggle();
}).trigger('click');
});
})();
/* Галерея */
(function(){
var root = document.getElementById('ss-art-gallery');
if(!root) return;
function q(a,b){ return a.querySelector(b); }
function qa(a,b){ return Array.prototype.slice.call(a.querySelectorAll(b)); }
var chips = qa(root,'.ss-chip');
function setFilter(val){
for(var ci=0; ci<chips.length; ci++){
var c = chips[ci];
var active = (c.getAttribute('data-filter')===val || (val==='all' && c.getAttribute('data-filter')==='all'));
c.classList.toggle('ss-chip-active', active);
}
var sections = qa(root,'.ss-section');
for(var si=0; si<sections.length; si++){
var section = sections[si];
var cards = qa(section,'.ss-card');
var visibleCount = 0;
for(var cj=0; cj<cards.length; cj++){
var card = cards[cj];
var show = (val==='all' || val===card.getAttribute('data-artist'));
card.classList.toggle('ss-hidden', !show);
if(show) visibleCount++;
}
section.style.display = (val==='all' || visibleCount>0)?'block':'none';
}
}
for(var i=0;i<chips.length;i++){
(function(ch){
ch.addEventListener('click', function(){ setFilter(ch.getAttribute('data-filter')); });
})(chips[i]);
}
setFilter('all');
var modal = document.createElement('div');
modal.className = 'ss-modal';
modal.innerHTML = '<div class="ss-modal-inner"><img class="ss-modal-img" alt=""/></div><div class="ss-modal-close" role="button">✖ Закрыть</div>';
root.appendChild(modal);
var modalImg = q(modal,'.ss-modal-img');
function originalFromThumb(u){
if(!u) return u;
if(u.indexOf('/thumb/')>-1){
var s = u.replace('/thumb/','/');
s = s.replace(/\/[^\/]*$/,'');
return s;
}
return u;
}
var images = qa(root,'.ss-card img');
for(var ii=0; ii<images.length; ii++){
(function(img){
img.style.cursor='zoom-in';
img.addEventListener('click', function(e){
e.preventDefault();
var src = originalFromThumb(img.getAttribute('src')) || img.getAttribute('src');
modalImg.setAttribute('src',src);
modalImg.style.maxWidth='90vw';
modalImg.style.maxHeight='90vh';
modal.classList.add('open');
});
})(images[ii]);
}
function closeModal(){ modal.classList.remove('open'); }
modal.addEventListener('click', function(e){ if(e.target===modal||e.target.classList.contains('ss-modal-close')) closeModal(); });
document.addEventListener('keydown', function(e){ if(e.key==='Escape') closeModal(); });
})();
/* Меню лора */
(function(){
var items = document.querySelectorAll('.custom-item');
for(var mi=0; mi<items.length; mi++){
(function(item){
var icon = item.querySelector('.custom-icon');
var linkEl = item.querySelector('a');
if(!linkEl) return;
var href = linkEl.getAttribute('href');
item.style.cursor='pointer';
item.onclick = function(){ window.location.href = href; };
item.onmousemove = function(e){
var rect = item.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var moveX = (x - rect.width/2)*0.02;
var moveY = (y - rect.height/2)*0.02;
item.style.backgroundPosition = (50 + moveX) + '% ' + (50 + moveY) + '%';
if(icon) icon.style.transform = 'translateY(-8px) scale(1.08)';
var hue = Math.round((x/rect.width)*360);
item.style.boxShadow =
'0 0 15px hsla(' + hue + ',100%,60%,0.7), ' +
'0 0 30px hsla(' + ((hue+30)%360) + ',100%,50%,0.4), ' +
'0 8px 20px rgba(0,0,0,0.5)';
};
item.onmouseleave = function(){
item.style.backgroundPosition='50% 50%';
if(icon) icon.style.transform='translateY(0) scale(1)';
item.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';
};
})(items[mi]);
}
})();
/* Химия */
(function() {
if (typeof mw === 'undefined' || !window.document) return;
function initCollapse() {
var headings = document.querySelectorAll('.chem-heading');
var hi = 0;
var len = headings.length;
for (; hi < len; hi++) {
(function(node) {
if (node.getAttribute('data-chem-attached')) return;
node.setAttribute('data-chem-attached', '1');
node.style.cursor = 'pointer';
node.addEventListener('click', function() {
var kind = node.getAttribute('data-kind') || '';
var wrapper = findWrapper(node, kind);
if (!wrapper) return;
var btn = node.querySelector('.collapse-btn');
if (wrapper.classList.contains('collapsed')) {
wrapper.style.maxHeight = wrapper.scrollHeight + 'px';
wrapper.classList.remove('collapsed');
wrapper.classList.add('expanded');
if (btn) btn.textContent = 'свернуть';
var cleanup = function() {
wrapper.style.maxHeight = '';
wrapper.removeEventListener('transitionend', cleanup);
};
wrapper.addEventListener('transitionend', cleanup);
} else {
var currentHeight = wrapper.scrollHeight;
wrapper.style.maxHeight = currentHeight + 'px';
wrapper.offsetHeight;
wrapper.style.maxHeight = '0px';
wrapper.classList.remove('expanded');
wrapper.classList.add('collapsed');
if (btn) btn.textContent = 'развернуть';
}
});
})(headings[hi]);
}
}
function findWrapper(node, kind) {
var parent = node.parentNode;
if (!parent) return null;
var wrappers = parent.querySelectorAll('.collapsible');
var wi = 0;
var wlen = wrappers.length;
for (; wi < wlen; wi++) {
if (wrappers[wi].getAttribute('data-kind') === kind) {
return wrappers[wi];
}
}
return null;
}
if (document.readyState === 'complete' || document.readyState === 'interactive') {
initCollapse();
} else {
document.addEventListener('DOMContentLoaded', initCollapse);
}
})();
/* Каталог страниц Marine Corps ----------------------------------------------------------------- */
(function () {
var catalog = document.querySelector('.scmc-catalog');
if (!catalog) return;
var STATUSES = [
{ value: 'green', label: '🟢 Готово' },
{ value: 'yellow', label: '🟡 Нужно обновить' },
{ value: 'red', label: '🔴 Нет страницы' },
{ value: 'blue', label: '🔵 Заморожено' }
];
function normalizeText(value) {
return String(value || '').replace(/\s+/g, ' ').trim();
}
function pageKey(value) {
return normalizeText(value).replace(/_/g, ' ').toLowerCase();
}
function encodeAttr(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function decodeAttr(value) {
var textarea = document.createElement('textarea');
textarea.innerHTML = String(value || '');
return textarea.value;
}
function makeEl(tag, className, text) {
var el = document.createElement(tag);
if (className) el.className = className;
if (text !== undefined) el.textContent = text;
return el;
}
function makeButton(text, className) {
var btn = document.createElement('button');
btn.type = 'button';
btn.className = className || 'scmc-catalog-btn';
btn.textContent = text;
return btn;
}
function getApi() {
return new mw.Api();
}
function getCurrentPageName() {
return mw.config.get('wgPageName').replace(/_/g, ' ');
}
function getPageWikitext() {
return getApi().get({
action: 'query',
prop: 'revisions',
titles: getCurrentPageName(),
rvprop: 'content',
rvslots: 'main',
formatversion: 2
}).then(function (data) {
var page = data.query.pages[0];
var rev = page.revisions && page.revisions[0];
if (!rev) {
throw new Error('Не удалось прочитать код страницы.');
}
if (rev.slots && rev.slots.main && typeof rev.slots.main.content === 'string') {
return rev.slots.main.content;
}
if (typeof rev.content === 'string') {
return rev.content;
}
throw new Error('Не удалось получить wikitext.');
});
}
function savePageWikitext(text, summary) {
return getApi().postWithToken('csrf', {
action: 'edit',
title: getCurrentPageName(),
text: text,
summary: summary || 'Обновление каталога Marine Corps',
formatversion: 2
});
}
function extractAttr(tag, names) {
for (var i = 0; i < names.length; i++) {
var name = names[i];
var re = new RegExp(name + '\\s*=\\s*(["\\\'])(.*?)\\1', 'i');
var match = tag.match(re);
if (match) {
return decodeAttr(match[2]);
}
}
return '';
}
function getRowDataFromTag(tag) {
return {
className: extractAttr(tag, ['class']) || 'scmc-catalog-row',
section: extractAttr(tag, ['data-section', 'data_section']),
page: extractAttr(tag, ['data-page', 'data_page']),
title: extractAttr(tag, ['data-title', 'data_title']),
scan: extractAttr(tag, ['data-scan', 'data_scan']),
status: extractAttr(tag, ['data-status', 'data_status']),
note: extractAttr(tag, ['data-note', 'data_note'])
};
}
function buildOpeningTag(data) {
var className = normalizeText(data.className || 'scmc-catalog-row');
var section = normalizeText(data.section);
var page = normalizeText(data.page);
var title = normalizeText(data.title || data.page);
var scan = normalizeText(data.scan);
var status = normalizeText(data.status || 'yellow');
var note = normalizeText(data.note);
var out = '<div class="' + encodeAttr(className) + '"';
out += ' data-section="' + encodeAttr(section) + '"';
out += ' data-page="' + encodeAttr(page) + '"';
out += ' data-title="' + encodeAttr(title) + '"';
if (scan) {
out += ' data-scan="' + encodeAttr(scan) + '"';
}
out += ' data-status="' + encodeAttr(status) + '"';
if (note) {
out += ' data-note="' + encodeAttr(note) + '"';
}
out += '>';
return out;
}
function getCatalogRowsFromText(text) {
var rows = [];
var re = /<div\b[^>]*\bscmc-catalog-row\b[^>]*>[\s\S]*?<\/div>/gi;
var match;
while ((match = re.exec(text)) !== null) {
var full = match[0];
var openingMatch = full.match(/^<div\b[^>]*>/i);
if (!openingMatch) continue;
var opening = openingMatch[0];
var data = getRowDataFromTag(opening);
if (!data.page) continue;
rows.push({
start: match.index,
end: match.index + full.length,
full: full,
opening: opening,
inner: full.slice(opening.length, full.length - 6),
data: data
});
}
return rows;
}
function findSingleRow(rows, page) {
var key = pageKey(page);
var matches = rows.filter(function (row) {
return pageKey(row.data.page) === key;
});
if (!matches.length) {
throw new Error('Строка каталога не найдена: ' + page);
}
if (matches.length > 1) {
throw new Error('В каталоге несколько строк с data-page="' + page + '". Сначала убери дубликат.');
}
return matches[0];
}
function setBusy(state) {
Array.prototype.forEach.call(document.querySelectorAll('.scmc-catalog-btn, .scmc-catalog-section-select, .scmc-catalog-status-select, .scmc-catalog-index'), function (el) {
el.disabled = !!state;
});
}
function updateSingleRow(page, updater, summary) {
setBusy(true);
return getPageWikitext().then(function (text) {
var rows = getCatalogRowsFromText(text);
var row = findSingleRow(rows, page);
var data = Object.assign({}, row.data);
updater(data);
if (!data.title) data.title = data.page;
var newOpening = buildOpeningTag(data);
var newFull = newOpening + row.inner + '</div>';
var newText = text.slice(0, row.start) + newFull + text.slice(row.end);
return savePageWikitext(newText, summary);
}).then(function () {
location.reload();
}).catch(function (error) {
alert(error.message || 'Не удалось сохранить изменение.');
setBusy(false);
});
}
function moveRowToPosition(page, targetPosition) {
setBusy(true);
return getPageWikitext().then(function (text) {
var rows = getCatalogRowsFromText(text);
var row = findSingleRow(rows, page);
var oldIndex = rows.indexOf(row);
var targetIndex = Math.max(0, Math.min(rows.length - 1, targetPosition - 1));
if (oldIndex === targetIndex) {
setBusy(false);
return;
}
var ordered = rows.map(function (item) {
return item.full;
});
var moved = ordered.splice(oldIndex, 1)[0];
ordered.splice(targetIndex, 0, moved);
var first = rows[0];
var last = rows[rows.length - 1];
var newText = text.slice(0, first.start) + ordered.join('\n') + text.slice(last.end);
return savePageWikitext(newText, 'Изменение порядка страниц в каталоге Marine Corps').then(function () {
location.reload();
});
}).catch(function (error) {
alert(error.message || 'Не удалось изменить позицию.');
setBusy(false);
});
}
function getRowDataFromElement(row) {
return {
section: normalizeText(row.getAttribute('data-section')),
page: normalizeText(row.getAttribute('data-page')),
title: normalizeText(row.getAttribute('data-title') || row.textContent),
scan: normalizeText(row.getAttribute('data-scan')),
status: normalizeText(row.getAttribute('data-status') || 'yellow'),
note: normalizeText(row.getAttribute('data-note'))
};
}
function getAllSections() {
var sections = {};
Array.prototype.forEach.call(catalog.querySelectorAll('.scmc-catalog-row'), function (row) {
var section = normalizeText(row.getAttribute('data-section'));
if (section) sections[section] = true;
});
return Object.keys(sections).sort(function (a, b) {
return a.localeCompare(b, 'ru');
});
}
function renderNoteText(data) {
var parts = [];
if (data.scan === 'stop') {
parts.push('Из основного проекта.');
}
if (data.note) {
parts.push(data.note);
}
return parts.join(' ');
}
function createStatusSelect(value, page) {
var select = document.createElement('select');
select.className = 'scmc-catalog-status-select';
select.setAttribute('data-status', value);
STATUSES.forEach(function (status) {
var option = document.createElement('option');
option.value = status.value;
option.textContent = status.label;
if (status.value === value) {
option.selected = true;
}
select.appendChild(option);
});
select.addEventListener('change', function () {
var newStatus = select.value;
updateSingleRow(page, function (data) {
data.status = newStatus;
}, 'Изменение статуса страницы в каталоге Marine Corps');
});
return select;
}
function createSectionSelect(value, page, sections) {
var select = document.createElement('select');
select.className = 'scmc-catalog-section-select';
sections.forEach(function (section) {
var option = document.createElement('option');
option.value = section;
option.textContent = section;
if (section === value) {
option.selected = true;
}
select.appendChild(option);
});
select.addEventListener('change', function () {
var newSection = select.value;
updateSingleRow(page, function (data) {
data.section = newSection;
}, 'Изменение раздела страницы в каталоге Marine Corps');
});
return select;
}
function enhanceRow(row, index, total, sections) {
if (row.getAttribute('data-scmc-enhanced') === 'true') return;
var data = getRowDataFromElement(row);
var page = data.page;
var title = data.title || page;
var isStop = data.scan === 'stop';
row.setAttribute('data-scmc-enhanced', 'true');
row.innerHTML = '';
var indexButton = makeButton(String(index + 1), 'scmc-catalog-index');
indexButton.title = 'Изменить позицию';
indexButton.addEventListener('click', function () {
var answer = prompt('На какое место переместить страницу? Сейчас: ' + (index + 1) + '. Всего: ' + total + '.', String(index + 1));
if (answer === null) return;
var target = parseInt(answer, 10);
if (!target || target < 1 || target > total) {
alert('Нужно число от 1 до ' + total + '.');
return;
}
moveRowToPosition(page, target);
});
var mainBox = makeEl('div', 'scmc-catalog-main');
var titleBox = makeEl('div', 'scmc-catalog-title');
var link = document.createElement('a');
link.href = mw.util.getUrl(page);
link.textContent = title;
titleBox.appendChild(link);
if (page && page !== title) {
titleBox.appendChild(makeEl('span', 'scmc-catalog-page', page));
}
mainBox.appendChild(titleBox);
var noteText = renderNoteText(data);
if (noteText) {
mainBox.appendChild(makeEl('div', 'scmc-catalog-note', noteText));
}
var noteButton = makeButton('✎', 'scmc-catalog-btn scmc-catalog-note-btn');
noteButton.title = 'Изменить заметку';
noteButton.addEventListener('click', function () {
var answer = prompt('Заметка для страницы "' + title + '". Оставь пустым, чтобы удалить заметку.', data.note || '');
if (answer === null) return;
updateSingleRow(page, function (newData) {
newData.note = normalizeText(answer);
}, 'Изменение заметки страницы в каталоге Marine Corps');
});
var stopButton = makeButton(isStop ? 'Основной' : 'Наш', 'scmc-catalog-btn scmc-catalog-stop-btn');
stopButton.setAttribute('data-active', isStop ? 'true' : 'false');
stopButton.title = isStop ? 'Страница из основного проекта. Нажми, чтобы убрать stop.' : 'Нажми, чтобы пометить как страницу из основного проекта.';
stopButton.addEventListener('click', function () {
updateSingleRow(page, function (newData) {
if (newData.scan === 'stop') {
newData.scan = '';
} else {
newData.scan = 'stop';
}
}, 'Изменение режима сканирования страницы в каталоге Marine Corps');
});
var sectionBox = makeEl('div', 'scmc-catalog-section');
sectionBox.appendChild(createSectionSelect(data.section, page, sections));
var statusBox = makeEl('div', 'scmc-catalog-status');
statusBox.appendChild(createStatusSelect(data.status, page));
row.appendChild(indexButton);
row.appendChild(mainBox);
row.appendChild(noteButton);
row.appendChild(stopButton);
row.appendChild(sectionBox);
row.appendChild(statusBox);
}
function buildTools(rows) {
if (document.querySelector('.scmc-catalog-tools')) return;
var tools = makeEl('div', 'scmc-catalog-tools');
var toolsRow = makeEl('div', 'scmc-catalog-tools-row');
var search = document.createElement('input');
search.className = 'scmc-catalog-search';
search.type = 'search';
search.placeholder = 'Поиск по названию, странице, разделу, статусу или заметке';
var filter = document.createElement('select');
filter.className = 'scmc-catalog-filter';
[
['all', 'Все страницы'],
['problem', 'Все проблемные'],
['green', 'Готово'],
['yellow', 'Нужно обновить'],
['red', 'Нет страницы'],
['blue', 'Заморожено'],
['stop', 'Из основного проекта'],
['note', 'С заметками']
].forEach(function (item) {
var option = document.createElement('option');
option.value = item[0];
option.textContent = item[1];
filter.appendChild(option);
});
var counter = makeEl('div', 'scmc-catalog-counter');
toolsRow.appendChild(search);
toolsRow.appendChild(filter);
toolsRow.appendChild(counter);
tools.appendChild(toolsRow);
catalog.parentNode.insertBefore(tools, catalog);
function applyFilter() {
var q = normalizeText(search.value).toLowerCase();
var mode = filter.value;
var visible = 0;
rows.forEach(function (item) {
var rowEl = item.row;
var data = getRowDataFromElement(rowEl);
var haystack = [
data.title,
data.page,
data.section,
data.status,
data.note,
data.scan === 'stop' ? 'из основного проекта основной stop' : ''
].join(' ').toLowerCase();
var okSearch = !q || haystack.indexOf(q) !== -1;
var okMode = true;
if (mode === 'problem') okMode = data.status !== 'green';
if (mode === 'green') okMode = data.status === 'green';
if (mode === 'yellow') okMode = data.status === 'yellow';
if (mode === 'red') okMode = data.status === 'red';
if (mode === 'blue') okMode = data.status === 'blue';
if (mode === 'stop') okMode = data.scan === 'stop';
if (mode === 'note') okMode = !!data.note;
if (okSearch && okMode) {
rowEl.classList.remove('scmc-catalog-hidden');
visible++;
} else {
rowEl.classList.add('scmc-catalog-hidden');
}
});
counter.textContent = 'Показано: ' + visible + ' / ' + rows.length;
}
search.addEventListener('input', applyFilter);
filter.addEventListener('change', applyFilter);
applyFilter();
}
function initCatalog() {
var rowElements = Array.prototype.slice.call(catalog.querySelectorAll('.scmc-catalog-row'));
var sections = getAllSections();
var rows = rowElements.map(function (row) {
return { row: row };
});
rowElements.forEach(function (row, index) {
enhanceRow(row, index, rowElements.length, sections);
});
buildTools(rows);
}
mw.hook('wikipage.content').add(function () {
initCatalog();
});
initCatalog();
})();
if (mw.config.get('wgPageName') === 'MC:Сканер_ссылок') {
mw.loader.load('/index.php?title=MediaWiki:ScmcScanner.css&action=raw&ctype=text/css', 'text/css');
mw.loader.load('/index.php?title=MediaWiki:ScmcScanner.js&action=raw&ctype=text/javascript');
}
/* Каталог страниц Marine Corps --------------------------------------------------------------END */