Merge "API: allow disabling TOC in action=parse"
[mediawiki.git] / resources / jquery / jquery.makeCollapsible.js
blob60c0afcd7bb91fd7d0890e187ed1972eaa478a83
1 /**
2  * jQuery makeCollapsible
3  *
4  * This will enable collapsible-functionality on all passed elements.
5  * - Will prevent binding twice to the same element.
6  * - Initial state is expanded by default, this can be overriden by adding class
7  *   "mw-collapsed" to the "mw-collapsible" element.
8  * - Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
9  * - The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).
10  *
11  * @author Krinkle, 2011-2012
12  *
13  * Dual license:
14  * @license CC-BY 3.0 <http://creativecommons.org/licenses/by/3.0>
15  * @license GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
16  */
17 ( function ( $, mw ) {
18         /**
19          * Handler for a click on a collapsible toggler.
20          *
21          * @param {jQuery} $collapsible
22          * @param {string} action The action this function will take ('expand' or 'collapse').
23          * @param {jQuery|null} [optional] $defaultToggle
24          * @param {Object|undefined} options
25          */
26         function toggleElement( $collapsible, action, $defaultToggle, options ) {
27                 var $collapsibleContent, $containers, hookCallback;
28                 options = options || {};
30                 // Validate parameters
32                 // $collapsible must be an instance of jQuery
33                 if ( !$collapsible.jquery ) {
34                         return;
35                 }
36                 if ( action !== 'expand' && action !== 'collapse' ) {
37                         // action must be string with 'expand' or 'collapse'
38                         return;
39                 }
40                 if ( $defaultToggle === undefined ) {
41                         $defaultToggle = null;
42                 }
43                 if ( $defaultToggle !== null && !$defaultToggle.jquery ) {
44                         // is optional (may be undefined), but if defined it must be an instance of jQuery.
45                         // If it's not, abort right away.
46                         // After this $defaultToggle is either null or a valid jQuery instance.
47                         return;
48                 }
50                 // Trigger a custom event to allow callers to hook to the collapsing/expanding,
51                 // allowing the module to be testable, and making it possible to
52                 // e.g. implement persistence via cookies
53                 $collapsible.trigger( action === 'expand' ? 'beforeExpand.mw-collapsible' : 'beforeCollapse.mw-collapsible' );
54                 hookCallback = function () {
55                         $collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
56                 };
58                 // Handle different kinds of elements
60                 if ( !options.plainMode && $collapsible.is( 'table' ) ) {
61                         // Tables
62                         // If there is a caption, hide all rows; otherwise, only hide body rows
63                         if ( $collapsible.find( '> caption' ).length ) {
64                                 $containers = $collapsible.find( '> * > tr' );
65                         } else {
66                                 $containers = $collapsible.find( '> tbody > tr' );
67                         }
68                         if ( $defaultToggle ) {
69                                 // Exclude table row containing togglelink
70                                 $containers = $containers.not( $defaultToggle.closest( 'tr' ) );
71                         }
73                         if ( action === 'collapse' ) {
74                                 // Hide all table rows of this table
75                                 // Slide doesn't work with tables, but fade does as of jQuery 1.1.3
76                                 // http://stackoverflow.com/questions/467336#920480
77                                 if ( options.instantHide ) {
78                                         $containers.hide();
79                                         hookCallback();
80                                 } else {
81                                         $containers.stop( true, true ).fadeOut().promise().done( hookCallback );
82                                 }
83                         } else {
84                                 $containers.stop( true, true ).fadeIn().promise().done( hookCallback );
85                         }
87                 } else if ( !options.plainMode && ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) ) {
88                         // Lists
89                         $containers = $collapsible.find( '> li' );
90                         if ( $defaultToggle ) {
91                                 // Exclude list-item containing togglelink
92                                 $containers = $containers.not( $defaultToggle.parent() );
93                         }
95                         if ( action === 'collapse' ) {
96                                 if ( options.instantHide ) {
97                                         $containers.hide();
98                                         hookCallback();
99                                 } else {
100                                         $containers.stop( true, true ).slideUp().promise().done( hookCallback );
101                                 }
102                         } else {
103                                 $containers.stop( true, true ).slideDown().promise().done( hookCallback );
104                         }
106                 } else {
107                         // Everything else: <div>, <p> etc.
108                         $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
110                         // If a collapsible-content is defined, act on it
111                         if ( !options.plainMode && $collapsibleContent.length ) {
112                                 if ( action === 'collapse' ) {
113                                         if ( options.instantHide ) {
114                                                 $collapsibleContent.hide();
115                                                 hookCallback();
116                                         } else {
117                                                 $collapsibleContent.slideUp().promise().done( hookCallback );
118                                         }
119                                 } else {
120                                         $collapsibleContent.slideDown().promise().done( hookCallback );
121                                 }
123                         // Otherwise assume this is a customcollapse with a remote toggle
124                         // .. and there is no collapsible-content because the entire element should be toggled
125                         } else {
126                                 if ( action === 'collapse' ) {
127                                         if ( options.instantHide ) {
128                                                 $collapsible.hide();
129                                                 hookCallback();
130                                         } else {
131                                                 if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
132                                                         $collapsible.fadeOut().promise().done( hookCallback );
133                                                 } else {
134                                                         $collapsible.slideUp().promise().done( hookCallback );
135                                                 }
136                                         }
137                                 } else {
138                                         if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
139                                                 $collapsible.fadeIn().promise().done( hookCallback );
140                                         } else {
141                                                 $collapsible.slideDown().promise().done( hookCallback );
142                                         }
143                                 }
144                         }
145                 }
146         }
148         /**
149          * Handles clicking/keypressing on the collapsible element toggle and other
150          * situations where a collapsible element is toggled (e.g. the initial
151          * toggle for collapsed ones).
152          *
153          * @param {jQuery} $toggle the clickable toggle itself
154          * @param {jQuery} $collapsible the collapsible element
155          * @param {jQuery.Event|null} e either the event or null if unavailable
156          * @param {Object|undefined} options
157          */
158         function togglingHandler( $toggle, $collapsible, e, options ) {
159                 var wasCollapsed, $textContainer, collapseText, expandText;
161                 if ( options === undefined ) {
162                         options = {};
163                 }
165                 if ( e ) {
166                         if ( e.type === 'click' && options.linksPassthru && $.nodeName( e.target, 'a' ) ) {
167                                 // Don't fire if a link was clicked, if requested  (for premade togglers by default)
168                                 return;
169                         } else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
170                                 // Only handle keypresses on the "Enter" or "Space" keys
171                                 return;
172                         } else {
173                                 e.preventDefault();
174                                 e.stopPropagation();
175                         }
176                 }
178                 // This allows the element to be hidden on initial toggle without fiddling with the class
179                 if ( options.wasCollapsed !== undefined ) {
180                         wasCollapsed = options.wasCollapsed;
181                 } else {
182                         wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
183                 }
185                 // Toggle the state of the collapsible element (that is, expand or collapse)
186                 $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
188                 // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
189                 if ( options.toggleClasses ) {
190                         $toggle
191                                 .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
192                                 .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
193                 }
195                 // Toggle the text ("Show"/"Hide"), if requested (for default togglers by default)
196                 if ( options.toggleText ) {
197                         collapseText = options.toggleText.collapseText;
198                         expandText = options.toggleText.expandText;
200                         $textContainer = $toggle.find( '> a' );
201                         if ( !$textContainer.length ) {
202                                 $textContainer = $toggle;
203                         }
204                         $textContainer.text( wasCollapsed ? collapseText : expandText );
205                 }
207                 // And finally toggle the element state itself
208                 toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
209         }
211         /**
212          * Make any element collapsible.
213          *
214          * Supported options:
215          * - collapseText: text to be used for the toggler when clicking it would
216          *   collapse the element. Default: the 'data-collapsetext' attribute of
217          *   the collapsible element or the content of 'collapsible-collapse'
218          *   message.
219          * - expandText: text to be used for the toggler when clicking it would
220          *   expand the element. Default: the 'data-expandtext' attribute of
221          *   the collapsible element or the content of 'collapsible-expand'
222          *   message.
223          * - collapsed: boolean, whether to collapse immediately. By default
224          *   collapse only if the elements has the 'mw-collapsible' class.
225          * - $customTogglers: jQuerified list of elements to be used as togglers
226          *   for this collapsible element. By default, if the collapsible element
227          *   has an id attribute like 'mw-customcollapsible-XXX', elements with a
228          *   *class* of 'mw-customtoggle-XXX' are made togglers for it.
229          * - plainMode: boolean, whether to use a "plain mode" when making the
230          *   element collapsible - that is, hide entire tables and lists (instead
231          *   of hiding only all rows but first of tables, and hiding each list
232          *   item separately for lists) and don't wrap other elements in
233          *   div.mw-collapsible-content. May only be used with custom togglers.
234          */
235         $.fn.makeCollapsible = function ( options ) {
236                 if ( options === undefined ) {
237                         options = {};
238                 }
240                 return this.each( function () {
241                         var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler, buildDefaultToggleLink,
242                                 premadeToggleHandler, $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
244                         // Ensure class "mw-collapsible" is present in case .makeCollapsible()
245                         // is called on element(s) that don't have it yet.
246                         $collapsible = $( this ).addClass( 'mw-collapsible' );
248                         // Return if it has been enabled already.
249                         if ( $collapsible.data( 'mw-made-collapsible' ) ) {
250                                 return;
251                         } else {
252                                 $collapsible.data( 'mw-made-collapsible', true );
253                         }
255                         // Use custom text or default?
256                         collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
257                         expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
259                         // Default click/keypress handler and toggle link to use when none is present
260                         actionHandler = function ( e, opts ) {
261                                 var defaultOpts = {
262                                         toggleClasses: true,
263                                         toggleText: { collapseText: collapseText, expandText: expandText }
264                                 };
265                                 opts = $.extend( defaultOpts, options, opts );
266                                 togglingHandler( $( this ), $collapsible, e, opts );
267                         };
268                         // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
269                         buildDefaultToggleLink = function () {
270                                 return $( '<a href="#"></a>' )
271                                         .text( collapseText )
272                                         .wrap( '<span class="mw-collapsible-toggle"></span>' )
273                                                 .parent()
274                                                 .prepend( '&nbsp;[' )
275                                                 .append( ']&nbsp;' )
276                                                 .on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
277                         };
279                         // Default handler for clicking on premade toggles
280                         premadeToggleHandler = function ( e, opts ) {
281                                 var defaultOpts = { toggleClasses: true, linksPassthru: true };
282                                 opts = $.extend( defaultOpts, options, opts );
283                                 togglingHandler( $( this ), $collapsible, e, opts );
284                         };
286                         // Check if this element has a custom position for the toggle link
287                         // (ie. outside the container or deeper inside the tree)
288                         if ( options.$customTogglers ) {
289                                 $customTogglers = $( options.$customTogglers );
290                         } else {
291                                 collapsibleId = $collapsible.attr( 'id' ) || '';
292                                 if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
293                                         $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) );
294                                 }
295                         }
297                         // Add event handlers to custom togglers or create our own ones
298                         if ( $customTogglers && $customTogglers.length ) {
299                                 actionHandler = function ( e, opts ) {
300                                         var defaultOpts = {};
301                                         opts = $.extend( defaultOpts, options, opts );
302                                         togglingHandler( $( this ), $collapsible, e, opts );
303                                 };
305                                 $toggleLink = $customTogglers;
306                                 $toggleLink.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
308                         } else {
309                                 // If this is not a custom case, do the default: wrap the
310                                 // contents and add the toggle link. Different elements are
311                                 // treated differently.
312                                 if ( $collapsible.is( 'table' ) ) {
314                                         // If the table has a caption, collapse to the caption
315                                         // as opposed to the first row
316                                         $caption = $collapsible.find( '> caption' );
317                                         if ( $caption.length ) {
318                                                 $toggle = $caption.find( '> .mw-collapsible-toggle' );
320                                                 // If there is no toggle link, add it to the end of the caption
321                                                 if ( !$toggle.length ) {
322                                                         $toggleLink = buildDefaultToggleLink().appendTo( $caption );
323                                                 } else {
324                                                         actionHandler = premadeToggleHandler;
325                                                         $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
326                                                 }
327                                         } else {
328                                                 // The toggle-link will be in one the the cells (td or th) of the first row
329                                                 $firstItem = $collapsible.find( 'tr:first th, tr:first td' );
330                                                 $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
332                                                 // If theres no toggle link, add it to the last cell
333                                                 if ( !$toggle.length ) {
334                                                         $toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
335                                                 } else {
336                                                         actionHandler = premadeToggleHandler;
337                                                         $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
338                                                 }
339                                         }
341                                 } else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
342                                         // The toggle-link will be in the first list-item
343                                         $firstItem = $collapsible.find( 'li:first' );
344                                         $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
346                                         // If theres no toggle link, add it
347                                         if ( !$toggle.length ) {
348                                                 // Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
349                                                 // to be "1". Except if the value-attribute is already used.
350                                                 // If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
351                                                 firstval = $firstItem.attr( 'value' );
352                                                 if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
353                                                         $firstItem.attr( 'value', '1' );
354                                                 }
355                                                 $toggleLink = buildDefaultToggleLink();
356                                                 $toggleLink.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
357                                         } else {
358                                                 actionHandler = premadeToggleHandler;
359                                                 $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
360                                         }
362                                 } else { // <div>, <p> etc.
364                                         // The toggle-link will be the first child of the element
365                                         $toggle = $collapsible.find( '> .mw-collapsible-toggle' );
367                                         // If a direct child .content-wrapper does not exists, create it
368                                         if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
369                                                 $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
370                                         }
372                                         // If theres no toggle link, add it
373                                         if ( !$toggle.length ) {
374                                                 $toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
375                                         } else {
376                                                 actionHandler = premadeToggleHandler;
377                                                 $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
378                                         }
379                                 }
380                         }
382                         // Attributes for accessibility. This isn't necessary when the toggler is already
383                         // an <a> or a <button> etc., but it doesn't hurt either, and it's consistent.
384                         $toggleLink.prop( 'tabIndex', 0 );
386                         // Initial state
387                         if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
388                                 // One toggler can hook to multiple elements, and one element can have
389                                 // multiple togglers. This is the sanest way to handle that.
390                                 actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
391                         }
392                 } );
393         };
394 }( jQuery, mediaWiki ) );