Difference between revisions of "MediaWiki:Common.js"

From Wiki Itajaí
Jump to navigation Jump to search
Line 1: Line 1:
 
/**
 
/**
 
  * jQuery makeCollapsible
 
  * jQuery makeCollapsible
 +
* Note: To avoid performance issues such as reflows, several styles are
 +
* shipped in mediawiki.makeCollapsible.styles to reserve space for the toggle control. Please
 +
* familiarise yourself with that CSS before making any changes to this code.
 
  *
 
  *
  * This will enable collapsible-functionality on all passed elements.
+
  * Dual licensed:
  * Will prevent binding twice to the same element.
+
  * - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
* Initial state is expanded by default, this can be overriden by adding class
+
  * - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
  * "mw-collapsed" to the "mw-collapsible" element.
 
* Elements made collapsible have class "mw-made-collapsible".
 
* Except for tables and lists, the inner content is wrapped in "mw-collapsible-content".
 
 
  *
 
  *
  * @author Krinkle <krinklemail@gmail.com>
+
  * @class jQuery.plugin.makeCollapsible
*
 
* Dual license:
 
* @license CC-BY 3.0 <http://creativecommons.org/licenses/by/3.0>
 
* @license GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 
 
  */
 
  */
( function( $, mw ) {
+
( function ( $, mw ) {
 +
  /**
 +
  * 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 ) {
 +
    var $collapsibleContent, $containers, hookCallback;
 +
    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' );
 +
    hookCallback = function () {
 +
      $collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
 +
    };
 +
 
 +
    // Handle different kinds of elements
 +
    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.
 +
      $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;
 +
      }
 +
    }
  
$.fn.makeCollapsible = function() {
+
    $containers.toggle( action === 'expand' );
 +
    hookCallback();
 +
  }
  
return this.each(function() {
+
  /**
var _fn = 'jquery.makeCollapsible> ';
+
  * 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 ) {
 +
    var wasCollapsed, $textContainer, collapseText, expandText;
 +
    options = options || {};
  
// Define reused variables and functions
+
    if ( e ) {
var $that = $(this).addClass( 'mw-collapsible' ), // case: $( '#myAJAXelement' ).makeCollapsible()
+
      if (
that = this,
+
        e.type === 'click' &&
collapsetext = $(this).attr( 'data-collapsetext' ),
+
        e.target.nodeName.toLowerCase() === 'a' &&
expandtext = $(this).attr( 'data-expandtext' ),
+
        $( e.target ).attr( 'href' )
toggleElement = function( $collapsible, action, $defaultToggle, instantHide ) {
+
      ) {
// Validate parameters
+
        // Don't fire if a link was clicked (for premade togglers)
if ( !$collapsible.jquery ) { // $collapsible must be an instance of jQuery
+
        return;
return;
+
      } else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
}
+
        // Only handle keypresses on the "Enter" or "Space" keys
if ( action != 'expand' && action != 'collapse' ) {
+
        return;
// action must be string with 'expand' or 'collapse'
+
      } else {
return;
+
        e.preventDefault();
}
+
        e.stopPropagation();
if ( typeof $defaultToggle == 'undefined' ) {
+
      }
$defaultToggle = null;
+
    }
}
 
if ( $defaultToggle !== null && !($defaultToggle instanceof $) ) {
 
// is optional (may be undefined), but if defined it must be an instance of jQuery.
 
// If it's not, abort right away.
 
// After this $defaultToggle is either null or a valid jQuery instance.
 
return;
 
}
 
  
var $containers = null;
+
    // This allows the element to be hidden on initial toggle without fiddling with the class
 +
    if ( options.wasCollapsed !== undefined ) {
 +
      wasCollapsed = options.wasCollapsed;
 +
    } else {
 +
      wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
 +
    }
  
if ( action == 'collapse' ) {
+
    // Toggle the state of the collapsible element (that is, expand or collapse)
 +
    $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
  
// Collapse the element
+
    // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
if ( $collapsible.is( 'table' ) ) {
+
    if ( options.toggleClasses ) {
// Hide all table rows of this table
+
      $toggle
// Slide doens't work with tables, but fade does as of jQuery 1.1.3
+
        .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
// http://stackoverflow.com/questions/467336#920480
+
        .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
$containers = $collapsible.find( '>tbody>tr' );
+
    }
if ( $defaultToggle ) {
 
// Exclude tablerow containing togglelink
 
$containers.not( $defaultToggle.closest( 'tr' ) ).stop(true, true).fadeOut();
 
} else {
 
if ( instantHide ) {
 
$containers.hide();
 
} else {
 
$containers.stop( true, true ).fadeOut();
 
}
 
}
 
  
} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
+
    // Toggle the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
$containers = $collapsible.find( '> li' );
+
    if ( options.toggleText ) {
if ( $defaultToggle ) {
+
      collapseText = options.toggleText.collapseText;
// Exclude list-item containing togglelink
+
      expandText = options.toggleText.expandText;
$containers.not( $defaultToggle.parent() ).stop( true, true ).slideUp();
 
} else {
 
if ( instantHide ) {
 
$containers.hide();
 
} else {
 
$containers.stop( true, true ).slideUp();
 
}
 
}
 
  
} else { // <div>, <p> etc.
+
      $textContainer = $toggle.find( '.mw-collapsible-text' );
var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
+
      if ( $textContainer.length ) {
 +
        $textContainer.text( wasCollapsed ? collapseText : expandText );
 +
      }
 +
    }
  
// If a collapsible-content is defined, collapse it
+
    // And finally toggle the element state itself
if ( $collapsibleContent.length ) {
+
    toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
if ( instantHide ) {
+
  }
$collapsibleContent.hide();
 
} else {
 
$collapsibleContent.slideUp();
 
}
 
  
// Otherwise assume this is a customcollapse with a remote toggle
+
  /**
// .. and there is no collapsible-content because the entire element should be toggled
+
  * Enable collapsible-functionality on all elements in the collection.
} else {
+
  *
if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
+
  * - Will prevent binding twice to the same element.
$collapsible.fadeOut();
+
  * - Initial state is expanded by default, this can be overridden by adding class
} else {
+
  *  "mw-collapsed" to the "mw-collapsible" element.
$collapsible.slideUp();
+
  * - 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 || {};
  
} else {
+
    this.each( function () {
 +
      var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler,
 +
        buildDefaultToggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
  
// Expand the element
+
      // Ensure class "mw-collapsible" is present in case .makeCollapsible()
if ( $collapsible.is( 'table' ) ) {
+
      // is called on element(s) that don't have it yet.
$containers = $collapsible.find( '>tbody>tr' );
+
      $collapsible = $( this ).addClass( 'mw-collapsible' );
if ( $defaultToggle ) {
 
// Exclude tablerow containing togglelink
 
$containers.not( $defaultToggle.parent().parent() ).stop(true, true).fadeIn();
 
} else {
 
$containers.stop(true, true).fadeIn();
 
}
 
  
} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
+
      // Return if it has been enabled already.
$containers = $collapsible.find( '> li' );
+
      if ( $collapsible.data( 'mw-made-collapsible' ) ) {
if ( $defaultToggle ) {
+
        return;
// Exclude list-item containing togglelink
+
      } else {
$containers.not( $defaultToggle.parent() ).stop( true, true ).slideDown();
+
        // Let CSS know that it no longer needs to worry about flash of unstyled content.
} else {
+
        // This will allow mediawiki.makeCollapsible.styles to disable temporary pseudo elements, that
$containers.stop( true, true ).slideDown();
+
        // are needed to avoid a flash of unstyled content.
}
+
        $collapsible.addClass( 'mw-made-collapsible' )
 +
          .data( 'mw-made-collapsible', true );
 +
      }
  
} else { // <div>, <p> etc.
+
      // Use custom text or default?
var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
+
      collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
 +
      expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
  
// If a collapsible-content is defined, collapse it
+
      // Default click/keypress handler and toggle link to use when none is present
if ( $collapsibleContent.length ) {
+
      actionHandler = function ( e, opts ) {
$collapsibleContent.slideDown();
+
        var defaultOpts = {
 +
          toggleClasses: true,
 +
          toggleText: { collapseText: collapseText, expandText: expandText }
 +
        };
 +
        opts = $.extend( defaultOpts, options, opts );
 +
        togglingHandler( $( this ), $collapsible, e, opts );
 +
      };
  
// Otherwise assume this is a customcollapse with a remote toggle
+
      // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
// .. and there is no collapsible-content because the entire element should be toggled
+
      buildDefaultToggleLink = function () {
} else {
+
        return $( '<a class="mw-collapsible-text"></a>' )
if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
+
          .text( collapseText )
$collapsible.fadeIn();
+
          .wrap( '<span class="mw-collapsible-toggle mw-collapsible-toggle-default"></span>' )
} else {
+
          .parent()
$collapsible.slideDown();
+
          .attr( {
}
+
            role: 'button',
}
+
            tabindex: 0
}
+
          } );
}
+
      };
},
 
// Toggles collapsible and togglelink class and updates text label
 
toggleLinkDefault = function( that, e ) {
 
var $that = $(that),
 
$collapsible = $that.closest( '.mw-collapsible.mw-made-collapsible' ).toggleClass( 'mw-collapsed' );
 
e.preventDefault();
 
e.stopPropagation();
 
  
// It's expanded right now
+
      // Check if this element has a custom position for the toggle link
if ( !$that.hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
+
      // (ie. outside the container or deeper inside the tree)
// Change link to "Show"
+
      if ( options.$customTogglers ) {
$that.removeClass( 'mw-collapsible-toggle-expanded' ).addClass( 'mw-collapsible-toggle-collapsed' );
+
        $customTogglers = $( options.$customTogglers );
if ( $that.find( '> a' ).length ) {
+
      } else {
$that.find( '> a' ).text( expandtext );
+
        collapsibleId = $collapsible.attr( 'id' ) || '';
} else {
+
        if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
$that.text( expandtext );
+
          $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
}
+
            .addClass( 'mw-customtoggle' );
// Collapse element
+
        }
toggleElement( $collapsible, 'collapse', $that );
+
      }
  
// It's collapsed right now
+
      // Add event handlers to custom togglers or create our own ones
} else {
+
      if ( $customTogglers && $customTogglers.length ) {
// Change link to "Hide"
+
        actionHandler = function ( e, opts ) {
$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
+
          var defaultOpts = {};
if ( $that.find( '> a' ).length ) {
+
          opts = $.extend( defaultOpts, options, opts );
$that.find( '> a' ).text( collapsetext );
+
          togglingHandler( $( this ), $collapsible, e, opts );
} else {
+
        };
$that.text( collapsetext );
 
}
 
// Expand element
 
toggleElement( $collapsible, 'expand', $that );
 
}
 
return;
 
},
 
// Toggles collapsible and togglelink class
 
toggleLinkPremade = function( $that, e ) {
 
var $collapsible = $that.eq(0).closest( '.mw-collapsible.mw-made-collapsible' ).toggleClass( 'mw-collapsed' );
 
if ( $(e.target).is('a') ) {
 
return true;
 
}
 
e.preventDefault();
 
e.stopPropagation();
 
  
// It's expanded right now
+
        $toggle = $customTogglers;
if ( !$that.hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
 
// Change toggle to collapsed
 
$that.removeClass( 'mw-collapsible-toggle-expanded' ).addClass( 'mw-collapsible-toggle-collapsed' );
 
// Collapse element
 
toggleElement( $collapsible, 'collapse', $that );
 
  
// It's collapsed right now
+
      } else {
} else {
+
        // If this is not a custom case, do the default: wrap the
// Change toggle to expanded
+
        // contents and add the toggle link. Different elements are
$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
+
        // treated differently.
// Expand element
 
toggleElement( $collapsible, 'expand', $that );
 
}
 
return;
 
},
 
// Toggles customcollapsible
 
toggleLinkCustom = function( $that, e, $collapsible ) {
 
// For the initial state call of customtogglers there is no event passed
 
if (e) {
 
e.preventDefault();
 
e.stopPropagation();
 
}
 
// Get current state and toggle to the opposite
 
var action = $collapsible.hasClass( 'mw-collapsed' ) ? 'expand' : 'collapse';
 
$collapsible.toggleClass( 'mw-collapsed' );
 
toggleElement( $collapsible, action, $that );
 
  
};
+
        if ( $collapsible.is( 'table' ) ) {
  
// Use custom text or default ?
+
          // If the table has a caption, collapse to the caption
if( !collapsetext ) {
+
          // as opposed to the first row
collapsetext = mw.msg( 'collapsible-collapse' );
+
          $caption = $collapsible.find( '> caption' );
}
+
          if ( $caption.length ) {
if ( !expandtext ) {
+
            $toggle = $caption.find( '> .mw-collapsible-toggle' );
expandtext = mw.msg( 'collapsible-expand' );
 
}
 
  
// Create toggle link with a space around the brackets (&nbsp;[text]&nbsp;)
+
            // If there is no toggle link, add it to the end of the caption
var $toggleLink =
+
            if ( !$toggle.length ) {
$( '<a href="#"></a>' )
+
              $toggle = buildDefaultToggleLink().appendTo( $caption );
.text( collapsetext )
+
            }
.wrap( '<span class="mw-collapsible-toggle"></span>' )
+
          } else {
.parent()
+
            // The toggle-link will be in one of the cells (td or th) of the first row
.prepend( '&nbsp;[' )
+
            $firstItem = $collapsible.find( 'tr:first th, tr:first td' );
.append( ']&nbsp;' )
+
            $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
.bind( 'click.mw-collapse', function(e) {
 
toggleLinkDefault( this, e );
 
} );
 
  
// Return if it has been enabled already.
+
            // If theres no toggle link, add it to the last cell
if ( $that.hasClass( 'mw-made-collapsible' ) ) {
+
            if ( !$toggle.length ) {
return;
+
              $toggle = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
} else {
+
            }
$that.addClass( 'mw-made-collapsible' );
+
          }
}
 
  
// Check if this element has a custom position for the toggle link
+
        } else if ( $collapsible.parent().is( 'li' ) &&
// (ie. outside the container or deeper inside the tree)
+
          $collapsible.parent().children( '.mw-collapsible' ).length === 1 &&
// Then: Locate the custom toggle link(s) and bind them
+
          $collapsible.find( '> .mw-collapsible-toggle' ).length === 0
if ( ( $that.attr( 'id' ) || '' ).indexOf( 'mw-customcollapsible-' ) === 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' );
  
var thatId = $that.attr( 'id' ),
+
          // If theres no toggle link, add it
$customTogglers = $( '.' + thatId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) );
+
          if ( !$toggle.length ) {
mw.log( _fn + 'Found custom collapsible: #' + thatId );
+
            // 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.
 +
            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 );
 +
          }
  
// Double check that there is actually a customtoggle link
+
        } else { // <div>, <p> etc.
if ( $customTogglers.length ) {
 
$customTogglers.bind( 'click.mw-collapse', function( e ) {
 
toggleLinkCustom( $(this), e, $that );
 
} );
 
} else {
 
mw.log( _fn + '#' + thatId + ': Missing toggler!' );
 
}
 
  
// Initial state
+
          // The toggle-link will be the first child of the element
if ( $that.hasClass( 'mw-collapsed' ) ) {
+
          $toggle = $collapsible.find( '> .mw-collapsible-toggle' );
$that.removeClass( 'mw-collapsed' );
 
toggleLinkCustom( $customTogglers, null, $that );
 
}
 
  
// If this is not a custom case, do the default:
+
          // If a direct child .content-wrapper does not exists, create it
// Wrap the contents add the toggle link
+
          if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
} else {
+
            $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
 +
          }
  
// Elements are treated differently
+
          // If theres no toggle link, add it
if ( $that.is( 'table' ) ) {
+
          if ( !$toggle.length ) {
// The toggle-link will be in one the the cells (td or th) of the first row
+
            $toggle = buildDefaultToggleLink().prependTo( $collapsible );
var $firstRowCells = $( 'tr:first th, tr:first td', that ),
+
          }
$toggle = $firstRowCells.find( '> .mw-collapsible-toggle' );
+
        }
 +
      }
  
// If theres no toggle link, add it to the last cell
+
      // Attach event handlers to togglelink
if ( !$toggle.length ) {
+
      $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
$firstRowCells.eq(-1).prepend( $toggleLink );
+
        .prop( 'tabIndex', 0 );
} else {
 
$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
 
toggleLinkPremade( $toggle, e );
 
} );
 
}
 
  
} else if ( $that.is( 'ul' ) || $that.is( 'ol' ) ) {
+
      $( this ).data( 'mw-collapsible', {
// The toggle-link will be in the first list-item
+
        collapse: function () {
var $firstItem = $( 'li:first', $that),
+
          actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
$toggle = $firstItem.find( '> .mw-collapsible-toggle' );
+
        },
 +
        expand: function () {
 +
          actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: true } );
 +
        },
 +
        toggle: function () {
 +
          actionHandler.call( $toggle.get( 0 ), null, null );
 +
        }
 +
      } );
  
// If theres no toggle link, add it
+
      // Initial state
if ( !$toggle.length ) {
+
      if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
// Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
+
        // One toggler can hook to multiple elements, and one element can have
// to be "1". Except if the value-attribute is already used.
+
        // multiple togglers. This is the sanest way to handle that.
// If no value was set WebKit returns "", Mozilla returns '-1', others return null or undefined.
+
        actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
var firstval = $firstItem.attr( 'value' );
+
      }
if ( firstval === undefined || !firstval || firstval == '-1' ) {
 
$firstItem.attr( 'value', '1' );
 
}
 
$that.prepend( $toggleLink.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent() );
 
} else {
 
$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
 
toggleLinkPremade( $toggle, e );
 
} );
 
}
 
  
} else { // <div>, <p> etc.
+
    } );
  
// The toggle-link will be the first child of the element
+
    /**
var $toggle = $that.find( '> .mw-collapsible-toggle' );
+
    * 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 );
  
// If a direct child .content-wrapper does not exists, create it
+
    return this;
if ( !$that.find( '> .mw-collapsible-content' ).length ) {
+
  };
$that.wrapInner( '<div class="mw-collapsible-content"></div>' );
 
}
 
  
// If theres no toggle link, add it
+
  /**
if ( !$toggle.length ) {
+
  * @class jQuery
$that.prepend( $toggleLink );
+
  * @mixins jQuery.plugin.makeCollapsible
} else {
+
  */
$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
 
toggleLinkPremade( $toggle, e );
 
} );
 
}
 
}
 
}
 
  
// Initial state (only for those that are not custom)
+
}( jQuery, mediaWiki ) );
if ( $that.hasClass( 'mw-collapsed' ) && ( $that.attr( 'id' ) || '').indexOf( 'mw-customcollapsible-' ) !== 0 ) {
 
$that.removeClass( 'mw-collapsed' );
 
// The collapsible element could have multiple togglers
 
// To toggle the initial state only click one of them (ie. the first one, eq(0) )
 
// Else it would go like: hide,show,hide,show for each toggle link.
 
toggleElement( $that, 'collapse', $toggleLink.eq(0), /* instantHide = */ true );
 
$toggleLink.eq(0).click();
 
}
 
} );
 
};
 
} )( jQuery, mediaWiki );
 

Revision as of 17:00, 6 June 2018

/**
 * jQuery makeCollapsible
 * Note: To avoid performance issues such as reflows, several styles are
 * shipped in mediawiki.makeCollapsible.styles to reserve space for the toggle control. Please
 * familiarise yourself with that CSS before making any changes to this code.
 *
 * Dual licensed:
 * - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
 * - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 *
 * @class jQuery.plugin.makeCollapsible
 */
( function ( $, mw ) {
  /**
   * 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 ) {
    var $collapsibleContent, $containers, hookCallback;
    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' );
    hookCallback = function () {
      $collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
    };

    // Handle different kinds of elements
    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.
      $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 ) {
    var wasCollapsed, $textContainer, collapseText, expandText;
    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
    if ( options.wasCollapsed !== undefined ) {
      wasCollapsed = options.wasCollapsed;
    } else {
      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 the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
    if ( options.toggleText ) {
      collapseText = options.toggleText.collapseText;
      expandText = options.toggleText.expandText;

      $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 );
  }

  /**
   * 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 () {
      var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler,
        buildDefaultToggleLink, $firstItem, collapsibleId, $customTogglers, firstval;

      // Ensure class "mw-collapsible" is present in case .makeCollapsible()
      // is called on element(s) that don't have it yet.
      $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?
      collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
      expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );

      // Default click/keypress handler and toggle link to use when none is present
      actionHandler = function ( e, opts ) {
        var defaultOpts = {
          toggleClasses: 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).
      buildDefaultToggleLink = function () {
        return $( '<a class="mw-collapsible-text"></a>' )
          .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)
      if ( options.$customTogglers ) {
        $customTogglers = $( options.$customTogglers );
      } else {
        collapsibleId = $collapsible.attr( 'id' ) || '';
        if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
          $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
            .addClass( 'mw-customtoggle' );
        }
      }

      // Add event handlers to custom togglers or create our own ones
      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.

        if ( $collapsible.is( 'table' ) ) {

          // If the table has a caption, collapse to the caption
          // as opposed to the first row
          $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 th, tr:first 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.
            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 )
        .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
      if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
        // One toggler can hook to multiple elements, and one element can have
        // multiple togglers. This is the sanest way to handle that.
        actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
      }

    } );

    /**
     * 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;
  };

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

}( jQuery, mediaWiki ) );