MediaWiki:Gadget-interfaceVariantConverter.js
外观
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
- Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
- Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
/**
* -------------------------------------------------------------------------
* !!! DON'T MODIFY THIS PAGE MANUALLY, YOUR CHANGES WILL BE OVERWRITTEN !!!
* -------------------------------------------------------------------------
*/
var _addText = '{{GHIACode|page=GHIA:MoegirlPediaInterfaceCodes/blob/master/src/gadgets/interfaceVariantConverter/Gadget-interfaceVariantConverter.js|user=[[U:星海子]]|co-authors=|longId=a157f65a20db84d70f63275717dff38cbffb9db9|shortId=a157f65a|summary=chore}}';
/* <pre> */
// WARNING: This script would break if source wikitext contains <pre> tags, won't fix.
// <pre>
"use strict";
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _assert_this_initialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _call_super(_this, derived, args) {
derived = _get_prototype_of(derived);
return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function get(target, property, receiver) {
var base = _super_prop_base(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver || target);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function _get_prototype_of(o) {
_get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _get_prototype_of(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _set_prototype_of(subClass, superClass);
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _possible_constructor_return(self, call) {
if (call && (_type_of(call) === "object" || typeof call === "function")) {
return call;
}
return _assert_this_initialized(self);
}
function _set_prototype_of(o, p) {
_set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _set_prototype_of(o, p);
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _super_prop_base(object, property) {
while(!Object.prototype.hasOwnProperty.call(object, property)){
object = _get_prototype_of(object);
if (object === null) break;
}
return object;
}
function _to_array(arr) {
return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _is_native_reflect_construct() {
try {
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
} catch (_) {}
return (_is_native_reflect_construct = function() {
return !!result;
})();
}
function _ts_generator(thisArg, body) {
var f, y, t, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["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
};
}
}
function _ts_values(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.");
}
// TODO: Fix MultilineTextInput initial height
// Test: https://zh.moegirl.org.cn/index.php?oldid=5572397
// declare var lrAivc: {
// [key: string]: any;
// };
// declare var OpenCC: any;
// declare var InPageEdit: {
// [key: string]: any;
// };
$(function() {
return function() {
return _async_to_generator(function() {
var pagename, username, pageid, basepage, api, zhAPI, lrAivc, prepopContent, _tmp, e, toParams, variantPage, REGEXP, escapeWikitext, restoreWikitext, _OO_ui_ProcessDialog, AIVCWindow, $body, windowManager, aivcDialog;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
pagename = mw.config.get("wgPageName");
username = mw.config.get("wgUserName");
// await mw.loader.using(["mediawiki.api", "oojs-ui"]);
pageid = mw.config.get("wgArticleId");
basepage = pagename.replace(/\/.*?$/, "");
api = new mw.Api(), zhAPI = /m?zh\.moegirl\.org\.cn/.test(location.hostname) ? api : new mw.ForeignApi("https://mzh.moegirl.org.cn/api.php", {
anonymous: true
});
lrAivc = $.extend({
main: [
"zh-cn",
"zh-tw",
"zh-hk"
],
dependent: {
"(main)": "zh-cn",
"zh-hans": "zh-cn",
"zh-hant": "zh-tw"
},
noteTA: {
G1: "MediaWiki"
},
autoPopulate: true,
useOpenCC: true,
manualAction: {
"zh-hk": function(t) {
return t.replaceAll("户", "戶");
},
"zh-tw": function(t) {
return t.replaceAll("名稱空間", "命名空間").replaceAll("記憶體", "內存");
}
},
watchlist: "nochange"
}, window.lr_aivc);
prepopContent = "";
_state.label = 1;
case 1:
_state.trys.push([
1,
5,
,
6
]);
if (!lrAivc.autoPopulate) return [
3,
3
];
return [
4,
api.get({
action: "parse",
assertuser: username,
pageid: pageid,
prop: "wikitext"
})
];
case 2:
_tmp = _state.sent().parse.wikitext["*"];
return [
3,
4
];
case 3:
_tmp = "";
_state.label = 4;
case 4:
prepopContent = _tmp;
return [
3,
6
];
case 5:
e = _state.sent();
return [
3,
6
];
case 6:
toParams = function(obj) {
return Object.entries(obj).map(function(param) {
var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
return "".concat(k, "=").concat(v);
}).join("|");
};
variantPage = function(variant) {
return variant === "(main)" ? "".concat(basepage) : "".concat(basepage, "/").concat(variant);
};
REGEXP = {
// [\s\S] works with new lines (avoids using dotall flag)
lcMarker: /-{([\s\S]*?)}-/g,
lcMarkerEsc: /-\\{([\s\S]*?)}\\-/g,
nowiki: /<nowiki>([\s\S]*?)<\/nowiki>/g,
link: /\[\[([\s\S]*?)(?:#([\s\S]*?))?(\|[\s\S]*?)?\]\]/g,
extLink: /([^[])\[([^[]+?)( [\s\S]+?)?\]([^\]])/g,
// extLink: /(?<!\[)\[([^[]+?)( [\s\S]+?)?\](?!\])/g,
template: /\{\{([\s\S]*?)\}\}/g,
htmlEntity: /&([a-zA-Z0-9#]+);/g,
noOCC: /<!--noOCC-->([\s\S]*?)<!--\/noOCC-->/gi
};
escapeWikitext = function(original) {
var nowikis = [], mappings = [];
var replaced = original;
// Preserve all LC markers (including those within nowiki)
replaced = replaced.replace(REGEXP.lcMarker, function(_, content) {
return "-\\{".concat(content, "}\\-");
});
// Temporarily strip nowiki
replaced = replaced.replace(REGEXP.nowiki, function(_, content) {
return "<nowiki>".concat(nowikis.push(content) - 1, "</nowiki>");
});
// Replace link targets and anchors with IDs
replaced = replaced.replace(REGEXP.link, function(match, target, anchor, text) {
return anchor || text ? "[[".concat(text ? mappings.push(target) - 1 : target).concat(anchor ? "#".concat(mappings.push(anchor) - 1) : "").concat(text || "", "]]") : match;
});
// Replace external link targets with IDs
replaced = replaced.replace(REGEXP.extLink, function(_, before, target, text, after) {
return "".concat(before, "[").concat(mappings.push(target) - 1).concat(text || "", "]").concat(after);
});
// replaced = replaced.replace(REGEXP.extLink, (_, target, text) => `[${mappings.push(target) - 1}${text || ""}]`);
// Replace template names and parameters with IDs
replaced = replaced.replace(REGEXP.template, function(_, params) {
var paramList = params.split("|");
mappings.push(paramList[0]);
paramList.shift();
return "".concat(paramList.reduce(function(acc, param) {
var _param_split = _to_array(param.split("=")), first = _param_split[0], rest = _param_split.slice(1);
// If rest is not empty, it's a named parameter; otherwise, it's a positional parameter
return rest.length ? "".concat(acc, "|").concat(mappings.push(first) - 1, "=").concat(rest.join("=")) : "".concat(acc, "|").concat(param);
}, "{{".concat(mappings.length - 1)), "}}");
});
// Replace LC markers with IDs
replaced = replaced.replace(REGEXP.lcMarkerEsc, function(_, content) {
return "-\\{".concat(mappings.push(content || "") - 1, "}\\-");
});
// Replace HTML entities with IDs
replaced = replaced.replace(REGEXP.htmlEntity, function(_, entity) {
return "&".concat(mappings.push(entity) - 1, ";");
});
// Restore nowiki
replaced = replaced.replace(REGEXP.nowiki, function(_, index) {
return "<nowiki><nowiki>".concat(nowikis[index], "</nowiki></nowiki>");
});
return {
replaced: replaced,
mappings: mappings
};
};
restoreWikitext = function(original, mappings) {
var nowikis = [];
var replaced = original;
// Temporarily strip nowiki
replaced = replaced.replace(REGEXP.nowiki, function(_, content) {
return "<nowiki>".concat(nowikis.push(content) - 1, "</nowiki>");
});
// Restore HTML entities
replaced = replaced.replace(REGEXP.htmlEntity, function(_, index) {
return "&".concat(mappings[index], ";");
});
// Restore template names and parameters
replaced = replaced.replace(REGEXP.template, function(_, params) {
var paramList = params.split("|");
var name = mappings[paramList[0]];
paramList.shift();
return "".concat(paramList.reduce(function(acc, param) {
var _param_split = _to_array(param.split("=")), first = _param_split[0], rest = _param_split.slice(1);
// If rest is not empty, it's a named parameter; otherwise, it's a positional parameter
return rest.length ? "".concat(acc, "|").concat(mappings[first], "=").concat(rest.join("=")) : "".concat(acc, "|").concat(param);
}, "{{".concat(name)), "}}");
});
// Restore external link targets
replaced = replaced.replace(REGEXP.extLink, function(_, before, target, text, after) {
return "".concat(before, "[").concat(mappings[target]).concat(text || "", "]").concat(after);
});
// replaced = replaced.replace(REGEXP.extLink, (_, target, text) => `[${mappings[target]}${text || ""}]`);
// Restore link targets
replaced = replaced.replace(REGEXP.link, function(match, target, anchor, text) {
return anchor || text ? "[[".concat(text ? mappings[target] : target).concat(mappings[anchor] ? "#".concat(mappings[anchor]) : "").concat(text || "", "]]") : match;
});
// Restore nowiki
replaced = replaced.replace(REGEXP.nowiki, function(_, index) {
return "<nowiki>".concat(nowikis[index], "</nowiki>");
});
// Restore all LC markers (including those within nowiki)
replaced = replaced.replace(REGEXP.lcMarkerEsc, function(_, index) {
var _mappings_index;
return "-{".concat((_mappings_index = mappings[index]) !== null && _mappings_index !== void 0 ? _mappings_index : index, "}-");
});
return replaced;
};
AIVCWindow = /*#__PURE__*/ function(_superClass) {
_inherits(AIVCWindow, _superClass);
function AIVCWindow(config) {
_class_call_check(this, AIVCWindow);
var _this;
// Parent constructor
_this = _call_super(this, AIVCWindow, [
config
]);
_this.config = config.data.config;
_this.prepopContent = config.data.prepopContent;
return _this;
}
_create_class(AIVCWindow, [
{
key: "initialize",
value: function initialize() {
// Parent method
_get(_get_prototype_of(AIVCWindow.prototype), "initialize", this).call(this);
this.configPanel = new OO.ui.PanelLayout({
scrollable: false,
expanded: false,
padded: true
});
this.confirmPanel = new OO.ui.PanelLayout({
scrollable: false,
expanded: false,
padded: true
});
this.ogText = new OO.ui.MultilineTextInputWidget({
value: this.prepopContent,
autosize: true
});
var textField = new OO.ui.FieldLayout(this.ogText, {
label: wgULS("原始内容", "原始內容"),
align: "top"
});
this.mainVariants = new OO.ui.TextInputWidget({
value: this.config.main.join(";")
});
var mainField = new OO.ui.FieldLayout(this.mainVariants, {
label: wgULS("主要变体", "主要變体"),
align: "top"
});
this.depVariants = new OO.ui.TextInputWidget({
value: Object.entries(this.config.dependent).map(function(param) {
var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
return "".concat(k, ":").concat(v);
}).join(";")
});
var depField = new OO.ui.FieldLayout(this.depVariants, {
label: wgULS("依赖变体", "依賴變体"),
align: "top"
});
this.noteTAParams = new OO.ui.TextInputWidget({
value: toParams(this.config.noteTA)
});
var noteTAField = new OO.ui.FieldLayout(this.noteTAParams, {
label: wgULS("NoteTA参数", "NoteTA參數"),
align: "top"
});
this.occCheckbox = new OO.ui.CheckboxInputWidget({
selected: this.config.useOpenCC
});
var occField = new OO.ui.FieldLayout(this.occCheckbox, {
label: "使用OpenCC",
align: "inline"
});
this.configPanel.$element.append(textField.$element, mainField.$element, depField.$element, noteTAField.$element, occField.$element);
this.stackLayout = new OO.ui.StackLayout({
items: [
this.configPanel,
this.confirmPanel
]
});
this.ogText.connect(this, {
resize: "updateSize"
});
this.$body.append(this.stackLayout.$element);
}
},
{
key: "getBodyHeight",
value: function getBodyHeight() {
return this.stackLayout.getCurrentItem().$element.outerHeight(true);
}
},
{
key: "getSetupProcess",
value: function getSetupProcess(data) {
var _this = this;
return _get(_get_prototype_of(AIVCWindow.prototype), "getSetupProcess", this).call(this, data).next(function() {
_this.actions.setMode("config");
_this.stackLayout.setItem(_this.configPanel);
}, this);
}
},
{
key: "getReadyProcess",
value: function getReadyProcess(data) {
var _this = this;
return _get(_get_prototype_of(AIVCWindow.prototype), "getReadyProcess", this).call(this, data).next(function() {
_this.ogText.focus();
}, this);
}
},
{
key: "getActionProcess",
value: function getActionProcess(action) {
var _this = this;
if (action === "cancel") {
return new OO.ui.Process(function() {
_this.close({
action: action
});
}, this);
} else if (action === "continue") {
return new OO.ui.Process($.when(function() {
return _async_to_generator(function() {
var _this, e;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_this = this;
this.config = $.extend(this.config, {
main: this.mainVariants.getValue().split(";"),
dependent: Object.fromEntries(this.depVariants.getValue().split(";").map(function(v) {
return v.split(":");
})),
noteTAStr: this.noteTAParams.getValue(),
useOpenCC: this.occCheckbox.isSelected(),
dependentInv: {}
});
if (this.config.main.includes("(main)")) {
throw new OO.ui.Error(wgULS("主页面不得作为主要变体", "主頁面不得作為主要變体"));
}
this.config.main.forEach(function(v) {
return _this.config.dependentInv[v] = [
v
];
});
try {
Object.entries(this.config.dependent).forEach(function(param) {
var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
return _this.config.dependentInv[v /* as string */ ].push(k);
});
} catch (e) {
console.error("[VariantConverter] Error: Key not found in dependentInv. Config dump:", this.config);
throw new OO.ui.Error(wgULS("依赖变体格式错误,请检查控制台", "依賴變体格式錯誤,請檢查控制臺"));
}
this.textInputs = {};
this.confirmPanel.$element.empty();
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
return [
4,
this.getVariants(this.ogText.getValue())
];
case 2:
_state.sent();
this.actions.setMode("confirm");
this.stackLayout.setItem(this.confirmPanel);
this.updateSize();
return [
3,
4
];
case 3:
e = _state.sent();
console.error("[VariantConverter] Error:", e);
throw new OO.ui.Error(e);
case 4:
return [
2
];
}
});
}).call(_this);
}()).promise(), this);
} else if (action === "back") {
this.actions.setMode("config");
this.stackLayout.setItem(this.configPanel);
this.updateSize();
} else if (action === "submit") {
return new OO.ui.Process($.when(function() {
return _async_to_generator(function() {
var e;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_state.trys.push([
0,
2,
,
3
]);
return [
4,
this.saveChanges()
];
case 1:
_state.sent();
this.close({
action: action
});
mw.notify("保存成功!", {
title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
type: "success",
tag: "lr-aivc"
});
setTimeout(function() {
return location.reload();
}, 730);
return [
3,
3
];
case 2:
e = _state.sent();
console.error("[VariantConverter] Error:", e);
throw new OO.ui.Error(e);
case 3:
return [
2
];
}
});
}).call(_this);
}()).promise(), this);
}
// Fallback to parent handler
return _get(_get_prototype_of(AIVCWindow.prototype), "getActionProcess", this).call(this, action);
}
},
{
key: "addVariant",
value: function addVariant(variant, text) {
var _this = this;
var _window_InPageEdit, _window;
this.textInputs[variant] = new OO.ui.MultilineTextInputWidget({
value: text,
autosize: true
});
var field = new OO.ui.FieldLayout(this.textInputs[variant], {
label: variant,
align: "top"
});
this.textInputs[variant].connect(this, {
resize: "updateSize"
});
this.confirmPanel.$element.append(field.$element);
if ((_window = window) === null || _window === void 0 ? void 0 : (_window_InPageEdit = _window.InPageEdit) === null || _window_InPageEdit === void 0 ? void 0 : _window_InPageEdit.quickDiff) {
this.confirmPanel.$element.append(new OO.ui.FieldLayout(new OO.ui.Widget({
content: [
new OO.ui.HorizontalLayout({
items: this.config.dependentInv[variant].map(function(v) {
return new OO.ui.ButtonWidget({
label: "".concat(wgULS("对比", "對比")).concat(v === "(main)" ? wgULS("主页面", "主頁面") : v)
}).on("click", function() {
return window.InPageEdit.quickDiff({
fromtitle: variantPage(v),
totext: _this.textInputs[variant].getValue(),
pageName: variantPage(v),
isPreview: true
});
});
})
})
]
})).$element);
}
}
},
{
key: "getVariants",
value: function getVariants(original) {
return _async_to_generator(function() {
var _escapeWikitext, replaced, mappings, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _this, _loop, _iterator, _step, err;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
this.confirmPanel.$element.append("<p>".concat(wgULS("请确认以下转换是否正确", "請確認以下轉換是否正確"), ":</p>"));
if (!(!window.OpenCC && this.config.useOpenCC)) return [
3,
2
];
// Load in order to prevent reference error
return [
4,
libCachedCode.injectCachedCode("https://npm.elemecdn.com/opencc-js@latest", "script")
];
case 1:
_state.sent();
_state.label = 2;
case 2:
_escapeWikitext = escapeWikitext(original), replaced = _escapeWikitext.replaced, mappings = _escapeWikitext.mappings;
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_state.label = 3;
case 3:
_state.trys.push([
3,
8,
9,
10
]);
_loop = function() {
var variant, _this_config_manualAction_variant, _this_config_manualAction, text, parsed, _, converted, occMappings, occVariant, converter, final, restored;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
variant = _step.value;
if (variant === "(main)") {
return [
2,
"continue"
];
}
text = "{{NoteTA|".concat(_this.config.noteTAStr, '}}<pre id="converted">-{}-').concat(replaced, "</pre>");
_ = $.parseHTML;
return [
4,
zhAPI.post({
action: "parse",
assertuser: username,
text: text,
contentmodel: "wikitext",
prop: "text",
uselang: variant,
disablelimitreport: true,
pst: true
})
];
case 1:
parsed = $.apply(void 0, [
_.apply($, [
_state.sent().parse.text["*"]
])
]);
converted = parsed.find("#converted").text();
if (_this.config.useOpenCC) {
occMappings = [];
converted = converted.replace(REGEXP.noOCC, function(_, content) {
return "<!--noOCC-->".concat(occMappings.push(content) - 1, "<!--/noOCC-->");
});
occVariant = variant.replace("hans", "cn").replace(/zh-(?:han)?/, "").replace("tw", "twp");
converter = OpenCC.Converter({
from: occVariant,
to: occVariant
});
converted = converter(converted);
converted = converted.replace(REGEXP.noOCC, function(_, index) {
return "<!--noOCC-->".concat(occMappings[index], "<!--/noOCC-->");
});
}
final = ((_this_config_manualAction_variant = (_this_config_manualAction = _this.config.manualAction)[variant]) === null || _this_config_manualAction_variant === void 0 ? void 0 : _this_config_manualAction_variant.call(_this_config_manualAction, converted)) || converted;
restored = restoreWikitext(final, mappings);
_this.addVariant(variant, restored);
return [
2
];
}
});
};
_iterator = this.config.main[Symbol.iterator]();
_state.label = 4;
case 4:
if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
3,
7
];
_this = this;
return [
5,
_ts_values(_loop())
];
case 5:
_state.sent();
_state.label = 6;
case 6:
_iteratorNormalCompletion = true;
return [
3,
4
];
case 7:
return [
3,
10
];
case 8:
err = _state.sent();
_didIteratorError = true;
_iteratorError = err;
return [
3,
10
];
case 9:
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
return [
7
];
case 10:
return [
2
];
}
});
}).call(this);
}
},
{
key: "saveChanges",
value: function saveChanges() {
return _async_to_generator(function() {
var _this, _, _tmp;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_this = this;
// Occasionally edits are not saved - keep this log until the bug is identified
_ = console.log;
_tmp = [
"[VariantConverter] Saved changes"
];
return [
4,
Promise.allSettled(this.config.main.map(function(variant) {
var text = _this.textInputs[variant].getValue();
return api.postWithToken("csrf", {
action: "edit",
assertuser: username,
title: variantPage(variant),
text: text,
summary: "自动转换自[[".concat(pagename, "]]"),
tags: "VariantConverter|Automation tool",
watchlist: _this.config.watchlist
});
}).concat(Object.entries(this.config.dependent).map(function(param) {
var _param = _sliced_to_array(param, 2), variant = _param[0], parent = _param[1];
var text = _this.textInputs[parent /* as string */ ].getValue();
return api.postWithToken("csrf", {
action: "edit",
assertuser: username,
title: variantPage(variant),
text: text,
summary: "自动转换自[[".concat(pagename, "]](同步").concat(parent, ")"),
tags: "VariantConverter|Automation tool",
watchlist: _this.config.watchlist
});
})))
];
case 1:
_.apply(console, _tmp.concat([
_state.sent()
]));
return [
2
];
}
});
}).call(this);
}
}
]);
return AIVCWindow;
}(_OO_ui_ProcessDialog = OO.ui.ProcessDialog);
_define_property(AIVCWindow, "static", _object_spread_props(_object_spread({}, _get(_get_prototype_of(AIVCWindow), "static", AIVCWindow)), {
tagName: "div",
name: "lr-aivc",
title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
actions: [
{
action: "cancel",
label: "取消",
flags: [
"safe",
"close",
"destructive"
],
modes: "config"
},
{
action: "continue",
label: wgULS("继续", "繼續"),
flags: [
"primary",
"progressive"
],
modes: "config"
},
{
action: "back",
label: "返回",
flags: [
"safe",
"back"
],
modes: "confirm"
},
{
action: "submit",
label: wgULS("确认", "確認"),
flags: [
"primary",
"progressive"
],
modes: "confirm"
}
]
}));
$body = $(document.body);
windowManager = new OO.ui.WindowManager();
$body.append(windowManager.$element);
aivcDialog = new AIVCWindow({
size: "large",
data: {
config: lrAivc,
prepopContent: prepopContent
}
});
windowManager.addWindows([
aivcDialog
]);
$(mw.util.addPortletLink("p-cactions", "#", wgULS("自动繁简转换", "自動繁簡轉換"), "ca-VariantConverter", wgULS("自动同步界面消息的繁简版本", "自動同步介面消息的繁簡版本"))).on("click", function(e) {
e.preventDefault();
$("#mw-notification-area").appendTo($body);
windowManager.openWindow(aivcDialog);
});
return [
2
];
}
});
})();
}();
}); // </pre>
/* </pre> */