MediaWiki:Gadget-Collapse-Captions.js

From wikishia

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.
/* Collapse the [[Commons:File captions]] box by default */

/*
This Gadget handles the collapse in three types of scenarios:
1. The Gadget is loaded way much after the the captionsPanel has been rendered.
2. The wikibase.mediainfo.filePageDisplay renders the panel, calling rebuildDOM.

Only the first time the Gadget shall collapse the panel by default, other times
are assumed to be triggered by user interacting with the panel.
*/

$( function() {
	if ( mw.config.get( 'wgNamespaceNumber' ) !== 6 || !document.getElementById( 'file' ) ) {
		return;
	}

	var doCollapse = ( function() {
		var initial = true;
		
		return function( $panel ) {
			if ( $panel === undefined ) {
				$panel = $( '.wbmi-entityview-captionsPanel' );
			}

			if ( $panel.length && !$panel.children( '.mw-collapsible-toggle' ).length ) {
				$panel.data( 'mw-made-collapsible', false );
				$panel.makeCollapsible( { collapsed: initial } );
				initial = false;
			}
		};
	}() );

	mw.loader.using( 'wikibase.mediainfo.filePageDisplay', function() {
		mw.hook( 'wikipage.content' ).add( function() {
			// Wait after the same hook in wikibase.mediainfo.filePageDisplay,
			// which destroys the panel, so we would fail.
			// This would hopefully only succeed under case #1, when the
			// initial rendering is long done and the rebuildDOM hook is
			// hopeless in observing the initial render.
			setTimeout( function() {
				doCollapse();
			}, 0 );
		} );

		// :(
		var CaptionsPanel = mw.loader.moduleRegistry[ 'wikibase.mediainfo.filePageDisplay' ].packageExports[ 'resources/filepage/CaptionsPanel.js' ];

		CaptionsPanel.prototype.rebuildDOM = function( orig ) {
			return function( $old, $new, preserve ) {
				// jQuery.Deferred exception: $new.find is not a function TypeError: $new.find is not a function
				var $panel;
				if ( $new && $new.querySelector ) {
					$panel = $( $new.querySelector( '.wbmi-entityview-captionsPanel' ) );
				} else {
					$panel = $new.find( '.wbmi-entityview-captionsPanel' );
				}
				doCollapse( $panel );

				return orig.call( this, $old, $new, preserve );
			};
		}( CaptionsPanel.prototype.rebuildDOM );
	} );
} );