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