跳转到内容

User:SunAfterRain/js/download.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
$.when(
	mw.loader.getState('ext.gadget.HanAssist')
		? mw.loader.using('ext.gadget.HanAssist')
		: new Promise((resolve, reject) => {
			const hook = mw.hook('userscript.SunAfterRain.HanAssist.ready');
			function hookCallback(HanAssist) {
				hook.remove(hookCallback);
				mw.loader.using([])
					.then((origRequire) => resolve(
						(module) => module === 'ext.gadget.HanAssist'
							? HanAssist
							: origRequire(module)
					));
			}
			hook.add(hookCallback);
		}),
	$.ready
).then((require) => {
	if (!mw.config.get('wgArticleId') || !mw.config.get('wgRevisionId') || mw.config.get('wgAction') !== 'view' || mw.config.get('wgDiffOldId')) {
		return;
	}
	
	const batchLocalize = require('ext.gadget.HanAssist').batchConv || mw.libs.HanAssist.parse;
	const msgs = batchLocalize({
		portlet: {
			hans: '下载',
			hant: '下載'
		},
		portletInfo: {
			hans: '下载本页',
			hant: '下載本頁'
		},
		prompt: {
			hans: '文件名称:',
			hant: '檔案名稱:'
		}
	});

	$(mw.util.addPortletLink('p-cactions', '', msgs.portlet, 't-download', msgs.portletInfo)).on('click', (e) => {
		e.preventDefault();

		const oldid = mw.config.get('wgRevisionId');
		let suffix = '.txt';
		let type = 'text/plain';

		switch (mw.config.get('wgPageContentModel')) {
			case 'wikitext':
				suffix = '.wikitext';
				type = 'text/x-wiki';
				break;
			case 'javascript':
				suffix = '.js';
				type = 'text/javascript';
				break;
			case 'css':
			case 'sanitized-css':
				suffix = '.css';
				type = 'text/css';
				break;
			case 'Scribunto':
				suffix = '.lua';
				type = 'text/lua';
				break;
		}
		
		let file = mw.config.get('wgPageName').replace(/[:\/\\*?'<>|]/g, '-').replace(new RegExp(suffix.replace(/\./g, '\\.') + '$'), '') +  '_' + mw.config.get('wgRevisionId') + suffix;
		file = prompt(msgs.prompt, file) || file;

		$.ajax(
			'/w/index.php?' + new URLSearchParams({
				action: 'raw',
				oldid,
				ctype: type
			}).toString()
		).done((data) => {
			const blob = new Blob([data], {
				type: type,
			});

			$('<a>')
				.attr({
					href: URL.createObjectURL(blob),
					download: file
				})
				.get(0)
				.click();
		});
	});
});