打开/关闭菜单
打开/关闭外观设置菜单
打开/关闭个人菜单
未登录
未登录用户的IP地址会在进行任意编辑后公开展示。

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

MediaWiki界面页面
 
(未显示同一用户的16个中间版本)
第1行: 第1行:
_addText="原作者[[zhmoe:u:BearBin|BearBin]]\n{{hide|标题=BSD 3-Clause License|内容=BSD 3-Clause License\n\nCopyright (c) 2023, BearBin\n\nRedistribution and use in source and binary forms, with or without<br>modification, are permitted provided that the following conditions are met:\n\n#Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n#Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE US OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.}}";
// 原作者萌娘百科BearBin
//遵循BSD 3-Clause License使用代码
//全文请参见上方文档
//GitHub仓库地址:https://github.com/BearBin1215/MoegirlPedia
(function() {
(function() {
     "use strict";
     "use strict";
     mw.hook("wikipage.content").add(() => {
     $(function() {
         console.log("ShowContributors.js 开始执行", {
         (function() {
            mediaWikiVersion: mw.config.get("wgVersion"),
             if (
            skin: mw.config.get("skin"),
                ![0, 2, 4, 10, 12, 14, 828, 274].includes(mw.config.get("wgNamespaceNumber")) ||
            namespace: mw.config.get("wgNamespaceNumber"),
                0 === mw.config.get("wgArticleId") ||
            action: mw.config.get("wgAction"),
                !["view", "history"].includes(mw.config.get("wgAction"))
             articleId: mw.config.get("wgArticleId")
             )
        });
                return;
 
        if (
            ![0, 2, 4, 10, 12, 14, 828, 274].includes(mw.config.get("wgNamespaceNumber")) ||
            0 === mw.config.get("wgArticleId") ||
            !["view", "history"].includes(mw.config.get("wgAction"))
        ) {
             console.log("脚本因条件不满足退出");
            return;
        }


        mw.loader.addStyleTag(`
             mw.loader.using([
            #show-contributor-button {
                "mediawiki.api",
                float: right;
                "mediawiki.notification",
                margin-left: .5em;
                "oojs-ui",
                margin-right: 0;
                "oojs-ui.styles.icons-interactions",
            }
                "jquery.tablesorter"
            #show-contributor-header {
            ]).then(function() {
                background: #fff;
                function ShowContributorDialog(config) {
                border-bottom: 1px solid #aaa;
                    OO.ui.Dialog.call(this, config);
                font-weight: 600;
                padding: .3em;
                position: sticky;
                text-align: center;
                top: 0;
            }
            #show-contributor-headline {
                font-size: 1.3em;
            }
            #show-contributor-close {
                border-radius: 50%;
                cursor: pointer;
                position: absolute;
                right: 5px;
                top: 5px;
            }
             #show-contributor-close:hover {
                background-color: #eee;
            }
            #show-contributor-table {
                margin: 0;
                width: 100%;
            }
            #show-contributor-table .user-avatar {
                border-radius: 50%;
                height: 20px;
                width: 20px;
            }
            .skin-citizen #show-contributor-button {
                float: none;
                margin: 0 0.5em 0 0;
                display: inline-flex;
                align-items: center;
                vertical-align: middle;
            }
            @media (min-width: 1120px) {
                .skin-citizen .citizen-page-header-inner {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
                .skin-citizen .citizen-page-heading {
                    flex-grow: 1;
                }
            }
            @media (max-width: 1119px) {
                .skin-citizen #show-contributor-button {
                    margin: 0.5em 0;
                    display: block;
                }
            }
        `);
 
        mw.loader.using([
            "mediawiki.api",
            "mediawiki.notification",
            "oojs-ui",
            "oojs-ui.styles.icons-interactions",
            "jquery.tablesorter"
        ]).then(() => {
            console.log("依赖模块加载成功");
 
            class ShowContributorDialog extends OO.ui.Dialog {
                constructor(config) {
                    super(config);
                     this.$table = $('<table id="show-contributor-table" class="wikitable" />');
                     this.$table = $('<table id="show-contributor-table" class="wikitable" />');
                     this.$tbody = $("<tbody />");
                     this.$tbody = $("<tbody />");
                     this.got = false;
                     this.got = false;
                 }
                 }
                 static name = "ShowContributor";
                 OO.inheritClass(ShowContributorDialog, OO.ui.Dialog);
                 static tagName = "div";
                ShowContributorDialog.static = ShowContributorDialog.static || {};
                ShowContributorDialog.static.name = "ShowContributor";
                 ShowContributorDialog.static.tagName = "div";


                 initialize() {
                 ShowContributorDialog.prototype.initialize = function() {
                     super.initialize();
                     OO.ui.Dialog.prototype.initialize.call(this);
                     this.$body.append(
                     this.$body.append(
                         $('<div id="show-contributor-header" />').append(
                         $('<div id="show-contributor-header" />').append(
                             $('<div id="show-contributor-headline">本页贡献统计</div>'),
                             $('<div id="show-contributor-headline">本页贡献统计</div>'),
                             new OO.ui.IconWidget({ icon: "close", id: "show-contributor-close" }).$element.on("click", () => this.close())
                             new OO.ui.IconWidget({icon:"close",id:"show-contributor-close"}).$element.on("click", function() {
                                this.close();
                            }.bind(this))
                         ),
                         ),
                         this.$table.append(
                         this.$table.append(
第113行: 第49行:
                     );
                     );
                     return this;
                     return this;
                 }
                 };


                 getContributors = async () => {
                 ShowContributorDialog.prototype.getContributors = function() {
                     console.log("开始获取贡献者数据");
                    var self = this;
                    const api = new mw.Api();
                     return new Promise(function(resolve, reject) {
                    const contributors = {};
                        var api = new mw.Api();
                    let continueToken = "";
                        var contributors = {};
                    let prevSize = 0;
                        var continueToken = "";
                    const params = {
                        var prevSize = 0;
                        action: "query",
                        var params = {
                        format: "json",
                            action: "query",
                        prop: "revisions",
                            format: "json",
                        titles: mw.config.get("wgPageName"),
                            prop: "revisions",
                        rvprop: "user|size",
                            titles: mw.config.get("wgPageName"),
                        rvlimit: "max",
                            rvprop: "user|size",
                        rvdir: "newer"
                            rvlimit: "max",
                    };
                            rvdir: "newer"
                    do {
                        };
                        if (continueToken) params.rvcontinue = continueToken;
                        function fetchRevisions() {
                        try {
                            if (continueToken) params.rvcontinue = continueToken;
                             const response = await api.get(params);
                             api.get(params).then(function(response) {
                            continueToken = response.continue?.rvcontinue;
                                continueToken = response.continue ? response.continue.rvcontinue : undefined;
                            for (const { user, size } of Object.values(response.query.pages)[0].revisions) {
                                var revisions = Object.values(response.query.pages)[0].revisions;
                                contributors[user] = contributors[user] || [];
                                for (var i = 0; i < revisions.length; i++) {
                                contributors[user].push(size - prevSize);
                                    var user = revisions[i].user;
                                prevSize = size;
                                    var size = revisions[i].size;
                            }
                                    contributors[user] = contributors[user] || [];
                        } catch (error) {
                                    contributors[user].push(size - prevSize);
                             console.error("API 请求失败:", error);
                                    prevSize = size;
                            mw.notify(`获取编辑记录失败:${error}`, { type: "error" });
                                }
                                if (continueToken) {
                                    fetchRevisions();
                                } else {
                                    resolve(contributors);
                                }
                             }).catch(function(error) {
                                mw.notify('获取编辑记录失败:' + error, { type: "error" });
                                reject(error);
                            });
                         }
                         }
                    } while (continueToken);
                        fetchRevisions();
                     console.log("贡献者数据:", contributors);
                     });
                    return contributors;
                 };
                 };


                 addRow = (tbody, { user, count, add, remove }) => {
                 ShowContributorDialog.prototype.addRow = function(tbody, data) {
                    var user = data.user;
                    var count = data.count;
                    var add = data.add;
                    var remove = data.remove;
                     tbody.append(
                     tbody.append(
                         $("<tr />").append(
                         $("<tr />").append(
第162行: 第110行:
                 };
                 };


                 showContributors = (contributors) => {
                 ShowContributorDialog.prototype.showContributors = function(contributors) {
                     this.$tbody.empty();
                     this.$tbody.empty();
                     for (const user in contributors) {
                     for (var user in contributors) {
                         this.addRow(this.$tbody, {
                         if (contributors.hasOwnProperty(user)) {
                             user,
                             var edits = contributors[user];
                            count: contributors[user].length,
                             var add = edits.reduce(function(sum, delta) {
                             add: contributors[user].reduce((s, n) => n > 0 ? s + n : s, 0),
                                return delta > 0 ? sum + delta : sum;
                             remove: contributors[user].reduce((s, n) => n < 0 ? s + n : s, 0)
                            }, 0);
                        });
                             var remove = edits.reduce(function(sum, delta) {
                                return delta < 0 ? sum + delta : sum;
                            }, 0);
                            this.addRow(this.$tbody, {
                                user: user,
                                count: edits.length,
                                add: add,
                                remove: remove
                            });
                        }
                     }
                     }
                     this.got = true;
                     this.got = true;
                 };
                 };
            }


            const windowManager = new OO.ui.WindowManager({ id: "show-contributor" });
                var windowManager = new OO.ui.WindowManager({id:"show-contributor"});
            $(document.body).append(windowManager.$element);
                $(document.body).append(windowManager.$element);
            const dialog = new ShowContributorDialog({ size: "large" });
                var dialog = new ShowContributorDialog({size:"large"});
            windowManager.addWindows([dialog]);
                windowManager.addWindows([dialog]);


            const button = new OO.ui.ButtonWidget({
                var button = new OO.ui.ButtonWidget({
                label: "本页贡献者",
                    label:"本页贡献者",
                icon: "search",
                    icon:"search",
                flags: "progressive",
                    flags:"progressive",
                id: " postcode://show-contributor-button"
                    id:"show-contributor-button"
            });
                });


            const insertButton = () => {
                var insertButton = function() {
                $("#show-contributor-button").detach();
                    $("#show-contributor-button").detach();
                const skin = mw.config.get("skin");
                    var skin = mw.config.get("skin");
                console.log("插入按钮,当前皮肤:", skin);
                    if (skin === "citizen") {
                if (skin === "citizen") {
                        if (window.innerWidth >= 1120) {
                    if (window.innerWidth >= 1120) {
                        if ($(".page-actions").length) {
                             $(".page-actions").prepend(button.$element);
                             $(".page-actions").prepend(button.$element);
                         } else {
                         } else {
                            console.error("未找到 .page-actions 容器");
                        }
                    } else {
                        if ($(".firstHeading-container").length) {
                             $(".firstHeading-container").append(button.$element);
                             $(".firstHeading-container").append(button.$element);
                        } else {
                            console.error("未找到 .firstHeading-container 容器");
                         }
                         }
                     }
                     } else if (skin === "vector-2022") {
                } else if (skin === "vector-2022") {
                    if ($("header.mw-body-header.vector-page-titlebar").length) {
                         $("header.mw-body-header.vector-page-titlebar").append(button.$element);
                         $("header.mw-body-header.vector-page-titlebar").append(button.$element);
                     } else {
                     } else {
                        console.error("未找到 header.mw-body-header.vector-page-titlebar 容器");
                    }
                } else {
                    if ($("#bodyContent").length) {
                         $("#bodyContent").prepend(button.$element);
                         $("#bodyContent").prepend(button.$element);
                    } else {
                        console.error("未找到 #bodyContent 容器");
                     }
                     }
                 }
                 };
                console.log("按钮是否存在:", $("#show-contributor-button").length);
            };


            insertButton();
                // 初始插入
                insertButton();


            let isWide = window.innerWidth >= 1120;
                // 仅在断点穿越时更新插入位置
            $(window).on("resize", () => {
                var isWide = window.innerWidth >= 1120;
                clearTimeout(window.__showContributorResizeTimer);
                $(window).on("resize", function() {
                window.__showContributorResizeTimer = setTimeout(() => {
                    clearTimeout(window.__showContributorResizeTimer);
                    const nowWide = window.innerWidth >= 1120;
                    window.__showContributorResizeTimer = setTimeout(function() {
                    if (nowWide !== isWide && mw.config.get("skin") === "citizen") {
                        var nowWide = window.innerWidth >= 1120;
                        isWide = nowWide;
                        if (nowWide !== isWide) {
                        insertButton();
                            isWide = nowWide;
                    }
                            insertButton();
                }, 200);
                        }
            });
                    }, 200);
                });


            button.on("click", async () => {
                // 点击事件
                console.log("按钮点击,尝试打开窗口");
                button.on("click", function() {
                if (!dialog.got) {
                    (function() {
                    button.setLabel("正在查询");
                        if (!dialog.got) {
                    const contributors = await dialog.getContributors();
                            button.setLabel("正在查询");
                    dialog.showContributors(contributors);
                            dialog.getContributors().then(function(contributors) {
                    dialog.$table.tablesorter();
                                dialog.showContributors(contributors);
                    button.setLabel("本页贡献者");
                                dialog.$table.tablesorter();
                }
                                button.setLabel("本页贡献者");
                windowManager.openWindow(dialog);
                                windowManager.openWindow(dialog);
                console.log("窗口打开状态:", windowManager);
                            }).catch(function(error) {
                                console.error('获取贡献者数据失败:', error);
                                button.setLabel("本页贡献者");
                            });
                        } else {
                            windowManager.openWindow(dialog);
                        }
                    })();
                });
             });
             });
         }).catch(err => {
         })();
            console.error("模块加载失败:", err);
        });
     });
     });
})();
})();

2025年6月17日 (二) 23:31的最新版本

_addText="原作者[[zhmoe:u:BearBin|BearBin]]\n{{hide|标题=BSD 3-Clause License|内容=BSD 3-Clause License\n\nCopyright (c) 2023, BearBin\n\nRedistribution and use in source and binary forms, with or without<br>modification, are permitted provided that the following conditions are met:\n\n#Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n#Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE US OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.}}";

// 原作者萌娘百科BearBin
//遵循BSD 3-Clause License使用代码
//全文请参见上方文档
//GitHub仓库地址:https://github.com/BearBin1215/MoegirlPedia
(function() {
    "use strict";
    $(function() {
        (function() {
            if (
                ![0, 2, 4, 10, 12, 14, 828, 274].includes(mw.config.get("wgNamespaceNumber")) ||
                0 === mw.config.get("wgArticleId") ||
                !["view", "history"].includes(mw.config.get("wgAction"))
            )
                return;

            mw.loader.using([
                "mediawiki.api",
                "mediawiki.notification",
                "oojs-ui",
                "oojs-ui.styles.icons-interactions",
                "jquery.tablesorter"
            ]).then(function() {
                function ShowContributorDialog(config) {
                    OO.ui.Dialog.call(this, config);
                    this.$table = $('<table id="show-contributor-table" class="wikitable" />');
                    this.$tbody = $("<tbody />");
                    this.got = false;
                }
                OO.inheritClass(ShowContributorDialog, OO.ui.Dialog);
                ShowContributorDialog.static = ShowContributorDialog.static || {};
                ShowContributorDialog.static.name = "ShowContributor";
                ShowContributorDialog.static.tagName = "div";

                ShowContributorDialog.prototype.initialize = function() {
                    OO.ui.Dialog.prototype.initialize.call(this);
                    this.$body.append(
                        $('<div id="show-contributor-header" />').append(
                            $('<div id="show-contributor-headline">本页贡献统计</div>'),
                            new OO.ui.IconWidget({icon:"close",id:"show-contributor-close"}).$element.on("click", function() {
                                this.close();
                            }.bind(this))
                        ),
                        this.$table.append(
                            $("<thead><th>用户</th><th>编辑数</th><th>增加字节数</th><th>删减字节数</th></thead>"),
                            this.$tbody
                        )
                    );
                    return this;
                };

                ShowContributorDialog.prototype.getContributors = function() {
                    var self = this;
                    return new Promise(function(resolve, reject) {
                        var api = new mw.Api();
                        var contributors = {};
                        var continueToken = "";
                        var prevSize = 0;
                        var params = {
                            action: "query",
                            format: "json",
                            prop: "revisions",
                            titles: mw.config.get("wgPageName"),
                            rvprop: "user|size",
                            rvlimit: "max",
                            rvdir: "newer"
                        };
                        function fetchRevisions() {
                            if (continueToken) params.rvcontinue = continueToken;
                            api.get(params).then(function(response) {
                                continueToken = response.continue ? response.continue.rvcontinue : undefined;
                                var revisions = Object.values(response.query.pages)[0].revisions;
                                for (var i = 0; i < revisions.length; i++) {
                                    var user = revisions[i].user;
                                    var size = revisions[i].size;
                                    contributors[user] = contributors[user] || [];
                                    contributors[user].push(size - prevSize);
                                    prevSize = size;
                                }
                                if (continueToken) {
                                    fetchRevisions();
                                } else {
                                    resolve(contributors);
                                }
                            }).catch(function(error) {
                                mw.notify('获取编辑记录失败:' + error, { type: "error" });
                                reject(error);
                            });
                        }
                        fetchRevisions();
                    });
                };

                ShowContributorDialog.prototype.addRow = function(tbody, data) {
                    var user = data.user;
                    var count = data.count;
                    var add = data.add;
                    var remove = data.remove;
                    tbody.append(
                        $("<tr />").append(
                            $("<td />").append(
                                $(`<a href="${mw.config.get("wgArticlePath").replace("$1", `User:${user}`)}" />`).text(user)
                            ),
                            `<td>${count}</td>`,
                            `<td>${add}</td>`,
                            `<td>${remove}</td>`
                        )
                    );
                };

                ShowContributorDialog.prototype.showContributors = function(contributors) {
                    this.$tbody.empty();
                    for (var user in contributors) {
                        if (contributors.hasOwnProperty(user)) {
                            var edits = contributors[user];
                            var add = edits.reduce(function(sum, delta) {
                                return delta > 0 ? sum + delta : sum;
                            }, 0);
                            var remove = edits.reduce(function(sum, delta) {
                                return delta < 0 ? sum + delta : sum;
                            }, 0);
                            this.addRow(this.$tbody, {
                                user: user,
                                count: edits.length,
                                add: add,
                                remove: remove
                            });
                        }
                    }
                    this.got = true;
                };

                var windowManager = new OO.ui.WindowManager({id:"show-contributor"});
                $(document.body).append(windowManager.$element);
                var dialog = new ShowContributorDialog({size:"large"});
                windowManager.addWindows([dialog]);

                var button = new OO.ui.ButtonWidget({
                    label:"本页贡献者",
                    icon:"search",
                    flags:"progressive",
                    id:"show-contributor-button"
                });

                var insertButton = function() {
                    $("#show-contributor-button").detach();
                    var skin = mw.config.get("skin");
                    if (skin === "citizen") {
                        if (window.innerWidth >= 1120) {
                            $(".page-actions").prepend(button.$element);
                        } else {
                            $(".firstHeading-container").append(button.$element);
                        }
                    } else if (skin === "vector-2022") {
                        $("header.mw-body-header.vector-page-titlebar").append(button.$element);
                    } else {
                        $("#bodyContent").prepend(button.$element);
                    }
                };

                // 初始插入
                insertButton();

                // 仅在断点穿越时更新插入位置
                var isWide = window.innerWidth >= 1120;
                $(window).on("resize", function() {
                    clearTimeout(window.__showContributorResizeTimer);
                    window.__showContributorResizeTimer = setTimeout(function() {
                        var nowWide = window.innerWidth >= 1120;
                        if (nowWide !== isWide) {
                            isWide = nowWide;
                            insertButton();
                        }
                    }, 200);
                });

                // 点击事件
                button.on("click", function() {
                    (function() {
                        if (!dialog.got) {
                            button.setLabel("正在查询");
                            dialog.getContributors().then(function(contributors) {
                                dialog.showContributors(contributors);
                                dialog.$table.tablesorter();
                                button.setLabel("本页贡献者");
                                windowManager.openWindow(dialog);
                            }).catch(function(error) {
                                console.error('获取贡献者数据失败:', error);
                                button.setLabel("本页贡献者");
                            });
                        } else {
                            windowManager.openWindow(dialog);
                        }
                    })();
                });
            });
        })();
    });
})();