User:Stang/js/TranslateVariants.js

// /* globals TranslateVariants:true */ /** * Adapted from https://zh.wikipedia.org/w/index.php?title=User:Xiplus/js/TranslateVariants.js */ (function {

if (mw.config.get('wgPageName').match(/^MediaWiki:[^/]+(\/zh)?$/)) { mw.loader.using(['mediawiki.api', 'mediawiki.ForeignApi']).then(function {			let link = mw.util.addPortletLink( 'p-cactions', '#',				'Translate variants' )			$(link).on('click', function { this.remove; main; });		});	} else { return; }

if (typeof (TranslateVariants) == 'undefined') { TranslateVariants = {}; }	if (typeof (TranslateVariants.summary) != 'string') { TranslateVariants.summary = 'Automatically converted variants of interface message $1 via TranslateVariants' }

function main { const langs = ['zh', 'zh-hans', 'zh-cn', 'zh-my', 'zh-sg', 'zh-hant', 'zh-hk', 'zh-mo', 'zh-tw']; const langname = { 'zh': '原始', 'zh-hans': '简体', 'zh-cn': '大陆简体', 'zh-my': '大马简体', 'zh-sg': '新加坡简体', 'zh-hant': '繁體', 'zh-hk': '香港繁體', 'zh-mo': '澳門繁體', 'zh-tw': '臺灣正體' }		let result = {};

var api = new mw.Api; var zhwpapi; var zhwpapi = new mw.ForeignApi('//zh.wikipedia.org/w/api.php');

var basepagetext = ''; let table = $(' ').prependTo('#bodyContent'); $(' Reminder: The TranslateVariants gadget is still in the experimental stage. After editing, please also check if the actual editing is correct! ').appendTo(table);

var defaultlangs = 'zh,zh-hans,zh-cn,zh-my,zh-sg,zh-hant,zh-hk,zh-mo,zh-tw'; var runlangs = prompt('Convert the following languages (separated by commas):', defaultlangs); if (runlangs === null) { runlangs = defaultlangs; }

var langqueue = runlangs.split(',').map(function(lang) {			return lang.trim		}).filter(function(lang) {			return langs.indexOf(lang) !== -1		});

api.get({			action: 'query',			prop: 'revisions',			rvprop: ['content', 'timestamp'],			titles: [mw.config.get('wgPageName')],			formatversion: '2',			curtimestamp: true		}).then(function(data) {			var page, revision;			if (!data.query || !data.query.pages) {				return $.Deferred.reject('unknown');			}			page = data.query.pages[0];			if (!page || page.invalid) {				return $.Deferred.reject('invalidtitle');			}			if (page.missing) {				return $.Deferred.reject('nocreate-missing');			}			revision = page.revisions[0];			return {				content: revision.content			};		}).then(function(data) {			let text = data.content;			result['zh'] = text;

text = text.replace(/[[\]{}<>|:*'_#&\s]/gim, function(s) {				return "&#" + s.charCodeAt(0) + ";";			});			text = text.replace(/(&#91;&#91;)((?:(?!&#124;)(?!&#93;).)+?)(&#124;(?:(?!&#93;).)+?&#93;&#93;)/g, '$1-{$2}-$3');			text = text.replace(/-&#123;(.+?)&#125;-/g, function(s) {				return s					.replace('-&#123;', '-{')					.replace('&#125;-', '}-')					.replace('&#124;', '|')					.replace('&#62;', '>')					.replace(/&#58;/g, ':')			});			basepagetext = text;

process; });

function process { if (langqueue.length === 0) { return; }

var lang = langqueue.shift; var diffTable = $('').appendTo(table); $(' ').appendTo(table);

const basename = mw.config.get('wgPageName').replace(/\/zh$/, ''); var targetTitle; if (lang == 'zh') { targetTitle = basename + ''; } else { targetTitle = basename + '/' + lang; }

var newtext;

zhwpapi.parse(				' ' + basepagetext + ' ',				{					'uselang': lang,					'prop': 'text'				}			).then(function(data) {				newtext = $(' ').html(data).find('#TVcontent').text;

return api.post({					action: 'query',					prop: 'revisions',					titles: [targetTitle],					rvdifftotext: newtext,					formatversion: '2',				}); }, function(err) { mw.notify('Parsing ' + lang + 'error:' + err); }).then(function(data) { let tool = $(' ' + lang + '（' + langname[lang] + '）（edit） ').appendTo(diffTable); let page = data.query.pages[0]; if (page.missing) { let submit = $('publish changes ').appendTo(tool); submit.on('click', function {						this.remove;						api.create( targetTitle, { summary: TranslateVariants.summary.replace(/\$1/g, mw.config.get('wgPageName')) }, newtext ).then(function { mw.notify('Edited ' + targetTitle); }, function(e) { mw.notify('Failed to edit ' + targetTitle + ':' + e); });					});					$(' ').html(newtext.replace(/[<>&]/gim, function(s) { return "&#" + s.charCodeAt(0) + ";"; })).appendTo(diffTable); return; }				let diff = page.revisions[0].diff.body; if (diff == '') { $(' No changes ').appendTo(tool); } else { let submit = $('Publish changes ').appendTo(tool); submit.on('click', function {						this.remove;						api.edit( targetTitle, function { return { text: newtext, summary: TranslateVariants.summary.replace(/\$1/g, mw.config.get('wgPageName')), nocreate: false };							}						).then(function { mw.notify('Edited ' + targetTitle); }, function(e) { mw.notify('Failed to edit ' + targetTitle + ':' + e); });					});					$(' ').html(diff).prepend('  ').appendTo(diffTable); }			}, function(err) { mw.notify('Failed to retrive diff of' + lang + ':' + err); }).always(function { process; });		}	}

}); //