mediawiki-skins-Citizen/resources/skins.citizen.scripts/checkboxHack.js

85 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-01-22 02:08:55 +00:00
var DRAWER_ID = 'mw-drawer',
DRAWER_BUTTON_ID = 'mw-drawer-button',
2021-01-22 02:08:55 +00:00
DRAWER_CHECKBOX_ID = 'mw-drawer-checkbox',
PERSONAL_MENU_ID = 'p-personal',
PERSONAL_MENU_BUTTON_ID = 'personalmenu-button',
2021-01-22 02:08:55 +00:00
PERSONAL_MENU_CHECKBOX_ID = 'personalmenu-checkbox';
/**
* Uncheck CSS hack checkbox when clicked outside
*
* @param {HTMLElement|HTMLElement[]} clickableElement
* @param {HTMLElement} button
2021-01-22 02:08:55 +00:00
* @param {HTMLElement} checkbox
*/
function uncheckOnClickOutside( clickableElement, button, checkbox ) {
2021-01-22 02:08:55 +00:00
var listener = function ( e ) {
var hideCond = e.target !== clickableElement;
if ( Array.isArray( clickableElement ) ) {
hideCond = clickableElement.indexOf( e.target ) === -1;
}
if ( e.target !== checkbox && hideCond ) {
if ( e.target !== button ) {
checkbox.checked = false;
}
2021-01-22 02:08:55 +00:00
document.removeEventListener( 'click', listener );
}
};
2021-01-29 18:50:20 +00:00
var keyboardListener = function ( event ) {
2021-01-29 18:50:20 +00:00
if ( event.key === 'Escape' && checkbox.checked === true ) {
checkbox.checked = false;
document.removeEventListener( 'click', listener );
}
};
var checkboxFn = function () {
if ( checkbox.checked ) {
document.addEventListener( 'click', listener );
} else {
document.removeEventListener( 'click', listener );
}
};
checkbox.removeEventListener( 'click', checkboxFn );
checkbox.addEventListener( 'click', checkboxFn );
document.removeEventListener( 'keydown', keyboardListener );
document.addEventListener( 'keydown', keyboardListener );
2021-01-22 02:08:55 +00:00
}
/**
* @return {void}
*/
function init() {
var drawer = document.getElementById( DRAWER_ID ),
drawerButton = document.getElementById( DRAWER_BUTTON_ID ),
2021-01-22 02:08:55 +00:00
drawerCheckbox = document.getElementById( DRAWER_CHECKBOX_ID ),
2021-02-03 20:47:32 +00:00
drawerSearch = document.getElementById( 'mw-drawer-search-input' ),
2021-01-22 02:08:55 +00:00
personalMenu = document.getElementById( PERSONAL_MENU_ID ),
personalMenuButton = document.getElementById( PERSONAL_MENU_BUTTON_ID ),
personalMenuCheckbox = document.getElementById( PERSONAL_MENU_CHECKBOX_ID ),
clickableDrawerElements = [];
drawer.querySelectorAll( '#mw-drawer-menu .mw-portal' ).forEach( function ( portal ) {
clickableDrawerElements.push( portal );
} );
drawer.querySelectorAll( '#mw-drawer-menu .mw-portal h3' ).forEach( function ( portalHeading ) {
clickableDrawerElements.push( portalHeading );
} );
if ( drawerSearch !== null ) {
clickableDrawerElements.push( drawerSearch );
}
uncheckOnClickOutside( clickableDrawerElements, drawerButton, drawerCheckbox );
uncheckOnClickOutside( personalMenu, personalMenuButton, personalMenuCheckbox );
2021-01-22 02:08:55 +00:00
}
module.exports = {
init: init
};