MediaWiki:Common.js: Difference between revisions

From Acadēmīa Latīnitātis
(Created page with "/** * Keep code in MediaWiki:Common.js to a minimum as it is unconditionally * loaded for all users on every wiki page. If possible create a gadget that is * enabled by default instead of adding it here (since gadgets are fully * optimized ResourceLoader modules with possibility to add dependencies etc.) * * Since Common.js isn't a gadget, there is no place to declare its * dependencies, so we have to lazy load them with mw.loader.using on demand and * then execu...")
 
No edit summary
Line 12: Line 12:
  */
  */


/* global mw, $ */
( function () {
/* jshint strict:false, browser:true */
/**
* Handler for a click on a collapsible toggler.
*
* @private
* @param {jQuery} $collapsible
* @param {string} action The action this function will take ('expand' or 'collapse').
* @param {jQuery|null} [$defaultToggle]
* @param {Object|undefined} [options]
*/
function toggleElement( $collapsible, action, $defaultToggle, options ) {
options = options || {};
 
// Validate parameters
 
// $collapsible must be an instance of jQuery
if ( !$collapsible.jquery ) {
return;
}
if ( action !== 'expand' && action !== 'collapse' ) {
// action must be string with 'expand' or 'collapse'
return;
}
if ( $defaultToggle === undefined ) {
$defaultToggle = null;
}
 
// Trigger a custom event to allow callers to hook to the collapsing/expanding,
// allowing the module to be testable, and making it possible to
// e.g. implement persistence via cookies
$collapsible.trigger( action === 'expand' ? 'beforeExpand.mw-collapsible' : 'beforeCollapse.mw-collapsible' );
var hookCallback = function () {
$collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
};


mw.loader.using( [ 'mediawiki.util' ] ).done( function () {
// Handle different kinds of elements
/* Begin of mw.loader.using callback */
var $containers;
if ( !options.plainMode && $collapsible.is( 'table' ) ) {
// Tables
// If there is a caption, hide all rows; otherwise, only hide body rows
if ( $collapsible.find( '> caption' ).length ) {
$containers = $collapsible.find( '> * > tr' );
} else {
$containers = $collapsible.find( '> tbody > tr' );
}
if ( $defaultToggle ) {
// Exclude table row containing togglelink
$containers = $containers.not( $defaultToggle.closest( 'tr' ) );
}


/**
} else if ( !options.plainMode && ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) ) {
* Map addPortletLink to mw.util
// Lists
* @deprecated: Use mw.util.addPortletLink instead.
$containers = $collapsible.find( '> li' );
*/
if ( $defaultToggle ) {
mw.log.deprecate( window, 'addPortletLink', mw.util.addPortletLink, 'Use mw.util.addPortletLink instead' );
// Exclude list-item containing togglelink
$containers = $containers.not( $defaultToggle.parent() );
}
} else {
// Everything else: <div>, <p> etc.
var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
 
// If a collapsible-content is defined, act on it
if ( !options.plainMode && $collapsibleContent.length ) {
$containers = $collapsibleContent;
 
// Otherwise assume this is a customcollapse with a remote toggle
// .. and there is no collapsible-content because the entire element should be toggled
} else {
$containers = $collapsible;
}
}
 
$containers.toggle( action === 'expand' );
hookCallback();
}


/**
/**
* Test if an element has a certain class
* Handle clicking/keypressing on the collapsible element toggle and other
* @deprecated:  Use $(element).hasClass() instead.
* situations where a collapsible element is toggled (e.g. the initial
* toggle for collapsed ones).
*
* @private
* @param {jQuery} $toggle the clickable toggle itself
* @param {jQuery} $collapsible the collapsible element
* @param {jQuery.Event|null} e either the event or null if unavailable
* @param {Object|undefined} options
*/
*/
mw.log.deprecate( window, 'hasClass', function ( element, className ) {
function togglingHandler( $toggle, $collapsible, e, options ) {
return $( element ).hasClass( className );
options = options || {};
}, 'Use jQuery.hasClass() instead' );


/**
if ( e ) {
* @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
if (
* @rev 6
e.type === 'click' &&
*/
e.target.nodeName.toLowerCase() === 'a' &&
var extraCSS = mw.util.getParamValue( 'withCSS' ),
$( e.target ).attr( 'href' )
extraJS = mw.util.getParamValue( 'withJS' );
) {
// Don't fire if a link was clicked (for premade togglers)
return;
} else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
// Only handle keypresses on the "Enter" or "Space" keys
return;
} else {
e.preventDefault();
e.stopPropagation();
}
}


if ( extraCSS ) {
// This allows the element to be hidden on initial toggle without fiddling with the class
if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
var wasCollapsed;
mw.loader.load( '/w/index.php?title=' + extraCSS + '&action=raw&ctype=text/css', 'text/css' );
if ( options.wasCollapsed !== undefined ) {
wasCollapsed = options.wasCollapsed;
} else {
} else {
mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
// eslint-disable-next-line no-jquery/no-class-state
wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
}
 
// Toggle the state of the collapsible element (that is, expand or collapse)
$collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
 
// Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
if ( options.toggleClasses ) {
$toggle
.toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
.toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
}
 
// Toggle `aria-expanded` attribute, if requested (for default and premade togglers by default).
if ( options.toggleARIA ) {
$toggle.attr( 'aria-expanded', wasCollapsed ? 'true' : 'false' );
}
}
}


if ( extraJS ) {
// Toggle the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
if ( options.toggleText ) {
mw.loader.load( '/w/index.php?title=' + extraJS + '&action=raw&ctype=text/javascript' );
var collapseText = options.toggleText.collapseText;
} else {
var expandText = options.toggleText.expandText;
mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
 
var $textContainer = $toggle.find( '.mw-collapsible-text' );
if ( $textContainer.length ) {
$textContainer.text( wasCollapsed ? collapseText : expandText );
}
}
}
// And finally toggle the element state itself
toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
}
}


/**
/**
* WikiMiniAtlas
* If the URL contains a hash followed by the fragment identifier of an
* element inside collapsed parents, expand them all and scroll to it.
*
*
* Description: WikiMiniAtlas is a popup click and drag world map.
* @private
*              This script causes all of our coordinate links to display the WikiMiniAtlas popup button.
*              The script itself is located on the Meta-Wiki because it is used by many projects.
*              See [[Meta:WikiMiniAtlas]] for more information.
* Note - use of this service is recommended to be replaced with mw:Help:Extension:Kartographer
*/
*/
$( function () {
function hashHandler() {
var requireWikiminiatlas = $( 'a.external.text[href*="geohack"]' ).length || $( 'div.kmldata' ).length;
var fragment = mw.util.getTargetFromFragment();
if ( requireWikiminiatlas ) {
if ( !fragment ) {
mw.loader.load( '//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript' );
// The fragment doesn't exist
return;
}
}
} );


/**
var $parents = $( fragment ).parents( '.mw-collapsed' );
* Collapsible tables; reimplemented with mw-collapsible
if ( !$parents.length ) {
* Styling is also in place to avoid FOUC
// The fragment is not in a collapsed element
*
return;
* Allows tables to be collapsed, showing only the header. See [[Help:Collapsing]].
}
* @version 3.0.0 (2018-05-20)
* @source https://www.mediawiki.org/wiki/MediaWiki:Gadget-collapsibleTables.js
* @author [[User:R. Koot]]
* @author [[User:Krinkle]]
* @author [[User:TheDJ]]
* @deprecated Since MediaWiki 1.20: Use class="mw-collapsible" instead which
* is supported in MediaWiki core. Shimmable since MediaWiki 1.32
*
* @param {jQuery} $content
*/
function makeCollapsibleMwCollapsible( $content ) {
var $tables = $content
.find( 'table.collapsible:not(.mw-collapsible)' )
.addClass( 'mw-collapsible' );


$.each( $tables, function ( index, table ) {
// Expand collapsed parents
// mw.log.warn( 'This page is using the deprecated class collapsible. Please replace it with mw-collapsible.');
$parents.each( function () {
if ( $( table ).hasClass( 'collapsed' ) ) {
var $collapsible = $( this );
$( table ).addClass( 'mw-collapsed' );
if ( $collapsible.data( 'mw-made-collapsible' ) ) {
// mw.log.warn( 'This page is using the deprecated class collapsed. Please replace it with mw-collapsed.');
$collapsible.data( 'mw-collapsible' ).expand();
} else {
// The collapsible has not been initialized, so just prevent it
// from being collapsed
$collapsible.removeClass( 'mw-collapsed' );
}
}
} );
} );
if ( $tables.length > 0 ) {
 
mw.loader.using( 'jquery.makeCollapsible' ).then( function () {
// Scroll to the fragment
$tables.makeCollapsible();
fragment.scrollIntoView();
} );
}
}
}
mw.hook( 'wikipage.content' ).add( makeCollapsibleMwCollapsible );


/**
/**
* Add support to mw-collapsible for autocollapse, innercollapse and outercollapse
* Enable collapsible-functionality on all elements in the collection.
*
* - Will prevent binding twice to the same element.
* - Initial state is expanded by default, this can be overridden by adding class
*  "mw-collapsed" to the "mw-collapsible" element.
* - Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
* - The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).
*
*
* Maintainers: TheDJ
* @param {Object} [options]
* @param {string} [options.collapseText] Text used for the toggler, when clicking it would
*  collapse the element. Default: the 'data-collapsetext' attribute of the
*  collapsible element or the content of 'collapsible-collapse' message.
* @param {string} [options.expandText] Text used for the toggler, when clicking it would
*  expand the element. Default: the 'data-expandtext' attribute of the
*  collapsible element or the content of 'collapsible-expand' message.
* @param {boolean} [options.collapsed] Whether to collapse immediately. By default
*  collapse only if the element has the 'mw-collapsed' class.
* @param {jQuery} [options.$customTogglers] Elements to be used as togglers
*  for this collapsible element. By default, if the collapsible element
*  has an id attribute like 'mw-customcollapsible-XXX', elements with a
*  **class** of 'mw-customtoggle-XXX' are made togglers for it.
* @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
*  element collapsible - that is, hide entire tables and lists (instead
*  of hiding only all rows but first of tables, and hiding each list
*  item separately for lists) and don't wrap other elements in
*  div.mw-collapsible-content. May only be used with custom togglers.
* @return {jQuery}
* @chainable
*/
*/
function mwCollapsibleSetup( $collapsibleContent ) {
$.fn.makeCollapsible = function ( options ) {
var $element,
options = options || {};
$toggle,
 
autoCollapseThreshold = 2;
this.each( function () {
$.each( $collapsibleContent, function ( index, element ) {
// Ensure class "mw-collapsible" is present in case .makeCollapsible()
$element = $( element );
// is called on element(s) that don't have it yet.
if ( $element.hasClass( 'collapsible' ) ) {
var $collapsible = $( this ).addClass( 'mw-collapsible' );
$element.find( 'tr:first > th:first' ).prepend( $element.find( 'tr:first > * > .mw-collapsible-toggle' ) );
 
// Return if it has been enabled already.
if ( $collapsible.data( 'mw-made-collapsible' ) ) {
return;
} else {
// Let CSS know that it no longer needs to worry about flash of unstyled content.
// This will allow mediawiki.makeCollapsible.styles to disable temporary pseudo elements, that
// are needed to avoid a flash of unstyled content.
$collapsible.addClass( 'mw-made-collapsible' )
.data( 'mw-made-collapsible', true );
}
}
if ( $collapsibleContent.length >= autoCollapseThreshold && $element.hasClass( 'autocollapse' ) ) {
 
$element.data( 'mw-collapsible' ).collapse();
// Use custom text or default?
} else if ( $element.hasClass( 'innercollapse' ) ) {
var collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
if ( $element.parents( '.outercollapse' ).length > 0 ) {
var expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
$element.data( 'mw-collapsible' ).collapse();
 
// Default click/keypress handler and toggle link to use when none is present
var actionHandler = function ( e, opts ) {
var defaultOpts = {
toggleClasses: true,
toggleARIA: true,
toggleText: { collapseText: collapseText, expandText: expandText }
};
opts = $.extend( defaultOpts, options, opts );
togglingHandler( $( this ), $collapsible, e, opts );
};
 
// Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
var buildDefaultToggleLink = function () {
return $( '<a>' )
.addClass( 'mw-collapsible-text' )
.text( collapseText )
.wrap( '<span class="mw-collapsible-toggle mw-collapsible-toggle-default"></span>' )
.parent()
.attr( {
role: 'button',
tabindex: 0
} );
};
 
// Check if this element has a custom position for the toggle link
// (ie. outside the container or deeper inside the tree)
var $customTogglers;
if ( options.$customTogglers ) {
$customTogglers = $( options.$customTogglers );
} else {
var collapsibleId = $collapsible.attr( 'id' ) || '';
if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
collapsibleId = $.escapeSelector( collapsibleId );
$customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
.addClass( 'mw-customtoggle' );
}
}
}
}
// because of colored backgrounds, style the link in the text color
 
// to ensure accessible contrast
// Add event handlers to custom togglers or create our own ones
$toggle = $element.find( '.mw-collapsible-toggle' );
var $toggle;
if ( $toggle.length ) {
if ( $customTogglers && $customTogglers.length ) {
// Make the toggle inherit text color
actionHandler = function ( e, opts ) {
if ( $toggle.parent()[ 0 ].style.color ) {
var defaultOpts = {};
$toggle.find( 'a' ).css( 'color', 'inherit' );
opts = $.extend( defaultOpts, options, opts );
togglingHandler( $( this ), $collapsible, e, opts );
};
 
$toggle = $customTogglers;
 
} else {
// If this is not a custom case, do the default: wrap the
// contents and add the toggle link. Different elements are
// treated differently.
 
var $firstItem;
if ( $collapsible.is( 'table' ) ) {
 
// If the table has a caption, collapse to the caption
// as opposed to the first row
var $caption = $collapsible.find( '> caption' );
if ( $caption.length ) {
$toggle = $caption.find( '> .mw-collapsible-toggle' );
 
// If there is no toggle link, add it to the end of the caption
if ( !$toggle.length ) {
$toggle = buildDefaultToggleLink().appendTo( $caption );
}
} else {
// The toggle-link will be in one of the cells (td or th) of the first row
$firstItem = $collapsible.find( 'tr' ).first().find( 'th, td' );
$toggle = $firstItem.find( '> .mw-collapsible-toggle' );
 
// If theres no toggle link, add it to the last cell
if ( !$toggle.length ) {
$toggle = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
}
}
 
} else if ( $collapsible.parent().is( 'li' ) &&
$collapsible.parent().children( '.mw-collapsible' ).length === 1 &&
$collapsible.find( '> .mw-collapsible-toggle' ).length === 0
) {
// special case of one collapsible in <li> tag
$toggle = buildDefaultToggleLink();
$collapsible.before( $toggle );
} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
// The toggle-link will be in the first list-item
$firstItem = $collapsible.find( 'li' ).first();
$toggle = $firstItem.find( '> .mw-collapsible-toggle' );
 
// If theres no toggle link, add it
if ( !$toggle.length ) {
// Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
// to be "1". Except if the value-attribute is already used.
// If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
var firstval = $firstItem.prop( 'value' );
if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
$firstItem.prop( 'value', '1' );
}
$toggle = buildDefaultToggleLink();
$toggle.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
}
 
} else { // <div>, <p> etc.
 
// The toggle-link will be the first child of the element
$toggle = $collapsible.find( '> .mw-collapsible-toggle' );
 
// If a direct child .content-wrapper does not exists, create it
if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
$collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
}
 
// If theres no toggle link, add it
if ( !$toggle.length ) {
$toggle = buildDefaultToggleLink().prependTo( $collapsible );
}
}
}
}
}
} );
}


mw.hook( 'wikipage.collapsibleContent' ).add( mwCollapsibleSetup );
// Attach event handlers to togglelink
$toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
.attr( 'aria-expanded', 'true' )
.prop( 'tabIndex', 0 );


/**
$( this ).data( 'mw-collapsible', {
* Magic editintros ****************************************************
collapse: function () {
*
actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
* Description: Adds editintros on disambiguation pages and BLP pages.
},
* Maintainers: [[User:RockMFR]]
expand: function () {
*
actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: true } );
* @param {string} name
},
*/
toggle: function () {
function addEditIntro( name ) {
actionHandler.call( $toggle.get( 0 ), null, null );
$( '.mw-editsection, #ca-edit, #ca-ve-edit' ).find( 'a' ).each( function ( i, el ) {
}
el.href = $( this ).attr( 'href' ) + '&editintro=' + name;
} );
} );
}


if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) {
// Initial state
$( function () {
// eslint-disable-next-line no-jquery/no-class-state
if ( document.getElementById( 'disambigbox' ) ) {
if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
addEditIntro( 'Template:Disambig_editintro' );
// One toggler can hook to multiple elements, and one element can have
// multiple togglers. This is the best way to handle that.
actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
}
}
} );
} );


$( function () {
// Attach hash handler
var cats = mw.config.get( 'wgCategories' );
window.addEventListener( 'hashchange', hashHandler );
if ( !cats ) {
return;
}
if ( $.inArray( 'Living people', cats ) !== -1 || $.inArray( 'Possibly living people', cats ) !== -1 ) {
addEditIntro( 'Template:BLP_editintro' );
}
} );
}


/* Actions specific to the edit page */
if ( mw.config.get( 'wgAction' ) === 'edit' || mw.config.get( 'wgAction' ) === 'submit' ) {
/**
/**
* Fix edit summary prompt for undo
* Fired after collapsible content has been initialized
*
* This gives an option to modify the collapsible behavior.
*
*
* Fixes the fact that the undo function combined with the "no edit summary prompter"
* @event wikipage_collapsibleContent
* complains about missing editsummary, if leaving the edit summary unchanged.
* @member mw.hook
* Added by [[User:Deskana]], code by [[User:Tra]].
* @param {jQuery} $content All the elements that have been made collapsible
*  See also [[phab:T10912]].
*/
*/
$( function () {
mw.hook( 'wikipage.collapsibleContent' ).fire( this );
if ( document.location.search.indexOf( 'undo=' ) !== -1 && document.getElementsByName( 'wpAutoSummary' )[ 0 ] ) {
 
document.getElementsByName( 'wpAutoSummary' )[ 0 ].value = '1';
return this;
}
};
} );
 
}
// Run hash handler right now in case the URL already has a hash
hashHandler();
 
/**
* @class jQuery
* @mixins jQuery.plugin.makeCollapsible
*/


/* End of mw.loader.using callback */
}() );
} );
/* DO NOT ADD CODE BELOW THIS LINE */

Revision as of 18:48, 26 December 2022

/**
 * Keep code in MediaWiki:Common.js to a minimum as it is unconditionally
 * loaded for all users on every wiki page. If possible create a gadget that is
 * enabled by default instead of adding it here (since gadgets are fully
 * optimized ResourceLoader modules with possibility to add dependencies etc.)
 *
 * Since Common.js isn't a gadget, there is no place to declare its
 * dependencies, so we have to lazy load them with mw.loader.using on demand and
 * then execute the rest in the callback. In most cases these dependencies will
 * be loaded (or loading) already and the callback will not be delayed. In case a
 * dependency hasn't arrived yet it'll make sure those are loaded before this.
 */

( function () {
	/**
	 * Handler for a click on a collapsible toggler.
	 *
	 * @private
	 * @param {jQuery} $collapsible
	 * @param {string} action The action this function will take ('expand' or 'collapse').
	 * @param {jQuery|null} [$defaultToggle]
	 * @param {Object|undefined} [options]
	 */
	function toggleElement( $collapsible, action, $defaultToggle, options ) {
		options = options || {};

		// Validate parameters

		// $collapsible must be an instance of jQuery
		if ( !$collapsible.jquery ) {
			return;
		}
		if ( action !== 'expand' && action !== 'collapse' ) {
			// action must be string with 'expand' or 'collapse'
			return;
		}
		if ( $defaultToggle === undefined ) {
			$defaultToggle = null;
		}

		// Trigger a custom event to allow callers to hook to the collapsing/expanding,
		// allowing the module to be testable, and making it possible to
		// e.g. implement persistence via cookies
		$collapsible.trigger( action === 'expand' ? 'beforeExpand.mw-collapsible' : 'beforeCollapse.mw-collapsible' );
		var hookCallback = function () {
			$collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
		};

		// Handle different kinds of elements
		var $containers;
		if ( !options.plainMode && $collapsible.is( 'table' ) ) {
			// Tables
			// If there is a caption, hide all rows; otherwise, only hide body rows
			if ( $collapsible.find( '> caption' ).length ) {
				$containers = $collapsible.find( '> * > tr' );
			} else {
				$containers = $collapsible.find( '> tbody > tr' );
			}
			if ( $defaultToggle ) {
				// Exclude table row containing togglelink
				$containers = $containers.not( $defaultToggle.closest( 'tr' ) );
			}

		} else if ( !options.plainMode && ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) ) {
			// Lists
			$containers = $collapsible.find( '> li' );
			if ( $defaultToggle ) {
				// Exclude list-item containing togglelink
				$containers = $containers.not( $defaultToggle.parent() );
			}
		} else {
			// Everything else: <div>, <p> etc.
			var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );

			// If a collapsible-content is defined, act on it
			if ( !options.plainMode && $collapsibleContent.length ) {
				$containers = $collapsibleContent;

			// Otherwise assume this is a customcollapse with a remote toggle
			// .. and there is no collapsible-content because the entire element should be toggled
			} else {
				$containers = $collapsible;
			}
		}

		$containers.toggle( action === 'expand' );
		hookCallback();
	}

	/**
	 * Handle clicking/keypressing on the collapsible element toggle and other
	 * situations where a collapsible element is toggled (e.g. the initial
	 * toggle for collapsed ones).
	 *
	 * @private
	 * @param {jQuery} $toggle the clickable toggle itself
	 * @param {jQuery} $collapsible the collapsible element
	 * @param {jQuery.Event|null} e either the event or null if unavailable
	 * @param {Object|undefined} options
	 */
	function togglingHandler( $toggle, $collapsible, e, options ) {
		options = options || {};

		if ( e ) {
			if (
				e.type === 'click' &&
				e.target.nodeName.toLowerCase() === 'a' &&
				$( e.target ).attr( 'href' )
			) {
				// Don't fire if a link was clicked (for premade togglers)
				return;
			} else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
				// Only handle keypresses on the "Enter" or "Space" keys
				return;
			} else {
				e.preventDefault();
				e.stopPropagation();
			}
		}

		// This allows the element to be hidden on initial toggle without fiddling with the class
		var wasCollapsed;
		if ( options.wasCollapsed !== undefined ) {
			wasCollapsed = options.wasCollapsed;
		} else {
			// eslint-disable-next-line no-jquery/no-class-state
			wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
		}

		// Toggle the state of the collapsible element (that is, expand or collapse)
		$collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );

		// Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
		if ( options.toggleClasses ) {
			$toggle
				.toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
				.toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
		}

		// Toggle `aria-expanded` attribute, if requested (for default and premade togglers by default).
		if ( options.toggleARIA ) {
			$toggle.attr( 'aria-expanded', wasCollapsed ? 'true' : 'false' );
		}

		// Toggle the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
		if ( options.toggleText ) {
			var collapseText = options.toggleText.collapseText;
			var expandText = options.toggleText.expandText;

			var $textContainer = $toggle.find( '.mw-collapsible-text' );
			if ( $textContainer.length ) {
				$textContainer.text( wasCollapsed ? collapseText : expandText );
			}
		}

		// And finally toggle the element state itself
		toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
	}

	/**
	 * If the URL contains a hash followed by the fragment identifier of an
	 * element inside collapsed parents, expand them all and scroll to it.
	 *
	 * @private
	 */
	function hashHandler() {
		var fragment = mw.util.getTargetFromFragment();
		if ( !fragment ) {
			// The fragment doesn't exist
			return;
		}

		var $parents = $( fragment ).parents( '.mw-collapsed' );
		if ( !$parents.length ) {
			// The fragment is not in a collapsed element
			return;
		}

		// Expand collapsed parents
		$parents.each( function () {
			var $collapsible = $( this );
			if ( $collapsible.data( 'mw-made-collapsible' ) ) {
				$collapsible.data( 'mw-collapsible' ).expand();
			} else {
				// The collapsible has not been initialized, so just prevent it
				// from being collapsed
				$collapsible.removeClass( 'mw-collapsed' );
			}
		} );

		// Scroll to the fragment
		fragment.scrollIntoView();
	}

	/**
	 * Enable collapsible-functionality on all elements in the collection.
	 *
	 * - Will prevent binding twice to the same element.
	 * - Initial state is expanded by default, this can be overridden by adding class
	 *   "mw-collapsed" to the "mw-collapsible" element.
	 * - Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
	 * - The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).
	 *
	 * @param {Object} [options]
	 * @param {string} [options.collapseText] Text used for the toggler, when clicking it would
	 *   collapse the element. Default: the 'data-collapsetext' attribute of the
	 *   collapsible element or the content of 'collapsible-collapse' message.
	 * @param {string} [options.expandText] Text used for the toggler, when clicking it would
	 *   expand the element. Default: the 'data-expandtext' attribute of the
	 *   collapsible element or the content of 'collapsible-expand' message.
	 * @param {boolean} [options.collapsed] Whether to collapse immediately. By default
	 *   collapse only if the element has the 'mw-collapsed' class.
	 * @param {jQuery} [options.$customTogglers] Elements to be used as togglers
	 *   for this collapsible element. By default, if the collapsible element
	 *   has an id attribute like 'mw-customcollapsible-XXX', elements with a
	 *   **class** of 'mw-customtoggle-XXX' are made togglers for it.
	 * @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
	 *   element collapsible - that is, hide entire tables and lists (instead
	 *   of hiding only all rows but first of tables, and hiding each list
	 *   item separately for lists) and don't wrap other elements in
	 *   div.mw-collapsible-content. May only be used with custom togglers.
	 * @return {jQuery}
	 * @chainable
	 */
	$.fn.makeCollapsible = function ( options ) {
		options = options || {};

		this.each( function () {
			// Ensure class "mw-collapsible" is present in case .makeCollapsible()
			// is called on element(s) that don't have it yet.
			var $collapsible = $( this ).addClass( 'mw-collapsible' );

			// Return if it has been enabled already.
			if ( $collapsible.data( 'mw-made-collapsible' ) ) {
				return;
			} else {
				// Let CSS know that it no longer needs to worry about flash of unstyled content.
				// This will allow mediawiki.makeCollapsible.styles to disable temporary pseudo elements, that
				// are needed to avoid a flash of unstyled content.
				$collapsible.addClass( 'mw-made-collapsible' )
					.data( 'mw-made-collapsible', true );
			}

			// Use custom text or default?
			var collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
			var expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );

			// Default click/keypress handler and toggle link to use when none is present
			var actionHandler = function ( e, opts ) {
				var defaultOpts = {
					toggleClasses: true,
					toggleARIA: true,
					toggleText: { collapseText: collapseText, expandText: expandText }
				};
				opts = $.extend( defaultOpts, options, opts );
				togglingHandler( $( this ), $collapsible, e, opts );
			};

			// Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
			var buildDefaultToggleLink = function () {
				return $( '<a>' )
					.addClass( 'mw-collapsible-text' )
					.text( collapseText )
					.wrap( '<span class="mw-collapsible-toggle mw-collapsible-toggle-default"></span>' )
					.parent()
					.attr( {
						role: 'button',
						tabindex: 0
					} );
			};

			// Check if this element has a custom position for the toggle link
			// (ie. outside the container or deeper inside the tree)
			var $customTogglers;
			if ( options.$customTogglers ) {
				$customTogglers = $( options.$customTogglers );
			} else {
				var collapsibleId = $collapsible.attr( 'id' ) || '';
				if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
					collapsibleId = $.escapeSelector( collapsibleId );
					$customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
						.addClass( 'mw-customtoggle' );
				}
			}

			// Add event handlers to custom togglers or create our own ones
			var $toggle;
			if ( $customTogglers && $customTogglers.length ) {
				actionHandler = function ( e, opts ) {
					var defaultOpts = {};
					opts = $.extend( defaultOpts, options, opts );
					togglingHandler( $( this ), $collapsible, e, opts );
				};

				$toggle = $customTogglers;

			} else {
				// If this is not a custom case, do the default: wrap the
				// contents and add the toggle link. Different elements are
				// treated differently.

				var $firstItem;
				if ( $collapsible.is( 'table' ) ) {

					// If the table has a caption, collapse to the caption
					// as opposed to the first row
					var $caption = $collapsible.find( '> caption' );
					if ( $caption.length ) {
						$toggle = $caption.find( '> .mw-collapsible-toggle' );

						// If there is no toggle link, add it to the end of the caption
						if ( !$toggle.length ) {
							$toggle = buildDefaultToggleLink().appendTo( $caption );
						}
					} else {
						// The toggle-link will be in one of the cells (td or th) of the first row
						$firstItem = $collapsible.find( 'tr' ).first().find( 'th, td' );
						$toggle = $firstItem.find( '> .mw-collapsible-toggle' );

						// If theres no toggle link, add it to the last cell
						if ( !$toggle.length ) {
							$toggle = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
						}
					}

				} else if ( $collapsible.parent().is( 'li' ) &&
					$collapsible.parent().children( '.mw-collapsible' ).length === 1 &&
					$collapsible.find( '> .mw-collapsible-toggle' ).length === 0
				) {
					// special case of one collapsible in <li> tag
					$toggle = buildDefaultToggleLink();
					$collapsible.before( $toggle );
				} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
					// The toggle-link will be in the first list-item
					$firstItem = $collapsible.find( 'li' ).first();
					$toggle = $firstItem.find( '> .mw-collapsible-toggle' );

					// If theres no toggle link, add it
					if ( !$toggle.length ) {
						// Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
						// to be "1". Except if the value-attribute is already used.
						// If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
						var firstval = $firstItem.prop( 'value' );
						if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
							$firstItem.prop( 'value', '1' );
						}
						$toggle = buildDefaultToggleLink();
						$toggle.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
					}

				} else { // <div>, <p> etc.

					// The toggle-link will be the first child of the element
					$toggle = $collapsible.find( '> .mw-collapsible-toggle' );

					// If a direct child .content-wrapper does not exists, create it
					if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
						$collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
					}

					// If theres no toggle link, add it
					if ( !$toggle.length ) {
						$toggle = buildDefaultToggleLink().prependTo( $collapsible );
					}
				}
			}

			// Attach event handlers to togglelink
			$toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
				.attr( 'aria-expanded', 'true' )
				.prop( 'tabIndex', 0 );

			$( this ).data( 'mw-collapsible', {
				collapse: function () {
					actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
				},
				expand: function () {
					actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: true } );
				},
				toggle: function () {
					actionHandler.call( $toggle.get( 0 ), null, null );
				}
			} );

			// Initial state
			// eslint-disable-next-line no-jquery/no-class-state
			if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
				// One toggler can hook to multiple elements, and one element can have
				// multiple togglers. This is the best way to handle that.
				actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
			}

		} );

		// Attach hash handler
		window.addEventListener( 'hashchange', hashHandler );

		/**
		 * Fired after collapsible content has been initialized
		 *
		 * This gives an option to modify the collapsible behavior.
		 *
		 * @event wikipage_collapsibleContent
		 * @member mw.hook
		 * @param {jQuery} $content All the elements that have been made collapsible
		 */
		mw.hook( 'wikipage.collapsibleContent' ).fire( this );

		return this;
	};

	// Run hash handler right now in case the URL already has a hash
	hashHandler();

	/**
	 * @class jQuery
	 * @mixins jQuery.plugin.makeCollapsible
	 */

}() );