-
Notifications
You must be signed in to change notification settings - Fork 27
/
Toggler.js
383 lines (347 loc) · 11.7 KB
/
Toggler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
var browser = require( './Browser' ).getSingleton(),
util = require( './util' ),
escapeSelector = util.escapeSelector,
arrowOptions = {
name: 'expand',
type: '',
isSmall: true,
additionalClassNames: 'indicator mw-ui-icon-flush-left'
},
Icon = require( './Icon' ),
alwaysCollapsed = document.body.classList.contains( 'collapsible-headings-collapsed' );
/**
*
* @typedef {Object} ToggledEvent
* @prop {boolean} expanded True if section is opened, false if closed.
* @prop {Page} page
* @prop {jQuery.Object} $heading
*/
/**
* A class for enabling toggling
*
* Toggling can be disabled on a sepcific heading by adding the
* collapsible-heading-disabled class.
*
* @class Toggler
* @param {Object} options
* @param {OO.EventEmitter} options.eventBus Object used to emit section-toggled events.
* @param {jQuery.Object} options.$container to apply toggling to
* @param {string} options.prefix a prefix to use for the id.
* @param {Page} options.page to allow storage of session for future visits
* @param {boolean} [options.isClosed]
*/
function Toggler( options ) {
this.eventBus = options.eventBus;
this._enable( options.$container, options.prefix, options.page, options.isClosed );
}
/**
* Using the settings module looks at what sections were previously expanded on
* existing page.
*
* @param {Page} page
* @return {Object} representing open sections
*/
function getExpandedSections( page ) {
var expandedSections = mw.storage.session.getObject( 'expandedSections' ) || {};
expandedSections[page.title] = expandedSections[page.title] || {};
return expandedSections;
}
/**
* Save expandedSections to sessionStorage
*
* @param {Object} expandedSections
*/
function saveExpandedSections( expandedSections ) {
mw.storage.session.setObject(
'expandedSections', expandedSections
);
}
/**
* Given an expanded heading, store it to sessionStorage.
* If the heading is collapsed, remove it from sessionStorage.
*
* @param {jQuery.Object} $heading - A heading belonging to a section
* @param {Page} page
*/
function storeSectionToggleState( $heading, page ) {
var headline = $heading.find( '.mw-headline' ).attr( 'id' ),
expandedSections = getExpandedSections( page );
if ( headline && expandedSections[page.title] ) {
var isSectionOpen = $heading.hasClass( 'open-block' );
if ( isSectionOpen ) {
expandedSections[page.title][headline] = true;
} else {
delete expandedSections[page.title][headline];
}
saveExpandedSections( expandedSections );
}
}
/**
* Expand sections that were previously expanded before leaving this page.
*
* @param {Toggler} toggler
* @param {jQuery.Object} $container
* @param {Page} page
*/
function expandStoredSections( toggler, $container, page ) {
var $sectionHeading, $headline,
expandedSections = getExpandedSections( page ),
$headlines = $container.find( '.section-heading span' );
$headlines.each( function () {
$headline = $container.find( this );
$sectionHeading = $headline.parents( '.section-heading' );
// toggle only if the section is not already expanded
if (
expandedSections[page.title][$headline.attr( 'id' )] &&
!$sectionHeading.hasClass( 'open-block' )
) {
toggler.toggle( $sectionHeading, page, true );
}
} );
}
/**
* Given a heading, toggle it and any of its children
*
* @memberof Toggler
* @instance
* @param {jQuery.Object} $heading A heading belonging to a section
* @param {Page} page
* @param {boolean} fromSaved Section is being toggled from a saved state
* @return {boolean}
*/
Toggler.prototype.toggle = function ( $heading, page, fromSaved ) {
if ( !fromSaved && $heading.hasClass( 'collapsible-heading-disabled' ) ) {
return false;
}
var self = this,
wasExpanded = $heading.is( '.open-block' );
$heading.toggleClass( 'open-block' );
arrowOptions.rotation = wasExpanded ? 0 : 180;
var indicator = new Icon( arrowOptions );
var $indicatorElement = $heading.data( 'indicator' );
if ( $indicatorElement ) {
$indicatorElement.attr( 'class', indicator.getClassName() );
}
var $headingLabel = $heading.find( '.mw-headline' );
$headingLabel.attr( 'aria-expanded', !wasExpanded );
var $content = $heading.next();
if ( $content.hasClass( 'open-block' ) ) {
$content.removeClass( 'open-block' );
// jquery doesn't allow custom values for the hidden attribute it seems.
$content.get( 0 ).setAttribute( 'hidden', 'until-found' );
} else {
$content.addClass( 'open-block' );
$content.removeAttr( 'hidden' );
}
/* T239418 We consider this event as a low-priority one and emit it asynchronously.
This ensures that any logic associated with section toggling is async and not contributing
directly to a slow click/press event handler.
Currently costly reflow-inducing viewport size computation is being done for lazy-loaded
images by the main listener to this event. */
mw.requestIdleCallback( function () {
/**
* Global event emitted after a section has been toggled
*
* @event section-toggled
* @type {ToggledEvent}
*/
self.eventBus.emit( 'section-toggled', {
expanded: wasExpanded,
$heading: $heading
} );
} );
if ( alwaysCollapsed || !browser.isWideScreen() ) {
storeSectionToggleState( $heading, page );
}
return true;
};
/**
* Enables toggling via enter and space keys
*
* @param {Toggler} toggler instance.
* @param {jQuery.Object} $heading
* @param {Page} page
*/
function enableKeyboardActions( toggler, $heading, page ) {
$heading.on( 'keypress', function ( ev ) {
if ( ev.which === 13 || ev.which === 32 ) {
// Only handle keypresses on the "Enter" or "Space" keys
toggler.toggle( $heading, page );
}
} ).find( 'a' ).on( 'keypress mouseup', function ( ev ) {
ev.stopPropagation();
} );
}
/**
* Reveals an element and its parent section as identified by it's id
*
* @memberof Toggler
* @instance
* @param {string} id An element ID within the $container
* @param {Object} $container jQuery element to search in
* @param {Page} page
* @return {boolean} Target ID was found
*/
Toggler.prototype.reveal = function ( id, $container, page ) {
var $target;
// jQuery will throw for hashes containing certain characters which can break toggling
try {
$target = $container.find( '#' + escapeSelector( id ) );
} catch ( e ) {}
if ( !$target || !$target.length ) {
return false;
}
var $heading = $target.parents( '.collapsible-heading' );
// The heading is not a section heading, check if in a content block!
if ( !$heading.length ) {
$heading = $target.parents( '.collapsible-block' ).prev( '.collapsible-heading' );
}
if ( $heading.length && !$heading.hasClass( 'open-block' ) ) {
this.toggle( $heading, page );
}
if ( $heading.length ) {
// scroll again after opening section (opening section makes the page longer)
window.scrollTo( 0, $target.offset().top );
}
return true;
};
/**
* Enables section toggling in a given container when wgMFCollapseSectionsByDefault
* is enabled.
*
* @memberof Toggler
* @instance
* @param {jQuery.Object} $container to apply toggling to
* @param {string} prefix a prefix to use for the id.
* @param {Page} page to allow storage of session for future visits
* @param {boolean} [isClosed] whether the element should begin closed
* @private
*/
Toggler.prototype._enable = function ( $container, prefix, page, isClosed ) {
var
self = this,
isWideScreen = browser.isWideScreen(),
collapseSectionsByDefault = mw.config.get( 'wgMFCollapseSectionsByDefault' );
if ( collapseSectionsByDefault === undefined ) {
// Old default behavior if on cached output
collapseSectionsByDefault = true;
}
// NB: 'expandSections' uses localStorage, unlike 'expandedSections' which uses sessionStorage
var expandSections = !collapseSectionsByDefault || mw.storage.get( 'expandSections' ) === 'true';
// FIXME This should use .find() instead of .children(), some extensions like Wikibase
// want to toggle other headlines than direct descendants of $container. (T95889)
$container.children( '.section-heading' ).each( function ( i ) {
var $heading = $container.find( this ),
$headingLabel = $heading.find( '.mw-headline' ),
$indicator = $heading.find( '.indicator' ),
id = prefix + 'collapsible-block-' + i;
// Be sure there is a `section` wrapping the section content.
// Otherwise, collapsible sections for this page is not enabled.
if ( $heading.next().is( 'section' ) ) {
var $content = $heading.next( 'section' );
$heading
.addClass( 'collapsible-heading ' )
.data( 'section-number', i )
.on( 'click', function ( ev ) {
// don't toggle, if the click target was a link
// (a link in a section heading)
// See T117880
if ( !ev.target.href ) {
// prevent taps/clicks on edit button after toggling (T58209)
ev.preventDefault();
self.toggle( $heading, page );
}
} );
$headingLabel
.attr( {
tabindex: 0,
role: 'button',
'aria-controls': id,
'aria-expanded': 'false'
} );
arrowOptions.rotation = expandSections ? 180 : 0;
var indicator = new Icon( arrowOptions );
if ( $indicator.length ) {
// replace the existing indicator
$indicator.replaceWith( indicator.$el );
} else {
indicator.prependTo( $heading );
}
$heading.data( 'indicator', indicator.$el );
$content
.addClass( 'collapsible-block' )
.eq( 0 )
.attr( {
// We need to give each content block a unique id as that's
// the only way we can tell screen readers what element we're
// referring to via `aria-controls`.
id: id
} )
.on( 'beforematch', function () {
self.toggle( $heading, page );
} )
.addClass( 'collapsible-block-js' )
.get( 0 ).setAttribute( 'hidden', 'until-found' );
enableKeyboardActions( self, $heading, page );
// When the collapsible-headings-collapsed class is present on the body,
// never expand **all** sections, regardless of device size or preferences.
// (T321618, T322628)
if (
!alwaysCollapsed && (
!isClosed && isWideScreen || expandSections
)
) {
// Expand sections by default on wide screen devices
// or if the expand sections setting is set.
// The wide screen logic for determining whether to collapse sections initially
// should be kept in sync with mobileoptions#initLocalStorageElements().
self.toggle( $heading, page );
}
}
} );
/**
* Checks the existing hash and toggles open any section that contains the fragment.
*
* @method
*/
function checkHash() {
// eslint-disable-next-line no-restricted-properties
var hash = window.location.hash;
if ( hash.indexOf( '#' ) === 0 ) {
hash = hash.slice( 1 );
// Per https://html.spec.whatwg.org/multipage/browsing-the-web.html#target-element
// we try the raw fragment first, then the percent-decoded fragment.
if ( !self.reveal( hash, $container, page ) ) {
var decodedHash = mw.util.percentDecodeFragment( hash );
if ( decodedHash ) {
self.reveal( decodedHash, $container, page );
}
}
}
}
/**
* Checks the value of wgInternalRedirectTargetUrl and sets the hash if present.
* checkHash() will reveal the collapsed section that contains it afterwards.
*
* @method
*/
function checkInternalRedirectAndHash() {
var internalRedirect = mw.config.get( 'wgInternalRedirectTargetUrl' ),
internalRedirectHash = internalRedirect ? internalRedirect.split( '#' )[1] : false;
if ( internalRedirectHash ) {
// eslint-disable-next-line no-restricted-properties
window.location.hash = internalRedirectHash;
}
}
checkInternalRedirectAndHash();
checkHash();
util.getWindow().on( 'hashchange', function () {
checkHash();
} );
if ( ( alwaysCollapsed || !browser.isWideScreen() ) && page ) {
expandStoredSections( this, $container, page );
}
};
Toggler._getExpandedSections = getExpandedSections;
Toggler._expandStoredSections = expandStoredSections;
module.exports = Toggler;