Debian Codegraph @

resources/src/jquery/jquery.makeCollapsible.js

raw symbols SCIP
1 /**
2 * jQuery makeCollapsible
3 * Note: To avoid performance issues such as reflows, several styles are
4 * shipped in mediawiki.makeCollapsible.styles to reserve space for the toggle control. Please
5 * familiarise yourself with that CSS before making any changes to this code.
6 *
7 * Dual licensed:
8 * - CC BY 3.0 <https://creativecommons.org/licenses/by/3.0>
9 * - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
10 */
11 /**
12 * Collapse a collection of elements.
13 *
14 * @module jquery.makeCollapsible
15 */
16 ( function () {
17 /**
18 * Handler for a click on a collapsible toggler.
19 *
20 * @private
21 * @param {jQuery} $collapsible
22 * @param {boolean} expand Expand the element, otherwise collapse
23 * @param {jQuery|null} [$defaultToggle]
24 * @param {Object|undefined} [options]
25 */
26 function toggleElement( $collapsible, expand, $defaultToggle, options ) {
27 options = options || {};
28
29 // Validate parameters
30
31 // $collapsible must be an instance of jQuery
32 if ( !$collapsible.jquery ) {
33 return;
34 }
35 if ( $defaultToggle === undefined ) {
36 $defaultToggle = null;
37 }
38
39 // Trigger a custom event to allow callers to hook to the collapsing/expanding,
40 // allowing the module to be testable, and making it possible to
41 // e.g. implement persistence via cookies
42 $collapsible.trigger( expand ? 'beforeExpand.mw-collapsible' : 'beforeCollapse.mw-collapsible' );
43 const hookCallback = function () {
44 $collapsible.trigger( expand ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
45 };
46
47 // Handle different kinds of elements
48 let $containers;
49 if ( !options.plainMode && $collapsible.is( 'table' ) ) {
50 // Tables
51 // If there is a caption, hide all rows; otherwise, only hide body rows
52 if ( $collapsible.find( '> caption' ).length ) {
53 $containers = $collapsible.find( '> * > tr' );
54 } else {
55 $containers = $collapsible.find( '> tbody > tr' );
56 }
57 if ( $defaultToggle ) {
58 // Exclude table row containing togglelink
59 $containers = $containers.not( $defaultToggle.closest( 'tr' ) );
60 }
61
62 } else if ( !options.plainMode && ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) ) {
63 // Lists
64 $containers = $collapsible.find( '> li' );
65 if ( $defaultToggle ) {
66 // Exclude list-item containing togglelink
67 $containers = $containers.not( $defaultToggle.parent() );
68 }
69 } else {
70 // Everything else: <div>, <p> etc.
71 const $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );
72
73 // If a collapsible-content is defined, act on it
74 if ( !options.plainMode && $collapsibleContent.length ) {
75 $containers = $collapsibleContent;
76
77 // Otherwise assume this is a customcollapse with a remote toggle
78 // .. and there is no collapsible-content because the entire element should be toggled
79 } else {
80 $containers = $collapsible;
81 }
82 }
83
84 $containers.toggle( expand );
85 hookCallback();
86 }
87
88 /**
89 * Handle clicking/keypressing on the collapsible element toggle and other
90 * situations where a collapsible element is toggled (e.g. the initial
91 * toggle for collapsed ones).
92 *
93 * @private
94 * @param {jQuery} $toggle the clickable toggle itself
95 * @param {jQuery} $collapsible the collapsible element
96 * @param {jQuery.Event|null} e either the event or null if unavailable
97 * @param {Object|undefined} options
98 */
99 function togglingHandler( $toggle, $collapsible, e, options ) {
100 options = options || {};
101
102 if ( e ) {
103 if (
104 e.type === 'click' &&
105 e.target.nodeName.toLowerCase() === 'a' &&
106 $( e.target ).attr( 'href' )
107 ) {
108 // Don't fire if a link was clicked (for premade togglers)
109 return;
110 } else if ( e.type === 'keydown' && e.which !== 13 && e.which !== 32 ) {
111 // Only handle the "Enter" or "Space" keys
112 return;
113 } else {
114 e.preventDefault();
115 e.stopPropagation();
116 }
117 }
118
119 // This allows the element to be hidden on initial toggle without fiddling with the class
120 let wasCollapsed;
121 if ( options.wasCollapsed !== undefined ) {
122 wasCollapsed = options.wasCollapsed;
123 } else {
124 // eslint-disable-next-line no-jquery/no-class-state
125 wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
126 }
127
128 // Toggle the state of the collapsible element (that is, expand or collapse)
129 $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );
130
131 // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
132 if ( options.toggleClasses ) {
133 $toggle
134 .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
135 .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
136 }
137
138 // Toggle `aria-expanded` attribute, if requested (for default and premade togglers by default).
139 if ( options.toggleARIA ) {
140 $toggle.attr( 'aria-expanded', wasCollapsed ? 'true' : 'false' );
141 }
142
143 // Toggle the text ("Show"/"Hide") within elements tagged with mw-collapsible-text
144 if ( options.toggleText ) {
145 const collapseText = options.toggleText.collapseText;
146 const expandText = options.toggleText.expandText;
147
148 const $textContainer = $toggle.find( '.mw-collapsible-text' );
149 if ( $textContainer.length ) {
150 $textContainer.text( wasCollapsed ? collapseText : expandText );
151 }
152 }
153
154 // And finally toggle the element state itself
155 toggleElement( $collapsible, !!wasCollapsed, $toggle, options );
156 }
157
158 /**
159 * If the URL contains a hash followed by the fragment identifier of an
160 * element inside collapsed parents, expand them all and scroll to it.
161 *
162 * @private
163 */
164 function hashHandler() {
165 const fragment = mw.util.getTargetFromFragment();
166 if ( !fragment ) {
167 // The fragment doesn't exist
168 return;
169 }
170
171 const $parents = $( fragment ).parents( '.mw-collapsed' );
172 if ( !$parents.length ) {
173 // The fragment is not in a collapsed element
174 return;
175 }
176
177 // Expand collapsed parents
178 $parents.each( function () {
179 const $collapsible = $( this );
180 if ( $collapsible.data( 'mw-made-collapsible' ) ) {
181 $collapsible.data( 'mw-collapsible' ).expand();
182 } else {
183 // The collapsible has not been initialized, so just prevent it
184 // from being collapsed
185 $collapsible.removeClass( 'mw-collapsed' );
186 }
187 } );
188
189 // Scroll to the fragment
190 fragment.scrollIntoView();
191 }
192
193 /**
194 * Enable collapsible-functionality on all elements in the collection.
195 *
196 * - Will prevent binding twice to the same element.
197 * - Initial state is expanded by default, this can be overridden by adding class
198 * "mw-collapsed" to the "mw-collapsible" element.
199 * - Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
200 * - The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).
201 *
202 * To use this {@link jQuery} plugin, load the `jquery.makeCollapsible` module with {@link mw.loader}.
203 *
204 * @example
205 * mw.loader.using( 'jquery.makeCollapsible' ).then( () => {
206 * $( 'table' ).makeCollapsible();
207 * } );
208 * @param {Object} [options]
209 * @param {string} [options.collapseText] Text used for the toggler, when clicking it would
210 * collapse the element. Default: the 'data-collapsetext' attribute of the
211 * collapsible element or the content of 'collapsible-collapse' message.
212 * @param {string} [options.expandText] Text used for the toggler, when clicking it would
213 * expand the element. Default: the 'data-expandtext' attribute of the
214 * collapsible element or the content of 'collapsible-expand' message.
215 * @param {boolean} [options.collapsed] Whether to collapse immediately. By default
216 * collapse only if the element has the 'mw-collapsed' class.
217 * @param {jQuery} [options.$customTogglers] Elements to be used as togglers
218 * for this collapsible element. By default, if the collapsible element
219 * has an id attribute like 'mw-customcollapsible-XXX', elements with a
220 * **class** of 'mw-customtoggle-XXX' are made togglers for it.
221 * @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
222 * element collapsible - that is, hide entire tables and lists (instead
223 * of hiding only all rows but first of tables, and hiding each list
224 * item separately for lists) and don't wrap other elements in
225 * div.mw-collapsible-content. May only be used with custom togglers.
226 * @return {jQuery}
227 * @memberof module:jquery.makeCollapsible
228 * @method
229 */
230 $.fn.makeCollapsible = function ( options ) {
231 options = options || {};
232
233 this.each( function () {
234 // Ensure class "mw-collapsible" is present in case .makeCollapsible()
235 // is called on element(s) that don't have it yet.
236 const $collapsible = $( this ).addClass( 'mw-collapsible' );
237
238 // Return if it has been enabled already.
239 if ( $collapsible.data( 'mw-made-collapsible' ) ) {
240 return;
241 } else {
242 // Let CSS know that it no longer needs to worry about flash of unstyled content.
243 // This will allow mediawiki.makeCollapsible.styles to disable temporary pseudo elements, that
244 // are needed to avoid a flash of unstyled content.
245 $collapsible.addClass( 'mw-made-collapsible' )
246 .data( 'mw-made-collapsible', true );
247 }
248
249 // Use custom text or default?
250 const collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
251 const expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );
252
253 // Default click/keydown handler and toggle link to use when none is present
254 let actionHandler = function ( e, opts ) {
255 const defaultOpts = {
256 toggleClasses: true,
257 toggleARIA: true,
258 toggleText: { collapseText: collapseText, expandText: expandText }
259 };
260 opts = Object.assign( defaultOpts, options, opts );
261
262 // Take care of cloned content (e.g. in reference popups): if the toggle
263 // link is not inside the original collapsible, make it toggle the
264 // cloned collapsible (which we expect to be there) instead of
265 // original.
266 let $currentCollapsible = $.contains( $collapsible.get( 0 ), this ) ?
267 $collapsible :
268 $( this ).closest( '.mw-collapsible' );
269 // However, if we still can't find the collapsible, fallback to original
270 if ( $currentCollapsible.length === 0 ) {
271 $currentCollapsible = $collapsible;
272 }
273
274 togglingHandler( $( this ), $currentCollapsible, e, opts );
275 };
276
277 // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
278 const buildDefaultToggleLink = function () {
279 return $( '<span>' )
280 .addClass( 'mw-collapsible-text' )
281 .text( collapseText )
282 .wrap( '<button type="button" class="mw-collapsible-toggle mw-collapsible-toggle-default"></button>' )
283 .parent();
284 };
285
286 // Check if this element has a custom position for the toggle link
287 // (ie. outside the container or deeper inside the tree)
288 let $customTogglers;
289 if ( options.$customTogglers ) {
290 $customTogglers = $( options.$customTogglers );
291 } else {
292 let collapsibleId = $collapsible.attr( 'id' ) || '';
293 if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
294 collapsibleId = $.escapeSelector( collapsibleId );
295 $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
296 .addClass( 'mw-customtoggle' );
297 }
298 }
299
300 // Add event handlers to custom togglers or create our own ones
301 let $toggle;
302 if ( $customTogglers && $customTogglers.length ) {
303 actionHandler = function ( e, opts ) {
304 const defaultOpts = {};
305 opts = Object.assign( defaultOpts, options, opts );
306 togglingHandler( $( this ), $collapsible, e, opts );
307 };
308
309 $toggle = $customTogglers;
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
316 let $firstItem;
317 if ( $collapsible.is( 'table' ) ) {
318
319 // If the table has a caption, collapse to the caption
320 // as opposed to the first row
321 const $caption = $collapsible.find( '> caption' );
322 if ( $caption.length ) {
323 $toggle = $caption.find( '> .mw-collapsible-toggle, .mw-collapsible-toggle-placeholder' ).first();
324
325 // If there is no toggle link, add it to the end of the caption
326 if ( !$toggle.length ) {
327 $toggle = buildDefaultToggleLink().appendTo( $caption );
328 }
329 } else {
330 // The toggle-link will be in one of the cells (td or th) of the first row
331 $firstItem = $collapsible.find( 'tr' ).first().find( 'th, td' );
332 $toggle = $firstItem.find( '> .mw-collapsible-toggle, .mw-collapsible-toggle-placeholder' ).first();
333
334 // If theres no toggle link, add it to the last cell
335 if ( !$toggle.length ) {
336 $toggle = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
337 }
338 }
339
340 } else if ( $collapsible.parent().is( 'li' ) &&
341 $collapsible.parent().children( '.mw-collapsible' ).length === 1 &&
342 $collapsible.find( '> .mw-collapsible-toggle, .mw-collapsible-toggle-placeholder' ).length === 0
343 ) {
344 // special case of one collapsible in <li> tag
345 $toggle = buildDefaultToggleLink();
346 $collapsible.before( $toggle );
347 } else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
348 // The toggle-link will be in the first list-item
349 $firstItem = $collapsible.find( 'li' ).first();
350 $toggle = $firstItem.find( '> .mw-collapsible-toggle, .mw-collapsible-toggle-placeholder' ).first();
351
352 // If theres no toggle link, add it
353 if ( !$toggle.length ) {
354 // Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
355 // to be "1". Except if the value-attribute is already used.
356 // If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
357 const firstval = $firstItem.prop( 'value' );
358 if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
359 $firstItem.prop( 'value', '1' );
360 }
361 $toggle = buildDefaultToggleLink();
362 $toggle.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
363 }
364
365 } else { // <div>, <p> etc.
366
367 // The toggle-link will be the first child of the element
368 $toggle = $collapsible.find( '> .mw-collapsible-toggle, .mw-collapsible-toggle-placeholder' ).first();
369
370 // If a direct child .content-wrapper does not exists, create it
371 if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
372 $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
373 }
374
375 // If theres no toggle link, add it
376 if ( !$toggle.length ) {
377 $toggle = buildDefaultToggleLink().prependTo( $collapsible );
378 }
379 }
380 }
381
382 // If the toggle is just a placeholder, replace it with a real one
383 // eslint-disable-next-line no-jquery/no-class-state
384 if ( $toggle.hasClass( 'mw-collapsible-toggle-placeholder' ) ) {
385 const $realToggle = buildDefaultToggleLink();
386 $toggle.replaceWith( $realToggle );
387 $toggle = $realToggle;
388 }
389
390 // Attach event handlers to togglelink
391 $toggle.on( 'click.mw-collapsible keydown.mw-collapsible', actionHandler )
392 .attr( 'aria-expanded', 'true' )
393 .prop( 'tabIndex', 0 );
394
395 $( this ).data( 'mw-collapsible', {
396 collapse: function () {
397 actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
398 },
399 expand: function () {
400 actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: true } );
401 },
402 toggle: function () {
403 actionHandler.call( $toggle.get( 0 ), null, null );
404 }
405 } );
406
407 // Initial state
408 // eslint-disable-next-line no-jquery/no-class-state
409 if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
410 // One toggler can hook to multiple elements, and one element can have
411 // multiple togglers. This is the best way to handle that.
412 actionHandler.call( $toggle.get( 0 ), null, { wasCollapsed: false } );
413 }
414
415 } );
416
417 // Attach hash handler
418 window.addEventListener( 'hashchange', hashHandler );
419
420 /**
421 * Fired after collapsible content has been initialized.
422 *
423 * This gives an option to modify the collapsible behavior.
424 *
425 * @event ~'wikipage.collapsibleContent'
426 * @memberof Hooks
427 * @param {jQuery} $collapsible An element that has been made collapsible
428 */
429 mw.hook( 'wikipage.collapsibleContent' ).fire( this );
430
431 return this;
432 };
433
434 // Run hash handler right now in case the URL already has a hash
435 hashHandler();
436
437 }() );