MediaWiki:Gadget-registerToDelete.js

From Moegirlpedia
Revision as of 00:44, 10 June 2022 by AnnAngela (talk | contribs)
Jump to: navigation, search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
// <pre>
// From [[Special:固定链接/5030142]]
// eslint-disable-next-line no-redeclare
/* global $, OO, mw, wgULS */
// await mw.loader.using(["oojs-ui", "ext.gadget.LocalObjectStorage"]);
"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 __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 (_) 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 __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));
};
$(function () { return (function () { return __awaiter(void 0, void 0, void 0, function () {
    var $body_1, FFDWindow, storage_1, localCache, windowManager_1, ffdDialog_1, e_1, parseError;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _b.trys.push([0, 2, , 3]);
                if ($(".noarticletext")[0] || $(".will2Be2Deleted")[0] || !mw.config.get("wgUserGroups").includes("patroller") && !(new URL(location.href).searchParams.get("AnnTools-debug") || "").split("|").includes("registerToDelete")) {
                    return [2 /*return*/];
                }
                $body_1 = $("body");
                $("#mw-notification-area").appendTo($body_1);
                FFDWindow = /** @class */ (function (_super) {
                    __extends(FFDWindow, _super);
                    function FFDWindow(config) {
                        var _this = 
                        // Parent constructor
                        _super.call(this, config) || this;
                        _this.storage = config.data.storage;
                        _this.localCache = config.data.localCache;
                        return _this;
                    }
                    FFDWindow.prototype.initialize = function () {
                        // Parent method
                        _super.prototype.initialize.call(this);
                        this.panelLayout = new OO.ui.PanelLayout({
                            scrollable: false,
                            expanded: false,
                            padded: true
                        });
                        this.reasonsDropdown = new OO.ui.DropdownInputWidget({
                            options: __spreadArray([{
                                    data: "",
                                    label: "Other (Please explain your reason manually)"
                                }], this.localCache, true)
                        });
                        this.detailsText = new OO.ui.TextInputWidget();
                        this.dbCheckbox = new OO.ui.CheckboxInputWidget();
                        this.enterCheckbox = new OO.ui.CheckboxInputWidget({
                            selected: this.storage.getItem("enterToSubmit")
                        });
                        this.reasonsDropdownMenu = this.reasonsDropdown.dropdownWidget.getMenu();
                        var reasonsField = new OO.ui.FieldLayout(this.reasonsDropdown, {
                            label: "Reason",
                            align: "top"
                        });
                        var detailsField = new OO.ui.FieldLayout(this.detailsText, {
                            label: "Detail",
                            align: "top"
                        });
                        var dbField = new OO.ui.FieldLayout(this.dbCheckbox, {
                            label: "The action is related to an application from discussion board",
                            align: "inline"
                        });
                        var enterField = new OO.ui.FieldLayout(this.enterCheckbox, {
                            label: "Press \"Enter\" key in the detail input to submit directly (configuration per browser)",
                            align: "inline"
                        });
                        this.panelLayout.$element.append(reasonsField.$element, detailsField.$element, dbField.$element, enterField.$element);
                        this.reasonsDropdownMenu.connect(this, { toggle: "dropdownToggle" });
                        this.detailsText.connect(this, { enter: "onEnter" });
                        this.enterCheckbox.connect(this, { change: "setStorage" });
                        this.$body.append(this.panelLayout.$element);
                    };
                    FFDWindow.prototype.setStorage = function (selected) {
                        this.storage.setItem("enterToSubmit", selected);
                    };
                    FFDWindow.prototype.onEnter = function () {
                        if (this.enterCheckbox.isSelected()) {
                            this.executeAction("submit");
                        }
                    };
                    FFDWindow.prototype.dropdownToggle = function (visible) {
                        var _this = this;
                        if (visible) {
                            // Manually resize
                            // TODO: make this animated
                            var newHeight_1 = parseFloat(this.$frame.css("height")) + 300;
                            this.withoutSizeTransitions(function () {
                                _this.$frame.css("height", newHeight_1);
                                _this.reasonsDropdownMenu.clip();
                            });
                        }
                        else {
                            this.updateSize();
                        }
                    };
                    FFDWindow.prototype.getBodyHeight = function () {
                        return this.panelLayout.$element.outerHeight(true);
                    };
                    FFDWindow.prototype.getReadyProcess = function (data) {
                        var _this = this;
                        return _super.prototype.getReadyProcess.call(this, data)
                            .next(function () {
                            _this.reasonsDropdown.focus();
                        }, this);
                    };
                    FFDWindow.prototype.getActionProcess = function (action) {
                        var _this = this;
                        var dfd = $.Deferred();
                        if (action === "cancel") {
                            return new OO.ui.Process(function () {
                                _this.close({ action: action });
                            }, this);
                        }
                        else if (action === "submit") {
                            return new OO.ui.Process(function () {
                                _this.reason = _this.reasonsDropdown.getValue();
                                _this.detail = _this.detailsText.getValue();
                                if (!_this.reason && !_this.detail) {
                                    dfd.reject(new OO.ui.Error("The detail input should not be empty."));
                                    return dfd.promise();
                                }
                                // if (reason) {
                                //     reason += detail ? (reason ? ":" : "") + detail : "";
                                // } else {
                                //     reason = detail;
                                // }
                                // if (isDB.isSelected()) {
                                //     reason = `讨论版申请:${reason}`;
                                // }
                                _this.reason = "".concat(_this.dbCheckbox.isSelected() ? "Application from discussion board" : "").concat(_this.reason ? "".concat(_this.reason).concat(_this.detail ? "\uFF1A".concat(_this.detail) : "") : _this.detail); // 压行
                                _this.flagTemplate().then(function () {
                                    _this.close({ action: action });
                                    mw.notify("Refresh soon...", {
                                        title: "Action succeeded",
                                        type: "success",
                                        tag: "lr-ffd"
                                    });
                                    dfd.resolve();
                                    setTimeout(function () { return location.reload(); }, 730);
                                })["catch"](function (e) {
                                    console.error("[FlagForDeletion] Error:", e);
                                    dfd.reject(new OO.ui.Error(e));
                                });
                                return dfd.promise();
                            }, this);
                        }
                        // Fallback to parent handler
                        return _super.prototype.getActionProcess.call(this, action);
                    };
                    FFDWindow.prototype.flagTemplate = function () {
                        return __awaiter(this, void 0, void 0, function () {
                            var api, template, d;
                            return __generator(this, function (_b) {
                                switch (_b.label) {
                                    case 0:
                                        api = new mw.Api();
                                        template = /^en/.test(location.hostname) ? "Awaiting_deletion" : "即将删除";
                                        return [4 /*yield*/, api.postWithToken("csrf", {
                                                action: "edit",
                                                format: "json",
                                                title: mw.config.get("wgPageName"),
                                                text: "<noinclude>{{".concat(template, "|1=").concat(this.reason, "|user=").concat(mw.config.get("wgUserName"), "}}</noinclude>"),
                                                summary: "\u6302\u5220\uFF1A".concat(this.reason),
                                                nocreate: true,
                                                watchlist: "nochange",
                                                tags: "Automation tool"
                                            })];
                                    case 1:
                                        d = _b.sent();
                                        if (d.error) {
                                            throw d.error.code;
                                        }
                                        return [2 /*return*/];
                                }
                            });
                        });
                    };
                    FFDWindow.static = $.extend(Object.create(_super.static), {
                        name: "lr-ffd",
                        title: "Register To Delete",
                        actions: [
                            {
                                action: "cancel",
                                label: "Cancel",
                                flags: ["safe", "close", "destructive"]
                            },
                            {
                                action: "submit",
                                label: "Confirm",
                                flags: ["primary", "progressive"]
                            },
                        ]
                    });
                    return FFDWindow;
                }(OO.ui.ProcessDialog));
                storage_1 = new LocalObjectStorage("AnnTools-registerToDelete");
                return [4 /*yield*/, new Promise(function (resolve) {
                        var cache = storage_1.getItem("deletereason-cache");
                        if (Array.isArray(cache)) {
                            resolve(cache);
                            return;
                        }
                        if (storage_1.getItem("deletereason-fetching")) {
                            var c_1 = setInterval(function () {
                                if (!storage_1.getItem("deletereason-fetching")) {
                                    clearInterval(c_1);
                                    resolve(storage_1.getItem("deletereason-cache"));
                                }
                            });
                            return;
                        }
                        storage_1.setItem("deletereason-fetching", true);
                        $.get("".concat(mw.config.get("wgServer") + mw.config.get("wgScriptPath"), "/MediaWiki:Deletereason-dropdown?action=raw"), function (reasons) {
                            var cache = [];
                            reasons.split(/\n+/).forEach(function (reason) {
                                if (reason.length === 0 || !reason.startsWith("*")) {
                                    return;
                                }
                                if (/^\*[^*]/.test(reason)) {
                                    cache.push({
                                        optgroup: reason.slice(1).trim()
                                    });
                                }
                                else if (/^\*\*[^*]/.test(reason)) {
                                    cache.push({
                                        data: reason.slice(2).trim(),
                                        label: reason.slice(2).trim()
                                    });
                                }
                            });
                            storage_1.setItem("deletereason-cache", cache);
                            storage_1.setItem("deletereason-fetching", false);
                            resolve(cache);
                        });
                    })];
            case 1:
                localCache = _b.sent();
                windowManager_1 = new OO.ui.WindowManager();
                $body_1.append(windowManager_1.$element);
                ffdDialog_1 = new FFDWindow({
                    size: "medium",
                    data: { storage: storage_1, localCache: localCache }
                });
                windowManager_1.addWindows([ffdDialog_1]);
                $(mw.util.addPortletLink("p-cactions", "#", "Register To Delete", "ca-lr-ffd", "".concat("Register To Delete this page", "[alt-shift-d]")), "d").on("click", function (e) {
                    e.preventDefault();
                    windowManager_1.openWindow(ffdDialog_1);
                    $body_1.css("overflow", "auto");
                });
                return [3 /*break*/, 3];
            case 2:
                e_1 = _b.sent();
                parseError = function (errLike, space) {
                    if (space === void 0) {
                        space = 4;
                    }
                    return JSON.stringify(errLike, function (_, v) {
                        if (v instanceof Error) {
                            var stack = [];
                            if (v.stack) {
                                stack.push.apply(stack, v.stack.split("\n").map(function (n) { return n.trim(); }).filter(function (n) { var _a; return ((_a = n === null || n === void 0 ? void 0 : n.length) !== null && _a !== void 0 ? _a : -1) > 0; }));
                            }
                            var keys = Object.keys(v).filter(function (key) { return !(key in Error.prototype); });
                            if (keys.length) {
                                stack.push(JSON.stringify(Object.fromEntries(keys.map(function (key) { return [key, v[key]]; })), null, space));
                            }
                            return stack.join("\n").trim() || "";
                        }
                        return v;
                    }, space).replace(/^"(.*)"$/, "$1");
                };
                oouiDialog.alert("Error: <br>" + oouiDialog.sanitize(parseError(e_1)), {
                    title: "Error occured"
                });
                console.error("[FlagForDeletion] Setup error:", e_1);
                return [3 /*break*/, 3];
            case 3: return [2 /*return*/];
        }
    });
}); })(); });
// </pre>