「MediaWiki:Common.js」:修訂間差異

出自Quickpedia wiki
無編輯摘要
無編輯摘要
第1行: 第1行:
/* === MediaWiki Custom Language Variant Handling === */
/**
* 所有用戶在加載任何頁面時,這裡的JavaScript都會加載
*/


$(function() {
mw.log.deprecate(window, 'JSConfig', {});
    // 在這裡加入 console.log,方便除錯
 
    console.log("wgContentLanguageVariants:", mw.config.get('wgContentLanguageVariants'));
mw.loader.using(['ext.gadget.site-lib', 'mediawiki.util']).then(function() {
    console.log("wgUserVariant:", mw.config.get('wgUserVariant'));


    // 1. **自定義語系下拉選單**
    var variants = mw.config.get('wgContentLanguageVariants'); // 獲取可用的語言變體


    // 篩選出只包含簡體和繁體的變體
     if (mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit' || mw.config.get('wgCanonicalSpecialPageName') === 'Search') {
    var filteredVariants = [];
        /* scripts specific to editing pages */
     if (variants) {
        importScript('MediaWiki:Common.js\/edit.js');
        for (var i = 0; i < variants.length; i++) {
    } else {
            var variantCode = variants[i];
        mw.loader.using('ext.visualEditor.desktopArticleTarget.init', function() {
            if (variantCode === 'zh-tw' || variantCode === 'zh-hant' ||
            mw.libs.ve.addPlugin(function() {
                variantCode === 'zh-cn' || variantCode === 'zh-hans') {
                 importScript('MediaWiki:Common.js\/edit.js');
                 filteredVariants.push(variantCode);
             });
             }
         });
         }
     }
     }


     // 如果篩選後有至少兩種語系變體,才建立下拉選單
     /**
     if (filteredVariants.length > 1) {
    * Helper script for .hlist class in Common.css
         var currentVariant = mw.config.get('wgUserVariant');
    * Add pseudo-selector class to last-child list items in IE8
        var languageDropdown = $('<div id="zh-variant-dropdown" class="portal"></div>'); // 增加portal class 讓外觀更像側邊欄組件
    * @source mediawiki.org/wiki/Snippets/Horizontal_lists
        languageDropdown.append('<h3>中文</h3>'); // 增加標題
    * @revision 6 (2014-08-23)
         var variantSelect = $('<select id="zh-variant-select"></select>');
    * @author [[User:Edokter]]
    */
    var profile = $.client.profile();
     if (profile.name === 'msie' && profile.versionNumber === 8) {
         mw.hook('wikipage.content').add(function($content) {
            $content.find('.hlist').find('dd:last-child, dt:last-child, li:last-child').addClass('hlist-last-child');
         });
    }


         for (var i = 0; i < filteredVariants.length; i++) {
    /* 避免在主條目的註腳中出現捲軸框 */
            var variantCode = filteredVariants[i];
    if (!mw.config.get('wgCanonicalNamespace')) {
            var variantName = '';
         $(function() {
            $('div#mw-content-text ol.references').each(function() {
                var needobjs=[], $curobj=$(this);
                do {
                    $curobj=$curobj.parent();
                    if (!$curobj) break;
                    if ($curobj.attr('id') === 'mw-content-text' || $curobj.prop('tagName').toLowerCase() === 'body') break;
                    if ($curobj.css('overflow').match(/(?: auto|scroll)/i) || $curobj.css('overflow-x').match(/(?:auto|scroll)/i) || $curobj.css('overflow-y').match(/(?:auto|scroll)/i)) {
                        /* null */
                    } else continue;
                    if ((''+$curobj.attr('class')).split(' ').indexOf('noprint') >= 0) return;
                    needobjs.push($curobj.get(0));
                } while (true);
                $(needobjs)
                    .css('overflow', 'visible')
                    .css('overflow-x', 'visible')
                    .css('overflow-y', 'visible')
                    .css('border', '')
                    .css('height', '')
                    .css('max-height', '');
            });
        });
    }


            switch (variantCode) {
    /**
                case 'zh-tw':
    * metaBox
                case 'zh-hant':
    * Funcionament de la Plantilla:Metacaixa
                    variantName = '繁體中文';
    * Implementat per: Usuari:Peleguer.
                    break;
    * Actualitzat per Joanjoc seguint les indicacions d'en Martorell
                 case 'zh-cn':
    */
                 case 'zh-hans':
    function MetaCaixaInit() {
                    variantName = '簡體中文';
        // S'executa al carregar-se la pàgina, si hi ha metacaixes,
                    break;
        // s'assignen els esdeveniments als botons
                 default:
        //alert('MetaCaixaInit');
                    // 這裡應該不會執行到,因為上面已經過濾了
        var i = 0; // Inicialitzem comptador de caixes
                    variantName = variantCode;
        for (i = 0; i <= 9; i++) {
            var vMc = document.getElementById('mc' + i);
            if (!vMc) break;
            //alert('MetaCaixaInit, trobada Metacaixa mc' + i);
            var j = 1, // Inicialitzem comptador de botons dins de la caixa
                vPsIni = 0; // Pestanya visible inicial
            for (j = 1; j <= 9; j++) {
                 var vBt = document.getElementById('mc' + i + 'bt' + j);
                if (!vBt) break;
                 //alert('MetaCaixaInit, trobat botó mc' + i + 'bt' + j);
                vBt.onclick = MetaCaixaMostraPestanya; // A cada botó assignem l'esdeveniment onclick
                //alert(vBt.className);
                if (vBt.className === 'mcBotoSel') vPsIni = j; // Si tenim un botó seleccionat, en guardem l'index
            }
            //alert('mc=' + i + ', ps=' + j + ', psini=' + vPsIni);
            if (vPsIni === 0) { // Si no tenim cap botó seleccionat, n'agafem un aleatòriament
                 vPsIni = 1 + Math.floor((j - 1) * Math.random());
                //alert('Activant Pestanya a l\'atzar; _mc' + i + 'bt' + vPsIni + '_');
                try {
                document.getElementById('mc' + i + 'ps' + vPsIni).style.display = 'block';
            document.getElementById('mc' + i + 'ps' + vPsIni).style.visibility = 'visible';
            document.getElementById('mc' + i + 'bt' + vPsIni).className = 'mcBotoSel';
                } catch(e) {
                // TypeError: null is not an object (evaluating 'document.getElementById('mc'+i+'ps'+vPsIni).style')
                }
             }
             }
        }
    }


             var option = $('<option>').val(variantCode).text(variantName);
    function MetaCaixaMostraPestanya() {
             if (variantCode === currentVariant) {
        // S'executa al clicar una pestanya,
                 option.prop('selected', true);
        // aquella es fa visible i les altres s'oculten
        var vMcNom = this.id.substr(0, 3), // A partir del nom del botó, deduïm el nom de la caixa
             vIndex = this.id.substr(5, 1), // I l'index
            i = 1;
        for (i = 1; i <= 9; i++) { // busquem totes les pestanyes d'aquella caixa
            //alert(vMcNom + 'ps' + i);
            var vPsElem = document.getElementById(vMcNom + 'ps' + i);
            if (!vPsElem) break;
             if (vIndex == i) { // Si és la pestanya bona la mostrem i canviem la classe de botó
                vPsElem.style.display = 'block';
                vPsElem.style.visibility = 'visible';
                document.getElementById(vMcNom + 'bt' + i).className = 'mcBotoSel';
            } else { // Sinó, l'ocultem i canviem la classe de botó
                vPsElem.style.display = 'none';
                 vPsElem.style.visibility = 'hidden';
                document.getElementById(vMcNom + 'bt' + i).className = 'mcBoto';
             }
             }
            variantSelect.append(option);
         }
         }
        return false; // evitem la recàrrega de la pàgina
    }
    $(MetaCaixaInit);


        variantSelect.on('change', function() {
    if (!+mw.user.options.get('discussiontools-newtopictool') || !+mw.user.options.get('discussiontools-betaenable')) {
            var selectedVariant = $(this).val();
        /* 智能讨论页编辑(新建) */
             var currentUrl = new URL(window.location.href);
        $(function() {
             // 設置 URL 參數 'variant'
             var catalk = $('#ca-talk');
            currentUrl.searchParams.set('variant', selectedVariant);
             if (catalk.hasClass('new') && mw.config.get('wgNamespaceNumber') != 2) {
            // 如果頁面當前有 /簡體 或 /繁體 這種路徑,需要移除它們,因為我們現在用 ?variant=
                var a = $('a:first', catalk);
            var pathParts = currentUrl.pathname.split('/');
                a.attr('href', a.attr('href') + '&section=new');
            var lastPart = pathParts[pathParts.length - 1];
            if (lastPart === '簡體' || lastPart === '繁體') {
                pathParts.pop(); // 移除最後一個部分
                currentUrl.pathname = pathParts.join('/');
             }
             }
            window.location.href = currentUrl.toString();
         });
         });
    }


        // 將下拉選單添加到側邊欄頂部 (通常是 #mw-panel 或 #p-navigation)
    /**
         // 選擇 #mw-panel 是為了讓它在整個側邊欄的頂部
    * Magic editintros
         $('#mw-panel').prepend(languageDropdown.append(variantSelect));
    * Description: Adds editintros on disambiguation pages, BLP pages, policy pages and guidlines.
         // 如果您的維基百科使用的是不同的側邊欄 ID,請調整這裡
    * Maintainers: [[User:RockMFR]]
         // 例如:$('#p-navigation').prepend(languageDropdown.append(variantSelect));
    */
    function addEditIntro(name) {
        $('.mw-editsection, #ca-edit').find('a').each(function(i, el) {
            el.href = $(this).attr('href') + '&editintro=' + name;
         });
    }
    if (mw.config.get('wgNamespaceNumber') === 0) {
         $(function() {
            if (document.getElementById('disambigbox')) addEditIntro('Template:Disambig_editintro');
        });
        $(function() {
            var cats = mw.config.get('wgCategories');
            if (!cats) return;
            if ($.inArray('在世人物', cats) !== -1) addEditIntro('Template:BLP_editintro');
            if (cats.some(function(cat){return /\d{4}年台灣電視劇集/.test(cat)})) addEditIntro('Template:TVdrama_editintro');
         });
    } else if (mw.config.get('wgNamespaceNumber') === 4) {
         $(function() {
            var cats = mw.config.get('wgCategories');
            if (!cats) return;
            if ($.inArray('維基百科方針與指引完整列表', cats) !== -1) addEditIntro('Template:Policy editintro');
        });
     }
     }


     // 2. **自動語系導向邏輯 (基於瀏覽器語系,並使用 ?variant= 參數)**
     /**
    // 只有當頁面URL中沒有 `?variant=` 參數時才自動導向
    * &withCSS= and &withJS= URL parameters
     var currentUrl = new URL(window.location.href);
    * Allow to try custom scripts from MediaWiki space
    if (!currentUrl.searchParams.has('variant')) {
    * without editing personal .css or .js files
         var browserLang = (navigator.language || navigator.userLanguage).toLowerCase();
    * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
         var simplifiedCodes = ['zh-cn', 'zh-sg', 'zh-hans'];
    * @rev 6
         var traditionalCodes = ['zh-tw', 'zh-hk', 'zh-mo', 'zh-hant'];
    */
 
     var extraCSS = mw.util.getParamValue('withCSS'),
        var targetVariant = '';
        extraJS = mw.util.getParamValue('withJS');
        if (simplifiedCodes.includes(browserLang)) {
    if (extraCSS) {
            targetVariant = 'zh-hans'; // 導向簡體變體
         if (extraCSS.match(/^MediaWiki:[^&<>=%#]*\.css$/)) {
         } else if (traditionalCodes.includes(browserLang)) {
            importStylesheet(extraCSS);
             targetVariant = 'zh-hant'; // 導向繁體變體
         } else {
            mw.notify('只允许从MediaWiki命名空间加载。', {title: '无效的withCSS值'});
         }
    }
    if (extraJS) {
         if (extraJS.match(/^MediaWiki:[^&<>=%#]*\.js$/)) {
             importScript(extraJS);
         } else {
         } else {
             // 如果瀏覽器語系既不是簡體也不是繁體中文,預設導向繁體
             mw.notify('只允许从MediaWiki命名空间加载。', {title: '无效的withJS值'});
            targetVariant = 'zh-hant';
         }
         }
    }
    /* 页面历史加&hilight=高亮 */
    var hilight = mw.util.getParamValue('hilight');
    if (mw.config.get('wgAction') === 'history' && hilight) {
        $.each(hilight.split(','), function(_, v) {
            $('input[name=oldid][value=' + v + ']').parent().addClass('not-patrolled');
        });
    }
    /* Main page hacks */
    if (mw.config.get('wgIsMainPage') && mw.config.get('wgAction') === 'view') {
        /* Remove red links */
        $('#mw-content-text a.new').contents().unwrap();
    }
});


         // 只有當目標變體與當前用戶變體不同時才導向
$(function() {
         if (targetVariant && mw.config.get('wgUserVariant') !== targetVariant) {
    /* 修正摺疊後定位變化 */
            currentUrl.searchParams.set('variant', targetVariant);
    if (location.hash) location.href = location.hash;
            // 同樣,如果頁面當前有 /簡體 或 /繁體 這種路徑,需要移除它們
 
            var pathParts = currentUrl.pathname.split('/');
    /* 引用錯誤標籤名字解碼 */
            var lastPart = pathParts[pathParts.length - 1];
    $('.anchordecodeme').each(function() {
            if (lastPart === '簡體' || lastPart === '繁體') {
        $(this).text(decodeURIComponent($(this).text().replace(/\.([0-9A-F]{2})/g, '%$1')));
                pathParts.pop();
    });
                currentUrl.pathname = pathParts.join('/');
 
            }
    /* Check for any client-side simplified/traditional Chinese conversion */
             window.location.href = currentUrl.toString();
    /* This routine must be placed here to make sure the field is inserted in time */
         }
    $('#antispam-container').append(
        $('<input type="text" />').attr({
            id: 'wpAntiConv',
            value: '\u6c49\u6f22'
         })
    );
 
});
 
// per [[Special:Diff/64919534/64925950]],展开折叠按钮的颜色
$(function collapseButtonColor() {
    var $toggle = $('.mw-collapsible-toggle');
    if ($toggle.length > 0) {
         if ($toggle.parent()[0].style.color) $toggle.find('a').css('color', 'inherit');
    }
});
 
if (mw.config.get('wgUserName') === null) {
mw.loader.load('ext.gadget.preserve-variant');
}
(function() {
    function showClock() {
        var now = new Date();
        return now.toLocaleTimeString('zh-TW', { hour12: false });
    }
 
    function insertClock() {
        if (document.getElementById('mw-header-clock')) return;
 
        var header = document.querySelector('#mw-panel + #mw-head .vector-user-links')
                    || document.querySelector('#p-personal'); // 找 Vector 右上用戶選單
        if (!header) return;
 
        var span = document.createElement('span');
        span.id = 'mw-header-clock';
        span.style.fontFamily = 'monospace';
        span.style.fontWeight = 'bold';
        span.style.marginLeft = '0.5em';
        span.style.color = '#000';
        span.innerText = showClock();
 
        header.appendChild(span);
 
        // 每秒更新
        setInterval(function() {
             span.innerText = showClock();
         }, 1000);
     }
     }


     // 3. **隱藏 MediaWiki 內建語系切換器 (如果存在)**
     mw.loader.using('mediawiki.util', function() {
    // 這部分是為了防止兩個語系選單同時出現,造成混淆
        // 等待頁面元素加載
    $(document).ready(function() { // 這個 ready 函數其實可以省略,因為外層已經是 $(function(){})
         document.addEventListener('DOMContentLoaded', insertClock);
         var variantsMenu = $('#p-variants'); // MediaWiki 標準語系選單 ID
         setTimeout(insertClock, 500); // 再保險一次
         if (variantsMenu.length > 0) {
            variantsMenu.hide(); // 直接隱藏整個內建選單
        }
     });
     });
})();
/**
* 在右上角個人選單中增加「深色模式」切換按鈕
* 插入位置:偏好設定 (pt-preferences) 之後
*/
mw.loader.using('mediawiki.util').then(function() {
    $(function() {
        // 1. 建立選單項目
        var portletLink = mw.util.addPortletLink(
            'p-personal',        // 目標:個人選單
            '#',                  // 連結路徑
            '切換深色模式',        // 顯示文字
            'pt-darkmode',        // 項目 ID
            '開啟或關閉深色模式',    // 懸停提示
            '',                  // 快捷鍵
            '#pt-watchlist'      // 插入在「監視清單」之前 = 「偏好設定」之後
        );
        // 2. 定義點擊後的動作
        $(portletLink).on('click', function(e) {
            e.preventDefault();
           
            // 這裡假設您是透過切換 <body> 的 class 來實現深色模式
            // 如果您是使用特定的 Darkmode 擴展,請將下方邏輯換成該擴展的 API
            $('body').toggleClass('dark-mode-active');
           
            // 存儲狀態到本地,讓重新整理後依然有效
            var isDark = $('body').hasClass('dark-mode-active');
            localStorage.setItem('user-dark-mode', isDark ? 'on' : 'off');
        });


}); // 此處為最外層 $(function() { ... }); 的結束
        // 3. 頁面加載時檢查之前的設定
// 等頁面完全載入後執行
        if (localStorage.getItem('user-dark-mode') === 'on') {
window.addEventListener('load', function() {
            $('body').addClass('dark-mode-active');
    // 隱藏整個 CAPTCHA 區塊
         }
    var captchaBlocks = document.querySelectorAll('.mw-captcha');
    captchaBlocks.forEach(function(el) {
         el.style.display = 'none';
     });
     });
    // 如果有單獨的輸入欄位,也隱藏它
    var captchaInput = document.getElementById('mw-input-captchaWord');
    if (captchaInput) {
        captchaInput.style.display = 'none';
    }
});
});

於 2026年3月8日 (日) 06:11 的修訂

/**
 * 所有用戶在加載任何頁面時,這裡的JavaScript都會加載
 */

mw.log.deprecate(window, 'JSConfig', {});

mw.loader.using(['ext.gadget.site-lib', 'mediawiki.util']).then(function() {


    if (mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit' || mw.config.get('wgCanonicalSpecialPageName') === 'Search') {
        /* scripts specific to editing pages */
        importScript('MediaWiki:Common.js\/edit.js');
    } else {
        mw.loader.using('ext.visualEditor.desktopArticleTarget.init', function() {
            mw.libs.ve.addPlugin(function() {
                importScript('MediaWiki:Common.js\/edit.js');
            });
        });
    }

    /**
     * Helper script for .hlist class in Common.css
     * Add pseudo-selector class to last-child list items in IE8
     * @source mediawiki.org/wiki/Snippets/Horizontal_lists
     * @revision 6 (2014-08-23)
     * @author [[User:Edokter]]
     */
    var profile = $.client.profile();
    if (profile.name === 'msie' && profile.versionNumber === 8) {
        mw.hook('wikipage.content').add(function($content) {
            $content.find('.hlist').find('dd:last-child, dt:last-child, li:last-child').addClass('hlist-last-child');
        });
    }

    /* 避免在主條目的註腳中出現捲軸框 */
    if (!mw.config.get('wgCanonicalNamespace')) {
        $(function() {
            $('div#mw-content-text ol.references').each(function() {
                var needobjs=[], $curobj=$(this);
                do {
                    $curobj=$curobj.parent();
                    if (!$curobj) break;
                    if ($curobj.attr('id') === 'mw-content-text' || $curobj.prop('tagName').toLowerCase() === 'body') break;
                    if ($curobj.css('overflow').match(/(?: auto|scroll)/i) || $curobj.css('overflow-x').match(/(?:auto|scroll)/i) || $curobj.css('overflow-y').match(/(?:auto|scroll)/i)) {
                        /* null */
                    } else continue;
                    if ((''+$curobj.attr('class')).split(' ').indexOf('noprint') >= 0) return;
                    needobjs.push($curobj.get(0));
                } while (true);
                $(needobjs)
                    .css('overflow', 'visible')
                    .css('overflow-x', 'visible')
                    .css('overflow-y', 'visible')
                    .css('border', '')
                    .css('height', '')
                    .css('max-height', '');
            });
        });
    }

    /**
     * metaBox
     * Funcionament de la Plantilla:Metacaixa
     * Implementat per: Usuari:Peleguer.
     * Actualitzat per Joanjoc seguint les indicacions d'en Martorell
     */
    function MetaCaixaInit() {
        // S'executa al carregar-se la pàgina, si hi ha metacaixes,
        // s'assignen els esdeveniments als botons
        //alert('MetaCaixaInit');
        var i = 0; // Inicialitzem comptador de caixes
        for (i = 0; i <= 9; i++) {
            var vMc = document.getElementById('mc' + i);
            if (!vMc) break;
            //alert('MetaCaixaInit, trobada Metacaixa mc' + i);
            var j = 1, // Inicialitzem comptador de botons dins de la caixa
                vPsIni = 0; // Pestanya visible inicial
            for (j = 1; j <= 9; j++) {
                var vBt = document.getElementById('mc' + i + 'bt' + j);
                if (!vBt) break;
                //alert('MetaCaixaInit, trobat botó mc' + i + 'bt' + j);
                vBt.onclick = MetaCaixaMostraPestanya; // A cada botó assignem l'esdeveniment onclick
                //alert(vBt.className);
                if (vBt.className === 'mcBotoSel') vPsIni = j; // Si tenim un botó seleccionat, en guardem l'index
            }
            //alert('mc=' + i + ', ps=' + j + ', psini=' + vPsIni);
            if (vPsIni === 0) { // Si no tenim cap botó seleccionat, n'agafem un aleatòriament
                vPsIni = 1 + Math.floor((j - 1) * Math.random());
                //alert('Activant Pestanya a l\'atzar; _mc' + i + 'bt' + vPsIni + '_');
                try {
                	document.getElementById('mc' + i + 'ps' + vPsIni).style.display = 'block';
            		document.getElementById('mc' + i + 'ps' + vPsIni).style.visibility = 'visible';
            		document.getElementById('mc' + i + 'bt' + vPsIni).className = 'mcBotoSel';
                } catch(e) {
                	// TypeError: null is not an object (evaluating 'document.getElementById('mc'+i+'ps'+vPsIni).style') 
                }
            }
        }
    }

    function MetaCaixaMostraPestanya() {
        // S'executa al clicar una pestanya,
        // aquella es fa visible i les altres s'oculten
        var vMcNom = this.id.substr(0, 3), // A partir del nom del botó, deduïm el nom de la caixa
            vIndex = this.id.substr(5, 1), // I l'index
            i = 1;
        for (i = 1; i <= 9; i++) { // busquem totes les pestanyes d'aquella caixa
            //alert(vMcNom + 'ps' + i);
            var vPsElem = document.getElementById(vMcNom + 'ps' + i);
            if (!vPsElem) break;
            if (vIndex == i) { // Si és la pestanya bona la mostrem i canviem la classe de botó
                vPsElem.style.display = 'block';
                vPsElem.style.visibility = 'visible';
                document.getElementById(vMcNom + 'bt' + i).className = 'mcBotoSel';
            } else { // Sinó, l'ocultem i canviem la classe de botó
                vPsElem.style.display = 'none';
                vPsElem.style.visibility = 'hidden';
                document.getElementById(vMcNom + 'bt' + i).className = 'mcBoto';
            }
        }
        return false; // evitem la recàrrega de la pàgina
    }
    $(MetaCaixaInit);

    if (!+mw.user.options.get('discussiontools-newtopictool') || !+mw.user.options.get('discussiontools-betaenable')) {
        /* 智能讨论页编辑(新建) */
        $(function() {
            var catalk = $('#ca-talk');
            if (catalk.hasClass('new') && mw.config.get('wgNamespaceNumber') != 2) {
                var a = $('a:first', catalk);
                a.attr('href', a.attr('href') + '&section=new');
            }
        });
    }

    /**
     * Magic editintros
     * Description: Adds editintros on disambiguation pages, BLP pages, policy pages and guidlines.
     * Maintainers: [[User:RockMFR]]
     */
    function addEditIntro(name) {
        $('.mw-editsection, #ca-edit').find('a').each(function(i, el) {
            el.href = $(this).attr('href') + '&editintro=' + name;
        });
    }
    if (mw.config.get('wgNamespaceNumber') === 0) {
        $(function() {
            if (document.getElementById('disambigbox')) addEditIntro('Template:Disambig_editintro');
        });
        $(function() {
            var cats = mw.config.get('wgCategories');
            if (!cats) return;
            if ($.inArray('在世人物', cats) !== -1) addEditIntro('Template:BLP_editintro');
            if (cats.some(function(cat){return /\d{4}年台灣電視劇集/.test(cat)})) addEditIntro('Template:TVdrama_editintro');
        });
    } else if (mw.config.get('wgNamespaceNumber') === 4) {
        $(function() {
            var cats = mw.config.get('wgCategories');
            if (!cats) return;
            if ($.inArray('維基百科方針與指引完整列表', cats) !== -1) addEditIntro('Template:Policy editintro');
        });
    }

    /**
     * &withCSS= and &withJS= URL parameters
     * Allow to try custom scripts from MediaWiki space
     * without editing personal .css or .js files
     * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
     * @rev 6
     */
    var extraCSS = mw.util.getParamValue('withCSS'),
        extraJS = mw.util.getParamValue('withJS');
    if (extraCSS) {
        if (extraCSS.match(/^MediaWiki:[^&<>=%#]*\.css$/)) {
            importStylesheet(extraCSS);
        } else {
            mw.notify('只允许从MediaWiki命名空间加载。', {title: '无效的withCSS值'});
        }
    }
    if (extraJS) {
        if (extraJS.match(/^MediaWiki:[^&<>=%#]*\.js$/)) {
            importScript(extraJS);
        } else {
            mw.notify('只允许从MediaWiki命名空间加载。', {title: '无效的withJS值'});
        }
    }

    /* 页面历史加&hilight=高亮 */
    var hilight = mw.util.getParamValue('hilight');
    if (mw.config.get('wgAction') === 'history' && hilight) {
        $.each(hilight.split(','), function(_, v) {
            $('input[name=oldid][value=' + v + ']').parent().addClass('not-patrolled');
        });
    }

    /* Main page hacks */
    if (mw.config.get('wgIsMainPage') && mw.config.get('wgAction') === 'view') {
        /* Remove red links */
        $('#mw-content-text a.new').contents().unwrap();
    }
});

$(function() {
    /* 修正摺疊後定位變化 */
    if (location.hash) location.href = location.hash;

    /* 引用錯誤標籤名字解碼 */
    $('.anchordecodeme').each(function() {
        $(this).text(decodeURIComponent($(this).text().replace(/\.([0-9A-F]{2})/g, '%$1')));
     });

    /* Check for any client-side simplified/traditional Chinese conversion */
    /* This routine must be placed here to make sure the field is inserted in time */
    $('#antispam-container').append(
        $('<input type="text" />').attr({
            id: 'wpAntiConv',
            value: '\u6c49\u6f22'
        })
    );

});

// per [[Special:Diff/64919534/64925950]],展开折叠按钮的颜色
$(function collapseButtonColor() {
    var $toggle = $('.mw-collapsible-toggle');
    if ($toggle.length > 0) {
        if ($toggle.parent()[0].style.color) $toggle.find('a').css('color', 'inherit');
    }
});

if (mw.config.get('wgUserName') === null) {
	mw.loader.load('ext.gadget.preserve-variant');
}
(function() {
    function showClock() {
        var now = new Date();
        return now.toLocaleTimeString('zh-TW', { hour12: false });
    }

    function insertClock() {
        if (document.getElementById('mw-header-clock')) return;

        var header = document.querySelector('#mw-panel + #mw-head .vector-user-links') 
                     || document.querySelector('#p-personal'); // 找 Vector 右上用戶選單
        if (!header) return;

        var span = document.createElement('span');
        span.id = 'mw-header-clock';
        span.style.fontFamily = 'monospace';
        span.style.fontWeight = 'bold';
        span.style.marginLeft = '0.5em';
        span.style.color = '#000';
        span.innerText = showClock();

        header.appendChild(span);

        // 每秒更新
        setInterval(function() {
            span.innerText = showClock();
        }, 1000);
    }

    mw.loader.using('mediawiki.util', function() {
        // 等待頁面元素加載
        document.addEventListener('DOMContentLoaded', insertClock);
        setTimeout(insertClock, 500); // 再保險一次
    });
})();
/**
 * 在右上角個人選單中增加「深色模式」切換按鈕
 * 插入位置:偏好設定 (pt-preferences) 之後
 */
mw.loader.using('mediawiki.util').then(function() {
    $(function() {
        // 1. 建立選單項目
        var portletLink = mw.util.addPortletLink(
            'p-personal',         // 目標:個人選單
            '#',                  // 連結路徑
            '切換深色模式',         // 顯示文字
            'pt-darkmode',        // 項目 ID
            '開啟或關閉深色模式',    // 懸停提示
            '',                   // 快捷鍵
            '#pt-watchlist'       // 插入在「監視清單」之前 = 「偏好設定」之後
        );

        // 2. 定義點擊後的動作
        $(portletLink).on('click', function(e) {
            e.preventDefault();
            
            // 這裡假設您是透過切換 <body> 的 class 來實現深色模式
            // 如果您是使用特定的 Darkmode 擴展,請將下方邏輯換成該擴展的 API
            $('body').toggleClass('dark-mode-active');
            
            // 存儲狀態到本地,讓重新整理後依然有效
            var isDark = $('body').hasClass('dark-mode-active');
            localStorage.setItem('user-dark-mode', isDark ? 'on' : 'off');
        });

        // 3. 頁面加載時檢查之前的設定
        if (localStorage.getItem('user-dark-mode') === 'on') {
            $('body').addClass('dark-mode-active');
        }
    });
});