Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Last active November 1, 2017 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GianlucaGuarini/b29e4b622c97fe52c7d1297f9fedecc3 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/b29e4b622c97fe52c7d1297f9fedecc3 to your computer and use it in GitHub Desktop.
Simple function to make your overlays element accessible
// 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