2022-11-25 13:13:48 +01:00
|
|
|
const ignoredClasses = [".flatpickr-calendar", ".modal-container"]
|
2022-11-25 13:08:34 +01:00
|
|
|
let clickHandlers = []
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handle a body click event
|
|
|
|
*/
|
|
|
|
const handleClick = event => {
|
|
|
|
// Ignore click if needed
|
|
|
|
for (let className of ignoredClasses) {
|
|
|
|
if (event.target.closest(className)) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process handlers
|
|
|
|
clickHandlers.forEach(handler => {
|
|
|
|
if (!handler.element.contains(event.target)) {
|
|
|
|
handler.callback?.(event)
|
2021-03-31 11:59:07 +02:00
|
|
|
}
|
2022-11-25 13:08:34 +01: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
|
|
|
}
|
2022-11-25 13:08:34 +01:00
|
|
|
}
|
2021-03-31 11:59:07 +02:00
|
|
|
|
2022-11-25 13:08:34 +01:00
|
|
|
/**
|
|
|
|
* Removes a click handler
|
|
|
|
*/
|
|
|
|
const removeHandler = id => {
|
|
|
|
clickHandlers = clickHandlers.filter(x => x.id !== id)
|
|
|
|
}
|
2021-03-31 11:59:07 +02:00
|
|
|
|
2022-11-25 13:08:34 +01: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 {
|
2022-11-25 13:08:34 +01:00
|
|
|
update: newCallback => updateHandler(id, element, newCallback),
|
|
|
|
destroy: () => removeHandler(id),
|
2021-03-31 11:59:07 +02:00
|
|
|
}
|
|
|
|
}
|