MediaWiki:Common-base.js

From Commons Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * Shared script used by other wikis.
 *
 */

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
floating-scroll v3.2.0
https://amphiluke.github.io/floating-scroll/
(c) 2022 Amphiluke
*/
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).jQuery)}(this,(function(t){"use strict";var i="horizontal",n="vertical",e={init:function(t,n){var e=this;e.orientationProps=function(t){var n=t===i;return{ORIENTATION:t,SIZE:n?"width":"height",X_SIZE:n?"height":"width",OFFSET_SIZE:n?"offsetWidth":"offsetHeight",OFFSET_X_SIZE:n?"offsetHeight":"offsetWidth",CLIENT_SIZE:n?"clientWidth":"clientHeight",CLIENT_X_SIZE:n?"clientHeight":"clientWidth",INNER_X_SIZE:n?"innerHeight":"innerWidth",SCROLL_SIZE:n?"scrollWidth":"scrollHeight",SCROLL_POS:n?"scrollLeft":"scrollTop",START:n?"left":"top",X_START:n?"top":"left",X_END:n?"bottom":"right"}}(n);var o=t.closest(".fl-scrolls-body");o.length&&(e.scrollBody=o),e.container=t[0],e.visible=!0,e.initWidget(),e.updateAPI(),e.addEventHandlers(),e.skipSyncContainer=e.skipSyncWidget=!1},initWidget:function(){var i=this,n=i.orientationProps,e=n.ORIENTATION,o=n.SIZE,r=n.SCROLL_SIZE,c=i.widget=t('<div class="fl-scrolls" data-orientation="'+e+'"></div>');t("<div></div>").appendTo(c)[o](i.container[r]),c.appendTo(i.container)},addEventHandlers:function(){var i=this;(i.eventHandlers=[{$el:t(window),handlers:{"destroyDetached.fscroll":function(t){"fscroll"===t.namespace&&i.destroyDetachedAPI()}}},{$el:i.scrollBody||t(window),handlers:{scroll:function(){i.updateAPI()},resize:function(){i.updateAPI()}}},{$el:i.widget,handlers:{scroll:function(){i.visible&&!i.skipSyncContainer&&i.syncContainer(),i.skipSyncContainer=!1}}},{$el:t(i.container),handlers:{scroll:function(){i.skipSyncWidget||i.syncWidget(),i.skipSyncWidget=!1},focusin:function(){setTimeout((function(){i.widget&&i.syncWidget()}),0)},"update.fscroll":function(t){"fscroll"===t.namespace&&i.updateAPI()},"destroy.fscroll":function(t){"fscroll"===t.namespace&&i.destroyAPI()}}}]).forEach((function(t){var i=t.$el,n=t.handlers;return i.bind(n)}))},checkVisibility:function(){var t=this,i=t.widget,n=t.container,e=t.scrollBody,o=t.orientationProps,r=o.SCROLL_SIZE,c=o.OFFSET_SIZE,l=o.X_START,s=o.X_END,d=o.INNER_X_SIZE,a=o.CLIENT_X_SIZE,f=i[0][r]<=i[0][c];if(!f){var h=n.getBoundingClientRect(),u=e?e[0].getBoundingClientRect()[s]:window[d]||document.documentElement[a];f=h[s]<=u||h[l]>u}t.visible===f&&(t.visible=!f,i.toggleClass("fl-scrolls-hidden"))},syncContainer:function(){var t=this,i=t.orientationProps.SCROLL_POS,n=t.widget[0][i];t.container[i]!==n&&(t.skipSyncWidget=!0,t.container[i]=n)},syncWidget:function(){var t=this,i=t.orientationProps.SCROLL_POS,n=t.container[i];t.widget[0][i]!==n&&(t.skipSyncContainer=!0,t.widget[0][i]=n)},updateAPI:function(){var i=this,n=i.orientationProps,e=n.SIZE,o=n.X_SIZE,r=n.OFFSET_X_SIZE,c=n.CLIENT_SIZE,l=n.CLIENT_X_SIZE,s=n.SCROLL_SIZE,d=n.START,a=i.widget,f=i.container,h=i.scrollBody,u=f[c],S=f[s];a[e](u),h||a.css(d,f.getBoundingClientRect()[d]+"px"),t("div",a)[e](S),S>u&&a[o](a[0][r]-a[0][l]+1),i.syncWidget(),i.checkVisibility()},destroyAPI:function(){var t=this;t.eventHandlers.forEach((function(t){var i=t.$el,n=t.handlers;return i.unbind(n)})),t.widget.remove(),t.eventHandlers=t.widget=t.container=t.scrollBody=null},destroyDetachedAPI:function(){t.contains(document.body,this.container)||this.destroyAPI()}};t.fn.floatingScroll=function(o,r){if(void 0===o&&(o="init"),void 0===r&&(r={}),"init"===o){var c=r.orientation,l=void 0===c?i:c;if(l!==i&&l!==n)throw new Error("Scrollbar orientation should be either “horizontal” or “vertical”");this.each((function(i,n){return Object.create(e).init(t(n),l)}))}else Object.prototype.hasOwnProperty.call(e,o+"API")&&this.trigger(o+".fscroll");return this},t((function(){t("body [data-fl-scrolls]").each((function(i,n){var e=t(n);e.floatingScroll("init",e.data("flScrolls")||{})}))}))}));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * common l10nFactory
 */
var l10nFactory = function($lang, $data) {
	return function ($key) {
		return $data[$key] && ($data[$key][$lang] || $data[$key]['en']) || '';
	};
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * common helper
 */
var isEditorActive = function() {
	var urlParams = new URLSearchParams(window.location.search);
	return (
		urlParams.get("action") === "edit" ||
		urlParams.get("action") === "submit" ||
		urlParams.get("veaction") === "edit" ||
		urlParams.get("veaction") === "editsource" ||
		urlParams.get("veaction") === "submit"
	);
};


///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Handle wide tables
 *
 * Display a horizontal floating scroll bar when the table width exceeds the page width.
 */
/**
 * Handle wide tables
 *
 * Display a horizontal floating scroll bar when the table width exceeds the page width.
 */
$.when($.ready, mw.loader.using(['mediawiki.util'])).then( function() {
	var TABLE_WIDE_CLASS = "table-wide";
	var TABLE_WIDE_INNER_CLASS = "table-wide-inner";

	var handleWideTables = function(tables) {
		var handler = mw.util.debounce(100, function() {
			if(!tables){
				return;
			}
			tables.forEach(function(table) {
				var $table = $(table);
				if(!$table.data('container')){
					$table.data('container', table.parentNode);
				}
				var container = $table.data('container');
				if(!container){
					return;
				}
				var $innerBox = $table.parent();
				var $outerBox = $innerBox.parent();
				var overwide = table.getBoundingClientRect().width > container.getBoundingClientRect().width;
				if($outerBox.hasClass(TABLE_WIDE_CLASS)){
					if(overwide){
						$innerBox.floatingScroll("update");
					}else{
						$outerBox.before($table).remove();
					}
				}else{
					if(overwide) {
						$('<div/>').addClass(TABLE_WIDE_INNER_CLASS).appendTo(
							$('<div/>').addClass(TABLE_WIDE_CLASS).insertBefore($table)
						).append($table).floatingScroll("init").floatingScroll("update");
					}
				}
			});
		});
		handler();
		$(window).on('load', handler).on('resize', handler);
	};

	mw.hook("wikipage.content").add(function() {
		if (!isEditorActive()) {
			var el = document.querySelector("#bodyContent");
			if (el) {
				handleWideTables(el.querySelectorAll("table"));
				$(window).on('resize', function(){
					handleWideTables(el.querySelectorAll("table"));
				});
			}
		}
	});
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Disable #mw-head collapsing
 * Hack from ARK
 */
mw.loader.using('skins.vector.legacy.js', function() {
	$.collapsibleTabs.handleResize = function () {};
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Make sidebar sections collapsible
 */
$(function(){
	$root = $(':root');
	$panel = $('#mw-panel');
	$portals = $("#mw-panel .portal");
	var s = function(){
		$portals.each(function(index, el){
			var $el = $(el);
			var $id = $el.attr("id");
			if(!$id){
				return;
			}
			// for < 1366px
			$el.removeClass('expanded');
			// for >= 1366px
			if(localStorage.getItem('sidebar_c_'+$id) === "y"){
				$el.addClass('collapsed').find('.body').slideUp(0);
			}
		});
	}
	s();
	$(window).on('resize', s);
	$portals.on("click", "h3", function(event){
		var $el = $(this).parent();
		var $id = $el.attr("id");
		if(!$id){
			return;
		}
		event.stopPropagation();
		var styles = getComputedStyle($root[0]);
		//Note: jQuery's .css() can not handle inexistent custom property properly.
		var sidebarWidth = parseInt(styles.getPropertyValue('--layout-sidebar-width')||styles.getPropertyValue('--main-layout-sidebar-width')) || 250;
		if($panel.width() <= sidebarWidth){
			$el.toggleClass('collapsed');
			if($el.hasClass('collapsed')){ // more consistent between class and slide status.
				localStorage.setItem('sidebar_c_'+$id, "y");
				$el.find('.body').slideUp('fast');
			}
			else{
				localStorage.setItem('sidebar_c_'+$id, "n");
				$el.find('.body').slideDown('fast');
			}
		}
		else{
			$("#mw-panel .portal").not($el).removeClass('expanded');
			$el.toggleClass('expanded');
		}
	});
});


///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * login status mark
 */
$(function(){
	if(mw.config.get("wgUserName") !== null){
		$('body').addClass('logged-in');
	}
	else{
		$('body').addClass('not-logged-in');
	}
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Content box customization
 */
$(function() {
	/* Disable triggering of new browser tab when clicking URL links that point to internal wiki addresses (purge, edit, etc) */
	$('a[href^="//'+window.location.hostname+'/"]').removeAttr('target');

	/* Hyperlink required modules in Module namespace */
	// Author: RheingoldRiver
	if (mw.config.get('wgCanonicalNamespace') === 'Module') {
		$('.s1, .s2').each(function () {
			var html = $(this).html();
			// the module name is surrounded by quotes, so we have to remove them
			var quote = html[0];
			var quoteRE = new RegExp('^' + quote + '|' + quote + '$', 'g');
			var name = html.replace(quoteRE, ""); // remove quotes
			// link the module name
			if (name.startsWith("Module:")) {
				var target = encodeURIComponent(name);
				var url = mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=' + target;
				$(this).html(quote + '<a href="' + url + '">' + name + '</a>' + quote);
			}
		});
	}
});