Debian Codegraph @

resources/src/mediawiki.page.ready/checkboxHack.js

raw symbols SCIP
1 /**
2 * Utility library for managing components using the [CSS checkbox hack]{@link https://css-tricks.com/the-checkbox-hack/}.
3 * To access call ```require('mediawiki.page.ready').checkboxHack```.
4 *
5 * The checkbox hack works without JavaScript for graphical user-interface users, but relies on
6 * enhancements to work well for screen reader users. This module provides required a11y
7 * interactivity for updating the `aria-expanded` accessibility state, and optional enhancements
8 * for avoiding the distracting focus ring when using a pointing device, and target dismissal on
9 * focus loss or external click.
10 *
11 * The checkbox hack is a prevalent pattern in MediaWiki similar to disclosure widgets[0]. Although
12 * dated and out-of-fashion, it's surprisingly flexible allowing for both `details` / `summary`-like
13 * patterns, menu components, and more complex structures (to be used sparingly) where the toggle
14 * button and target are in different parts of the Document without an enclosing element, so long as
15 * they can be described as a sibling to the input. It's complicated and frequent enough to warrant
16 * single implementation.
17 *
18 * In time, proper disclosure widgets should replace checkbox hacks. However, the second pattern has
19 * no equivalent so the checkbox hack may have a continued use case for some time to come.
20 *
21 * When the abstraction is leaky, the underlying implementation is simpler than anything built to
22 * hide it. Attempts to abstract the functionality for the second pattern failed so all related code
23 * celebrates the implementation as directly as possible.
24 *
25 * All the code assumes that when the input is checked, the target is in an expanded state.
26 *
27 * Consider the disclosure widget pattern first mentioned:
28 *
29 * ```html
30 * <details> <!-- Container -->
31 * <summary>Click to expand navigation menu</summary> <!-- Button -->
32 * <ul> <!-- Target -->
33 * <li>Main page</li>
34 * <li>Random article</li>
35 * <li>Donate to Wikipedia</li>
36 * </ul>
37 * </details>
38 * ```
39 *
40 * Which is represented verbosely by a checkbox hack as such:
41 *
42 * ```html
43 * <div> <!-- Container -->
44 * <input <!-- Visually hidden checkbox -->
45 * type="checkbox"
46 * id="sidebar-checkbox"
47 * class="mw-checkbox-hack-checkbox"
48 * {{#visible}}checked{{/visible}}
49 * role="button"
50 * aria-labelledby="sidebar-button"
51 * aria-expanded="true||false"
52 * aria-haspopup="true"> <!-- Optional attribute -->
53 * <label <!-- Button -->
54 * id="sidebar-button"
55 * class="mw-checkbox-hack-button"
56 * for="sidebar-checkbox"
57 * aria-hidden="true">
58 * Click to expand navigation menu
59 * </label>
60 * <ul id="sidebar" class="mw-checkbox-hack-target"> <!-- Target -->
61 * <li>Main page</li>
62 * <li>Random article</li>
63 * <li>Donate to Wikipedia</li>
64 * </ul>
65 * </div>
66 * ```
67 *
68 * Where the checkbox is the input, the label is the button, and the target is the unordered list.
69 * `aria-haspopup` is an optional attribute that can be applied when dealing with popup elements (i.e. menus).
70 *
71 * Note that while the label acts as a button for visual users (i.e. it's usually styled as a button and is clicked),
72 * the checkbox is what's actually interacted with for keyboard and screenreader users. Many of the HTML attributes
73 * and JS enhancements serve to give the checkbox the behavior and semantics of a button.
74 * For this reason any hover/focus/active state styles for the button should be applied based on the checkbox state
75 * (i.e. https://github.com/wikimedia/mediawiki/blob/master/resources/src/mediawiki.ui.button/button.less#L90)
76 *
77 * Consider the disparate pattern:
78 *
79 * ```html
80 * <!-- ... -->
81 * <!-- The only requirement is that the button and target can be described as a sibling to the
82 * checkbox. -->
83 * <input
84 * type="checkbox"
85 * id="sidebar-checkbox"
86 * class="mw-checkbox-hack-checkbox"
87 * {{#visible}}checked{{/visible}}
88 * role="button"
89 * aria-labelledby="sidebar-button"
90 * aria-expanded="true||false"
91 * aria-haspopup="true">
92 * <!-- ... -->
93 * <label
94 * id="sidebar-button"
95 * class="mw-checkbox-hack-button"
96 * for="sidebar-checkbox"
97 * aria-hidden="true">
98 * Toggle navigation menu
99 * </label>
100 * <!-- ... -->
101 * <ul id="sidebar" class="mw-checkbox-hack-target">
102 * <li>Main page</li>
103 * <li>Random article</li>
104 * <li>Donate to Wikipedia</li>
105 * </ul>
106 * <!-- ... -->
107 * ```
108 *
109 * Which is the same as the disclosure widget but without the enclosing container and the input only
110 * needs to be a preceding sibling of the button and target. It's possible to bend the checkbox hack
111 * further to allow the button and target to be at an arbitrary depth so long as a parent can be
112 * described as a succeeding sibling of the input, but this requires a mixin implementation that
113 * duplicates the rules for each relation selector.
114 *
115 * Exposed APIs should be considered stable.
116 *
117 * Accompanying checkbox hack styles are tracked in T252774.
118 *
119 * [0]: https://developer.mozilla.org/docs/Web/HTML/Element/details
120 *
121 * @namespace CheckboxHack
122 * @memberof module:mediawiki.page.ready
123 */
124 /**
125 * Revise the button's `aria-expanded` state to match the checked state.
126 *
127 * @memberof module:mediawiki.page.ready.CheckboxHack
128 * @param {HTMLInputElement} checkbox
129 * @param {HTMLElement} button
130 */
131 function updateAriaExpanded( checkbox, button ) {
132 if ( button ) {
133 mw.log.warn( '[1.38] The button parameter in updateAriaExpanded is deprecated, aria-expanded will be applied to the checkbox going forward. View the updated checkbox hack documentation for more details.' );
134 button.setAttribute( 'aria-expanded', checkbox.checked.toString() );
135 return;
136 }
137
138 checkbox.setAttribute( 'aria-expanded', checkbox.checked.toString() );
139 }
140
141 /**
142 * Set the checked state and fire the 'input' event.
143 * Programmatic changes to checkbox.checked do not trigger an input or change event.
144 * The input event in turn will call updateAriaExpanded().
145 *
146 * setCheckedState() is called when a user event on some element other than the checkbox
147 * should result in changing the checkbox state.
148 *
149 * Per https://html.spec.whatwg.org/multipage/indices.html#event-input
150 * Input event is fired at controls when the user changes the value.
151 * Per https://html.spec.whatwg.org/multipage/input.html#checkbox-state-(type=checkbox):event-input
152 * Fire an event named input at the element with the bubbles attribute initialized to true.
153 *
154 * https://html.spec.whatwg.org/multipage/indices.html#event-change
155 * For completeness the 'change' event should be fired too,
156 * however we make no use of the 'change' event,
157 * nor expect it to be used, thus firing it
158 * would be unnecessary load.
159 *
160 * @param {HTMLInputElement} checkbox
161 * @param {boolean} checked
162 * @ignore
163 */
164 function setCheckedState( checkbox, checked ) {
165 checkbox.checked = checked;
166 // Chrome and Firefox sends the builtin Event with .bubbles == true and .composed == true.
167 /** @type {Event} */
168 let e;
169 if ( typeof Event === 'function' ) {
170 e = new Event( 'input', { bubbles: true, composed: true } );
171 } else {
172 // IE 9-11, FF 6-10, Chrome 9-14, Safari 5.1, Opera 11.5, Android 3-4.3
173 e = document.createEvent( 'CustomEvent' );
174 if ( !e ) {
175 return;
176 }
177 e.initCustomEvent( 'input', true /* canBubble */, false, false );
178 }
179 checkbox.dispatchEvent( e );
180 }
181
182 /**
183 * Returns true if the Event's target is an inclusive descendant of any the checkbox hack's
184 * constituents (checkbox, button, or target), and false otherwise.
185 *
186 * @param {HTMLInputElement} checkbox
187 * @param {HTMLElement} button
188 * @param {Node} target
189 * @param {Event} event
190 * @return {boolean}
191 * @ignore
192 */
193 function containsEventTarget( checkbox, button, target, event ) {
194 return event.target instanceof Node && (
195 checkbox.contains( event.target ) ||
196 button.contains( event.target ) ||
197 target.contains( event.target )
198 );
199 }
200
201 /**
202 * Dismiss the target when event is outside the checkbox, button, and target.
203 * In simple terms this closes the target (menu, typically) when clicking somewhere else.
204 *
205 * @param {HTMLInputElement} checkbox
206 * @param {HTMLElement} button
207 * @param {Node} target
208 * @param {Event} event
209 * @ignore
210 */
211 function dismissIfExternalEventTarget( checkbox, button, target, event ) {
212 if ( checkbox.checked && !containsEventTarget( checkbox, button, target, event ) ) {
213 setCheckedState( checkbox, false );
214 }
215 }
216
217 /**
218 * Update the `aria-expanded` attribute based on checkbox state (target visibility) changes.
219 *
220 * @memberof module:mediawiki.page.ready.CheckboxHack
221 * @param {HTMLInputElement} checkbox
222 * @param {HTMLElement} button
223 * @return {function(): void} Cleanup function that removes the added event listeners.
224 */
225 function bindUpdateAriaExpandedOnInput( checkbox, button ) {
226 if ( button ) {
227 mw.log.warn( '[1.38] The button parameter in bindUpdateAriaExpandedOnInput is deprecated, aria-expanded will be applied to the checkbox going forward. View the updated checkbox hack documentation for more details.' );
228 }
229
230 const listener = updateAriaExpanded.bind( undefined, checkbox, button );
231 // Whenever the checkbox state changes, update the `aria-expanded` state.
232 checkbox.addEventListener( 'input', listener );
233
234 return function () {
235 checkbox.removeEventListener( 'input', listener );
236 };
237 }
238
239 /**
240 * Manually change the checkbox state to avoid a focus change when using a pointing device.
241 *
242 * @memberof module:mediawiki.page.ready.CheckboxHack
243 * @param {HTMLInputElement} checkbox
244 * @param {HTMLElement} button
245 * @return {function(): void} Cleanup function that removes the added event listeners.
246 */
247 function bindToggleOnClick( checkbox, button ) {
248 function listener( event ) {
249 // Do not allow the browser to handle the checkbox. Instead, manually toggle it which does
250 // not alter focus.
251 event.preventDefault();
252 setCheckedState( checkbox, !checkbox.checked );
253 }
254 button.addEventListener( 'click', listener, true );
255
256 return function () {
257 button.removeEventListener( 'click', listener, true );
258 };
259 }
260
261 /**
262 * Manually change the checkbox state when the button is focused and SPACE is pressed.
263 *
264 * @deprecated Use `bindToggleOnEnter` instead.
265 * @memberof module:mediawiki.page.ready.CheckboxHack
266 * @param {HTMLInputElement} checkbox
267 * @param {HTMLElement} button
268 * @return {function(): void} Cleanup function that removes the added event listeners.
269 */
270 function bindToggleOnSpaceEnter( checkbox, button ) {
271 mw.log.warn( '[1.38] bindToggleOnSpaceEnter is deprecated. Use `bindToggleOnEnter` instead.' );
272
273 function isEnterOrSpace( /** @type {KeyboardEvent} */ event ) {
274 return event.key === ' ' || event.key === 'Enter';
275 }
276
277 function onKeydown( /** @type {KeyboardEvent} */ event ) {
278 // Only handle SPACE and ENTER.
279 if ( !isEnterOrSpace( event ) ) {
280 return;
281 }
282 // Prevent the browser from scrolling when pressing space. The browser will
283 // try to do this unless the "button" element is a button or a checkbox.
284 // Depending on the actual "button" element, this also possibly prevents a
285 // native click event from being triggered so we programatically trigger a
286 // click event in the keyup handler.
287 event.preventDefault();
288 }
289
290 function onKeyup( /** @type {KeyboardEvent} */ event ) {
291 // Only handle SPACE and ENTER.
292 if ( !isEnterOrSpace( event ) ) {
293 return;
294 }
295
296 // A native button element triggers a click event when the space or enter
297 // keys are pressed. Since the passed in "button" may or may not be a
298 // button, programmatically trigger a click event to make it act like a
299 // button.
300 button.click();
301 }
302
303 button.addEventListener( 'keydown', onKeydown );
304 button.addEventListener( 'keyup', onKeyup );
305
306 return function () {
307 button.removeEventListener( 'keydown', onKeydown );
308 button.removeEventListener( 'keyup', onKeyup );
309 };
310 }
311
312 /**
313 * Manually change the checkbox state when the button is focused and Enter is pressed.
314 *
315 * @memberof module:mediawiki.page.ready.CheckboxHack
316 * @param {HTMLInputElement} checkbox
317 * @return {function(): void} Cleanup function that removes the added event listeners.
318 */
319 function bindToggleOnEnter( checkbox ) {
320 function onKeyup( /** @type {KeyboardEvent} */ event ) {
321 // Only handle ENTER.
322 if ( event.key !== 'Enter' ) {
323 return;
324 }
325
326 setCheckedState( checkbox, !checkbox.checked );
327 }
328
329 checkbox.addEventListener( 'keyup', onKeyup );
330
331 return function () {
332 checkbox.removeEventListener( 'keyup', onKeyup );
333 };
334 }
335
336 /**
337 * Dismiss the target when clicking elsewhere and update the `aria-expanded` attribute based on
338 * checkbox state (target visibility).
339 *
340 * @memberof module:mediawiki.page.ready.CheckboxHack
341 * @param {window} window
342 * @param {HTMLInputElement} checkbox
343 * @param {HTMLElement} button
344 * @param {Node} target
345 * @return {function(): void} Cleanup function that removes the added event listeners.
346 */
347 function bindDismissOnClickOutside( window, checkbox, button, target ) {
348 const listener = dismissIfExternalEventTarget.bind( undefined, checkbox, button, target );
349 window.addEventListener( 'click', listener, true );
350
351 return function () {
352 window.removeEventListener( 'click', listener, true );
353 };
354 }
355
356 /**
357 * Dismiss the target when focusing elsewhere and update the `aria-expanded` attribute based on
358 * checkbox state (target visibility).
359 *
360 * @param {window} window
361 * @param {HTMLInputElement} checkbox
362 * @param {HTMLElement} button
363 * @param {Node} target
364 * @return {function(): void} Cleanup function that removes the added event listeners.
365 * @memberof module:mediawiki.page.ready.CheckboxHack
366 */
367 function bindDismissOnFocusLoss( window, checkbox, button, target ) {
368 // If focus is given to any element outside the target, dismiss the target. Setting a focusout
369 // listener on the target would be preferable, but this interferes with the click listener.
370 const listener = dismissIfExternalEventTarget.bind( undefined, checkbox, button, target );
371 window.addEventListener( 'focusin', listener, true );
372
373 return function () {
374 window.removeEventListener( 'focusin', listener, true );
375 };
376 }
377
378 /**
379 * Dismiss the target when clicking on a link to prevent the target from being open
380 * when navigating to a new page.
381 *
382 * @param {HTMLInputElement} checkbox
383 * @param {Node} target
384 * @return {function(): void} Cleanup function that removes the added event listeners.
385 * @memberof module:mediawiki.page.ready.CheckboxHack
386 */
387 function bindDismissOnClickLink( checkbox, target ) {
388 function dismissIfClickLinkEvent( event ) {
389 // Handle clicks to links and link children elements
390 if (
391 // check that the element wasn't removed from the DOM.
392 event.target && event.target.parentNode &&
393 ( event.target.nodeName === 'A' || event.target.parentNode.nodeName === 'A' )
394 ) {
395 setCheckedState( checkbox, false );
396 }
397 }
398 target.addEventListener( 'click', dismissIfClickLinkEvent );
399
400 return function () {
401 target.removeEventListener( 'click', dismissIfClickLinkEvent );
402 };
403 }
404
405 /**
406 * Dismiss the target when clicking or focusing elsewhere and update the `aria-expanded` attribute
407 * based on checkbox state (target visibility) changes made by **the user.** When tapping the button
408 * itself, clear the focus outline.
409 *
410 * This function calls the other bind* functions and is the only expected interaction for most use
411 * cases. It's constituents are provided distinctly for the other use cases.
412 *
413 * @memberof module:mediawiki.page.ready.CheckboxHack
414 * @param {window} window
415 * @param {HTMLInputElement} checkbox The underlying hidden checkbox that controls target
416 * visibility.
417 * @param {HTMLElement} button The visible label icon associated with the checkbox. This button
418 * toggles the state of the underlying checkbox.
419 * @param {Node} target The Node to toggle visibility of based on checkbox state.
420 * @return {function(): void} Cleanup function that removes the added event listeners.
421 */
422 function bind( window, checkbox, button, target ) {
423 const cleanups = [
424 bindUpdateAriaExpandedOnInput( checkbox ),
425 bindToggleOnClick( checkbox, button ),
426 bindToggleOnEnter( checkbox ),
427 bindDismissOnClickOutside( window, checkbox, button, target ),
428 bindDismissOnFocusLoss( window, checkbox, button, target ),
429 bindDismissOnClickLink( checkbox, target )
430 ];
431
432 return function () {
433 cleanups.forEach( ( cleanup ) => {
434 cleanup();
435 } );
436 };
437 }
438
439 module.exports = {
440 updateAriaExpanded,
441 bindUpdateAriaExpandedOnInput,
442 bindToggleOnClick,
443 bindToggleOnSpaceEnter,
444 bindToggleOnEnter,
445 bindDismissOnClickOutside,
446 bindDismissOnFocusLoss,
447 bindDismissOnClickLink,
448 bind
449 };