2
0
mirror of https://github.com/frappe/books.git synced 2025-01-26 16:48:28 +00:00
books/src/renderer/helpers.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

40 lines
963 B
TypeScript
Raw Normal View History

import { Directive } from 'vue';
type OutsideClickCallback = (e: Event) => void;
const instanceMap: Map<HTMLElement, OutsideClickCallback> = new Map();
export const outsideClickDirective: Directive<
HTMLElement,
OutsideClickCallback
> = {
beforeMount(el, binding) {
const clickHandler = function (e: Event) {
onDocumentClick(e, el, binding.value);
};
removeHandlerIfPresent(el);
instanceMap.set(el, clickHandler);
document.addEventListener('click', clickHandler);
},
unmounted(el) {
removeHandlerIfPresent(el);
},
};
function onDocumentClick(e: Event, el: HTMLElement, fn: OutsideClickCallback) {
const target = e.target as Node;
if (el !== target && !el.contains(target)) {
fn?.(e);
}
}
function removeHandlerIfPresent(el: HTMLElement) {
const clickHandler = instanceMap.get(el);
if (!clickHandler) {
return;
}
instanceMap.delete(el);
document.removeEventListener('click', clickHandler);
}