budibase/packages/bbui/src/Actions/click_outside.js

55 lines
1.2 KiB
JavaScript
Raw Normal View History

const ignoredClasses = [".flatpickr-calendar"]
let clickHandlers = []
/**
* Handle a body click event
*/
const handleClick = event => {
// Ignore click if needed
for (let className of ignoredClasses) {
if (event.target.closest(className)) {
console.log("ignore")
return
}
}
// Process handlers
clickHandlers.forEach(handler => {
if (!handler.element.contains(event.target)) {
handler.callback?.(event)
2021-03-31 11:59:07 +02:00
}
})
}
document.documentElement.addEventListener("click", handleClick, true)
/**
* Adds or updates a click handler
*/
const updateHandler = (id, element, callback) => {
let existingHandler = clickHandlers.find(x => x.id === id)
if (!existingHandler) {
clickHandlers.push({ id, element, callback })
} else {
existingHandler.callback = callback
2021-03-31 11:59:07 +02:00
}
}
2021-03-31 11:59:07 +02:00
/**
* Removes a click handler
*/
const removeHandler = id => {
clickHandlers = clickHandlers.filter(x => x.id !== id)
}
2021-03-31 11:59:07 +02:00
/**
* Svelte action to apply a click outside handler for a certain element
*/
export default (element, callback) => {
const id = Math.random()
updateHandler(id, element, callback)
2021-03-31 11:59:07 +02:00
return {
update: newCallback => updateHandler(id, element, newCallback),
destroy: () => removeHandler(id),
2021-03-31 11:59:07 +02:00
}
}