跳转到内容

MediaWiki:Gadget-edit0.js:修订间差异

勤求古训,博采众方
鹿野耕云留言 | 贡献
无编辑摘要
鹿野耕云留言 | 贡献
无编辑摘要
第1行: 第1行:
// [[en:MediaWiki:Gadget-edittop.js]]
// [[en:MediaWiki:Gadget-edittop.js]]
// Optimized for MediaWiki 1.43+ and modern skins (Vector 2022), without redundant i18n
// Verified spelling/grammar - Last update: 2024-03-20
// Improved by: [Your Name/ID]
(function($, mw) {
(function($, mw) {
     'use strict';
     "use strict";


     // 1. 基础校验:仅在允许的操作和非负命名空间生效
     // [1] Early exit conditions.
     const ALLOWED_ACTIONS = ['view', 'purge'];
     if (
    const currentAction = mw.config.get('wgAction');
        mw.config.get("wgAction") !== "view" ||
    const currentNamespace = mw.config.get('wgNamespaceNumber');
        mw.config.get("wgNamespaceNumber") < 0 ||
    if (!ALLOWED_ACTIONS.includes(currentAction) || currentNamespace < 0) {
        document.querySelectorAll(".cloned-top-edit-button").length > 0
    ) {
         return;
         return;
     }
     }


     // 2. 页面加载完成后执行(确保DOM已渲染)
     // [2] Internationalization with fallbacks.
     $(function() {
     const BUTTON_TEXTS = new Map([
        // 核心配置:简化版多语言标题(保留主流语种,按需扩展)
         ["en", "Edit lead section"],
         const BUTTON_TITLES = {
        ["zh", "编辑首段"],
            en: 'Edit lead section',
        ["zh-hans", "编辑首段"],
            zh: '编辑简介',
        ["zh-cn", "编辑首段"],
            'zh-hans': '编辑简介',
        ["zh-tw", "編輯首段"],
            'zh-cn': '编辑简介',
        ["ja", "はじめの編集"]
            'zh-hant': '編輯首段',
    ]);
            'zh-tw': '編輯首段',
            de: 'Einleitungsabschnitt bearbeiten',
            es: 'Editar sección introductoria',
            fr: 'Modifier le résumé introductif',
            ja: '導入部を編集',
            ru: 'Редактировать вступление'
        };


         // 3. 确定按钮标题(优先用户语言,兜底英文)
    const getLocalizedText = (langCode) => {
        const userLang = mw.config.get('wgUserLanguage');
         return BUTTON_TEXTS.get(langCode) ??
        const buttonTitle = BUTTON_TITLES[userLang] ?? BUTTON_TITLES.en;
              BUTTON_TEXTS.get(langCode.split("-")[0]) ??  
              BUTTON_TEXTS.get("en");
    };


        // 4. 定位内容容器(兼容Vector 2022/旧版/自定义皮肤)
    // [3] Modern URL builder.
         const $contentContainer = $('#content, #mw_content, .mw-content-container').first();
    const buildEditUrl = () => {
         if (!$contentContainer.length) {
         const params = new Map([
             console.warn('Edittop Gadget: Content container not found, exiting.');
            ["title", mw.config.get("wgPageName")],
            return;
            ["section", "0"],
        }
            ["summary", "/* top */"]
        ]);
 
         const isVE = (
            mw.config.get("wgVisualEditor")?.isVisualEditor ??
            document.querySelector(".ve-edit-toolbar") !== null ??
             false
        );
        params.set(isVE ? "veaction" : "action", "edit");
 
        return `${mw.config.get("wgScript")}?${new URLSearchParams([...params]).toString()}`;
    };


        // 5. 克隆现有编辑分段按钮(确保有可复用的按钮模板)
    // [4] DOM operations.
         const $originalEditSection = $contentContainer.find('.mw-editsection:not(.plainlinks)').first();
    const initializeButton = () => {
        if (!$originalEditSection.length) {
         try {
            console.warn('Edittop Gadget: Original edit section button not found, exiting.');
            const $editSection = $(".mw-editsection:first,.mw-editsection-last:first");
             return;
            if ($editSection.length === 0) {
        }
                throw new Error("No editable section found.");
        const $clonedButton = $originalEditSection.clone();
             }


        // 6. 清除克隆按钮的重复ID(避免DOM ID冲突)
            const $button = $editSection.clone()
        $clonedButton.removeAttr('id').find('[id]').removeAttr('id');
                .removeAttr("id")
                .find("[id]").removeAttr("id").end()
                .addClass("cloned-top-edit-button")
                .attr("aria-label", getLocalizedText(mw.config.get("wgUserLanguage")));


        // 7. 处理编辑链接(区分可视化编辑器VE和传统编辑器)
            $button.find("a")
        const $editLink = $clonedButton.find('a').first();
                .attr({
        const isVE = $editLink.attr('href')?.includes('veaction=edit') ?? false;
                    href: buildEditUrl(),
        // 用mw.util.getUrl生成标准链接,自动处理编码和参数格式
                    title: getLocalizedText(mw.config.get("wgUserLanguage"))
        const editParams = {
                })
            [isVE ? 'veaction' : 'action']: 'edit',
                .text(getLocalizedText(mw.config.get("wgUserLanguage")));
            section: 0, // 0代表页面首段(引言部分)
            summary: '/* top */' // 预填编辑摘要,标识“编辑首段”操作
        };
        const editUrl = mw.util.getUrl(mw.config.get('wgPageName'), editParams);


        // 8. 更新克隆按钮的属性(链接+标题)
            const $heading = $([
        $editLink.attr({
                "#firstHeading",
            'href': editUrl,
                ".mw-first-heading",
             'title': buttonTitle
                ".page-heading",
        });
                ".firstHeading",
                "#section_0 h1"
             ].join(",")).first();


        // 9. 定位标题容器并添加按钮(适配所有主流皮肤标题结构)
            if ($heading.length) {
        const $titleContainer = $('#mw-page-title-main, #firstHeading, #content h1, #mw_header h1').first();
                $heading.append(
        if ($titleContainer.length) {
                    $("<span>").addClass("mw-editsection").append($button)
            $titleContainer.append($clonedButton);
                );
         } else {
                mw.hook("wikipage.editform").fire($button);
             console.warn('Edittop Gadget: Title container not found, button not added.');
            } else {
                throw new Error("No suitable heading found.");
            }
         } catch (e) {
             console.error("EditTopButton failed:", e);
            mw.track("gadget.edittop.error", e.message);
         }
         }
     });
     };
 
    // [5] Execution flow.
    if (document.readyState === "complete") {
        initializeButton();
    } else {
        $(document).one("ready mw.loader.ready", initializeButton);
    }
})(jQuery, mw);
})(jQuery, mw);

2025年11月2日 (日) 20:13的版本

// [[en:MediaWiki:Gadget-edittop.js]]
// Verified spelling/grammar - Last update: 2024-03-20
(function($, mw) {
    "use strict";

    // [1] Early exit conditions.
    if (
        mw.config.get("wgAction") !== "view" || 
        mw.config.get("wgNamespaceNumber") < 0 ||
        document.querySelectorAll(".cloned-top-edit-button").length > 0
    ) {
        return;
    }

    // [2] Internationalization with fallbacks.
    const BUTTON_TEXTS = new Map([
        ["en", "Edit lead section"],
        ["zh", "编辑首段"],
        ["zh-hans", "编辑首段"],
        ["zh-cn", "编辑首段"],
        ["zh-tw", "編輯首段"],
        ["ja", "はじめの編集"]
    ]);

    const getLocalizedText = (langCode) => {
        return BUTTON_TEXTS.get(langCode) ?? 
               BUTTON_TEXTS.get(langCode.split("-")[0]) ?? 
               BUTTON_TEXTS.get("en");
    };

    // [3] Modern URL builder.
    const buildEditUrl = () => {
        const params = new Map([
            ["title", mw.config.get("wgPageName")],
            ["section", "0"],
            ["summary", "/* top */"]
        ]);

        const isVE = (
            mw.config.get("wgVisualEditor")?.isVisualEditor ??
            document.querySelector(".ve-edit-toolbar") !== null ??
            false
        );
        params.set(isVE ? "veaction" : "action", "edit");

        return `${mw.config.get("wgScript")}?${new URLSearchParams([...params]).toString()}`;
    };

    // [4] DOM operations.
    const initializeButton = () => {
        try {
            const $editSection = $(".mw-editsection:first,.mw-editsection-last:first");
            if ($editSection.length === 0) {
                throw new Error("No editable section found.");
            }

            const $button = $editSection.clone()
                .removeAttr("id")
                .find("[id]").removeAttr("id").end()
                .addClass("cloned-top-edit-button")
                .attr("aria-label", getLocalizedText(mw.config.get("wgUserLanguage")));

            $button.find("a")
                .attr({
                    href: buildEditUrl(),
                    title: getLocalizedText(mw.config.get("wgUserLanguage"))
                })
                .text(getLocalizedText(mw.config.get("wgUserLanguage")));

            const $heading = $([
                "#firstHeading",
                ".mw-first-heading",
                ".page-heading",
                ".firstHeading",
                "#section_0 h1"
            ].join(",")).first();

            if ($heading.length) {
                $heading.append(
                    $("<span>").addClass("mw-editsection").append($button)
                );
                mw.hook("wikipage.editform").fire($button);
            } else {
                throw new Error("No suitable heading found.");
            }
        } catch (e) {
            console.error("EditTopButton failed:", e);
            mw.track("gadget.edittop.error", e.message);
        }
    };

    // [5] Execution flow.
    if (document.readyState === "complete") {
        initializeButton();
    } else {
        $(document).one("ready mw.loader.ready", initializeButton);
    }
})(jQuery, mw);