Открыть меню
Переключить меню настроек
Открыть персональное меню
Вы не представились системе
Ваш IP-адрес будет виден всем, если вы внесёте какие-либо изменения.

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

Страница интерфейса MediaWiki
Нет описания правки
Отмена версии 25641, сделанной Defer (обсуждение)
Метка: отмена
Строка 324: Строка 324:


// Colonial Marines - JS by Renata (Defer) ---------------------------------------------------------
// Colonial Marines - JS by Renata (Defer) ---------------------------------------------------------
/* Каталог страниц Marine Corps */
 
(function () {
(function () {
     if (typeof mw === 'undefined' || !window.document) return;
     if (typeof mw === 'undefined' || !window.document) return;
Строка 353: Строка 353:
         var tools = document.querySelector('.scmc-catalog-tools');
         var tools = document.querySelector('.scmc-catalog-tools');
         var sections = Array.prototype.slice.call(document.querySelectorAll('.scmc-catalog-section'));
         var sections = Array.prototype.slice.call(document.querySelectorAll('.scmc-catalog-section'));
         if (!tools || !sections.length) return;
         if (!tools || !sections.length) return;
        buildCatalogTools(tools);


         var items = collectItems(sections);
         var items = collectItems(sections);
Строка 385: Строка 382:
         document.addEventListener('click', function (e) {
         document.addEventListener('click', function (e) {
             var statusButton = e.target.closest('.scmc-catalog-status');
             var statusButton = e.target.closest('.scmc-catalog-status');
             if (statusButton) {
             if (statusButton) {
                 e.preventDefault();
                 e.preventDefault();
Строка 398: Строка 394:
             }
             }
         });
         });
        function buildCatalogTools(toolsNode) {
            toolsNode.innerHTML = '';
            var searchInput = document.createElement('input');
            searchInput.className = 'scmc-catalog-search';
            searchInput.type = 'search';
            searchInput.placeholder = 'Поиск по названию, разделу, статусу или комментарию...';
            var filtersWrap = document.createElement('div');
            filtersWrap.className = 'scmc-catalog-filters';
            [
                ['all', 'Все'],
                ['green', '🟢 Готово'],
                ['yellow', '🟡 Нужно обновить'],
                ['red', '🔴 Нет страницы'],
                ['blue', '🔵 Заморожено'],
                ['problem', 'Проблемные']
            ].forEach(function (row, index) {
                var button = document.createElement('button');
                button.type = 'button';
                button.setAttribute('data-status', row[0]);
                button.className = 'scmc-catalog-filter' + (index === 0 ? ' is-active' : '');
                button.textContent = row[1];
                filtersWrap.appendChild(button);
            });
            var counterNode = document.createElement('div');
            counterNode.className = 'scmc-catalog-counter';
            toolsNode.appendChild(searchInput);
            toolsNode.appendChild(filtersWrap);
            toolsNode.appendChild(counterNode);
        }


         function collectItems(sectionList) {
         function collectItems(sectionList) {
Строка 440: Строка 401:
                 var sectionTitle = '';
                 var sectionTitle = '';
                 var head = section.querySelector('.scmc-card-head');
                 var head = section.querySelector('.scmc-card-head');
                 if (head) sectionTitle = cleanText(head.textContent);
                 if (head) sectionTitle = cleanText(head.textContent);


Строка 448: Строка 408:
                     var ownText = getOwnText(li);
                     var ownText = getOwnText(li);
                     var match = ownText.match(/[🟢🟡🔴🔵]/);
                     var match = ownText.match(/[🟢🟡🔴🔵]/);
                     var link = li.querySelector('a');
                     var link = li.querySelector(':scope > a') || li.querySelector('a');


                     if (!match || !link) return;
                     if (!match || !link) return;
Строка 538: Строка 498:
                 var label = row[1];
                 var label = row[1];
                 var option = document.createElement('button');
                 var option = document.createElement('button');
                 option.type = 'button';
                 option.type = 'button';
                 option.textContent = label;
                 option.textContent = label;
Строка 563: Строка 522:
         function changeStatus(li, button, newStatus) {
         function changeStatus(li, button, newStatus) {
             var oldStatus = li.getAttribute('data-status');
             var oldStatus = li.getAttribute('data-status');
             if (!newStatus || newStatus === oldStatus) return;
             if (!newStatus || newStatus === oldStatus) return;


Строка 599: Строка 557:
                 var page = data.query.pages[0];
                 var page = data.query.pages[0];
                 var content = page.revisions[0].slots.main.content;
                 var content = page.revisions[0].slots.main.content;
                 var oldEmoji = statusMap[oldStatus].emoji;
                 var oldEmoji = statusMap[oldStatus].emoji;
                 var newEmoji = statusMap[newStatus].emoji;
                 var newEmoji = statusMap[newStatus].emoji;
                 var updated = replaceStatusInSource(content, target, oldEmoji, newEmoji);
                 var updated = replaceStatusInSource(content, target, oldEmoji, newEmoji);


Строка 646: Строка 606:


         function lineMatchesTarget(line, target) {
         function lineMatchesTarget(line, target) {
             var variants = getTargetVariants(target);
             var escaped = escapeRegExp(target);
 
            for (var i = 0; i < variants.length; i++) {
                var item = variants[i];


                if (line.indexOf('[[' + item + '|') !== -1) return true;
            if (line.indexOf('[[' + target + '|') !== -1) return true;
                if (line.indexOf('[[' + item + ']]') !== -1) return true;
            if (line.indexOf('[[' + target + ']]') !== -1) return true;
                if (line.indexOf(item) !== -1 && line.indexOf('[[') !== -1) return true;
            if (line.indexOf(target) !== -1 && line.indexOf('[[') !== -1) return true;
                if (line.indexOf(item) !== -1 && line.indexOf('http') !== -1) return true;
            }
 
            return false;
        }
 
        function getTargetVariants(target) {
            var list = [];
            var clean = String(target || '').trim();
 
            add(clean);
            add(clean.replace(/_/g, ' '));
            add(clean.replace(/ /g, '_'));


             try {
             try {
                 add(decodeURIComponent(clean));
                 var decoded = decodeURIComponent(target);
                add(decodeURIComponent(clean).replace(/_/g, ' '));
                 if (decoded !== target && line.indexOf(decoded) !== -1) return true;
                 add(decodeURIComponent(clean).replace(/ /g, '_'));
             } catch (e) {}
             } catch (e) {}


             function add(value) {
             return new RegExp('\\[\\[' + escaped + '(\\||\\]\\])').test(line);
                if (value && list.indexOf(value) === -1) list.push(value);
            }
 
            return list;
         }
         }


Строка 701: Строка 640:


                 var visible = statusOk && textOk;
                 var visible = statusOk && textOk;
                 li.classList.toggle('scmc-catalog-hidden', !visible);
                 li.classList.toggle('scmc-catalog-hidden', !visible);


Строка 719: Строка 657:


                 var parent = item.li.parentElement;
                 var parent = item.li.parentElement;
                 while (parent) {
                 while (parent) {
                     if (parent.tagName && parent.tagName.toLowerCase() === 'ul') {
                     if (parent.tagName && parent.tagName.toLowerCase() === 'ul') {
                         var parentLi = parent.parentElement;
                         var parentLi = parent.parentElement;
                         if (parentLi && parentLi.classList && parentLi.classList.contains('scmc-catalog-item')) {
                         if (parentLi && parentLi.classList && parentLi.classList.contains('scmc-catalog-item')) {
                             parentLi.classList.remove('scmc-catalog-hidden');
                             parentLi.classList.remove('scmc-catalog-hidden');
Строка 736: Строка 672:
         function statusWordMatches(status, word) {
         function statusWordMatches(status, word) {
             if (!statusMap[status]) return false;
             if (!statusMap[status]) return false;
             var words = statusMap[status].words;
             var words = statusMap[status].words;
             for (var i = 0; i < words.length; i++) {
             for (var i = 0; i < words.length; i++) {
                 if (words[i].indexOf(word) !== -1 || word.indexOf(words[i]) !== -1) return true;
                 if (words[i].indexOf(word) !== -1 || word.indexOf(words[i]) !== -1) return true;
             }
             }
             return false;
             return false;
         }
         }
Строка 772: Строка 705:
                 } else if (node.nodeType === Node.ELEMENT_NODE) {
                 } else if (node.nodeType === Node.ELEMENT_NODE) {
                     var tag = node.tagName.toLowerCase();
                     var tag = node.tagName.toLowerCase();
                     if (tag !== 'ul' && tag !== 'ol') {
                     if (tag !== 'ul' && tag !== 'ol') {
                         text += node.textContent + ' ';
                         text += node.textContent + ' ';
Строка 783: Строка 715:


         function getLinkTarget(link) {
         function getLinkTarget(link) {
            var title = link.getAttribute('title');
            if (title && title.trim()) return title.trim();
             var href = link.getAttribute('href') || '';
             var href = link.getAttribute('href') || '';
            if (!href) return '';


             if (href) {
             var titleMatch = href.match(/[?&]title=([^&]+)/);
                var titleMatch = href.match(/[?&]title=([^&]+)/);
            if (titleMatch) return decodeURIComponent(titleMatch[1]).replace(/_/g, '_');
 
                if (titleMatch) {
                    return decodeURIComponent(titleMatch[1]);
                }
 
                var parts = href.split('/');
                var last = parts[parts.length - 1] || '';


                if (last) {
             var parts = href.split('/');
                    return decodeURIComponent(last);
             var last = parts[parts.length - 1] || '';
                }
             return decodeURIComponent(last).replace(/_/g, '_');
            }
 
             var title = link.getAttribute('title');
 
             if (title && title.trim()) {
                return title.trim();
            }
 
             return cleanText(link.textContent);
         }
         }


         function cleanText(text) {
         function cleanText(text) {
             return String(text || '').replace(/\s+/g, ' ').trim();
             return String(text || '').replace(/\s+/g, ' ').trim();
        }
        function escapeRegExp(str) {
            return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
         }
         }
     });
     });

Версия от 19:18, 12 июня 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); 
    } 
})();

// Colonial Marines - JS by Renata (Defer) ---------------------------------------------------------

(function () {
    if (typeof mw === 'undefined' || !window.document) return;

    var statusMap = {
        green: { emoji: '🟢', words: ['готово', 'готов'] },
        yellow: { emoji: '🟡', words: ['нужно обновить', 'обновить', 'устарело'] },
        red: { emoji: '🔴', words: ['нет страницы', 'нет', 'пусто'] },
        blue: { emoji: '🔵', words: ['заморожено', 'заморожен'] }
    };

    var emojiToStatus = {
        '🟢': 'green',
        '🟡': 'yellow',
        '🔴': 'red',
        '🔵': 'blue'
    };

    function ready(fn) {
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }

    ready(function () {
        var tools = document.querySelector('.scmc-catalog-tools');
        var sections = Array.prototype.slice.call(document.querySelectorAll('.scmc-catalog-section'));
        if (!tools || !sections.length) return;

        var items = collectItems(sections);
        if (!items.length) return;

        var search = tools.querySelector('.scmc-catalog-search');
        var filters = Array.prototype.slice.call(tools.querySelectorAll('.scmc-catalog-filter'));
        var counter = tools.querySelector('.scmc-catalog-counter');
        var activeStatus = 'all';

        enhanceItems(items);
        update();

        if (search) {
            search.addEventListener('input', update);
        }

        filters.forEach(function (btn) {
            btn.addEventListener('click', function () {
                activeStatus = btn.getAttribute('data-status') || 'all';
                filters.forEach(function (b) {
                    b.classList.toggle('is-active', b === btn);
                });
                update();
            });
        });

        document.addEventListener('click', function (e) {
            var statusButton = e.target.closest('.scmc-catalog-status');
            if (statusButton) {
                e.preventDefault();
                e.stopPropagation();
                openStatusMenu(statusButton);
                return;
            }

            var menu = document.querySelector('.scmc-status-menu');
            if (menu && !e.target.closest('.scmc-status-menu')) {
                menu.remove();
            }
        });

        function collectItems(sectionList) {
            var result = [];

            sectionList.forEach(function (section) {
                var sectionTitle = '';
                var head = section.querySelector('.scmc-card-head');
                if (head) sectionTitle = cleanText(head.textContent);

                var listItems = Array.prototype.slice.call(section.querySelectorAll('.scmc-card-body li'));

                listItems.forEach(function (li) {
                    var ownText = getOwnText(li);
                    var match = ownText.match(/[🟢🟡🔴🔵]/);
                    var link = li.querySelector(':scope > a') || li.querySelector('a');

                    if (!match || !link) return;

                    var status = emojiToStatus[match[0]];
                    if (!status) return;

                    var title = cleanText(link.textContent);
                    var target = getLinkTarget(link);

                    if (!target) return;

                    li.classList.add('scmc-catalog-item');
                    li.setAttribute('data-status', status);
                    li.setAttribute('data-title', title);
                    li.setAttribute('data-target', target);
                    li.setAttribute('data-section', sectionTitle);

                    result.push({
                        li: li,
                        link: link,
                        title: title,
                        target: target,
                        section: sectionTitle,
                        status: status,
                        emoji: match[0]
                    });
                });
            });

            return result;
        }

        function enhanceItems(itemList) {
            itemList.forEach(function (item) {
                replaceOwnStatusEmoji(item.li, item.status);
            });
        }

        function replaceOwnStatusEmoji(li, status) {
            var nodes = Array.prototype.slice.call(li.childNodes);
            var emoji = statusMap[status].emoji;

            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];

                if (node.nodeType !== Node.TEXT_NODE) continue;

                var text = node.nodeValue;
                if (!/[🟢🟡🔴🔵]/.test(text)) continue;

                var parts = text.split(/[🟢🟡🔴🔵]/);
                var before = document.createTextNode(parts[0]);
                var after = document.createTextNode(parts.slice(1).join(emoji));

                var button = document.createElement('button');
                button.type = 'button';
                button.className = 'scmc-catalog-status';
                button.setAttribute('data-status', status);
                button.title = 'Изменить статус';
                button.textContent = emoji;

                li.insertBefore(before, node);
                li.insertBefore(button, node);
                li.insertBefore(after, node);
                li.removeChild(node);
                return;
            }
        }

        function openStatusMenu(button) {
            var oldMenu = document.querySelector('.scmc-status-menu');
            if (oldMenu) oldMenu.remove();

            var li = button.closest('.scmc-catalog-item');
            if (!li) return;

            var rect = button.getBoundingClientRect();
            var menu = document.createElement('div');
            menu.className = 'scmc-status-menu';

            [
                ['green', '🟢 Готово'],
                ['yellow', '🟡 Нужно обновить'],
                ['red', '🔴 Нет страницы'],
                ['blue', '🔵 Заморожено']
            ].forEach(function (row) {
                var status = row[0];
                var label = row[1];
                var option = document.createElement('button');
                option.type = 'button';
                option.textContent = label;

                option.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    menu.remove();
                    changeStatus(li, button, status);
                });

                menu.appendChild(option);
            });

            document.body.appendChild(menu);

            var left = Math.min(rect.left, window.innerWidth - menu.offsetWidth - 12);
            var top = rect.bottom + 8;

            menu.style.left = Math.max(12, left) + 'px';
            menu.style.top = top + 'px';
        }

        function changeStatus(li, button, newStatus) {
            var oldStatus = li.getAttribute('data-status');
            if (!newStatus || newStatus === oldStatus) return;

            var target = li.getAttribute('data-target');
            var title = li.getAttribute('data-title') || target;

            button.classList.add('scmc-status-saving');

            saveStatus(target, oldStatus, newStatus, title)
                .then(function () {
                    li.setAttribute('data-status', newStatus);
                    button.setAttribute('data-status', newStatus);
                    button.textContent = statusMap[newStatus].emoji;
                    button.classList.remove('scmc-status-saving');
                    update();
                })
                .catch(function (err) {
                    button.classList.remove('scmc-status-saving');
                    alert(err.message || 'Не удалось сохранить статус.');
                });
        }

        function saveStatus(target, oldStatus, newStatus, title) {
            var api = new mw.Api();
            var pageName = mw.config.get('wgPageName');

            return api.get({
                action: 'query',
                prop: 'revisions',
                titles: pageName,
                rvprop: 'content',
                rvslots: 'main',
                formatversion: 2
            }).then(function (data) {
                var page = data.query.pages[0];
                var content = page.revisions[0].slots.main.content;

                var oldEmoji = statusMap[oldStatus].emoji;
                var newEmoji = statusMap[newStatus].emoji;

                var updated = replaceStatusInSource(content, target, oldEmoji, newEmoji);

                if (!updated.changed) {
                    throw new Error('Не нашёл строку для страницы: ' + title);
                }

                if (updated.ambiguous) {
                    throw new Error('Нашлось несколько похожих строк для страницы: ' + title + '. Лучше изменить этот статус вручную.');
                }

                return api.postWithToken('csrf', {
                    action: 'edit',
                    title: pageName,
                    text: updated.text,
                    summary: 'Обновление статуса страницы: ' + title,
                    minor: true
                });
            });
        }

        function replaceStatusInSource(content, target, oldEmoji, newEmoji) {
            var lines = content.split('\n');
            var indexes = [];

            for (var i = 0; i < lines.length; i++) {
                if (lineMatchesTarget(lines[i], target) && lines[i].indexOf(oldEmoji) !== -1) {
                    indexes.push(i);
                }
            }

            if (!indexes.length) {
                return { changed: false, ambiguous: false, text: content };
            }

            if (indexes.length > 1) {
                return { changed: false, ambiguous: true, text: content };
            }

            var idx = indexes[0];
            lines[idx] = lines[idx].replace(oldEmoji, newEmoji);

            return { changed: true, ambiguous: false, text: lines.join('\n') };
        }

        function lineMatchesTarget(line, target) {
            var escaped = escapeRegExp(target);

            if (line.indexOf('[[' + target + '|') !== -1) return true;
            if (line.indexOf('[[' + target + ']]') !== -1) return true;
            if (line.indexOf(target) !== -1 && line.indexOf('[[') !== -1) return true;

            try {
                var decoded = decodeURIComponent(target);
                if (decoded !== target && line.indexOf(decoded) !== -1) return true;
            } catch (e) {}

            return new RegExp('\\[\\[' + escaped + '(\\||\\]\\])').test(line);
        }

        function update() {
            var query = search ? cleanText(search.value).toLowerCase() : '';
            var words = query ? query.split(/\s+/).filter(Boolean) : [];
            var visibleCount = 0;

            items.forEach(function (item) {
                var li = item.li;
                var status = li.getAttribute('data-status');
                var text = buildSearchText(li).toLowerCase();

                var statusOk =
                    activeStatus === 'all' ||
                    activeStatus === status ||
                    (activeStatus === 'problem' && status !== 'green');

                var textOk = words.every(function (word) {
                    return text.indexOf(word) !== -1 || statusWordMatches(status, word);
                });

                var visible = statusOk && textOk;
                li.classList.toggle('scmc-catalog-hidden', !visible);

                if (visible) visibleCount++;
            });

            revealParentsOfVisibleItems();

            if (counter) {
                counter.textContent = 'Показано: ' + visibleCount + ' из ' + items.length;
            }
        }

        function revealParentsOfVisibleItems() {
            items.forEach(function (item) {
                if (item.li.classList.contains('scmc-catalog-hidden')) return;

                var parent = item.li.parentElement;
                while (parent) {
                    if (parent.tagName && parent.tagName.toLowerCase() === 'ul') {
                        var parentLi = parent.parentElement;
                        if (parentLi && parentLi.classList && parentLi.classList.contains('scmc-catalog-item')) {
                            parentLi.classList.remove('scmc-catalog-hidden');
                        }
                    }

                    parent = parent.parentElement;
                }
            });
        }

        function statusWordMatches(status, word) {
            if (!statusMap[status]) return false;
            var words = statusMap[status].words;
            for (var i = 0; i < words.length; i++) {
                if (words[i].indexOf(word) !== -1 || word.indexOf(words[i]) !== -1) return true;
            }
            return false;
        }

        function buildSearchText(li) {
            var status = li.getAttribute('data-status');
            var title = li.getAttribute('data-title') || '';
            var target = li.getAttribute('data-target') || '';
            var section = li.getAttribute('data-section') || '';
            var statusLabel = statusMap[status] ? statusMap[status].words.join(' ') : '';

            return [
                title,
                target,
                section,
                status,
                statusLabel,
                getOwnText(li)
            ].join(' ');
        }

        function getOwnText(el) {
            var text = '';
            var nodes = Array.prototype.slice.call(el.childNodes);

            nodes.forEach(function (node) {
                if (node.nodeType === Node.TEXT_NODE) {
                    text += node.nodeValue + ' ';
                } else if (node.nodeType === Node.ELEMENT_NODE) {
                    var tag = node.tagName.toLowerCase();
                    if (tag !== 'ul' && tag !== 'ol') {
                        text += node.textContent + ' ';
                    }
                }
            });

            return cleanText(text);
        }

        function getLinkTarget(link) {
            var title = link.getAttribute('title');
            if (title && title.trim()) return title.trim();

            var href = link.getAttribute('href') || '';
            if (!href) return '';

            var titleMatch = href.match(/[?&]title=([^&]+)/);
            if (titleMatch) return decodeURIComponent(titleMatch[1]).replace(/_/g, '_');

            var parts = href.split('/');
            var last = parts[parts.length - 1] || '';
            return decodeURIComponent(last).replace(/_/g, '_');
        }

        function cleanText(text) {
            return String(text || '').replace(/\s+/g, ' ').trim();
        }

        function escapeRegExp(str) {
            return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
    });
})();

// Colonial Marines - JS by Renata (Defer) ------------------------------------------------END