Utensa:Fierodelveneto/common.js
// Copied from https://ar.wikipedia.org/wiki/ميدياويكي:Gadget-QuickEdit.js
/* global mw */
/// <reference path="../typings/jquery/jquery.d.ts"/>
/**
* Wikiplus
* Author:+Eridanus Sora/@妹空酱
* Github:https://github.com/Last-Order/Wikiplus
*/
/**
* ä¾èµ–组件:MoeNotification
* https://github.com/Last-Order/MoeNotification
*/
'use strict';
var _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function MoeNotification() {
var self = this;
this.display = function (text, type, callback) {
var _callback = callback || function () {};
var _text = text || 'å–µ~';
var _type = type || 'success';
$("#MoeNotification").append($("<div>").addClass('MoeNotification-notice').addClass('MoeNotification-notice-' + _type).append('<span>' + _text + '</span>'));
$("#MoeNotification").find('.MoeNotification-notice').last().fadeIn(300);
self.bind();
self.clear();
_callback($("#MoeNotification").find('.MoeNotification-notice').last());
};
this.create = {
success: function success(text, callback) {
var _callback = callback || function () {};
self.display(text, 'success', _callback);
},
warning: function warning(text, callback) {
var _callback = callback || function () {};
self.display(text, 'warning', _callback);
},
error: function error(text, callback) {
var _callback = callback || function () {};
self.display(text, 'error', _callback);
}
};
this.clear = function () {
if ($(".MoeNotification-notice").length >= 10) {
$("#MoeNotification").children().first().fadeOut(150, function () {
$(this).remove();
});
setTimeout(self.clear, 300);
} else {
return false;
}
};
this.empty = function (f) {
$(".MoeNotification-notice").each(function (i) {
if ($.isFunction(f)) {
var object = this;
setTimeout(function () {
f($(object));
}, 200 * i);
} else {
$(this).delay(i * 200).fadeOut('fast', function () {
$(this).remove();
});
}
});
};
this.bind = function () {
$(".MoeNotification-notice").mouseover(function () {
self.slideRight($(this));
});
};
this.slideRight = function (object, speed) {
object.css('position', 'relative');
object.animate({
right: "200%"
}, speed || 150, function () {
$(this).fadeOut('fast', function () {
$(this).remove();
});
});
};
this.init = function () {
$("body").append('<div id="MoeNotification"></div>');
};
if (!($("#MoeNotification").length > 0)) {
this.init();
}
}
$(function () {
var i18nData = {};
var scriptPath = location.protocol + '//wikiplus-app.smartgslb.com';
i18nData['en-us'] = i18nData['fr-fr'] = i18nData['ar-sa'] = i18nData['ar'] = {
"__language": "en-us",
"__author": ["Eridanus Sora", "AnnAngela", "YinYan"],
"__version": "210",
"unknown_error_name": "Eror sconosesto",
"api_unaccessiable": "API of this wiki is not available",
"api_unwriteable": "Write API of this wiki is not available",
"fail_to_get_timestamp": "Failed to get the timestamp of this page.",
"fail_to_get_edittoken": "Failed to get the EditToken of this page.",
"fail_to_get_pageinfo": "Failed to load infomation of this page",
"not_autoconfirmed_user": "You are not an autoconfiremd user",
"hit_abusefilter": "Your edit hit the abusefilter(s)",
"unknown_edit_error": "Unknown edit error",
"unknown_edit_error_message": "Unknown edit error($1)",
"notitle": "The title parameter must be set",
"notext": "The text parameter must be set",
"notoken": "The token parameter must be set",
"invalidsection": "The section parameter must be set to an integer or 'new'",
"protectedtitle": "This title has been protected from creation",
"cantcreate": "You don't have permission to create new pages",
"cantcreate_anon": "Anonymous users can't create new pages",
"articleexists": "The article you tried to create has already existed",
"noimageredirect_anon": "Anonymous users can't create image redirects",
"noimageredirect": "You don't have the permission to create image redirects",
"spamdetected": "Your edit was rejected because it contained a spam fragment",
"filtered": "The filter callback function rejected your edit",
"contenttoobig": "The content you submitted exceeds the article size limit",
"noedit_anon": "Anonymous users can't edit pages",
"noedit": "You don't have the permission to edit pages",
"pagedeleted": "The page was deleted during your edit",
"emptypage": "Creating new, empty pages is not allowed",
"emptynewsection": "Creating empty new sections is not possible.",
"editconflict": "Edit Conflict! Don't panic. Please check the difference between your content below and the existing revision, then refresh the page to make another submit",
"revwrongpage": "The revision you are editing now is not one a valid reversions of this page",
"undofailure": "Undo failed due to conflicts.",
"missingtitle": "Missing title in your edit/creation",
"mustbeposted": "The edit must be submited by POST method",
"readapidenied": "Read API Denied",
"writeapidenied": "Write API Denied",
"noapiwrite": "No available write API in this wiki",
"badtoken": "Eror inte el salvar",
"missingparam": "One of the parameters title, pageid is required",
"invalidparammix": "The parameters title, pageid can not be used together",
"invalidtitle": "Invalid page title",
"nosuchpageid": "Inexistent page ID",
"pagecannotexist": "No access to create a new page in this namespace",
"nosuchrevid": "Inexisting reversion ID",
"badmd5": "Invalid MD5",
"hookaborted": "Your edit was rejected by the hook(s)",
"parseerror": "Failed to parse the wikitext of this page",
"summaryrequired": "Somàrio dimandà",
"blocked": "You have been already BLOCKED",
"ratelimited": "You've exceeded your rate limit. Please have a tea and try again later",
"unknownerror": "Eror sconosesto",
"nosuchsection": "There is no such section",
"sectionsnotsupported": "Can't edit in this section",
"editnotsupported": "Can't edit in this section by writing section",
"appendnotsupported": "Can't append/prepend wikitext to this page",
"redirect_appendonly": "Only append/prepend can be made to this page because of the rules of the redirect page",
"badformat": "The requested serialization format can not be applied to the page's content model",
"customcssprotected": "You're not allowed to edit custom CSS pages",
"customjsprotected": "You're not allowed to edit custom JavaScript pages",
"cascadeprotected": "This page is under a cascading protection",
"network_edit_error": "Failed to edit this page because of network errors",
"redirect_to_summary": "[[$1]]",
"redirect_from_summary": "Da [[$1]] a [[$2]]",
"need_init": "WikiPlus haven't been loaded completely. It's a rare occasion so you can try to refresh and try again.",
"fail_to_get_wikitext": "Failed to load the wikitext of this page",
"quickedit_topbtn": "Cànbio ràpido",
"quickedit_sectionbtn": "cànbio ràpido",
"fail_to_init_quickedit": "Failed to initialize WikiPlus",
"back": "Indrio",
"goto_editbox": "Toła de cànbio",
"summary_placehold": "Somàrio",
"submit": "Invia",
"publish_page": "Pùblega voxe",
"publish_change": "Pùblega canbiaminti",
"preview": "Vista prèvia",
"cancel": "Descançeła",
"mark_minoredit": "Canbio picenin Par incolar: --~ ~ ~ ~ <noinclude></noinclude> <includeonly></includeonly> <sup></sup> <sub></sub> <kbd></kbd> <pre></pre> <code><nowiki></nowiki></code> {{rispondi a|}",
"onclose_confirm": "[Wikiplus] Do you really want to close this page when you are still editing it, as you will lose all your unsaved work?",
"fail_to_get_wikitext_when_edit": "Failed to load wikitext for your edit",
"cant_parse_wikitext": "Failed to parse the wikitext",
"loading_preview": "Vista prèvia",
"submitting_edit": "Drio salvar i canbiaminti",
"edit_success": "Canbi salvai in 1$ ms",
"empty_page_confirm": "The wikitext in your edit is empty, which will empty this page.\r\nPlease set the value of key \"empty\" true to allow this kind of edits. (This is a tip for developers)",
"cross_page_edit": "The content you are editing belongs to another page, please wait...",
"cross_page_edit_submit": "Salva...",
"cross_page_edit_error": "Failed to load the infomation",
"install_tip": "Do you allow WikiPlus to collect insensitive data to help us develop WikiPlus and provide feedback to current site: $1 ?",
"accept": "Aceta",
"decline": "Declinea",
"install_finish": "Fine instalamento",
"loading": "Cargamento...",
"cant_add_funcbtn": "Failed to add buttons for WikiPlus",
"wikiplus_settings": "Inpostasion cànbio ràpido",
"wikiplus_settings_desc": "Modifegar ła inpostasion in baxe ai seventi stàndar",
"wikiplus_settings_placeholder": "Your setting is empty, please modify your setting according to the documentation.",
"wikiplus_settings_grammar_error": "Eror de sintase inte el to cànbio",
"wikiplus_settings_saved": "Inpostasion realixae",
"redirect_from": "Fa rimandi verso cuà",
"redirect_desc": "Rimanda voxe verso de sta voxe",
"empty_input": "Empty input",
"redirect_saved": "Redirection is finished",
"uninited": "Wikiplus is not completely initialized, please refeash this page",
"cant_parse_i18ncache": "Failed to parse the cache of i18n file",
"cant_load_language": "Failed to load i18n file",
"history_edit_warning": " // You are trying to edit a history revision of this page. This will apply to the latest revision. Please be careful.",
"create_page_tip": "<!-- You are now creating a new page. Please delete this line and be careful. -->",
"continue": "sèvita",
"default_summary_suffix": "Cànbio faxesto co CànbioRàpido"
};
/**
* åŠ è½½å…¶ä»–è¯è¨€æ–‡ä»¶
* @param {string} language è¯è¨€å
*/
function loadLanguage(language) {
$.ajax({
url: "https://ar.wikipedia.org/w/index.php?title=MediaWiki:Gadget-QuickEdit/lang.js&action=raw&ctype=text/javascript", //scriptPath + '/languages/get.php?lang=' + language,
dataType: 'json',
success: function success(data) {
if (data.__language && data.__version) {
if (i18nData[data.__language]) {
if (data.__version >= i18nData[data.__language].__version) {
i18nData[data.__language] = data;
console.log('æ›´æ–°è¯è¨€ç‰ˆæœ¬' + data.___language + '至' + data.___version);
} else {
// æœåŠ¡ç«¯æœªè·Ÿè¿›è¯è¨€ç‰ˆæœ¬ 䏿›´æ–°æœ¬åœ°ç¼“å˜
}
} else {
i18nData[data.__language] = data;
}
localStorage.Wikiplus_i18nCache = JSON.stringify(i18nData); //更新缓å˜
}
},
error: function error(e) {
console.log('æ— æ³•åŠ è½½è¯è¨€' + language);
}
});
}
/**
* 多è¯è¨€è½¬æ¢
* @param {stirng} key å—æ®µæ ‡è¯†å
* @return {string} ç»è¿‡è½¬æ¢çš„内容 如未找到对应的多è¯è¨€å—段 åˆ™è¿”å›žç®€ä½“ä¸æ–‡
*/
function i18n(key) {
var language;
try {
language = "ar-sa" // JSON.parse(localStorage.Wikiplus_Settings)['language'] || window.navigator.language.toLowerCase();
} catch (e) {
language = window.navigator.language.toLowerCase();
}
if (i18nData[language] && i18nData[language][key]) {
return i18nData[language][key];
} else if (i18nData['en-us'][key]) {
return i18nData['en-us'][key];
} else {
return 'undefined';
}
}
/**
* 获得错误信æ¯
* @param {stirng} name
* @return {object} {number,message}
*/
function getErrorInfo(name) {
var errorList = {
unknown_error_name: {
number: 1001,
message: i18n('unknown_error_name')
},
api_unaccessiable: {
number: 1002
},
api_unwriteable: {
number: 1003
},
fail_to_get_timestamp: {
number: 1004
},
fail_to_get_edittoken: {
number: 1005
},
fail_to_get_pageinfo: {
number: 1006
},
not_autoconfirmed_user: {
number: 1007
},
hit_abusefilter: {
number: 1008
},
unknown_edit_error: {
number: 1009
},
unknown_edit_error_message: {
number: 1010
},
notitle: {
number: 1011
},
notext: {
number: 1012
},
notoken: {
number: 1013
},
invalidsection: {
number: 1014
},
protectedtitle: {
number: 1015
},
cantcreate: {
number: 1016
},
cantcreate_anon: {
number: 1017
},
articleexists: {
number: 1018
},
noimageredirect_anon: {
number: 1019
},
noimageredirect: {
number: 1020
},
spamdetected: {
number: 1021
},
filtered: {
number: 1022
},
contenttoobig: {
number: 1023
},
noedit_anon: {
number: 1025
},
noedit: {
number: 1026
},
pagedeleted: {
number: 1027
},
emptypage: {
number: 1028
},
emptynewsection: {
number: 1029
},
editconflict: {
number: 1030
},
revwrongpage: {
number: 1031
},
undofailure: {
number: 1032
},
missingtitle: {
number: 1033
},
mustbeposted: {
number: 1034
},
readapidenied: {
number: 1035
},
writeapidenied: {
number: 1036
},
noapiwrite: {
number: 1037
},
badtoken: {
number: 1038
},
missingparam: {
number: 1039
},
invalidparammix: {
number: 1040
},
invalidtitle: {
number: 1041
},
nosuchpageid: {
number: 1042
},
pagecannotexist: {
number: 1043
},
nosuchrevid: {
number: 1044
},
badmd5: {
number: 1045
},
hookaborted: {
number: 1046
},
parseerror: {
number: 1047
},
summaryrequired: {
number: 1048
},
blocked: {
number: 1049
},
ratelimited: {
number: 1050
},
unknownerror: {
number: 1051
},
nosuchsection: {
number: 1052
},
sectionsnotsupported: {
number: 1053
},
editnotsupported: {
number: 1054
},
appendnotsupported: {
number: 1055
},
redirect_appendonly: {
number: 1056
},
badformat: {
number: 1057
},
customcssprotected: {
number: 1058
},
customjsprotected: {
number: 1059
},
cascadeprotected: {
number: 1060
},
network_edit_error: {
number: 1061
},
need_init: {
number: 1062
},
fail_to_get_wikitext: {
number: 1063
},
fail_to_init_quickedit: {
number: 1064
},
fail_to_get_wikitext_when_edit: {
number: 1065
},
cant_parse_wikitext: {
number: 1066
},
empty_page_confirm: {
number: 1067
},
uninited: {
number: 1068
},
cant_parse_i18ncache: {
number: 1069
},
cant_load_language: {
number: 1070
}
};
if (errorList[name]) {
if (errorList[name].message) {
return {
number: errorList[name].number,
message: errorList[name].message
};
} else if (i18n(name) !== 'undefined') {
return {
number: errorList[name].number,
message: i18n(name)
};
} else {
return {
number: errorList[name].number,
message: i18n('unknownerror')
};
}
} else {
return {
number: errorList.unknown_error_name.number,
message: errorList.unknown_error_name.message
};
}
}
/**
* 判æ–值是å¦å˜åœ¨äºŽæ•°ç»„
* @param {string} value
* @param {array} array
* @return {boolean} whether the value is in the array
*/
function inArray(value) {
var array = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
return $.inArray(value, array) === -1 ? false : true;
}
/**
* 抛出错误
* @param {string} name
* @return boolean
*/
function throwError(name, message) {
var errInfo = getErrorInfo(name);
var e = new Error();
e.number = errInfo.number;
e.message = message || errInfo.message;
console.log('%c致命错误[' + e.number + ']:' + e.message, 'color:red');
console.log(e);
return e;
}
/**
* å°†mw的段è½çš„id转æ¢ä¸ºå¯æ˜¾ç¤ºçš„æ–‡æœ¬
* @param {string} URL
* @return string
*/
var Wikipage = (function () {
function Wikipage() {
var pageName = arguments.length <= 0 || arguments[0] === undefined ? window.mw.config.get('wgPageName') : arguments[0];
_classCallCheck(this, Wikipage);
console.log('页é¢ç±»æž„建ä¸');
//å¯ç”¨æ€§å’Œæƒé™æ£€æµ‹
if (!window.mw) {
console.log('页é¢Javascript载入ä¸å®Œå…¨æˆ–è¿™ä¸æ˜¯ä¸€ä¸ªMediawiki站点');
return;
}
if (false || false) {
throwError('api_unaccessiable');
return;
}
if (!inArray('autoconfirmed', window.mw.config.get('wgUserGroups'))) {
throwError('not_autoconfirmed_user');
return;
}
//从MediaWiki定义的全局å˜é‡ä¸èŽ·å¾—ä¿¡æ¯
this.pageName = pageName.replace(/ /ig, '_'); // Mediawiki处ç†ç©ºæ ¼æ—¶å¯èƒ½ä¼šå‡ºé”™
this.revisionId = window.mw.config.get('wgRevisionId');
this.articleId = window.mw.config.get('wgArticleId');
this.API = location.protocol + '//' + location.host + window.mw.config.get('wgScriptPath') + '/api.php';
//从API获得编辑令牌和起始时间戳
this.editToken = {};
this.timeStamp = {};
this.init(this.pageName, {
success: function success() {
console.log('WikiplusåŠ è½½å®Œæ¯•');
},
fail: function fail(e) {
console.log('Wikiplus未能æ£ç¡®åŠ è½½(' + e.message + ')');
}
});
}
/**
* é’ˆå¯¹éžæœ¬é¡µé¢çš„编辑 æä¾›é‡å®šä¹‰æ—¶é—´æˆ³å’Œæƒæ ‡æŽ¥å£
* @param {string} titile æ ‡é¢˜
* @param {object} callback 回调函数
*/
_createClass(Wikipage, [{
key: 'reConstruct',
value: function reConstruct(title) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
this.init(title, callback);
}
/**
* 获å–页é¢åŸºç¡€ä¿¡æ¯å¹¶è®°å½•
*/
}, {
key: 'init',
value: function init(title, callback, config) {
if (title === undefined) title = this.pageName;
if (callback === undefined) callback = {};
var self = this;
callback.success = callback.success || new Function();
callback.fail = callback.success || new Function();
$.ajax({
type: 'GET',
dataType: 'json',
url: this.API,
data: {
'action': 'query',
'prop': 'revisions|info',
'titles': title,
'rvprop': 'timestamp',
'format': 'json'
},
beforeSend: function beforeSend() {
console.time('الوقت ');
},
success: function success(data) {
if (data && data.query && data.query.pages) {
var info = data.query.pages;
for (var key in info) {
if (key !== '-1') {
if (info[key].revisions && info[key].revisions.length > 0) {
self.timeStamp[title] = info[key].revisions[0].timestamp;
} else {
callback.fail(throwError('fail_to_get_timestamp'));
}
if (mw.user.tokens.get('csrfToken') && mw.user.tokens.get('csrfToken') !== '+\\') {
self.editToken[title] = mw.user.tokens.get('csrfToken');
console.log('æˆåŠŸèŽ·å¾—ç¼–è¾‘ä»¤ç‰Œ æ¥è‡ªå‰ç«¯API');
} else {
//å‰ç«¯æ‹¿ä¸åˆ°Token å°è¯•通过API
$.ajax({
url: self.API,
type: "GET",
dataType: "json",
data: {
'action': 'query',
'meta': 'tokens',
'format': 'json'
},
success: function success(data) {
if (data.query && data.query.tokens && data.query.tokens.csrftoken && data.query.tokens.csrftoken !== '+\\') {
self.editToken[title] = data.query.tokens.csrftoken;
console.log('æˆåŠŸèŽ·å¾—ç¼–è¾‘ä»¤ç‰Œ 通过åŽç«¯API');
} else {
callback.fail(throwError('fail_to_get_edittoken'));
}
},
error: function error(e) {
callback.fail(throwError('fail_to_get_edittoken'));
}
});
callback.fail(throwError('fail_to_get_edittoken'));
}
} else {
if (mw.config.get('wgArticleId') === 0) {
// 如果是空页é¢å°±åªæ‹¿ä¸€ä¸ªedittoken
if (mw.user.tokens.get('csrfToken') && mw.user.tokens.get('csrfToken') !== '+\\') {
self.editToken[title] = mw.user.tokens.get('csrfToken');
console.log('æˆåŠŸèŽ·å¾—ç¼–è¾‘ä»¤ç‰Œ æ¥è‡ªå‰ç«¯API');
self.inited = true;
} else {
self.inited = false;
callback.fail(throwError('fail_to_get_edittoken'));
}
} else {
// å¦‚æžœä¸æ˜¯ 那就是失败了 抛出错误
self.inited = false;
callback.fail(throwError('fail_to_get_pageinfo'));
}
}
}
}
}
}).done(function () {
console.timeEnd('获得页é¢åŸºç¡€ä¿¡æ¯æ—¶é—´è€—æ—¶');
self.inited = self.inited === false ? false : true;
callback.success();
});
}
/**
* 页é¢ç¼–辑
* @param {string} content 页é¢å†…容
* @param {string} title 页颿 ‡é¢˜ 默认为当å‰é¡µé¢æ ‡é¢˜
* @param {object} callback 回调函数
* @param {object} config 设置 覆盖到默认的设置
*/
}, {
key: 'edit',
value: function edit(content) {
var title = arguments.length <= 1 || arguments[1] === undefined ? this.pageName : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var config = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
var self = this;
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
if (content === undefined) {
if (!config.empty === true) {
callback.fail(throwError('empty_page_confirm'));
return false;
}
}
if (self.inited) {
$.ajax({
type: 'POST',
url: self.API,
data: $.extend({
'action': 'edit',
'format': 'json',
'text': content,
'title': title,
'token': self.editToken[title] || self.editToken[self.pageName],
'basetimestamp': self.timeStamp[title]
}, config),
success: function success(data) {
if (data && data.edit) {
if (data.edit.result && data.edit.result == 'Success') {
callback.success();
} else {
if (data.edit.code) {
//防滥用过滤器
callback.fail(throwError('hit_abusefilter', i18n('hit_abusefilter') + ':' + data.edit.info.replace('/Hit AbuseFilter: /ig', '') + '<br><small>' + data.edit.warning + '</small>'));
} else {
callback.fail(throwError('unknown_edit_error'));
}
}
} else if (data && data.error && data.error.code) {
callback.fail(throwError(data.error.code.replace(/-/ig, '_')), i18n('unknown_edit_error_message').replace(/\$1/ig, data.error.code));
} else if (data.code) {
callback.fail(throwError('unknown_edit_error'), i18n('unknown_edit_error_message').replace(/\$1/ig, data.code));
} else {
callback.fail(throwError('unknown_edit_error'));
}
},
error: function error(e) {
callback.fail(throwError('network_edit_error'));
}
});
} else {
callback.fail(throwError('uninited'));
}
}
/**
* 编辑段è½
* @param {number} section 段è½ç¼–å·
* @param {string} content 内容
* @param {string} title 页颿 ‡é¢˜
* @param {object} callback 回调函数
* @param {object} config 设置
*/
}, {
key: 'editSection',
value: function editSection(section, content) {
var title = arguments.length <= 2 || arguments[2] === undefined ? this.pageName : arguments[2];
var config = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
var callback = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4];
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
this.edit(content, title, callback, $.extend({
'section': section
}, config));
}
/**
* é‡å®šå‘页é¢è‡³
* @param {string} target ç›®æ ‡é¡µé¢æ ‡é¢˜
* @param {string} title 页é¢å 默认为当å‰é¡µé¢
* @param {object} callback 回调函数
*/
}, {
key: 'redirectTo',
value: function redirectTo(target) {
var title = arguments.length <= 1 || arguments[1] === undefined ? this.pageName : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
this.edit('#RINVIA [[' + target + ']]', title, callback, {
'summary': i18n('redirect_to_summary').replace(/\$1/ig, target)
});
}
/**
* é‡å®šå‘自
* @param {string} origin é‡å®šå‘é¡µæ ‡é¢˜
* @param {string} title é‡å®šå‘ç›®æ ‡é¡µæ ‡é¢˜ 默认为当å‰é¡µ
* @param {object} callback
*/
}, {
key: 'redirectFrom',
value: function redirectFrom(origin) {
var title = arguments.length <= 1 || arguments[1] === undefined ? this.pageName : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var force = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
var data = {
summary: i18n('redirect_from_summary').replace(/\$1/ig, origin).replace(/\$2/ig, title)
};
if (!force) {
data.createonly = 'true';
}
this.edit('#RINVIA [[' + title + ']]', origin, callback, data);
}
/**
* 获得页é¢ç»´åŸºæ–‡æœ¬
* @param {object} callback 回调函数
* @param {string} title 页颿 ‡é¢˜ 默认为当å‰é¡µé¢
* @param {object} config 设置
*/
}, {
key: 'getWikiText',
value: function getWikiText() {
var callback = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var title = arguments.length <= 1 || arguments[1] === undefined ? this.pageName : arguments[1];
var config = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
$.ajax({
url: location.protocol + '//' + location.host + mw.config.get('wgScriptPath') + '/index.php',
type: "GET",
dataType: "text",
cache: false,
data: $.extend({
'title': title,
'action': 'raw'
}, config),
beforeSend: function beforeSend() {
console.time('الوقت ');
},
success: function success(data) {
console.timeEnd('نجاح ');
callback.success(data);
},
error: function error(e) {
callback.fail(throwError('fail_to_get_wikitext'));
}
});
}
/**
* è§£æžWikitext
* @param {string} wikitext 维基文本
* @param {object} callback 回调函数
* @param {object} config 设置
*/
}, {
key: 'parseWikiText',
value: function parseWikiText(wikitext, callback, config) {
if (wikitext === undefined) wikitext = '';
if (callback === undefined) callback = {};
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
$.ajax({
type: 'POST',
dataType: 'json',
data: $.extend({
'format': 'json',
'action': 'parse',
'text': wikitext,
'title': this.pageName,
'pst': 'true'
}, config),
url: this.API,
success: function success(data) {
if (data && data.parse && data.parse.text) {
callback.success(data.parse.text['*']);
} else {
callback.fail(throwError('cant_parse_wikitext'));
}
}
});
}
}]);
return Wikipage;
})();
$(document).ready(function () {
var Wikiplus = (function () {
_createClass(Wikiplus, [{
key: 'initQuickEdit',
/**
* åŠ è½½å¿«é€Ÿç¼–è¾‘ ç¬¬ä¸€æ¥ æ’入页颿Œ‰é’®å¹¶ç»‘定入å£äº‹ä»¶
*/
value: function initQuickEdit() {
var callback = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var self = this;
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
if (!(mw.config.get('wgIsArticle') && mw.config.get('wgAction') === "view" && mw.config.get('wgIsProbablyEditable'))) {
console.log('è¯¥é¡µé¢æ— 法编辑 快速编辑界é¢åŠ è½½ç»ˆæ¢');
return;
}
//顶部编辑入å£
var topBtn = $('<li>').attr('id', 'Wikiplus-Edit-TopBtn').append($('<span>').append($('<a>').attr('href', 'javascript:void(0)').text('' + i18n('quickedit_topbtn')))).data({
number: -1,
target: self.kotori.pageName
});
if ($('#ca-edit').length > 0 && $('#Wikiplus-Edit-TopBtn').length == 0) {
$('#ca-edit').before(topBtn);
}
if ($('.mw-editsection').length > 0) {
self.sectionMap = {};
//段è½å¿«é€Ÿç¼–辑按钮
var sectionBtn = $('<span>').append($('<span>').addClass('mw-editsection-divider').text(' | ')).append($('<a>').addClass('Wikiplus-Edit-SectionBtn').attr('href', 'javascript:void(0)').text(i18n('quickedit_sectionbtn')));
$('.mw-editsection').each(function (i) {
try {
var editURL = $(this).find("a").last().attr('href');
var sectionNumber = editURL.match(/&[ve]*section\=([^&]+)/)[1].replace(/T-/ig, '');
var sectionTargetName = decodeURI(editURL.match(/title=(.+?)&/)[1]);
var cloneNode = $(this).prev().clone();
cloneNode.find('.mw-headline-number').remove();
var sectionName = $.trim(cloneNode.text());
self.sectionMap[sectionNumber] = {
name: sectionName,
target: sectionTargetName
};
var _sectionBtn = sectionBtn.clone();
_sectionBtn.find('.Wikiplus-Edit-SectionBtn').data({
number: sectionNumber,
name: sectionName,
target: sectionTargetName
});
$(this).find('.mw-editsection-bracket').last().before(_sectionBtn);
} catch (e) {
throwError('fail_to_init_quickedit');
}
});
}
$('.Wikiplus-Edit-SectionBtn').click(function () {
self.initQuickEditInterface($(this)); //直接把DOMä¼ é€’ç»™ä¸‹ä¸€æ¥
});
$('#Wikiplus-Edit-TopBtn').click(function () {
self.initQuickEditInterface($(this));
});
}
/**
* åŠ è½½å¿«é€Ÿç¼–è¾‘ä¸»ç•Œé¢ç›¸å…³å†…容
*/
}, {
key: 'initQuickEditInterface',
value: function initQuickEditInterface(obj) {
var self = this;
var sectionNumber = obj.data('number');
var sectionTargetName = obj.data('target');
if (this.kotori.inited) {
if ($('.noarticletext').length > 0) {
//这是一个空页é¢
this.preloadData[sectionTargetName + '.-1'] = i18n('create_page_tip');
}
if (mw.config.get('wgCurRevisionId') === mw.config.get('wgRevisionId')) {
if (this.preloadData[sectionTargetName + '.' + sectionNumber] === undefined) {
this.notice.create.success(i18n('loading'));
this.preload(sectionNumber, sectionTargetName, {
success: function success(data) {
obj.data('content', data);
self.notice.empty();
self.displayQuickEditInterface(obj);
},
fail: function fail(e) {
throwError('fail_to_get_wikitext_when_edit');
}
});
} else {
obj.data('content', self.preloadData[sectionTargetName + '.' + sectionNumber]);
self.displayQuickEditInterface(obj);
}
} else {
this.notice.create.warning(i18n('history_edit_warning'));
this.notice.create.success(i18n('loading'));
this.preload(sectionNumber, sectionTargetName, {
success: function success(data) {
obj.data('content', data);
self.notice.empty();
self.displayQuickEditInterface(obj, '' + i18n('history_edit_warning'));
},
fail: function fail(data) {
throwError('fail_to_get_wikitext_when_edit');
}
}, {
'oldid': mw.config.get('wgRevisionId')
});
}
}
}
/**
* 显示快速编辑界é¢å¹¶ç»‘定事件
*/
}, {
key: 'displayQuickEditInterface',
value: function displayQuickEditInterface(obj) {
var message = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
var self = this;
var isNewPage = $('.noarticletext').length > 0;
var sectionNumber = obj.data('number');
var sectionName = obj.data('name');
var sectionTargetName = obj.data('target');
var sectionContent = obj.data('content');
var summary = self.getSetting('defaultSummary', {
'sectionName': sectionName,
'sectionNumber': sectionNumber,
'sectionTargetName': sectionTargetName
});
if (summary === undefined) {
if (sectionName === undefined) {
summary = i18n('default_summary_suffix');
} else {
summary = '/* ' + sectionName + ' */ ' + i18n('default_summary_suffix');
}
}
//DOM定义
var heightBefore = $(document).scrollTop(); //è®°ä½å½“å‰é«˜åº¦
var backBtn = $('<span>').attr('id', 'Wikiplus-Quickedit-Back').addClass('Wikiplus-Btn').text('' + i18n('back')); //返回按钮
var jumpBtn = $('<span>').attr('id', 'Wikiplus-Quickedit-Jump').addClass('Wikiplus-Btn').append($('<a>').attr('href', '#Wikiplus-Quickedit').text('' + i18n('goto_editbox'))); //到编辑框
var inputBox = $('<textarea>').attr('id', 'Wikiplus-Quickedit'); //主编辑框
var previewBox = $('<div>').attr('id', 'Wikiplus-Quickedit-Preview-Output'); //预览输出
var summaryBox = $('<input>').attr('id', 'Wikiplus-Quickedit-Summary-Input').attr('placeholder', '' + i18n('summary_placehold')); //编辑摘è¦è¾“å…¥
var editSubmitBtn = $('<button>').attr('id', 'Wikiplus-Quickedit-Submit').text(i18n(isNewPage ? 'publish_page' : 'publish_change') + ' - ctrl+s'); //æäº¤æŒ‰é’®
var previewSubmitBtn = $('<button>').attr('id', 'Wikiplus-Quickedit-Preview-Submit').text('' + i18n('preview')); //预览按钮
var isMinorEdit = $('<div>').append($('<input>').attr({ 'type': 'checkbox', 'id': 'Wikiplus-Quickedit-MinorEdit' })).append($('<label>').attr('for', 'Wikiplus-Quickedit-MinorEdit').text(i18n('mark_minoredit') + ' - ctrl+shift+s')).css({ 'margin': '5px', 'display': 'inline' });
//DOM定义结æŸ
var editBody = $('<div>').append(backBtn, jumpBtn, previewBox, inputBox, summaryBox, $('<br>'), editSubmitBtn, previewSubmitBtn, isMinorEdit);
this.createDialogBox('' + i18n('quickedit_topbtn') + message, editBody, 1000, function () {
$('#Wikiplus-Quickedit').text(sectionContent);
$('#Wikiplus-Quickedit-Summary-Input').val(summary);
//事件绑定
//返回
$("#Wikiplus-Quickedit-Back").click(function () {
$('.Wikiplus-InterBox').fadeOut('fast', function () {
window.onclose = window.onbeforeunload = undefined; //å–æ¶ˆé¡µé¢å…³é—确认
$(this).remove();
});
});
//预览
var onPreload = $('<div>').addClass('Wikiplus-Banner').text('' + i18n('loading_preview'));
$('#Wikiplus-Quickedit-Preview-Submit').click(function () {
var wikiText = $('#Wikiplus-Quickedit').val();
$(this).prop('disabled', true);
$('#Wikiplus-Quickedit-Preview-Output').fadeOut(100, function () {
$('#Wikiplus-Quickedit-Preview-Output').html('').append(onPreload);
$('#Wikiplus-Quickedit-Preview-Output').fadeIn(100);
});
$('html, body').animate({ scrollTop: heightBefore }, 200); //返回顶部
self.kotori.parseWikiText(wikiText, {
success: function success(data) {
$('#Wikiplus-Quickedit-Preview-Output').fadeOut('100', function () {
$('#Wikiplus-Quickedit-Preview-Output').html('<hr><div class="mw-body-content">' + data + '</div><hr>');
$('#Wikiplus-Quickedit-Preview-Output').fadeIn('100');
$('#Wikiplus-Quickedit-Preview-Submit').prop('disabled', false);
});
}
});
});
//æäº¤
$('#Wikiplus-Quickedit-Submit').click(function () {
var wikiText = $('#Wikiplus-Quickedit').val();
var summary = $('#Wikiplus-Quickedit-Summary-Input').val();
var timer = new Date().valueOf();
var onEdit = $('<div>').addClass('Wikiplus-Banner').text('' + i18n('submitting_edit'));
var addtionalConfig = {
'summary': summary
};
if (sectionNumber !== -1) {
addtionalConfig['section'] = sectionNumber;
}
if ($('#Wikiplus-Quickedit-MinorEdit').is(':checked')) {
addtionalConfig['minor'] = 'true';
} else {
addtionalConfig['notminor'] = 'true';
}
//准备编辑 ç¦ç”¨å„类按钮 返回顶部 显示信æ¯
$('#Wikiplus-Quickedit-Submit,#Wikiplus-Quickedit,#Wikiplus-Quickedit-Preview-Submit').prop('disabled', true);
$('html, body').animate({ scrollTop: heightBefore }, 200);
//开始æäº¤ç¼–辑
if (sectionTargetName === self.kotori.pageName) {
$('#Wikiplus-Quickedit-Preview-Output').fadeOut(100, function () {
$('#Wikiplus-Quickedit-Preview-Output').html('').append(onEdit);
$('#Wikiplus-Quickedit-Preview-Output').fadeIn(100);
});
self.kotori.edit(wikiText, sectionTargetName, {
success: function success() {
var useTime = new Date().valueOf() - timer;
$('#Wikiplus-Quickedit-Preview-Output').find('.Wikiplus-Banner').css('background', 'rgb(255, 255, 255)');
$('#Wikiplus-Quickedit-Preview-Output').find('.Wikiplus-Banner').text(('' + i18n('edit_success')).replace(/\$1/ig, useTime.toString()));
self.sendStatistic(sectionTargetName, useTime);
window.onclose = window.onbeforeunload = undefined; //å–æ¶ˆé¡µé¢å…³é—确认
setTimeout(function () {
location.reload();
}, 500);
},
fail: function fail(e) {
console.log(e);
$('#Wikiplus-Quickedit-Submit,#Wikiplus-Quickedit,#Wikiplus-Quickedit-Preview-Submit').prop('disabled', false);
$('.Wikiplus-Banner').css('background', 'rgba(218, 142, 167, 0.65)');
$('.Wikiplus-Banner').html(e.message);
}
}, addtionalConfig);
} else {
//ç¼–è¾‘ç›®æ ‡éžå½“å‰é¡µé¢
$('#Wikiplus-Quickedit-Preview-Output').fadeOut(100, function () {
$('#Wikiplus-Quickedit-Preview-Output').html('').append(onEdit.text(i18n('cross_page_edit')));
$('#Wikiplus-Quickedit-Preview-Output').fadeIn(100);
});
self.kotori.reConstruct(sectionTargetName, {
success: function success() {
$('.Wikiplus-Banner').text(i18n('cross_page_edit_submit'));
self.kotori.edit(wikiText, sectionTargetName, {
success: function success() {
var useTime = new Date().valueOf() - timer;
$('#Wikiplus-Quickedit-Preview-Output').find('.Wikiplus-Banner').css('background', 'rgb(255,255,255)');
$('#Wikiplus-Quickedit-Preview-Output').find('.Wikiplus-Banner').text(('' + i18n('edit_success')).replace(/\$1/ig, '' + useTime));
self.sendStatistic(sectionTargetName, useTime);
window.onclose = window.onbeforeunload = undefined; //å–æ¶ˆé¡µé¢å…³é—确认
setTimeout(function () {
location.reload();
}, 500);
},
fail: function fail(e) {
$('#Wikiplus-Quickedit-Submit,#Wikiplus-Quickedit,#Wikiplus-Quickedit-Preview-Submit').prop('disabled', false);
$('.Wikiplus-Banner').css('background', 'rgba(218, 142, 167, 0.65)');
$('.Wikiplus-Banner').text(e.message);
}
}, addtionalConfig);
},
fail: function fail(e) {
$('.Wikiplus-Banner').css('background', 'rgba(218, 142, 167, 0.65)');
$('.Wikiplus-Banner').text(i18n('cross_page_edit_error'));
}
});
}
});
//å¿«æ·é”®
//Ctrl+Sæäº¤ Ctrl+Shift+Så°ç¼–辑
$('#Wikiplus-Quickedit,#Wikiplus-Quickedit-Summary-Input,#Wikiplus-Quickedit-MinorEdit').keydown(function (e) {
if (e.ctrlKey && e.which == 83) {
if (e.shiftKey) {
$('#Wikiplus-Quickedit-MinorEdit').click();
}
$('#Wikiplus-Quickedit-Submit').click();
e.preventDefault();
e.stopPropagation();
}
});
//ç”±äºŽæ˜¯å¼‚æ¥æäº¤ Wikipluså³ä½¿ç¼–辑失败 也ä¸ä¼šä¸¢å¤±æ•°æ® 唯一丢失数æ®çš„å¯èƒ½æ€§æ˜¯æ‰‹æ»‘关了页é¢
//第一 å…³é—页é¢ç¡®è®¤
$('#Wikiplus-Quickedit').keydown(function () {
window.onclose = window.onbeforeunload = function () {
return '' + i18n('onclose_confirm');
};
});
//Esc退出
if (self.getSetting('esc_to_exit_quickedit') === 'true') {
$(document).keydown(function (e) {
if (e.which === 27) {
$("#Wikiplus-Quickedit-Back").click();
}
});
}
});
}
/**
* 编辑设置
*/
}, {
key: 'editSettings',
value: function editSettings() {
var self = this;
self.addFunctionButton(i18n('wikiplus_settings'), 'Wikiplus-Settings-Intro', function () {
var input = $('<textarea>').attr('id', 'Wikiplus-Setting-Input').attr('rows', '10');
var applyBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-Setting-Apply').text(i18n('submit'));
var cancelBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-Setting-Cancel').text(i18n('cancel'));
var content = $('<div>').append(input).append($('<hr>')).append(applyBtn).append(cancelBtn); //拼接
self.createDialogBox(i18n('wikiplus_settings_desc'), content, 600, function () {
if (localStorage.Wikiplus_Settings) {
$('#Wikiplus-Setting-Input').val(localStorage.Wikiplus_Settings);
} else {
$('#Wikiplus-Setting-Input').attr('placeholder', i18n('wikiplus_settings_placeholder'));
}
$('#Wikiplus-Setting-Apply').click(function () {
var settings = $('#Wikiplus-Setting-Input').val();
try {
settings = JSON.parse(settings);
} catch (e) {
self.notice.create.error(i18n('wikiplus_settings_grammar_error'));
return;
}
localStorage.Wikiplus_Settings = JSON.stringify(settings);
$('.Wikiplus-InterBox-Content').html('').append($('<div>').addClass('Wikiplus-Banner').text(i18n('wikiplus_settings_saved')));
$('.Wikiplus-InterBox').fadeOut(300, function () {
$(this).remove();
});
});
$('#Wikiplus-Setting-Cancel').click(function () {
$('.Wikiplus-InterBox').fadeOut(300, function () {
$(this).remove();
});
});
});
});
}
/**
* 快速é‡å®šå‘页é¢è‡³æ¤é¡µé¢
*/
}, {
key: 'simpleRedirector',
value: function simpleRedirector() {
var self = this;
self.addFunctionButton(i18n('redirect_from'), 'Wikiplus-SR-Intro', function () {
var input = $('<input>').addClass('Wikiplus-InterBox-Input');
var applyBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-SR-Apply').text(i18n('submit') + " - ctrl+s");
var cancelBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-SR-Cancel').text(i18n('cancel'));
var continueBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-SR-Continue').text(i18n('continue'));
var content = $('<div>').append(input).append($('<hr>')).append(applyBtn).append(cancelBtn); //拼接
self.createDialogBox(i18n('redirect_desc'), content, 600, function () {
applyBtn.click(function () {
if ($('.Wikiplus-InterBox-Input').val() != '') {
var title = $('.Wikiplus-InterBox-Input').val();
$('.Wikiplus-InterBox-Content').html('<div class="Wikiplus-Banner">' + i18n('submitting_edit') + '</div>');
self.kotori.redirectFrom(title, self.kotori.pageName, {
success: function success() {
$('.Wikiplus-Banner').text(i18n('redirect_saved'));
$('.Wikiplus-InterBox').fadeOut(300);
location.href = mw.config.get('wgArticlePath').replace(/\$1/ig, title);
},
fail: function fail(e) {
$('.Wikiplus-Banner').css('background', 'rgba(218, 142, 167, 0.65)');
$('.Wikiplus-Banner').text(e.message);
if (e.number === 1018) {
// ç›®æ ‡é¡µé¢å·²ç»å˜åœ¨ 确认哟
$('.Wikiplus-InterBox-Content').append($('<hr>')).append(continueBtn).append(cancelBtn);
continueBtn.click(function () {
$('.Wikiplus-InterBox-Content').html('<div class="Wikiplus-Banner">' + i18n('submitting_edit') + '</div>');
self.kotori.redirectFrom(title, self.kotori.pageName, {
success: function success() {
$('.Wikiplus-Banner').text(i18n('redirect_saved'));
$('.Wikiplus-InterBox').fadeOut(300);
location.href = mw.config.get('wgArticlePath').replace(/\$1/ig, title);
},
fail: function fail(e) {
$('.Wikiplus-Banner').css('background', 'rgba(218, 142, 167, 0.65)');
$('.Wikiplus-Banner').text(e.message);
}
}, true);
});
cancelBtn.click(function () {
$('.Wikiplus-InterBox-Close').click();
});
}
}
});
} else {
self.showNotice.create.warning(i18n('empty_input'));
}
});
$('#Wikiplus-SR-Cancel').click(function () {
$('.Wikiplus-InterBox').fadeOut(300, function () {
$(this).remove();
});
});
//اختصار تأكيد التحميل
$('.Wikiplus-InterBox').keydown(function (e) {
if (e.ctrlKey && e.which == 83) {
$('#Wikiplus-SR-Apply').click();
e.preventDefault();
e.stopPropagation();
}
});
});
});
}
/**
* 预读å–相关事件绑定
*/
}, {
key: 'preloadEventBinding',
value: function preloadEventBinding() {
var self = this;
$("#toc").children("ul").find("a").each(function (i) {
$(this).mouseover(function () {
$(this).unbind('mouseover');
self.preload(i + 1);
});
});
}
/**
* 检查多è¯è¨€å®šä¹‰ç¼“å˜æ˜¯å¦è¿‡æœŸ
*/
}, {
key: 'checki18nCache',
value: function checki18nCache() {
if (localStorage.Wikiplus_i18nCache) {
try {
var _i18nData = JSON.parse(localStorage.Wikiplus_i18nCache);
for (var languages in _i18nData) {
if (_i18nData[languages]['__version'] === this.langVersion) {
i18nData[_i18nData[languages]['__language']] = _i18nData[languages];
} else {
console.log('多è¯è¨€æ–‡ä»¶[' + languages + ']å·²ç»è¿‡æœŸ');
loadLanguage(_i18nData[languages]['__language']); //å°è¯•釿–°å–
}
}
} catch (e) {
throwError('cant_parse_i18ncache');
}
} else {
localStorage.Wikiplus_i18nCache = JSON.stringify(i18nData);
}
}
/**
* 为所有å¯èƒ½çš„ç¼–è¾‘é“¾æŽ¥åŠ ä¸Šå¿«é€Ÿç¼–è¾‘æŒ‰é’®
*/
}, {
key: 'editEveryWhere',
value: function editEveryWhere() {
var self = this;
$('#mw-content-text a.external').each(function (i) {
var url = $(this).attr('href');
var reg = /(([^?&=]+)(?:=([^?&=]*))*)/g;
var params = {},
match;
while (match = reg.exec(url)) {
params[match[2]] = decodeURIComponent(match[3]);
}
if (params.action === 'edit' && params.title !== undefined && params.section !== 'new') {
$(this).after($('<a>').attr({
'href': "javascript:void(0)",
'class': "Wikiplus-Edit-EveryWhereBtn"
}).text('(' + i18n('quickedit_sectionbtn') + ')').data({
'target': decodeURIComponent(params.title),
'number': params.section || -1
}));
}
});
}
/**
* ===========================
* 以上是功能函数 以下是通用函数
* ===========================
*/
/**
* åˆ›å»ºå¯¹è¯æ¡†
* @param {string} title å¯¹è¯æ¡†æ ‡é¢˜
* @param {HTML} content 内容
* @param {interger} width 宽度 å•ä½åƒç´ 默认600px
* @param {function} callback 回调函数
*/
}, {
key: 'createDialogBox',
value: function createDialogBox() {
var title = arguments.length <= 0 || arguments[0] === undefined ? 'Dialog Box' : arguments[0];
var content = arguments.length <= 1 || arguments[1] === undefined ? $('<div>') : arguments[1];
var width = arguments.length <= 2 || arguments[2] === undefined ? 600 : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? new Function() : arguments[3];
if ($('.Wikiplus-InterBox').length > 0) {
$('.Wikiplus-InterBox').each(function () {
$(this).remove();
});
}
var clientWidth = document.body.clientWidth;
var clientHeight = document.body.clientHeight;
var diglogBox = $('<div>').addClass('Wikiplus-InterBox').css({
'margin-right': clientWidth / 2 - width / 2,
'top': $(document).scrollTop() + clientHeight * 0.2,
'display': 'none'
}).append($('<div>').addClass('Wikiplus-InterBox-Header').html(title)).append($('<div>').addClass('Wikiplus-InterBox-Content').append(content)).append($('<span>').text('×').addClass('Wikiplus-InterBox-Close'));
$('body').append(diglogBox);
$('.Wikiplus-InterBox').width(width);
$('.Wikiplus-InterBox-Close').click(function () {
$(this).parent().fadeOut('fast', function () {
window.onclose = window.onbeforeunload = undefined; //å–æ¶ˆé¡µé¢å…³é—确认
$(this).remove();
});
});
//拖曳
var bindDragging = function bindDragging(element) {
element.mousedown(function (e) {
var baseX = e.clientX;
var baseY = e.clientY;
var baseOffsetX = element.parent().offset().right;
var baseOffsetY = element.parent().offset().top;
$(document).mousemove(function (e) {
element.parent().css({
'margin-right': baseOffsetX + e.clientX - baseX,
'top': baseOffsetY + e.clientY - baseY
});
});
$(document).mouseup(function () {
element.unbind('mousedown');
$(document).unbind('mousemove');
$(document).unbind('mouseup');
bindDragging(element);
});
});
};
bindDragging($('.Wikiplus-InterBox-Header'));
$('.Wikiplus-InterBox').fadeIn(500);
callback();
}
/**
* å¢žåŠ åŠŸèƒ½æŒ‰é’®
* @param {string} text 按钮å
* @param {string} id 按钮id
* @param {function} clickEvent 点击事件
*/
}, {
key: 'addFunctionButton',
value: function addFunctionButton(text, id, clickEvent) {
var button = $('<li></li>').attr('id', id).append($('<a></a>').attr('href', 'javascript:void(0);').text(text));
if ($('#p-cactions').length > 0) {
$('#p-cactions ul').append(button);
$('#p-cactions ul').find('li').last().click(clickEvent);
} else {
throwError('cant_add_funcbtn');
}
}
/**
* 预读å–内容
* @param {interger} section 段è½ç¼–å· é»˜è®¤ä¸º-1å³å…¨é¡µ
* @param {string} title 页é¢å 默认为当å‰é¡µé¢
* @param {object} callback 回调
*/
}, {
key: 'preload',
value: function preload() {
var section = arguments.length <= 0 || arguments[0] === undefined ? -1 : arguments[0];
var title = arguments.length <= 1 || arguments[1] === undefined ? this.kotori.pageName : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var config = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
callback.success = callback.success || new Function();
callback.fail = callback.fail || new Function();
var self = this;
if (config.oldid !== undefined) {
// oldid 优先于 页é¢å
console.log(typeof config.oldid);
if (this.preloadData[config.oldid + '.' + section]) {
console.log('[修订版本' + config.oldid + '.' + section + ']å·²ç»é¢„è¯»å– è·³è¿‡æœ¬æ¬¡é¢„è¯»å–');
callback.success(this.preloadData[config.oldid + '.' + section]);
return;
}
} else {
if (this.preloadData[title + '.' + section]) {
console.log('[' + title + '.' + section + ']å·²ç»é¢„è¯»å– è·³è¿‡æœ¬æ¬¡é¢„è¯»å–');
callback.success(this.preloadData[title + '.' + section]);
return;
}
}
this.kotori.getWikiText({
success: function success(data) {
if (config.oldid !== undefined) {
self.preloadData[config.oldid + '.' + section] = data;
console.log('预读å–[修订版本' + config.oldid + '.' + section + ']æˆåŠŸ');
} else {
self.preloadData[title + '.' + section] = data;
console.log('预读å–[' + title + '.' + section + ']æˆåŠŸ');
}
callback.success(data);
},
fail: function fail(e) {
if (config.oldid !== undefined) {
console.log('预读å–[修订版本' + config.oldid + '.' + section + ']失败');
} else {
console.log('预读å–[' + title + '.' + section + ']失败:' + e.message);
}
callback.fail(e);
}
}, title, $.extend({
section: section === -1 ? '' : section
}, config));
}
/**
* æäº¤ç»Ÿè®¡æ•°æ®
* @param {string} title 页é¢å
* @param {interger} useTime 用时 å•使¯«ç§’
*/
}, {
key: 'sendStatistic',
value: function sendStatistic(title, useTime) {
if (title === undefined) title = mw.config.get('wgPageName');
if (localStorage.Wikiplus_SendStatistics == 'True') {
$.ajax({
url: scriptPath + '/statistics/api/submit',
type: 'POST',
dataType: 'json',
data: {
'wikiname': mw.config.get('wgSiteName'),
'usetime': useTime,
'username': mw.config.get('wgUserName'),
'pagename': title
},
success: function success(data) {
//æäº¤æˆåŠŸ
}
});
}
}
/**
* 检查安装
* @param {function} callback 回调函数
*/
}, {
key: 'checkInstall',
value: function checkInstall(callback) {
var self = this;
if (!localStorage.Wikiplus_Installed || localStorage.Wikiplus_Installed == 'False') {
//安装
var install = function install() {
localStorage.Wikiplus_Installed = 'True'; //æ ‡è®°å·²å®‰è£…
localStorage.Wikiplus_Version = self.version;
localStorage.Wikiplus_StartUseAt = new Date().valueOf();
localStorage.Wikiplus_SrartEditCount = mw.config.get('wgUserEditCount');
localStorage.Wikiplus_Settings = JSON.stringify(self.defaultSettings);
$('.Wikiplus-InterBox').fadeOut('fast', function () {
self.notice.create.success(i18n('install_finish'));
$(this).remove();
});
};
/*var notice = $('<div>').text(i18n('install_tip').replace(/\$1/ig, mw.config.get('wgSiteName'))).attr('id', 'Wikiplus-InterBox-Content');
var applyBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-Setting-Apply').text(i18n('accept'));
var cancelBtn = $('<div>').addClass('Wikiplus-InterBox-Btn').attr('id', 'Wikiplus-Setting-Cancel').text(i18n('decline'));
var content = $('<div>').append(notice).append($('<hr>')).append(applyBtn).append(cancelBtn); //拼接
self.createDialogBox('安装Wikiplus', content, 600, function () {
$('#Wikiplus-InterBox-Content').css('display', 'none');
$('#Wikiplus-Setting-Apply').click(function () {
localStorage.Wikiplus_SendStatistics = 'False';
install();
});
$('#Wikiplus-Setting-Cancel').click(function () {
localStorage.Wikiplus_SendStatistics = 'False';
install();
});
});*/
}
}
/**
* 获å–设置值
* @param {string} key é”®å
* @param {object} object ä¼ å…¥å¯ç”¨å‚æ•°
*/
}, {
key: 'getSetting',
value: function getSetting(key, object) {
var w = object;
try {
var settings = JSON.parse(localStorage.Wikiplus_Settings);
} catch (e) {
return localStorage.Wikiplus_Settings || '';
}
try {
var _setting = new Function('return ' + settings[key]);
if (typeof _setting == 'function') {
try {
if (_setting()(w) === true) {
return undefined;
} else {
return _setting()(w) || settings[key];
}
} catch (e) {
return settings[key];
}
} else {
return settings[key];
}
} catch (e) {
try {
return settings[key];
} catch (e) {
return undefined;
}
}
}
}, {
key: 'initBasicFunctions',
value: function initBasicFunctions() {
this.initQuickEdit(); //åŠ è½½å¿«é€Ÿç¼–è¾‘
this.editSettings(); //编辑设置
this.simpleRedirector(); //快速é‡å®šå‘
this.preloadEventBinding(); //预读å–
if (!this.getSetting('disableEditEveryWhere')) {
this.editEveryWhere(); //ä»»æ„编辑
}
}
}, {
key: 'initRecentChangesPageFunctions',
value: function initRecentChangesPageFunctions() {}
}, {
key: 'initAdvancedFunctions',
value: function initAdvancedFunctions() {}
}]);
function Wikiplus() {
_classCallCheck(this, Wikiplus);
this.version = '2.2.14';
this.langVersion = '210';
this.releaseNote = 'Bug ä¿®æ£';
this.notice = new MoeNotification();
this.inValidNameSpaces = [-1, 8964];
this.defaultSettings = {
'key': 'value',
'documatation': 'https://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E'
};
console.log('æ£åœ¨åŠ è½½Wikiplus ' + this.version);
//载入CSS
$("head").append("<link>");
$("head").children(":last").attr({
rel: "stylesheet",
type: "text/css",
href: "//ar.wikipedia.org/w/index.php?title=MediaWiki:Gadget-QuickEdit.css&action=raw&ctype=text/css"
});
//一些åˆå§‹åŒ–工作
this.preloadData = {};
this.checkInstall(); //安装检查
//è¯è¨€æ£€æµ‹
var language = this.getSetting('language') && this.getSetting('language').toLowerCase() || window.navigator.language.toLowerCase();
//版本检查
/*if (!(this.version === localStorage.Wikiplus_Version)) {
localStorage.Wikiplus_Version = this.version;
this.notice.create.success('Wikiplus ' + this.version);
this.notice.create.success(language === 'zh-cn' ? this.releaseNote : 'Minor bug fixes.'); // é¿å…给其他è¯è¨€ç”¨æˆ·ä¸å¿…è¦çš„ç†è§£å›°éš¾
}*/
if (i18nData[language] === undefined) {
loadLanguage(language);
}
//真æ£çš„åˆå§‹åŒ–
if (!inArray(mw.config.get('wgNameSpaceNumber'), this.inValidNameSpaces) && mw.config.get('wgIsArticle') && mw.config.get('wgAction') === "view") {
this.kotori = new Wikipage();
this.checki18nCache();
this.initBasicFunctions();
} else {
console.log('ä¸ç¬¦åˆåŠ è½½æ¡ä»¶ Wikiplus终æ¢');
}
}
return Wikiplus;
})();
window.Wikiplus = new Wikiplus();
});
});
/*
//
//
//
//
//
//
//
//
//
//
//
//Instalador de script
mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Enterprisey/script-installer.js&action=raw&ctype=text/javascript');
/*
This page defines a TemplateScript library. It's not meant to be referenced
directly. See [[Wikisource:TemplateScript]] for usage.
*/
/* global $, pathoschild */
/**
* TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
* @see https://meta.wikimedia.org/wiki/TemplateScript
* @update-token [[File:Pathoschild/templatescript.js]]
*/
// <nowiki>
mw.loader.load('//tools-static.wmflabs.org/meta/scripts/i18n/es.js');
$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function() {
/*********
** Define library
*********/
pathoschild.TemplateScript.library.define({
key: 'wikisource.proofreading',
name: 'Istrumenti de trascrision',
url: '//ca.wikisource.org/wiki/Wikisource:TemplateScript',
description: 'Na sèrie de strumenti de <a href="https://infokontak.com/vec/Juto:Voze de trascrision"> trascrision.',
categories: [
{
name: 'Istrumenti de trascrision',
scripts: [
{ key: 'add-header', name: 'Zonta intestasion', scriptUrl:'Special:MyPage/titols.js', script: function(editor) { addPageHeader(editor); }, forNamespaces: 'page', accessKey:'1' },
{ key: 'add-footer', name: 'Zonta pie voze', scriptUrl:'Special:MyPage/titols.js', script: function(editor) { addPageFooter(editor); }, forNamespaces: 'page', accessKey:'2' },
{ key: 'ocr', name: 'OCR (reconosimento automàtego de testo)', script: function(editor) { do_hocr(); }, forNamespaces: 'page', accessKey:'3' },
{ key: 'cleanup-ocr', name: 'Netar OCR', script: function(editor) { pageCleanup(editor); }, forNamespaces: 'page', accessKey:'4' },
{ key: 'make-refs', name: 'Far notasion', script: function(editor) { makeReference(editor); }, forNamespaces: 'page', accessKey:'5' },
{ key: 'smallcaps', name: 'A versałeta', script: function(editor) { smallcaps(editor); }, forNamespaces: 'page' },
{ key: 'uppercase', name: 'A maiúscole', script: function(editor) { upper(editor); }, forNamespaces: 'page' },
{ key: 'lowercase', name: 'A menúscole', script: function(editor) { lower(editor); }, forNamespaces: 'page' }
]
}
]
});
/*********
** Page context
*********/
var state = {
initialised: false, // whether the page context has been initialised
page: {
number: null, // the djvu page number extracted from the URL
proofed: null
},
specialFormats: [] // work-specific header template formats
};
/*********
** Private methods
*********/
/**
* Initialise the data needed by the page tools.
*/
var _initialise = function() {
// only initialise once
//if(state.initialised)
// return;
//state.initialised = true;
// get page metadata
var pn = /\.(?:djvu|pdf)\/([0-9]+)/g.exec($("#firstHeading").html());
var pq = document.getElementById('pagequality');
state.page = {
number: pn !== null ? parseInt(pn[1], 10) : null,
proofed: pq && pq.getAttribute('class') && pq.getAttribute('class').match(/quality0|quality[2-4]/)
};
// get user-defined work formats
// expected format:
// {
// title: /History of England /,
// evenHeader: '{{rh|...}}',
// oddHeader: '{{rh|...}}',
// footer: '',
// footerWithReferences: '{{smallrefs}}'
// }
if(window.specialFormats) state.specialFormats = window.specialFormats.concat(state.specialFormats);
};
/**
* Convert the text to title case based on English rules.
* @param {string} text The text to convert.
*/
var _titlecase = function(text) {
// split text into individual words and examine them one by one
var words = text.toLowerCase().split(" ");
$.each(function(i, words) {
switch(word) {
case "a":
case "à":
case "e":
case "é":
case "è":
case "ł":
case "i":
case "o":
case "ó":
case "ò":
case "u":
case "el":
case "ła":
case "i":
case "łe":
case "un":
case "na":
case "on":
case "dei":
case "de":
case "del":
case "de ła":
case "de łe":
break; // don't capitalise articles, "to" as part of an infinitive, prepositions or short conjunctions
default: // capitalise everything else
words[i] = word.substring(0, 1).toUpperCase() + word.substring(1, words[i].length);
break;
}
});
// capitalise first word regardless
words[0] = words[0].substring(0, 1).toUpperCase() + words[0].substring(1, words[0].length);
// capitalise last word regardless
var last = words.length-1;
words[last] = words[last].substring(0, 1).toUpperCase() + words[last].substring(1, words[last].length);
// reconstruct title
return words.join(' ');
};
/*********
** Script methods
*********/
/**
* Add a {{running header}} template to the page.
* @param {object} editor The script helpers for the page.
*/
var addPageHeader = function(editor) {
_initialise();
if(state.page.number === null)
return;
var isEven = (state.page.number % 2 === 0);
var generic = true;
var headertext = '';
if(window.titulos) state.specialFormats = window.titulos(state.page.number);
for (var f in state.specialFormats) {
var format = state.specialFormats[f];
if (mw.config.get('wgTitle').match(format.title)) {
headertext = isEven ? format.evenHeader : format.oddHeader;
generic = false;
break;
}
}
// no special header matched, use a generic running header
if (generic) {
if (isEven)
headertext = '{{RH|left='+state.page.number+'|center=}}'; // assume verso, with page number at left
else
headertext = '{{RH|center=|right='+state.page.number+'}}';
}
$('#wpHeaderTextbox').val(function(i, val) {
return $.trim(val + '\n' + headertext);
});
};
/**
* Clean up OCR errors in the text, and push <noinclude> content at the top
* & bottom of the page into the header & footer boxes respectively.
* @param {object} editor The script helpers for the page.
*/
var pageCleanup = function(editor) {
_initialise();
// push <noinclude> content at the top & bottom into the header & footer
if (editor.get().match(/^<noinclude\>/)) {
var text = editor.get();
var e = text.indexOf("</noinclude>");
$('#wpHeaderTextbox').val(function(i, val) {
return $.trim(val + "\n" + text.substr(11, e-11).replace(/^\s+|\s+$/g, ''));
});
editor.set(text.substr(e+12));
}
if (editor.get().match(/<\/noinclude\>$/)) {
var text = editor.get();
var s = text.lastIndexOf("<noinclude>");
$('#wpFooterTextbox').val(function(i, val) {
return $.trim(text.substr(s+11, text.length-s-11-12).replace(/^\s+|\s+$/g, '') + "\n" + val);
});
editor.set(text.substr(0, s));
}
// clean up text
editor
// remove trailing spaces at the end of each line
.replace(/ +\n/g, '\n')
// remove trailing whitespace preceding a hard line break
.replace(/ +<br *\/?>/g, '<br />')
// remove trailing whitespace and numerals at the end of page text
// (numerals are nearly always page numbers in the footer)
.replace(/[\s\d]+$/g, '')
.replace(/^[\s\d]+/g,'')
// remove trailing spaces at the end of refs
.replace(/ +<\/ref>/g, '</ref>')
// remove trailing spaces at the end of template calls
.replace(/ +}}/g, '}}')
// convert double-hyphen to mdash (avoiding breaking HTML comment syntax)
.replace(/([^\!])--([^>])/g, '$1—$2')
// remove spacing around mdash, but only if it has spaces on both sides
// (we don't want to remove the trailing space from "...as follows:— ",
// bearing in mind that the space will already be gone if at end of line).
.replace(/ +— +/g, '—')
// join words that are hyphenated across a line break
// (but leave "|-" table syntax alone)
.replace(/([^\|])-\n/g, '$1');
// clean up pages if they don't have <poem>
if (!editor.contains('<poem>')) {
editor
// lines that start with " should probably be new lines,
// if the previous line ends in punctuation,
// other than a comma or semicolon
// and let's get rid of trailing space while we're at it
.replace(/([^\n\w,;])\n\" */g, '$1\n\n"')
// lines that end with " should probably precede a new line,
// unless preceded by a comma,
// or unless the new line starts with a lower-case letter;
// and let's get rid of preceding space while we're at it
.replace(/([^,])\ *\"\n([^a-z\n])/g, '$1"\n\n$2')
// remove single line breaks; preserve multiple.
// but not if there's a tag, template or table syntax either side of the line break
.replace(/([^>}\|\n])\n([^:#\*<{\|\n])/g, '$1 $2')
// collapse sequences of spaces into a single space
.replace(/ +/g, ' ');
}
// more page cleanup
editor
// dump spurious hard breaks at the end of paragraphs
.replace(/<br *\/?>\n\n/g, '\n\n')
//caracter fantasma
.replace(/[�]/g,'')
// remove unwanted spaces around punctuation marks
.replace(/ ([;:\?!,\.])/g, '$1')
// unicodify
.replace(/—/g, '—')
.replace(/–/g, '–')
.replace(/"/g, '"')
// straighten quotes and apostrophes.
.replace(/[“”]/g, '"')
.replace(/[‘’`]/g, '\'')
//OCR fixes
.replace(/(a[bh]a )/g, 'aba ')
.replace(/(a[bh]an )/g, 'aban ')
.replace(/(acccn)/g, 'accen')
.replace(/([an][iïíìl!1I]x)/g, 'aix')
.replace(/(x[6d])/g, 'xó')
.replace(/(a[iïíìl!1I]g[anou][nu])/g, 'algun')
.replace(/(a[iïíìl!1I]g[un]a)/g, 'aigua')
.replace(/(aU)/g, 'all')
.replace(/( attre )/g, ' altre ')
.replace(/( a[iïíìl!1I][rtl]r)/g, ' altr')
.replace(/( a[iïíìl!1I][8s] )/g, ' als ')
.replace(/(anl )/g, 'ant ')
.replace(/b[ce]rt/g, 'bert')
.replace(/(b[6d])/g, 'bó')
.replace(/( calala)/g, ' catala')
.replace(/(c[iïíìl!1I][56d] )/g, 'ció ')
.replace(/(c[iïíìl!1I][56d][ns][8s] )/g, 'cions ')
.replace(/( corn )/g, ' com ')
.replace(/( co[un][iïíìl!1I] )/g, ' com ')
.replace(/(cb)/g, 'ch')
.replace(/(c[iïíìl!1I] )/g, 'ci ') //ofici
.replace(/(cuU)/g, 'cull')
.replace(/(d[*'\"])/g, 'd\'')
.replace(/( d[ocs] )/g, ' de ')
.replace(/(d[ce][iïíìl!1I]x)/g, 'deix')
.replace(/( d[ce][iïíìl!1I] )/g, ' del ')
.replace(/( d[ce][iïíìl!1I][8s] )/g, ' dels ')
.replace(/(d[ce][s8])/g, 'des')
.replace(/(D[ce][anu] )/g, 'Deu ')
.replace(/(d6[nu])/g, 'déu')
.replace(/(d[!1I])/g, 'di')
.replace(/(d[iïíìl!1I]g)/g, 'dig')
.replace(/dfs/g, 'dís')
.replace(/([nu][bh][ec][nu])/g, 'uhen')
.replace(/(drc)/g, 'dre')
.replace(/(dr[iïíìl!1I])/g, 'dri')
.replace(/([ce]o[nu][ce][ce][bh])/g, 'conech')
.replace(/(efe[ce][ce])/g, 'efecc')
.replace(/([BE][iïíìl!1I] )/g, 'El ')
.replace(/(EU )/g, 'Ell ')
.replace(/( [ce][iïíìl!1I] )/g, ' el ')
.replace(/([ -][ce][iïíìl!1I][8s] )/g, ' els ')
.replace(/( [ce][iïíìl!1I][iïíìl!1I] )/g, ' ell ')
.replace(/(eU)/g, 'ell')
.replace(/(cm)/g, 'em')
.replace(/[BE][nqu] /g, 'En ')
.replace(/ cn/g, ' en')
.replace(/ [ce][un] /g,' en ')
.replace(/[ce]n[lt] /g, 'ent ')
.replace(/ [ce]n[it]r[ce]/g, ' entre')
.replace(/ [ce]s /g, ' es ')
.replace(/[ce][8s][ce]ri/g, 'escri')
.replace(/[ce][8s][ce]r /g, 'eser ')
.replace(/ [ceo][8s][8s][ceo]r /g, ' esser ')
.replace(/ [ce][s8][lt]([aáà])([ t])/g, ' est$1$2')
.replace(/exlr/g, 'extr')
.replace(/fc/g, 'fe')
.replace(/f[ce][nu][lt]/g, 'fent')
.replace(/f[1!Iil]([bcdfgjlmnpqrstvxyz])/g, 'fi$1') //fic,fim...
.replace(/[fí][iïíìl!1I][iïíìl!1I][iïíìl!1I]/g, 'fill')
.replace(/(g[iïíìl!1I][6é]s)/g, 'glés')
.replace(/g[nu][óé]/g, 'gué')
.replace(/gn[ce]/g, 'gne') //p.ex. digne
.replace(/gu[ce]/g, 'gue')
.replace(/g[nu]t/g, 'gut')
.replace(/[hb]a[nu] /g, 'han ')
.replace(/[hb]ab[ce]m/g, 'havem')
.replace(/[hb]av[iïíìl!1I]a/g, 'havia')
.replace(/([hb]av[iïíìl!1I][ce][nu])/g, 'havien')
.replace(/([hb][iïíìl!1I] [hb]a)/g, 'hi ha')
.replace(/ [bh]a /g, ' ha ')
.replace(/h[iïìl!1I]/g, 'hi')
.replace(/[bh][oe]m[ce]/g, 'home')
.replace(/(horn)/g, 'hom')
.replace(/( [bh]o[no]t )/g, ' hont ')
.replace(/([iïíìl!1]U)/g, 'ill')
.replace(/([iïíìl!1I]n[lt] )/g, 'int ')
.replace(/J[ce][s8]/g, 'Jes')
.replace(/jomada/g, 'jornada')
.replace(/ [iïíìl!1I][nu]r /g, ' lur ')
.replace(/ [*'´\\^][iïíìl!1I] /g, ' \'l ')
.replace(/L[*´\\^]/g, 'L\'')
.replace(/([ .,;])[iïíìl!1I][*'´\\^]/g, '$1l\'')
.replace(/Ta([iy])gua/g, 'l\'a$1gua')
.replace(/V a/g, 'l\' a')
.replace(/ [iïíìl!1]a /g, ' la ')
.replace(/ [iïíìl!1][ec][a8s] /g, ' les ')
.replace(/ [iïíìl!1]i /g, ' li ')
.replace(/[UI][iïíìl!1I][bh]r[ec]/g, 'Uibre')
.replace(/ii([aáàeéèiíìoóòuúù])/g, 'll$1') //"iiibre"
.replace(/ [iïíìl!1]o /g, ' lo ')
.replace(/ [iïíìl!1]o[a8s] /g, ' los ')
.replace(/Uoc/g, 'lloc')
.replace(/U[nu][nu]/g, 'llun')
.replace(/([*'´][iïíìl!1I][8s])/g, '\'ls')
.replace(/( M[8s] )/g, ' \'\ls ')
.replace(/( [iïíìl!1][8s] )/g, ' ls ')
.replace(/ ine /g, 'me')
.replace(/m[ce]([ '])/g, 'me$1')
.replace(/(loient )/g, 'lment ')
.replace(/(ni[ce][nu]y)/g, 'menys')
.replace(/(mo[iïíìl!1]t)/g, 'molt')
.replace(/(—jN)/g, '—¡N')
.replace(/(n[*'\\^])/g, 'n\'')
.replace(/([*'\\^]n)/g, '\'n')
.replace(/ [nu]o /g, ' no ')
.replace(/nl([ ;.:r])/g, 'nt$1') //entre, -nt
.replace(/(oU)/g, 'oll')
.replace(/(—jP)/g, '—¡P')
.replace(/(prc)/g, 'pre')
.replace(/pnn/g, 'pun')
.replace(/(—[ij]Q)/g, '—¡Q')
.replace(/(Q[anou][ce])/g, 'Que')
.replace(/(Q[anou][iïíìl!1I])/g, 'Qui')
.replace(/([çq][*'\\^])/g, 'q\'')
.replace(/([çq][nu][*'\\^])/g, 'qu\'')
.replace(/([çq][anou][anou][il])/g, 'qual')
.replace(/([çq][anou][anou][nu])/g, 'quan')
.replace(/([çq][anou][ceo])/g, 'que')
.replace(/([çq]ii[ceo])/g, 'que')
.replace(/qae/g, 'que')
.replace(/([çq]u[ce] [iïíìl!1I] )/g, 'que l ')
.replace(/([çq][anou][óé])/g, 'qué')
.replace(/([çq][anou][ce]s[lt])/g, 'quest')
.replace(/([çq][anou][iïíìl!1I])/g, 'qui')
.replace(/(rcg)/g, 'reg') //tb podria ser "rog"
.replace(/(rcr)/g, 'rer') //tb podria ser "ror"
.replace(/rcy/g, 'rey')
.replace(/(Sl)/g, 'Si')
.replace(/([s8][*'\\^])/g, 's\'')
.replace(/([*'\\^]s)/g, '\'s')
.replace(/ [sa8][ce] /g, ' se ')
.replace(/([8s]cc)/g, 'sec')
.replace(/scd/g, 'sed')
.replace(/scg/g, 'seg')
.replace(/([8s][ceo][çgq][eo][nu])/g, 'segon')
.replace(/( [8s]cr )/g, ' ser ') //tb podria ser " sor "
.replace(/( [8s][ce]r[ce])/g, ' sere')
.replace(/( [8s]o[nD] )/g, ' son ')
.replace(/([8s]lr)/g, 'str') //vostra
.replace(/(t[*'\\^])/g, 't\'')
.replace(/([*'\\^]t)/g, '\'t')
.replace(/[lt]am[6b]([éèe])/g, 'tamb$1')
.replace(/[lt]amp[ceo][ceo]/g, 'tampoc')
.replace(/( tc )/g, ' te ')
.replace(/[lt][ce]rr/g, 'terr')
.replace(/(tU)/g, 'tll')
.replace(/ [tl][iIïíìÏÌÍIL][un][ce]([h ;.:])/g, ' tinc$1')
.replace(/(trc)/g, 'tre') //tb "tro"
.replace(/( [nu][nu] )/g, ' un ') //tb " nu "
.replace(/( [nu][nu][oa] )/g, ' una ') //tb " nua "
.replace(/(uU)/g, 'ull')
.replace(/(▼)/g, 'V')
.replace(/v[ce]ll/g, 'vell')
.replace(/(•)/g, '.');
};
/**
* As you work your way through the page, when you encounter a reference, just mark it with <ref></ref> tags and continue.
* Once you've got to the end of the page and proofed the references, simply highlight each reference in turn,
* and use this function to move it to its proper position.
* @param {object} editor The script helpers for the page.
*/
var makeReference = function(editor) {
_initialise();
var editbox = $('#wpTextbox1').get(0);
editbox.focus();
var refStart = editbox.selectionStart;
var refEnd = editbox.selectionEnd;
var firstref = editbox.value.indexOf('<ref></ref>');
if (firstref != -1) {
editbox.value = editbox.value.slice(0,firstref+5)
+ editbox.value.slice(refStart, refEnd)
+ editbox.value.slice(firstref+5, refStart)
+ editbox.value.slice(refEnd);
}
addPageFooter(editor);
};
/**
* Insert formatted references into the footer box if needed.
* @param {object} editor The script helpers for the page.
*/
var addPageFooter = function(editor) {
_initialise();
var editbox = $('#wpTextbox1').get(0);
var footerbox;
var generic;
var format;
var f;
if(window.titulos) state.specialFormats = window.titulos(state.page.number);
if (editbox.value.indexOf("<ref") == -1 && editbox.value.indexOf("{{#tag:ref") == -1) {
// page contains no refs
generic = true;
for (f in state.specialFormats) {
format = state.specialFormats[f];
if (mw.config.get('wgTitle').match(format.title)) {
footerbox = format.footer;
generic = false;
break;
}
}
// no special footer matched, use just strip out the references tag
if (generic)
footerbox = '';
}
else {
generic = true;
for (f in state.specialFormats) {
format = state.specialFormats[f];
if (mw.config.get('wgTitle').match(format.title)) {
footerbox = format.footerWithReferences;
generic = false;
break;
}
}
// no special footer matched, so use a generic ref tag
if (generic)
footerbox = '{{Notasion}}';
}
$('#wpFooterTextbox').val(footerbox);
};
/**
* Mark the selected text with {{sc}}. If the text is uppercase, it will be converted to titlecase.
* @param {object} editor The script helpers for the page.
*/
var smallcaps = function(editor) {
_initialise();
editor.replaceSelection(function(text) {
// Applying small-caps to all-caps text is pointless...
// ... unless the all-caps is OCR of text that is actually small-caps.
// Check if text is all-caps, and if it is, convert it to title case before applying small-caps.
if (text == text.toUpperCase())
text = _titlecase(text);
return '{{maj|' + text + '}}';
});
};
/**
* Convert the text to uppercase.
* @param {object} editor The script helpers for the page.
*/
var upper = function(editor) {
_initialise();
editor.replaceSelection(function(text) {
return text.toUpperCase();
});
};
var lower = function(editor) {
_initialise();
editor.replaceSelection(function(text) {
return text.toLowerCase();
});
};
/*global $, mw*/
/*
* Query an ocr for a given Page:, first try to get the hocr text layer as it's available
* for most book, fast and of a better quality. If it fails, try the older and slower
* ocr method. hocr fail around 1/5000 books. ocr should never fails as it use the image
* visible on the Page:.
*/
var lang = mw.config.get( 'wgContentLanguage' );
function disable_input(set)
{
if (set) {
$(document).keyup(function(e) {
if (e.which == 27) { disable_input(false); }
});
}
set ? $('#wsOcr1').off('click') : $('#wsOcr1').on('click', do_hocr);
$('#wpTextbox1').prop('disabled', set);
}
function ocr_callback(data) {
if (data.error) {
alert(data.text);
} else {
// Checking if tb is disabled is required with chrome as ESC doesn't kill
// the query.
var tb = document.getElementById("wpTextbox1");
if (tb.disabled)
tb.value = data.text;
}
disable_input(false);
}
function hocr_callback(data) {
if (data.error) {
// Fallback to the slow way.
disable_input(false);
do_ocr();
return;
} else {
// Checking if tb is disabled is required with chrome as ESC doesn't kill
// the query.
var tb = document.getElementById("wpTextbox1");
if (tb.disabled) {
localStorage.ws_hOCR = data.text;
var text = $(data.text).text();
// Ugly as hell.
text = text.replace(/[ ]*\n[ ]*/g, '\n')
.replace(/\n\n\n\n/g, '@_@_@_@_@_@')
.replace(/\n\n/g, '\n')
.replace(/@_@_@_@_@_@/g, '\n\n')
.replace(/\n\n\n/g, '\n\n');
tb.value = $.trim(text);
}
}
disable_input(false);
}
function do_hocr() {
disable_input(true);
var request_url = '//tools.wmflabs.org/phetools/hocr_cgi.py?cmd=hocr&book='
+ encodeURIComponent(mw.config.get('wgTitle')) + '&lang=' + lang + '&user=' + mw.config.get('wgUserName');
$.getJSON(request_url).done(hocr_callback).fail(do_ocr);
}
function do_ocr() {
if ($( '.prp-page-image img' ).length) {
disable_input(true);
// server side can't use protocol relative url, request it as https:
var url_image = 'https:' + $( '.prp-page-image img' ).attr('src');
var request_url = "//tools.wmflabs.org/phetools/ocr.php?cmd=ocr&url="+url_image+"&lang="+lang+"&user="+mw.config.get('wgUserName');
$.getJSON( request_url ).done( ocr_callback );
}
}
});
// </nowiki>Content Disclaimer
Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.
- The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
- There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
- It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
- Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
- Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.
Index:
pl ar de en es fr it arz nl ja pt ceb sv uk vi war zh ru af ast az bg zh-min-nan bn be ca cs cy da et el eo eu fa gl ko hi hr id he ka la lv lt hu mk ms min no nn ce uz kk ro simple sk sl sr sh fi ta tt th tg azb tr ur zh-yue hy my ace als am an hyw ban bjn map-bms ba be-tarask bcl bpy bar bs br cv nv eml hif fo fy ga gd gu hak ha hsb io ig ilo ia ie os is jv kn ht ku ckb ky mrj lb lij li lmo mai mg ml zh-classical mr xmf mzn cdo mn nap new ne frr oc mhr or as pa pnb ps pms nds crh qu sa sah sco sq scn si sd szl su sw tl shn te bug vec vo wa wuu yi yo diq bat-smg zu lad kbd ang smn ab roa-rup frp arc gn av ay bh bi bo bxr cbk-zam co za dag ary se pdc dv dsb myv ext fur gv gag inh ki glk gan guw xal haw rw kbp pam csb kw km kv koi kg gom ks gcr lo lbe ltg lez nia ln jbo lg mt mi tw mwl mdf mnw nqo fj nah na nds-nl nrm nov om pi pag pap pfl pcd krc kaa ksh rm rue sm sat sc trv stq nso sn cu so srn kab roa-tara tet tpi to chr tum tk tyv udm ug vep fiu-vro vls wo xh zea ty ak bm ch ny ee ff got iu ik kl mad cr pih ami pwn pnt dz rmy rn sg st tn ss ti din chy ts kcg ve









