Last active
November 1, 2017 10:57
-
-
Save GianlucaGuarini/b29e4b622c97fe52c7d1297f9fedecc3 to your computer and use it in GitHub Desktop.
Simple function to make your overlays element accessible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// forked by a script of https://github.com/nilssolanki | |
import { add } from 'bianco.events' | |
/** | |
* A list of all the open overlays, tooltips, sidebars etc. | |
* @type {Map} | |
*/ | |
const openOverlays = new Map() | |
/** | |
* Add an opened overlay to the queue | |
* @param {*} key – Any kind of js instance | |
* @param {Function} closerFn – A function to allow closing the overlay | |
* @returns {Map} - the overlays map | |
*/ | |
export function subscribe(key, closerFn) { | |
openOverlays.set(key, closerFn) | |
return openOverlays | |
} | |
/** | |
* @param {*} key – The instance used to register the overlay close function | |
* @returns {Boolean} true if the overlay was correctly unsubscribed | |
*/ | |
export function unsubscribe(key) { | |
const found = openOverlays.has(key) | |
if (found) openOverlays.delete(key) | |
return found | |
} | |
const ESC_KEY = 27 | |
/** | |
* If the esc key is pressed, close the last overlay added to the list | |
*/ | |
add(document, 'keyup', ({ keyCode }) => { | |
if (keyCode === ESC_KEY && openOverlays.size) { | |
const [, closerFn] = Array.from(openOverlays).pop() | |
closerFn() | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment