Merge "jquery.makeCollapsible: Togglers accessibility"
[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 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 // Don't fire if a link was clicked, if requested (for premade togglers by default)
164 if ( options.linksPassthru && $.nodeName( e.target, 'a' ) ) {
165 return;
166 } else {
167 e.preventDefault();
168 e.stopPropagation();
169 }
170 }
171
172 wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
173
174 // Toggle the state of the collapsible element (that is, expand or collapse)
175 $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
176
177 // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
178 if ( options.toggleClasses ) {
179 $toggle
180 .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
181 .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
182 }
183
184 // Toggle the text ("Show"/"Hide"), if requested (for default togglers by default)
185 if ( options.toggleText ) {
186 collapseText = options.toggleText.collapseText;
187 expandText = options.toggleText.expandText;
188
189 $textContainer = $toggle.find( '> a' );
190 if ( !$textContainer.length ) {
191 $textContainer = $toggle;
192 }
193 $textContainer.text( wasCollapsed ? collapseText : expandText );
194 }
195
196 // And finally toggle the element state itself
197 toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
198 }
199
200 /**
201 * Make any element collapsible.
202 *
203 * Supported options:
204 * - collapseText: text to be used for the toggler when clicking it would
205 * collapse the element. Default: the 'data-collapsetext' attribute of
206 * the collapsible element or the content of 'collapsible-collapse'
207 * message.
208 * - expandText: text to be used for the toggler when clicking it would
209 * expand the element. Default: the 'data-expandtext' attribute of
210 * the collapsible element or the content of 'collapsible-expand'
211 * message.
212 * - collapsed: boolean, whether to collapse immediately. By default
213 * collapse only if the elements has the 'mw-collapsible' class.
214 * - $customTogglers: jQuerified list of elements to be used as togglers
215 * for this collapsible element. By default, if the collapsible element
216 * has an id attribute like 'mw-customcollapsible-XXX', elements with a
217 * *class* of 'mw-customtoggle-XXX' are made togglers for it.
218 * - plainMode: boolean, whether to use a "plain mode" when making the
219 * element collapsible - that is, hide entire tables and lists (instead
220 * of hiding only all rows but first of tables, and hiding each list
221 * item separately for lists) and don't wrap other elements in
222 * div.mw-collapsible-content. May only be used with custom togglers.
223 */
224 $.fn.makeCollapsible = function ( options ) {
225 if ( options === undefined ) {
226 options = {};
227 }
228
229 return this.each( function () {
230 var $collapsible, collapseText, expandText, $toggle, clickHandler, buildDefaultToggleLink,
231 premadeToggleHandler, $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
232
233 // Ensure class "mw-collapsible" is present in case .makeCollapsible()
234 // is called on element(s) that don't have it yet.
235 $collapsible = $( this ).addClass( 'mw-collapsible' );
236
237 // Return if it has been enabled already.
238 if ( $collapsible.data( 'mw-made-collapsible' ) ) {
239 return;
240 } else {
241 $collapsible.data( 'mw-made-collapsible', true );
242 }
243
244 // Use custom text or default?
245 collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
246 expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
247
248 // Default click handler and toggle link to use when none is present
249 clickHandler = function ( e, opts ) {
250 var defaultOpts = {
251 toggleClasses: true,
252 toggleText: { collapseText: collapseText, expandText: expandText }
253 };
254 opts = $.extend( defaultOpts, options, opts );
255 togglingHandler( $( this ), $collapsible, e, opts );
256 };
257 // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
258 buildDefaultToggleLink = function () {
259 return $( '<a href="#"></a>' )
260 .text( collapseText )
261 .wrap( '<span class="mw-collapsible-toggle"></span>' )
262 .parent()
263 .prepend( '&nbsp;[' )
264 .append( ']&nbsp;' )
265 .on( 'click.mw-collapsible', clickHandler );
266 };
267
268 // Default handler for clicking on premade toggles
269 premadeToggleHandler = function ( e, opts ) {
270 var defaultOpts = { toggleClasses: true, linksPassthru: true };
271 opts = $.extend( defaultOpts, options, opts );
272 togglingHandler( $( this ), $collapsible, e, opts );
273 };
274
275 // Check if this element has a custom position for the toggle link
276 // (ie. outside the container or deeper inside the tree)
277 if ( options.$customTogglers ) {
278 $customTogglers = $( options.$customTogglers );
279 } else {
280 collapsibleId = $collapsible.attr( 'id' ) || '';
281 if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
282 mw.log( lpx + 'Found custom collapsible: #' + collapsibleId );
283 $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) );
284
285 // Double check that there is actually a customtoggle link
286 if ( !$customTogglers.length ) {
287 mw.log( lpx + '#' + collapsibleId + ': Missing toggler!' );
288 }
289 }
290 }
291
292 // Bind the togglers
293 if ( $customTogglers && $customTogglers.length ) {
294 clickHandler = function ( e, opts ) {
295 var defaultOpts = {};
296 opts = $.extend( defaultOpts, options, opts );
297 togglingHandler( $( this ), $collapsible, e, opts );
298 };
299
300 $toggleLink = $customTogglers;
301 $toggleLink.on( 'click.mw-collapsible', clickHandler );
302
303 } else {
304 // If this is not a custom case, do the default: wrap the
305 // contents and add the toggle link. Different elements are
306 // treated differently.
307 if ( $collapsible.is( 'table' ) ) {
308 // The toggle-link will be in one the the cells (td or th) of the first row
309 $firstItem = $collapsible.find( 'tr:first th, tr:first td' );
310 $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
311
312 // If theres no toggle link, add it to the last cell
313 if ( !$toggle.length ) {
314 $toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
315 } else {
316 clickHandler = premadeToggleHandler;
317 $toggleLink = $toggle.on( 'click.mw-collapsible', clickHandler );
318 }
319
320 } else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
321 // The toggle-link will be in the first list-item
322 $firstItem = $collapsible.find( 'li:first' );
323 $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
324
325 // If theres no toggle link, add it
326 if ( !$toggle.length ) {
327 // Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
328 // to be "1". Except if the value-attribute is already used.
329 // If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
330 firstval = $firstItem.attr( 'value' );
331 if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
332 $firstItem.attr( 'value', '1' );
333 }
334 $toggleLink = buildDefaultToggleLink();
335 $toggleLink.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
336 } else {
337 clickHandler = premadeToggleHandler;
338 $toggleLink = $toggle.on( 'click.mw-collapsible', clickHandler );
339 }
340
341 } else { // <div>, <p> etc.
342
343 // The toggle-link will be the first child of the element
344 $toggle = $collapsible.find( '> .mw-collapsible-toggle' );
345
346 // If a direct child .content-wrapper does not exists, create it
347 if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
348 $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
349 }
350
351 // If theres no toggle link, add it
352 if ( !$toggle.length ) {
353 $toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
354 } else {
355 clickHandler = premadeToggleHandler;
356 $toggleLink = $toggle.on( 'click.mw-collapsible', clickHandler );
357 }
358 }
359 }
360
361 // Attributes for accessibility. This isn't necessary when the toggler is already
362 // an <a> or a <button> etc., but it doesn't hurt either, and it's consistent.
363 $toggleLink.prop( 'tabIndex', 0 ).attr( 'role', 'button' );
364
365 // Initial state
366 if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
367 // Remove here so that the toggler goes in the right direction (the class is re-added)
368 $collapsible.removeClass( 'mw-collapsed' );
369 // One toggler can hook to multiple elements, and one element can have
370 // multiple togglers. This is the sanest way to handle that.
371 clickHandler.call( $toggleLink.get( 0 ), null, { instantHide: true } );
372 }
373 } );
374 };
375 }( jQuery, mediaWiki ) );