pinafore/routes/_utils/delegate.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-02-10 19:30:13 +00:00
// Delegate certain events to the global document for perf purposes.
import { mark, stop } from './marks'
const callbacks = {}
if (process.browser && process.env.NODE_ENV !== 'production') {
window.delegateCallbacks = callbacks
}
2018-02-11 17:37:13 +00:00
function onEvent (e) {
2018-02-10 19:30:13 +00:00
let { type, keyCode, target } = e
if (!(type === 'click' || (type === 'keydown' && keyCode === 13))) {
// we're not interested in any non-click or non-Enter events
return
}
if (type === 'click') {
let selection = window.getSelection()
let selectionStr = selection && selection.toString()
2018-12-03 07:19:15 +00:00
if (selectionStr && selectionStr.length && target.contains(selection.anchorNode)) {
return // ignore if the user is selecting text inside the clickable area
}
}
2018-02-10 19:30:13 +00:00
mark('delegate onEvent')
let key
let element = target
while (element) {
2018-03-01 03:16:11 +00:00
if ((key = element.getAttribute('delegate-key'))) {
2018-02-10 19:30:13 +00:00
break
}
element = element.parentElement
}
2018-02-25 00:12:25 +00:00
if (key && callbacks[key]) {
callbacks[key](e)
2018-02-10 19:30:13 +00:00
}
stop('delegate onEvent')
}
export function registerClickDelegates (component, delegates) {
Object.assign(callbacks, delegates)
component.on('destroy', () => {
Object.keys(delegates).forEach(key => {
delete callbacks[key]
})
})
2018-02-10 19:30:13 +00:00
}
export function registerClickDelegate (component, key, callback) {
registerClickDelegates(component, { [key]: callback })
2018-02-10 19:30:13 +00:00
}
if (process.browser) {
document.addEventListener('click', onEvent)
document.addEventListener('keydown', onEvent)
2018-02-11 17:37:13 +00:00
}