User:Crowley666/js/import.js

維基詞典,自由的多語言詞典

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

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

// 见[[mw:Manual:CORS]]、[[mw:API:Cross-site requests]]
mw.loader.using('mediawiki.ForeignApi');
var pn = mw.config.get('wgPageName');
if (pn.startsWith('User:Qnm/') || // User:Qnm/9至99随便用
	pn.startsWith('Template:') || pn.startsWith('Module:')) {
	importexportinit();
	mw.util.addPortletLink('p-cactions', 'javascript:importpage()', '导入页面', 'ca-import-page',
							'导入页面', '', document.getElementById('ca-history'));  // 快捷键设为''
	mw.util.addPortletLink('p-cactions', 'javascript:importdoc()', '导入文档', 'ca-import-doc',
							'导入文档', '', document.getElementById('ca-history'));
	mw.util.addPortletLink('p-cactions', 'javascript:importboth()', '导入两者', 'ca-import-both',
							'导入两者', '', document.getElementById('ca-history'));
	mw.util.addPortletLink('p-cactions', 'javascript:importedit()', '导入编辑区', 'ca-import-edit',
							'导入编辑区', '', document.getElementById('ca-history'));
} else if (pn == 'Wiktionary:Sandbox' || pn == 'Wiktionary:沙盒') {
	importexportinit();
	mw.util.addPortletLink('p-cactions', 'javascript:importsandbox()', '导入沙盒', 'ca-import-sandbox',
							'导入沙盒', '', document.getElementById('ca-history'));
	mw.util.addPortletLink('p-cactions', 'javascript:revertsandbox()', '复原沙盒', 'ca-revert-sandbox',
							'复原沙盒', '', document.getElementById('ca-history'));
}

function importpage() {
	var from = pn, to = pn;
	importpagecore(from, to);
}

function importedit() {
    if (document.forms.editform) {
    	var from = pn, to = pn;
    	// 这种方法对Module的编辑框无效,也对手机版无效
    	var txt = document.editform.wpTextbox1;
    	var sum = document.editform.wpSummary;
    	importpagecore(from, to, function(text, summary){ txt.value = text; sum.value = summary; });
    }
}

function importdoc() {
	var from = pn, to = pn;
	if (!isdoc(from)) {
		from = from + '/documentation';
		to = to + '/doc';
	}
	if (mw.config.get('wgWikibaseItemId')) {
		link = $("a.interlanguage-link-target[lang='en']").attr('href'); 
		if (link) {
			from = decodeURI(link.split('/wiki/')[1]) + '/documentation';
		}
	}
	importpagecore(from, to);
}

// 不支持在文档页面importboth
function importboth() {
	var from = pn, to = pn;
	if (isdoc(from)) {
		from = from.replace('/documentation', '');
		from = from.replace('/doc', '');
		to = from;
	}
	[from, to] = importpagecore(from, to);
	importpagecore(from + '/documentation', to + '/doc');
}

function importsandbox() {
	importpagecore('Wiktionary:Sandbox', 'Wiktionary:沙盒');
}

function revertsandbox() {
	const api = new mw.ForeignApi('https://cd.100ke.info/w/api.php');
	api.postWithToken('csrf', {
		action: 'edit',
		title: 'Wiktionary:沙盒',
		text: '{{sandbox}}',
		summary: '复原沙盒'
	}).fail(function(){ mw.notify('复原失败'); }).done(function(){ mw.notify('复原成功'); });
}

// 将部分首字母大写恢复为小写
function decapital(title) {
	var re = /^(Template:|Module:)(.*)$/;
	var m = re.exec(title);
	if (m) {
		var re1, m1;
		if (m[1] == 'Template:') {
			re1 = /^(Han |IPA|PIE|PL:|R:|RQ:|Robert |Swadesh|Thomas|U:|User |User:|VL-)|(quotation templates|quotation templates\/documentation| Hypernyms| Hypernyms\/documentation)$/;
		} else {
			re1 = /^(IPA|Quotations|R:|RQ:|Swadesh|Unicode|User:|VL-)/;  // 注:全部translit均已搬运
		}
		m1 = re1.exec(m[2]);
		if (m1) {
			return title;
		} else {
			return m[1] + m[2][0].toLowerCase() + m[2].slice(1);
		}
	} else {
		return title;
	}
}

function importpagecore(from, to, modify) {
	if (from.endsWith('/doc')) from = from.replace('/doc', '/documentation');
	if (to.endsWith('/documentation')) to = to.replace('/documentation', '/doc');
	from = decapital(from);
	// 若有跨语言链接,使用跨语言链接的标题。
	// 使用本地DOM数据是为了降低延迟。不适用手机版,若实在需要,应使用api获取
	if (mw.config.get('wgWikibaseItemId')) {
		link = $("a.interlanguage-link-target[lang='en']").attr('href'); 
		if (link) {
			from = decodeURI(link.split('/wiki/')[1]) + (isdoc(from) ? '/documentation' : '');
		}
	}
	const apifrom = new mw.ForeignApi('https://en.wiktionary.org/w/api.php');
	apifrom.get({
		action: 'query',
		titles: from,
		prop: 'revisions|langlinks',
		indexpageids: 1,
		rvprop: 'content',
		lllang: 'zh'
	}).then(function(result) {
		result = result.query;
		if (result.pageids[0] === "-1") {
			mw.notify('页面不存在');
			return;
		}
		var rpage = result.pages[result.pageids[0]];
		if (rpage.langlinks) {
			to = rpage.langlinks[0]['*'];
		}
		var text = rpage.revisions[0]['*'];
		var summary = '[[User:EdwardAlexanderCrowley/js/import.js|搬运]]自[[:en:' + from + ']]';
		if (from == 'Wiktionary:Sandbox') text = '{{sandbox}}\n' + text;
		if (modify != undefined) {
			modify(text, summary);
			return;
		}
		if (mw.util && mw.util.getParamValue && mw.util.getParamValue('redlink') === '1') {
			if (document.editform) {
				if (document.editform.wpTextbox1) document.editform.wpTextbox1.value = text;
				if (document.editform.wpSummary) document.editform.wpSummary.value = summary;
				$('input#wpWatchthis').prop('checked', false);
			}
		}
		const apito = new mw.Api();
		return apito.postWithToken('csrf', {
			action: 'edit',
			title: to,
			text: text,
			summary: summary,
			watchlist: 'nochange'
		}).fail(function() {
			mw.notify('搬运失败');
		}).then(function() {
			mw.notify('搬运成功');
			if (!rpage.langlinks && canlink(from)) {
				const apidata = new mw.ForeignApi('https://www.wikidata.org/w/api.php');
				apidata.postWithToken('csrf', {
					action: 'wblinktitles',
					fromsite: 'enwiktionary',
					fromtitle: from,
					tosite: 'zhwiktionary',
					totitle: to,
					bot: 1
				}).fail(function(result) {
					var msg = { "no-external-page": "页面为重定向", "failed-save": "链接失败,可能需要IPBE"};
					if (msg[result]) {
						mw.notify(msg[result]);
					} else {
						mw.notify("未知错误:" + result);
					}
				}).done(function() {
					mw.notify('链接成功');
				});
			}
		});
	});
	return [from, to];
}

function canlink(p) {
	return !(p.endsWith('/documentation') || p.endsWith('/doc')
		|| p.endsWith('/testcase') || p.endsWith('/testcases')
		|| p.startsWith('User:') || p.startsWith('Module:User:')
		|| p.endsWith('.css'));
}

function isdoc(p) {
	return p.endsWith('/documentation') || p.endsWith('/doc');
}

function importexportinit() {
	var e;
	if (mw.config.get('skin') != "minerva") return;
	if ((e = $('ul.toggle-list__list#p-tb')).length) {
		e.attr('id', 'p-cactions'); return;
	}
	e = $('<li id="page-actions-overflow" class="page-actions-menu__list-item"><div class="toggle-list "><input type="checkbox" id="page-actions-overflow-checkbox" class="toggle-list__checkbox" role="button" aria-labelledby="page-actions-overflow-toggle" aria-expanded="false"><label id="page-actions-overflow-toggle" class="toggle-list__toggle mw-ui-icon mw-ui-icon-element mw-ui-icon-wikimedia-language-base20 mw-ui-icon-with-label-desktop" for="page-actions-overflow-checkbox" data-event-name="ui.overflowmenu">More</label><ul class="toggle-list__list new page-actions-overflow-list toggle-list__list--drop-down" id="p-cactions"></ul></div></li>');
	$('.page-actions-menu__list').append(e);

	var selector='.toggle-list',toggleSelector='.toggle-list__toggle',checkboxSelector='.toggle-list__checkbox';
	function bind(window,component){
		var toggle=component.querySelector(toggleSelector),checkbox=(component.querySelector(checkboxSelector));
		window.addEventListener('click',function(event){if(event.target!==toggle&&event.target!==checkbox){_dismiss(checkbox);}},!0);
		window.addEventListener('focusin',function(event){if(event.target instanceof Node&&!component.contains(event.target)){_dismiss(checkbox);}},!0);
		checkbox.addEventListener('change',_updateAriaExpanded.bind(undefined,checkbox));
	}
	function _dismiss(checkbox){checkbox.checked=!1;_updateAriaExpanded(checkbox);}
	function _updateAriaExpanded(checkbox){checkbox.setAttribute('aria-expanded',(!!checkbox.checked).toString());}

	bind(window, document.querySelector('#page-actions-overflow'));
}