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.
 
 
  *
 
  *
  * Dual licensed:
+
  * This will enable collapsible-functionality on all passed elements.
  * - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
+
  * Will prevent binding twice to the same element.
  * - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
+
* Initial state is expanded by default, this can be overriden by adding class
 +
* "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".
 
  *
 
  *
  * @class jQuery.plugin.makeCollapsible
+
  * @author Krinkle <krinklemail@gmail.com>
 +
*
 +
* 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
+
$.fn.makeCollapsible = function() {
      // .. and there is no collapsible-content because the entire element should be toggled
 
      } else {
 
        $containers = $collapsible;
 
      }
 
    }
 
  
    $containers.toggle( action === 'expand' );
+
return this.each(function() {
    hookCallback();
+
var _fn = 'jquery.makeCollapsible> ';
  }
 
  
  /**
+
// Define reused variables and functions
  * Handle clicking/keypressing on the collapsible element toggle and other
+
var $that = $(this).addClass( 'mw-collapsible' ), // case: $( '#myAJAXelement' ).makeCollapsible()
  * situations where a collapsible element is toggled (e.g. the initial
+
that = this,
  * toggle for collapsed ones).
+
collapsetext = $(this).attr( 'data-collapsetext' ),
  *
+
expandtext = $(this).attr( 'data-expandtext' ),
  * @private
+
toggleElement = function( $collapsible, action, $defaultToggle, instantHide ) {
  * @param {jQuery} $toggle the clickable toggle itself
+
// Validate parameters
  * @param {jQuery} $collapsible the collapsible element
+
if ( !$collapsible.jquery ) { // $collapsible must be an instance of jQuery
  * @param {jQuery.Event|null} e either the event or null if unavailable
+
return;
  * @param {Object|undefined} options
+
}
  */
+
if ( action != 'expand' && action != 'collapse' ) {
  function togglingHandler( $toggle, $collapsible, e, options ) {
+
// action must be string with 'expand' or 'collapse'
    var wasCollapsed, $textContainer, collapseText, expandText;
+
return;
    options = options || {};
+
}
 +
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;
 +
}
  
    if ( e ) {
+
var $containers = null;
      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 ( action == 'collapse' ) {
    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)
+
// Collapse the element
    $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
+
if ( $collapsible.is( 'table' ) ) {
 +
// Hide all table rows of this table
 +
// Slide doens't work with tables, but fade does as of jQuery 1.1.3
 +
// http://stackoverflow.com/questions/467336#920480
 +
$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();
 +
}
 +
}
  
    // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
+
} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
    if ( options.toggleClasses ) {
+
$containers = $collapsible.find( '> li' );
      $toggle
+
if ( $defaultToggle ) {
        .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
+
// Exclude list-item containing togglelink
        .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
+
$containers.not( $defaultToggle.parent() ).stop( true, true ).slideUp();
    }
+
} else {
 +
if ( instantHide ) {
 +
$containers.hide();
 +
} else {
 +
$containers.stop( true, true ).slideUp();
 +
}
 +
}
  
    // Toggle the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
+
} else { // <div>, <p> etc.
    if ( options.toggleText ) {
+
var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
      collapseText = options.toggleText.collapseText;
 
      expandText = options.toggleText.expandText;
 
  
      $textContainer = $toggle.find( '.mw-collapsible-text' );
+
// If a collapsible-content is defined, collapse it
      if ( $textContainer.length ) {
+
if ( $collapsibleContent.length ) {
        $textContainer.text( wasCollapsed ? collapseText : expandText );
+
if ( instantHide ) {
      }
+
$collapsibleContent.hide();
    }
+
} else {
 +
$collapsibleContent.slideUp();
 +
}
  
    // And finally toggle the element state itself
+
// Otherwise assume this is a customcollapse with a remote toggle
    toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
+
// .. and there is no collapsible-content because the entire element should be toggled
  }
+
} else {
 +
if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
 +
$collapsible.fadeOut();
 +
} else {
 +
$collapsible.slideUp();
 +
}
 +
}
 +
}
  
  /**
+
} else {
  * 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 () {
+
// Expand the element
      var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler, buildDefaultToggleLink,
+
if ( $collapsible.is( 'table' ) ) {
        $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
+
$containers = $collapsible.find( '>tbody>tr' );
 +
if ( $defaultToggle ) {
 +
// Exclude tablerow containing togglelink
 +
$containers.not( $defaultToggle.parent().parent() ).stop(true, true).fadeIn();
 +
} else {
 +
$containers.stop(true, true).fadeIn();
 +
}
  
      // Ensure class "mw-collapsible" is present in case .makeCollapsible()
+
} else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
      // is called on element(s) that don't have it yet.
+
$containers = $collapsible.find( '> li' );
      $collapsible = $( this ).addClass( 'mw-collapsible' );
+
if ( $defaultToggle ) {
 +
// Exclude list-item containing togglelink
 +
$containers.not( $defaultToggle.parent() ).stop( true, true ).slideDown();
 +
} else {
 +
$containers.stop( true, true ).slideDown();
 +
}
  
      // Return if it has been enabled already.
+
} else { // <div>, <p> etc.
      if ( $collapsible.data( 'mw-made-collapsible' ) ) {
+
var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
        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?
+
// If a collapsible-content is defined, collapse it
      collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
+
if ( $collapsibleContent.length ) {
      expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
+
$collapsibleContent.slideDown();
  
      // Default click/keypress handler and toggle link to use when none is present
+
// Otherwise assume this is a customcollapse with a remote toggle
      actionHandler = function ( e, opts ) {
+
// .. and there is no collapsible-content because the entire element should be toggled
        var defaultOpts = {
+
} else {
          toggleClasses: true,
+
if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
          toggleText: { collapseText: collapseText, expandText: expandText }
+
$collapsible.fadeIn();
        };
+
} else {
        opts = $.extend( defaultOpts, options, opts );
+
$collapsible.slideDown();
        togglingHandler( $( this ), $collapsible, e, opts );
+
}
      };
+
}
 +
}
 +
}
 +
},
 +
// 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();
  
      // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
+
// It's expanded right now
      buildDefaultToggleLink = function () {
+
if ( !$that.hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
        return $( '<a class="mw-collapsible-text"></a>' )
+
// Change link to "Show"
          .text( collapseText )
+
$that.removeClass( 'mw-collapsible-toggle-expanded' ).addClass( 'mw-collapsible-toggle-collapsed' );
          .wrap( '<span class="mw-collapsible-toggle mw-collapsible-toggle-default"></span>' )
+
if ( $that.find( '> a' ).length ) {
          .parent()
+
$that.find( '> a' ).text( expandtext );
          .attr( {
+
} else {
            role: 'button',
+
$that.text( expandtext );
            tabindex: 0
+
}
          } )
+
// Collapse element
          .on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
+
toggleElement( $collapsible, 'collapse', $that );
      };
 
  
      // Check if this element has a custom position for the toggle link
+
// It's collapsed right now
      // (ie. outside the container or deeper inside the tree)
+
} else {
      if ( options.$customTogglers ) {
+
// Change link to "Hide"
        $customTogglers = $( options.$customTogglers );
+
$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
      } else {
+
if ( $that.find( '> a' ).length ) {
        collapsibleId = $collapsible.attr( 'id' ) || '';
+
$that.find( '> a' ).text( collapsetext );
        if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
+
} else {
          $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
+
$that.text( collapsetext );
            .addClass( 'mw-customtoggle' );
+
}
        }
+
// 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();
  
      // Add event handlers to custom togglers or create our own ones
+
// It's expanded right now
      if ( $customTogglers && $customTogglers.length ) {
+
if ( !$that.hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
        actionHandler = function ( e, opts ) {
+
// Change toggle to collapsed
          var defaultOpts = {};
+
$that.removeClass( 'mw-collapsible-toggle-expanded' ).addClass( 'mw-collapsible-toggle-collapsed' );
          opts = $.extend( defaultOpts, options, opts );
+
// Collapse element
          togglingHandler( $( this ), $collapsible, e, opts );
+
toggleElement( $collapsible, 'collapse', $that );
        };
 
  
        $toggleLink = $customTogglers
+
// It's collapsed right now
          .on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
+
} else {
          .prop( 'tabIndex', 0 );
+
// Change toggle to expanded
 +
$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
 +
// 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 );
  
      } 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' ) ) {
+
// Use custom text or default ?
 +
if( !collapsetext ) {
 +
collapsetext = mw.msg( 'collapsible-collapse' );
 +
}
 +
if ( !expandtext ) {
 +
expandtext = mw.msg( 'collapsible-expand' );
 +
}
  
          // If the table has a caption, collapse to the caption
+
// Create toggle link with a space around the brackets (&nbsp;[text]&nbsp;)
          // as opposed to the first row
+
var $toggleLink =
          $caption = $collapsible.find( '> caption' );
+
$( '<a href="#"></a>' )
          if ( $caption.length ) {
+
.text( collapsetext )
            $toggle = $caption.find( '> .mw-collapsible-toggle' );
+
.wrap( '<span class="mw-collapsible-toggle"></span>' )
 +
.parent()
 +
.prepend( '&nbsp;[' )
 +
.append( ']&nbsp;' )
 +
.bind( 'click.mw-collapse', function(e) {
 +
toggleLinkDefault( this, e );
 +
} );
  
            // If there is no toggle link, add it to the end of the caption
+
// Return if it has been enabled already.
            if ( !$toggle.length ) {
+
if ( $that.hasClass( 'mw-made-collapsible' ) ) {
              $toggleLink = buildDefaultToggleLink().appendTo( $caption );
+
return;
            } else {
+
} else {
              $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
+
$that.addClass( 'mw-made-collapsible' );
                .prop( 'tabIndex', 0 );
+
}
            }
 
          } 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
+
// Check if this element has a custom position for the toggle link
            if ( !$toggle.length ) {
+
// (ie. outside the container or deeper inside the tree)
              $toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
+
// Then: Locate the custom toggle link(s) and bind them
            } else {
+
if ( ( $that.attr( 'id' ) || '' ).indexOf( 'mw-customcollapsible-' ) === 0 ) {
              $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
 
                .prop( 'tabIndex', 0 );
 
            }
 
          }
 
  
        } else if ( $collapsible.parent().is( 'li' ) &&
+
var thatId = $that.attr( 'id' ),
          $collapsible.parent().children( '.mw-collapsible' ).length === 1 &&
+
$customTogglers = $( '.' + thatId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) );
          $collapsible.find( '> .mw-collapsible-toggle' ).length === 0
+
mw.log( _fn + 'Found custom collapsible: #' + thatId );
        ) {
 
          // special case of one collapsible in <li> tag
 
          $toggleLink = buildDefaultToggleLink();
 
          $collapsible.before( $toggleLink );
 
        } 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
+
// Double check that there is actually a customtoggle link
          if ( !$toggle.length ) {
+
if ( $customTogglers.length ) {
            // Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
+
$customTogglers.bind( 'click.mw-collapse', function( e ) {
            // to be "1". Except if the value-attribute is already used.
+
toggleLinkCustom( $(this), e, $that );
            // If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
+
} );
            firstval = $firstItem.prop( 'value' );
+
} else {
            if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
+
mw.log( _fn + '#' + thatId + ': Missing toggler!' );
              $firstItem.prop( 'value', '1' );
+
}
            }
 
            $toggleLink = buildDefaultToggleLink();
 
            $toggleLink.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
 
          } else {
 
            $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
 
              .prop( 'tabIndex', 0 );
 
          }
 
  
        } else { // <div>, <p> etc.
+
// Initial state
 +
if ( $that.hasClass( 'mw-collapsed' ) ) {
 +
$that.removeClass( 'mw-collapsed' );
 +
toggleLinkCustom( $customTogglers, null, $that );
 +
}
  
          // The toggle-link will be the first child of the element
+
// If this is not a custom case, do the default:
          $toggle = $collapsible.find( '> .mw-collapsible-toggle' );
+
// Wrap the contents add the toggle link
 +
} else {
  
          // If a direct child .content-wrapper does not exists, create it
+
// Elements are treated differently
          if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
+
if ( $that.is( 'table' ) ) {
            $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
+
// The toggle-link will be in one the the cells (td or th) of the first row
          }
+
var $firstRowCells = $( 'tr:first th, tr:first td', that ),
 +
$toggle = $firstRowCells.find( '> .mw-collapsible-toggle' );
  
          // If theres no toggle link, add it
+
// If theres no toggle link, add it to the last cell
          if ( !$toggle.length ) {
+
if ( !$toggle.length ) {
            $toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
+
$firstRowCells.eq(-1).prepend( $toggleLink );
          } else {
+
} else {
            $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
+
$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
              .prop( 'tabIndex', 0 );
+
toggleLinkPremade( $toggle, e );
          }
+
} );
        }
+
}
      }
 
  
      $( this ).data( 'mw-collapsible', {
+
} else if ( $that.is( 'ul' ) || $that.is( 'ol' ) ) {
        collapse: function () {
+
// The toggle-link will be in the first list-item
          actionHandler.call( $toggleLink.get( 0 ), null, { wasCollapsed: false } );
+
var $firstItem = $( 'li:first', $that),
        },
+
$toggle = $firstItem.find( '> .mw-collapsible-toggle' );
        expand: function () {
 
          actionHandler.call( $toggleLink.get( 0 ), null, { wasCollapsed: true } );
 
        },
 
        toggle: function () {
 
          actionHandler.call( $toggleLink.get( 0 ), null, null );
 
        }
 
      } );
 
  
      // Initial state
+
// If theres no toggle link, add it
      if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
+
if ( !$toggle.length ) {
        // One toggler can hook to multiple elements, and one element can have
+
// Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
        // multiple togglers. This is the sanest way to handle that.
+
// to be "1". Except if the value-attribute is already used.
        actionHandler.call( $toggleLink.get( 0 ), null, { wasCollapsed: false } );
+
// If no value was set WebKit returns "", Mozilla returns '-1', others return null or undefined.
      }
+
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
    * Fired after collapsible content has been initialized
+
var $toggle = $that.find( '> .mw-collapsible-toggle' );
    *
 
    * 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;
+
// If a direct child .content-wrapper does not exists, create it
  };
+
if ( !$that.find( '> .mw-collapsible-content' ).length ) {
 +
$that.wrapInner( '<div class="mw-collapsible-content"></div>' );
 +
}
  
  /**
+
// If theres no toggle link, add it
  * @class jQuery
+
if ( !$toggle.length ) {
  * @mixins jQuery.plugin.makeCollapsible
+
$that.prepend( $toggleLink );
  */
+
} else {
 +
$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
 +
toggleLinkPremade( $toggle, e );
 +
} );
 +
}
 +
}
 +
}
  
}( jQuery, mediaWiki ) );
+
// Initial state (only for those that are not custom)
 +
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:55, 28 May 2018

/**
 * jQuery makeCollapsible
 *
 * This will enable collapsible-functionality on all passed elements.
 * Will prevent binding twice to the same element.
 * Initial state is expanded by default, this can be overriden by adding class
 * "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>
 *
 * 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 ) {

$.fn.makeCollapsible = function() {

	return this.each(function() {
		var _fn = 'jquery.makeCollapsible> ';

		// Define reused variables and functions
		var	$that = $(this).addClass( 'mw-collapsible' ), // case: $( '#myAJAXelement' ).makeCollapsible()
			that = this,
			collapsetext = $(this).attr( 'data-collapsetext' ),
			expandtext = $(this).attr( 'data-expandtext' ),
			toggleElement = function( $collapsible, action, $defaultToggle, instantHide ) {
				// Validate parameters
				if ( !$collapsible.jquery ) { // $collapsible must be an instance of jQuery
					return;
				}
				if ( action != 'expand' && action != 'collapse' ) {
					// action must be string with 'expand' or 'collapse'
					return;
				}
				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;

				if ( action == 'collapse' ) {

					// Collapse the element
					if ( $collapsible.is( 'table' ) ) {
						// Hide all table rows of this table
						// Slide doens't work with tables, but fade does as of jQuery 1.1.3
						// http://stackoverflow.com/questions/467336#920480
						$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' ) ) {
						$containers = $collapsible.find( '> li' );
						if ( $defaultToggle ) {
							// Exclude list-item containing togglelink
							$containers.not( $defaultToggle.parent() ).stop( true, true ).slideUp();
						} else {
							if ( instantHide ) {
								$containers.hide();
							} else {
								$containers.stop( true, true ).slideUp();
							}
						}

					} else { // <div>, <p> etc.
						var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );

						// If a collapsible-content is defined, collapse it
						if ( $collapsibleContent.length ) {
							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
						} else {
							if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
								$collapsible.fadeOut();
							} else {
								$collapsible.slideUp();
							}
						}
					}

				} else {

					// Expand the element
					if ( $collapsible.is( 'table' ) ) {
						$containers = $collapsible.find( '>tbody>tr' );
						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' ) ) {
						$containers = $collapsible.find( '> li' );
						if ( $defaultToggle ) {
							// Exclude list-item containing togglelink
							$containers.not( $defaultToggle.parent() ).stop( true, true ).slideDown();
						} else {
							$containers.stop( true, true ).slideDown();
						}

					} else { // <div>, <p> etc.
						var $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );

						// If a collapsible-content is defined, collapse it
						if ( $collapsibleContent.length ) {
							$collapsibleContent.slideDown();

						// Otherwise assume this is a customcollapse with a remote toggle
						// .. and there is no collapsible-content because the entire element should be toggled
						} else {
							if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
								$collapsible.fadeIn();
							} else {
								$collapsible.slideDown();
							}
						}
					}
				}
			},
			// 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
				if ( !$that.hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
					// Change link to "Show"
					$that.removeClass( 'mw-collapsible-toggle-expanded' ).addClass( 'mw-collapsible-toggle-collapsed' );
					if ( $that.find( '> a' ).length ) {
						$that.find( '> a' ).text( expandtext );
					} else {
						$that.text( expandtext );
					}
					// Collapse element
					toggleElement( $collapsible, 'collapse', $that );

				// It's collapsed right now
				} else {
					// Change link to "Hide"
					$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
					if ( $that.find( '> a' ).length ) {
						$that.find( '> a' ).text( collapsetext );
					} 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
				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 {
					// Change toggle to expanded
					$that.removeClass( 'mw-collapsible-toggle-collapsed' ).addClass( 'mw-collapsible-toggle-expanded' );
					// 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 );

			};

		// Use custom text or default ?
		if( !collapsetext ) {
			collapsetext = mw.msg( 'collapsible-collapse' );
		}
		if ( !expandtext ) {
			expandtext = mw.msg( 'collapsible-expand' );
		}

		// Create toggle link with a space around the brackets (&nbsp;[text]&nbsp;)
		var $toggleLink =
			$( '<a href="#"></a>' )
				.text( collapsetext )
				.wrap( '<span class="mw-collapsible-toggle"></span>' )
				.parent()
				.prepend( '&nbsp;[' )
				.append( ']&nbsp;' )
				.bind( 'click.mw-collapse', function(e) {
					toggleLinkDefault( this, e );
				} );

		// Return if it has been enabled already.
		if ( $that.hasClass( 'mw-made-collapsible' ) ) {
			return;
		} else {
			$that.addClass( 'mw-made-collapsible' );
		}

		// Check if this element has a custom position for the toggle link
		// (ie. outside the container or deeper inside the tree)
		// Then: Locate the custom toggle link(s) and bind them
		if ( ( $that.attr( 'id' ) || '' ).indexOf( 'mw-customcollapsible-' ) === 0 ) {

			var thatId = $that.attr( 'id' ),
				$customTogglers = $( '.' + thatId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) );
			mw.log( _fn + 'Found custom collapsible: #' + thatId );

			// Double check that there is actually a customtoggle link
			if ( $customTogglers.length ) {
				$customTogglers.bind( 'click.mw-collapse', function( e ) {
					toggleLinkCustom( $(this), e, $that );
				} );
			} else {
				mw.log( _fn + '#' + thatId + ': Missing toggler!' );
			}

			// Initial state
			if ( $that.hasClass( 'mw-collapsed' ) ) {
				$that.removeClass( 'mw-collapsed' );
				toggleLinkCustom( $customTogglers, null, $that );
			}

		// If this is not a custom case, do the default:
		// Wrap the contents add the toggle link
		} else {

			// Elements are treated differently
			if ( $that.is( 'table' ) ) {
				// The toggle-link will be in one the the cells (td or th) of the first row
				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
				if ( !$toggle.length ) {
					$firstRowCells.eq(-1).prepend( $toggleLink );
				} else {
					$toggleLink = $toggle.unbind( 'click.mw-collapse' ).bind( 'click.mw-collapse', function( e ) {
						toggleLinkPremade( $toggle, e );
					} );
				}

			} else if ( $that.is( 'ul' ) || $that.is( 'ol' ) ) {
				// The toggle-link will be in the first list-item
				var	$firstItem = $( 'li:first', $that),
					$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 null or undefined.
					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' );

				// If a direct child .content-wrapper does not exists, create it
				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 ) {
					$that.prepend( $toggleLink );
				} 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)
		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 );