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