MediaWiki:Script/Popup.js

ХӀара гӀирс Википеди чуьра бу — маьрша энциклопеди

Билгалдаккхар: Ӏалашйинчул тӀаьхьа хийцамаш га браузеран кэш цӀанйан йезаш хила мега.

  • Firefox / Safari: Shift тӀетаӀийна йитина, гӀирсийн панелан тӀера тӀетаӀайе Карлайаккха йа Ctrl+F5 йа Ctrl+R (⌘+R Mac тӀехь)
  • Google Chrome: тӀетаӀайе Ctrl+Shift+R (⌘+Shift+R Mac тӀехь)
  • Internet Explorer / Edge: тӀетаӀийна йитина Ctrl, тӀетаӀайе Карлайаккха йа тӀетаӀайе Ctrl+F5
  • Opera: тӀетаӀайе Ctrl+F5.
/*
 * По идее и с теоретической помощью участника:Serhio Magpie, с благодарностью.
 * Создание попапов с заранее заданным содержимым при нажатии на кнопку-ссылку на странице.
 * Этот скрипт создан для шаблонов Интерактивных схем метрополитена,
 * но им можно пользоваться и для создания попапа в других случаях.
 */

if ($('.popup-extend').length)
	$(function() {
		var api,
			links,
			windowManager,
			allwayslinks,
			change = {},
			userLanguage = mw.config.get('wgUserLanguage');
		const pairs = [
			['&lt;templatestyles ', '<templatestyles '],
			['&lt;span ', '<span '],
			['&lt;div ', '<div '],
			['&lt;/', '</'],
			['&#039;', "'"],
			['&gt;', '>']
		];

		function showPage(event) {
			var cur = $(event.currentTarget).closest('.popup-table').find('.imgtogglemini'),
				version = mw.html.escape(cur.data('version'));
			windowManager.getWindow(version).then(function() {
					openWindow(version);
				})
				.fail(function() {
					var proposed, pagename = mw.html.escape(cur.data('pagename')),
						qr = cur.data('query'),
						width = window.innerWidth;
					Object.keys(qr).forEach(function(item) {
						qr[item] = mw.html.escape(qr[item]);
						Object.values(pairs).forEach(function(value) {
							qr[item] = qr[item].replaceAll(value[0], value[1]);
						});
					});
					var imagewidth = Math.floor(Math.max(width * 0.6,
						Number(mw.html.escape('' + cur.data('width')))));
					var minwidth = Number(mw.html.escape('' + cur.data('textwidth')));
					change[version] = (imagewidth + minwidth < width) ? imagewidth : false;
					var curpopup = '.popup-version-opened-' + version;
					api.get({
							action: 'parse',
							contentmodel: 'wikitext',
							text: qr[0] + '|pagename=' + pagename + '|language=' + userLanguage +
								'|width=' + imagewidth + qr[1],
							prop: 'text',
							format: 'json',
							formatversion: 2
						})
						.done(function(data) {
							var pd = createPopup(pagename, data.parse.text, version);
							openWindow(version, width, function() {
								if (change[version]) {
									waitForElm(curpopup + ' .mw-collapsible').then(function(coll) {
										var div = $(coll).parent().children().first().children().first().next(),
											shrink = $('.popup-version-opened-' + version +
												' .shrink').css('test-align', 'center');
										div.css({
											width: Number(div.css('width').match(/\d+/)[0]) + 20,
											maxHeight: (proposed = (window.innerHeight - pd.getContentHeight() +
												pd.getBodyHeight() - Math.floor(3.5 *
													$(($(coll).closest('table').find('tr'))[0]).height()))) + shrink.height(),
											overflowY: 'auto'
										});
										$(coll).css({
											maxHeight: proposed - 15,
											overflowY: 'auto'
										});
										$(coll).wrap($('<td>')).parent().after(shrink).after($('<hr>'));
										if (coll.clientWidth < minwidth + 6) {
											$(coll).css({
												clear: 'both',
												maxHeight: 'none',
												overflowY: 'inherit'
											});
											div.css({
												maxHeight: 'none',
												overflowY: 'inherit'
											});
											$(curpopup).find('.noresize').css('float', 'inherit');
										}
									});
								}
								mw.util.addCSS('.popup-' + version +
									' .mw-collapsible-toggle {display:none;}');
							});
						});
				});
		}

		function createPopup(title, content, version) {
			var dialog, ProcessDialog = function(config) {
				ProcessDialog.super.call(this, config);
			};
			OO.inheritClass(ProcessDialog, OO.ui.ProcessDialog);
			ProcessDialog.static.name = 'myDialog';
			ProcessDialog.static.title = title;
			ProcessDialog.static.actions = [{
					action: 'close',
					modes: ['normal', 'small'],
					label: mw.msg('centralnotice-close-title'),
					flags: 'safe'
				},
				{
					action: 'shrink',
					modes: 'normal',
					label: mw.msg('visualeditor-expandable-less'),
					flags: 'primary'
				},
				{
					action: 'expand',
					modes: 'small',
					label: mw.msg('visualeditor-expandable-more'),
					flags: 'primary'
				}
			];
			ProcessDialog.prototype.initialize = function() {
				ProcessDialog.super.prototype.initialize.apply(this, arguments);
				this.content = new OO.ui.PanelLayout({
					padded: true,
					expanded: false
				});
				this.content.$element.append(content);
				this.$body.append(this.content.$element);
				ProcessDialog.prototype.getSetupProcess = function(data) {
					return ProcessDialog.super.prototype.getSetupProcess.call(this, data)
						.next(function() {
							this.actions.setMode('normal');
							setSize(version, 'full');
						}, this);
				};
			};
			ProcessDialog.prototype.getActionProcess = function(action) {
				var dialog = this;
				if (action == 'close') {
					toggleColor(version);
					return new OO.ui.Process(function() {
						dialog.close({
							action: 'close'
						});
					});
				}
				if (action) {
					this.actions.setMode(action == 'shrink' ? 'small' : 'normal');
					setSize(version, action == 'shrink' ? 'large' : 'full');
				}
				return ProcessDialog.super.prototype.getActionProcess.call(this, action);
			};
			windowManager.addWindows({
				[version]: (dialog = new ProcessDialog({
					classes: ['popup-window', 'popup-' + version]
				}))
			});
			var shrink = $('.popup-' + version).find('.shrink');
			shrink.html($('<a>').html(shrink.html()));
			shrink.click(function() {
				toggleColor(version);
				windowManager.closeWindow(version);
			});
			return dialog;
		}

		function waitForElm(selector) {
			return new Promise(function(resolve) {
				if (document.querySelector(selector)) {
					return resolve(document.querySelector(selector));
				}

				const observer = new MutationObserver(function() {
					if (document.querySelector(selector)) {
						resolve(document.querySelector(selector));
						observer.disconnect();
					}
				});

				observer.observe(document.body, {
					childList: true,
					subtree: true
				});
			});
		}

		function changelist(version, maxwidth) {
			var cur = $('.popup-version-opened-' + version);
			cur.find('ol').addClass('hlist');
			if (change[version]) {
				var des = cur.find('*'),
					popup = cur.find('.popupclass');
				des.each(function(data) {
					var item = $(des[data]);
					if (item.css('clear') == 'both')
						item.css('clear', 'inherit');
					if (item.css('max-width') != 'none')
						item.css('max-width', '');
				});
				popup.find('hr').remove();
				popup.find('.noresize').css('float', 'left');
				popup.parent().css('width', Math.floor(Math.max(maxwidth * 0.96, change[version])));
			}
		}

		function setSize(version, size) {
			windowManager.getWindow(version).then(function(data) {
				data.setSize(size);
			});
		}

		function openWindow(version, width, callback) {
			windowManager.openWindow(version)
				.opened.then(function() {
					$('body').trigger('refresh-imagehighlight-' + (links ? 'links' : 'nolinks'));
					if (width)
						changelist(version, width);
					if (callback)
						callback();
				});
		}

		function toggleColor(version) {
			var curclick = $('.popup-version-' + version),
				coll = $('.popup-version-opened-' + version).find('.mw-made-collapsible')
				.hasClass('mw-collapsed');
			curclick.find('.popup-extend-' + (coll ? 'nolinks' : 'links')).addClass('popup-history');
			curclick.find('.popup-extend-' + (coll ? 'links' : 'nolinks')).removeClass('popup-history');
		}

		function createcallback(value) {
			return function() {
				var cur = $(this);
				cur.html($('<a>').html(cur.html()));
				cur.click(function(event) {
					if (!windowManager) {
						windowManager = new OO.ui.WindowManager();
						$(document.body).append(windowManager.$element);
					}
					links = value;
					showPage(event);
				});
			};
		}

		mw.loader.using(['mediawiki.util', 'mediawiki.api', 'oojs', 'oojs-ui'])
			.then(function() {
				if (!$('.skin-minerva').length)
					$('.popup-placeholder').remove();
				api = new mw.Api();
				mw.util.addCSS('.popup-history {background: #c6f6c6;}');
				api.loadMessagesIfMissing(['centralnotice-close-title', 'visualeditor-expandable-less',
					'visualeditor-expandable-more'
				], {
					amlang: userLanguage
				}).then(function() {
					if ($('.popup-extend-links').length) {
						$('.popup-extend-links').each(createcallback(true));
						$('.popup-extend-nolinks').each(createcallback(false));
					} else {
						$('.popup-extend-nolinks').each(createcallback(true));
						allwayslinks = true;
					}
				});
			});
	});