مدیاویکی:Gadget-asbox.js

از ایران پدیا
پرش به ناوبری پرش به جستجو

نکته: پس از انتشار ممکن است برای دیدن تغییرات نیاز باشد که حافظهٔ نهانی مرورگر خود را پاک کنید.

  • فایرفاکس / سافاری: کلید Shift را نگه دارید و روی دکمهٔ Reload کلیک کنید، یا کلید‌های Ctrl-F5 یا Ctrl-R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-R)
  • گوگل کروم: کلیدهای Ctrl+Shift+R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-Shift-R)
  • اینترنت اکسپلورر/ Edge: کلید Ctrl را نگه‌دارید و روی دکمهٔ Refresh کلیک کنید، یا کلید‌های Ctrl-F5 را با هم فشار دهید
  • اپرا: Ctrl-F5 را بفشارید.
/*global jQuery, mediaWiki*/
/* <nowiki> */
/*!
 * Developed by: [[User:Ebrahim]]
 */
(function ($, mw) {
	'use strict';

	if (mw.config.get('wgNamespaceNumber') !== 0 || mw.config.get('wgAction') !== 'view') {
		return;
	}

	function savePage(summary, content) {
		return new mw.Api().post({
			action: 'edit',
			title: mw.config.get('wgPageName'),
			summary: summary,
			text: content,
			format: 'json',
			token: mw.user.tokens.get('editToken')
		});
	}

	function loadPage() {
		return new mw.Api().get({
			action: 'query',
			prop: 'revisions',
			titles: mw.config.get('wgPageName'),
			rvprop: 'content',
			format: 'json'
		}).then(function (data) {
			return $.map(data.query.pages, function (value) { return value; })[0].revisions[0]['*'];
		});
	}

	/**
	 * This will help on better sorting on Persian string array
	 */
	function dePersian(input) { // solve persian problem on sorting by replace characters in strings
		return input.replace(/ی/g, "ي")
			.replace(/ک/g, "ك")
			.replace(/گ/g, "كی")
			.replace(/ژ/g, "زی")
			.replace(/چ/g, "جی")
			.replace(/پ/g, "بی");
	}

	/**
	 * String comparator for Persian
	 */
	function customComparator(a, b) {
		var keyA = dePersian(a),
			keyB = dePersian(b);

		if (keyA < keyB) {
			return -1;
		}
		if (keyA > keyB) {
			return 1;
		}
		return 0;
	}

	/**
	 * Is a recursive function to retrieve all stub templates consequently
	 */
	function getAllStubTemplates(array, eicontinue) {
		return new mw.Api().get({
			action: 'query',
			list: 'embeddedin',
			eititle: 'Template:Asbox',
			eilimit: 500,
			einamespace: 10,
			format: 'json',
			eicontinue: eicontinue,
			'continue': ''
		}).then(function (data) {
			if (!array) { array = []; }
			array = array.concat($.map(data.query.embeddedin, function (value) {
				return value.title;
			}));
			if (!data['continue']) {
				return array;
			}
			return getAllStubTemplates(array, data['continue'].eicontinue);
		});
	}
	
	/**
	 * check if is expired, currently expires in three days
	 */
	function isExpired(cacheTime) {
		return (new Date().getTime() - cacheTime) > (1000 * 60 * 60 * 24 * 3);
	}
	
	/**
	 * If browser support localStorage, this would use it
	 */
	function cachedGetAllStubTemplates() {
		if (window.localStorage !== undefined) {
			var object, defer;
			try {
				object = JSON.parse(localStorage.getItem('allStubTemplates'));
			} catch (ignore) {}
			if (object && !isExpired(parseInt(object.timestamp))) {
				defer = $.Deferred();
				return $.Deferred().resolve(object.value);
			}
		}
		return getAllStubTemplates().then(function (array) {
			if (array.length > 0 && window.localStorage !== undefined) {
				try {
					window.localStorage.setItem('allStubTemplates', JSON.stringify({
						value: array,
						timestamp: new Date().getTime()
					}));
				} catch(ignore) {}
			}
			return array;
		});
	}

	function getParsedTemplate(template) {
		return new mw.Api().post({
			action: 'parse',
			text: '{' + '{' + template + '}}',
			contentmodel: 'wikitext',
			prop: 'text'
		}).then(function (data) { return data.parse.text['*']; });
	}

	$.when($.ready, mw.loader.using('oojs-ui')).then(function () {
		$('#ca-stub-adder').remove();
		$(mw.util.addPortletLink('p-cactions', '#', 'خرد', 'ca-stub-adder', 'افزودن الگوی خرد')).click(function (e) {
			e.preventDefault();
			
			var stubSelect = $('<select>', {
				style: 'padding: 1px; vertical-align: baseline; font-family: inherit',
				html: '<option value="" selected="selected">در حال بارگیری فهرست الگوها، کمی درنگ کنید</option>'
			});
			var asboxPreviewPlaceholder = $('<div>', { style: 'padding-top: 1em; height: 3em' });
			
			var form = $('<div>', {
				style: 'position: relative;'
			}).append($('<div>', {
				style: 'margin-top: 0.4em;',
				html: 'انتخاب الگوی خرد: '
			}).append(stubSelect, asboxPreviewPlaceholder));
			
			// Hack
			mw.util.addCSS('.oo-ui-window-frame { width: 600px!important; }');
			
			OO.ui.confirm(form).then(function (confirmed) {
				if (!confirmed) return;
	
				var template = stubSelect.val();
				if (!template) { return; }
				
				mw.notify('افزودن الگوی خرد…');
	
				loadPage().then(function (content) {
					content = content.replace(
						new RegExp('{' + '{\\s*([^:}]*:)?(خرد|ناقص|' + mw.RegExp.escape(template) + ')\\s*}}\\n*', 'g'),
						''
					).replace(/\n+$/, '');
					if (!/خرد\}\}$/.test(content)) {
						content = content + '\n\n';
					}
					return savePage('افزودن الگوی خرد به کمک ابزار', content + '\n' + '{' + '{' + template + '}}');
				}).then(function (data) {
					if (data.edit.result === 'Success') {
						window.location.reload();
					} else {
						mw.notify('Unknown result from API.');
					}
				}, function () {
					mw.notify('Edit failed.');
				});
			});
	
			cachedGetAllStubTemplates().then(function (stubs) {
				stubs = stubs
					.filter(function (x) { return x !== 'الگو:خرد'; })
					.filter(function (x) {
						return !/^الگو:(\w|فرودگاه-)/.exec(x);
					});
				stubs.push('');
				stubs.sort(customComparator);
				stubSelect.empty().change(function () {
					var template = stubSelect.val();
					if (!template) {
						asboxPreviewPlaceholder.html('');
						return;
					}
					asboxPreviewPlaceholder.html('<center><img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" /></center>');
					getParsedTemplate(template).then(function (html) {
						asboxPreviewPlaceholder.html(html);
					});
				}).append($.map(stubs, function (value) {
					return $('<option>', {
						html: value.replace(/^[^:]*:/, ""),
						val: value.replace(/^[^:]*:/, "")
					});
				}));
			});
		});
	});
}(jQuery, mediaWiki));