MCBBS Wiki欢迎您共同参与编辑!在参与编辑之前请先阅读Wiki方针

如果在编辑的过程中遇到了什么问题,可以去讨论板提问。

为了您能够无阻碍地参与编辑 未验证/绑定过邮箱的用户,请尽快绑定/验证

MCBBS Wiki GitHub群组已上线!

您可以在回声洞中发表吐槽!

服务器状态监控。点击进入

本站由MCBBS用户自行搭建,与MCBBS及东银河系漫游指南(北京)科技有限公司没有从属关系。点此了解 MCBBS Wiki 不是什么>>

用户:坑触可/js/quickSave.js

来自MCBBS Wiki
跳到导航 跳到搜索

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer或Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:Ctrl-F5
// From MoegirlPedia. MediaWiki:Gadget-quickSave.js

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
$(function () {
    var e_1, _a;
    var wgUserGroups = mw.config.get("wgUserGroups");
    if (!/^讨论:讨论板\/[^存]+$/.test(mw.config.get("wgPageName"))) {
        return;
    }
    if (!wgUserGroups.includes("sysop") && !wgUserGroups.includes("patroller")) {
        return;
    }
    var $body = $("body");
    $("#mw-notification-area").appendTo($body);
    var api = new mw.Api();
    var Log = (function () {
        function Log() {
            this.$element = $("<li>");
            this.$content = $("<div>").addClass("AnnTools_log").appendTo(this.$element);
            this.$message = $("<div>").addClass("AnnTools_log_message").appendTo(this.$content);
            this.$status = $("<div>").addClass("AnnTools_log_status").appendTo(this.$content);
        }
        Log.prototype.appendMessage = function (str) {
            this.$message.append($("<span>").text(str));
        };
        Log.prototype.setStatus = function (status) {
            if (!status) {
                this.$content.removeClass("AnnTools_log-success AnnTools_log-failed");
                this.$status.empty();
            }
            else if (status === "success") {
                this.$content.removeClass("AnnTools_log-failed");
                this.$content.addClass("AnnTools_log-success");
                this.$status.text(Log.statusTexts.SUCCESS);
            }
            else if (status === "failed") {
                this.$content.removeClass("AnnTools_log-success");
                this.$content.addClass("AnnTools_log-failed");
                this.$status.text(Log.statusTexts.FAILED);
            }
        };
        Log.statusTexts = {
            SUCCESS: "成功",
            FAILED: "失败"
        };
        return Log;
    }());
    var Progress = (function () {
        function Progress(steps, dialog) {
            this.progressBarWidget = new OO.ui.ProgressBarWidget({
                progress: 0
            });
            this.progressLogWidget = new OO.ui.Widget();
            this.$progressLogList = $("<ol>");
            this.currentStep = 0;
            this.steps = steps;
            this.dialog = dialog;
            this.progressLogWidget.$element.append(this.$progressLogList);
            this.generateNewLogLine();
        }
        Progress.prototype.cleanUp = function () {
            this.currentStep = 0;
            this.progressBarWidget.setProgress(0);
            this.$progressLogList.empty();
            this.generateNewLogLine();
        };
        Progress.prototype.generateNewLogLine = function () {
            this.logLine = new Log();
            this.$progressLogList.append(this.logLine.$element);
        };
        Progress.prototype.log = function (message) {
            this.logLine.appendMessage(message);
        };
        Progress.prototype.error = function (message) {
            this.logLine.appendMessage(message);
            this.logLine.setStatus("failed");
        };
        Progress.prototype.nextStep = function (newLogLine) {
            if (newLogLine === void 0) { newLogLine = true; }
            this.logLine.setStatus("success");
            this.currentStep++;
            this.progressBarWidget.setProgress(100 * this.currentStep / this.steps);
            if (newLogLine) {
                this.generateNewLogLine();
                this.dialog.delayUpdateSize();
            }
        };
        Progress.prototype.finish = function () {
            this.currentStep = this.steps - 1;
            this.nextStep(false);
        };
        return Progress;
    }());
    var QSWindow = (function (_super) {
        __extends(QSWindow, _super);
        function QSWindow(config) {
            var _this = _super.call(this, config) || this;
            _this.template = "../";
            _this.date = new Date();
            _this.savePageTitle = "".concat(mw.config.get("wgPageName"), "/\u5B58\u6863/").concat(_this.date.getFullYear(), "\u5E74").concat(_this.date.getMonth() < 9 ? "0".concat(_this.date.getMonth() + 1) : _this.date.getMonth() + 1, "\u6708");
            _this.panelLayout = new OO.ui.PanelLayout({
                scrollable: false,
                expanded: false,
                padded: true
            });
            _this.sectionTitleWidget = new OO.ui.Widget({
                classes: ["AnnTools_paragraphs"]
            });
            _this.progress = new Progress(6, _this);
            _this.progressBarFieldLayout = new OO.ui.FieldLayout(_this.progress.progressBarWidget, {
                label: QSWindow.bolbLabel("执行进度"),
                align: "top"
            });
            _this.progressLogFieldLayout = new OO.ui.FieldLayout(_this.progress.progressLogWidget, {
                align: "top"
            });
            _this.hideProgress();
            return _this;
        }
        Object.defineProperty(QSWindow.prototype, "sectionTitle", {
            get: function () {
                return this.sectionTitleWidget.getData();
            },
            enumerable: false,
            configurable: true
        });
        QSWindow.prototype.initialize = function () {
            var _a;
            _super.prototype.initialize.call(this);
            (_a = this.panelLayout.$element).append.apply(_a, __spreadArray([], __read([
                [this.sectionTitleWidget, "段落标题:"],
            ].map(function (_a) {
                var _b = __read(_a, 2), fieldWidget = _b[0], labelText = _b[1];
                return new OO.ui.FieldLayout(fieldWidget, {
                    label: QSWindow.bolbLabel(labelText),
                    align: "top"
                }).$element;
            })), false));
            this.panelLayout.$element.append(this.progressBarFieldLayout.$element, this.progressLogFieldLayout.$element);
            this.$body.append(this.panelLayout.$element);
        };
        QSWindow.prototype.getBodyHeight = function () {
            return this.panelLayout.$element.outerHeight(true);
        };
        QSWindow.prototype.getActionProcess = function (action) {
            var _this = this;
            if (action === "cancel") {
                return new OO.ui.Process(function () { return _this.close({ action: action }).closed.promise(); }).next(function () {
                    _this.hideProgress();
                });
            }
            if (action === "submit") {
                return new OO.ui.Process($.when((function () { return __awaiter(_this, void 0, void 0, function () {
                    var toclist, _a, _b, section, e_2;
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                this.showProgress();
                                this.progress.log("开始检测段落标题……");
                                _b = (_a = Object).fromEntries;
                                return [4, api.post({
                                        action: "parse",
                                        format: "json",
                                        pageid: mw.config.get("wgArticleId"),
                                        prop: "sections"
                                    })];
                            case 1:
                                toclist = _b.apply(_a, [(_c.sent()).parse.sections.map(function (_a) {
                                        var anchor = _a.anchor, index = _a.index;
                                        return [anchor, index];
                                    })]);
                                if (!Reflect.has(toclist, this.sectionTitle)) {
                                    throw new OO.ui.Error("小工具无法根据段落标题找到该段落,请移除该段落标题内的模板后再行操作……", {
                                        recoverable: false
                                    });
                                }
                                section = toclist[this.sectionTitle];
                                _c.label = 2;
                            case 2:
                                _c.trys.push([2, 4, , 5]);
                                return [4, this.quickSave({ section: section })];
                            case 3:
                                _c.sent();
                                mw.notify("即将刷新……", {
                                    title: "存档成功",
                                    type: "success",
                                    tag: "AnnTools_QuickSave"
                                });
                                setTimeout(function () { return location.reload(); }, 730);
                                return [3, 5];
                            case 4:
                                e_2 = _c.sent();
                                console.error("[QuickSave] Error:", e_2);
                                throw new OO.ui.Error(e_2);
                            case 5: return [2];
                        }
                    });
                }); })()).promise(), this);
            }
            return _super.prototype.getActionProcess.call(this, action);
        };
        QSWindow.prototype.quickSave = function (_a) {
            var section = _a.section;
            return __awaiter(this, void 0, void 0, function () {
                var sectionContent, sectionTitleRaw, sectionTitleSafe, listResult;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            this.progress.log("标题存在!");
                            this.progress.nextStep();
                            this.progress.log("正在获取段落内容……");
                            return [4, $.ajax({
                                    url: "".concat(mw.config.get("wgServer")).concat(mw.config.get("wgScriptPath"), "/index.php"),
                                    data: {
                                        title: mw.config.get("wgPageName"),
                                        action: "raw",
                                        section: section
                                    }
                                })];
                        case 1:
                            sectionContent = _b.sent();
                            sectionTitleRaw = sectionContent.match(/==(.*)==/);
                            if (sectionTitleRaw && sectionTitleRaw[1]) {
                                sectionTitleRaw = sectionTitleRaw[1];
                            }
                            else {
                                sectionTitleRaw = this.sectionTitle;
                            }
                            this.progress.nextStep();
                            this.progress.log("正在存档该段落内容……");
                            return [4, api.postWithToken("csrf", {
                                    action: "edit",
                                    format: "json",
                                    title: this.savePageTitle,
                                    text: sectionContent.replace("==".concat(sectionTitleRaw, "=="), "").trim(),
                                    section: "new",
//                                    tags: "快速存档讨论串|Automation tool",
                                    sectiontitle: sectionTitleRaw,
                                    summary: "\u5FEB\u901F\u5B58\u6863\u8BA8\u8BBA\u4E32\uFF1A/* ".concat(this.sectionTitle, " */")
                                })];
                        case 2:
                            _b.sent();
                            this.progress.nextStep();
                            this.progress.log("正在标记该段落为已存档……");
                            sectionTitleSafe = this.sectionTitle;
                            if (/_\d+$/.test(this.sectionTitle) && document.getElementById(this.sectionTitle.replace(/_\d+$/, ""))) {
                                sectionTitleSafe = sectionTitleSafe.replace(/_\d+$/, "");
                            }
                            return [4, api.postWithToken("csrf", {
                                    action: "edit",
                                    format: "json",
                                    title: mw.config.get("wgPageName"),
                                    summary: "\u5FEB\u901F\u5B58\u6863\u8BA8\u8BBA\u4E32\uFF1A/* ".concat(this.sectionTitle, " */"),
                                    text: "==".concat(sectionTitleRaw, "==\n{{Saved|link=").concat(this.savePageTitle, "|title=").concat(sectionTitleSafe.replace(/\|/g, "{{!}}"), "}}"),
                                    section: section,
//                                    tags: "快速存档讨论串|Automation tool"
                                })];
                        case 3:
                            _b.sent();
                            this.progress.nextStep();
                            this.progress.log("正在检查存档页面是否带有档案馆模板……");
                            return [4, api.post({
                                    action: "query",
                                    format: "json",
                                    prop: "templates",
                                    titles: this.savePageTitle,
                                    tltemplates: "../"
                                })];
                        case 4:
                            listResult = _b.sent();
                            if (Array.isArray(Object.values(listResult.query.pages)[0].templates) && Object.values(listResult.query.pages)[0].templates.length > 0) {
                                this.progress.log("模板存在!");
                                this.progress.finish();
                                return [2];
                            }
                            this.progress.nextStep();
                            this.progress.log("正在向存档页添加档案馆模板……");
                            return [4, api.postWithToken("csrf", {
                                    action: "edit",
                                    format: "json",
                                    title: this.savePageTitle,
                                    prependtext: "{{".concat(this.template, "}}\n"),
//                                    tags: "快速存档讨论串|Automation tool",
                                    summary: "添加档案馆模板"
                                })];
                        case 5:
                            _b.sent();
                            this.progress.finish();
                            return [2];
                    }
                });
            });
        };
        QSWindow.prototype.setSectionTitle = function (sectionTitle) {
            this.sectionTitleWidget.setData(sectionTitle);
            this.sectionTitleWidget.$element.text(sectionTitle);
        };
        QSWindow.prototype.hideProgress = function () {
            this.progressBarFieldLayout.$element.hide();
            this.progressLogFieldLayout.$element.hide();
            this.progress.cleanUp();
        };
        QSWindow.prototype.showProgress = function () {
            this.progressBarFieldLayout.$element.show();
            this.progressLogFieldLayout.$element.show();
            this.delayUpdateSize();
        };
        QSWindow.prototype.delayUpdateSize = function () {
            var _this = this;
            this.updateSize();
            setTimeout(function () {
                _this.updateSize();
            }, 500);
        };
        QSWindow.static = __assign(__assign({}, _super.static), { tagName: "div", name: "AnnTools_QuickSave", title: "公共讨论页段落存档工具", actions: [
                {
                    action: "cancel",
                    label: "取消",
                    flags: ["safe", "close", "destructive"]
                },
                {
                    action: "submit",
                    label: "确认",
                    flags: ["primary", "progressive"]
                },
            ] });
        QSWindow.bolbLabel = function (text) { return $("<span>").addClass("AnnTools_bolb").text(text); };
        return QSWindow;
    }(OO.ui.ProcessDialog));
    var windowManager = new OO.ui.WindowManager();
    $body.append(windowManager.$element);
    var qsDialog = new QSWindow();
    windowManager.addWindows([qsDialog]);
    var _loop_1 = function (ele) {
        var self_1 = $(ele);
        var content = self_1.nextUntil("h2").not("h2");
        if (content.hasClass("saveNotice")) {
            return "continue";
        }
        var sectionTitle = self_1.find(".mw-headline").attr("id");
        var button = $("<a>");
        button.attr("href", "javascript:void(0);").prop("draggable", false).addClass("AnnTools_QuickSave").text("快速存档");
        self_1.find(".mw-editsection-bracket").first()
            .after('<span class="mw-editsection-divider"> | </span>')
            .after(button);
        button.on("click", function () {
            if (!qsDialog.isVisible()) {
                qsDialog.setSectionTitle(sectionTitle);
                windowManager.openWindow(qsDialog);
            }
            return false;
        });
        var quicksave = self_1.find(".AnnTools_QuickSave");
        if (self_1.find(".AnnTools_MarkAsResolved")[0]) {
            var divider = quicksave.next(".mw-editsection-divider");
            if (divider.length > 0) {
                self_1.find(".mw-editsection .mw-editsection-bracket").first().after(divider).after(quicksave);
            }
        }
    };
    try {
        for (var _b = __values($("#mw-content-text > .mw-parser-output > h2, #mw-content-text > .mw-parser-output > .discussionContainer > h2")), _c = _b.next(); !_c.done; _c = _b.next()) {
            var ele = _c.value;
            _loop_1(ele);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
});

/* </pre> */