2
0
mirror of https://github.com/frappe/books.git synced 2025-01-25 16:18:33 +00:00
books/src/renderer/helpers.ts
18alantom af8ffcbf71 fix: window-drag on Windows
- remove listener on unmounting outside click
2022-07-21 18:10:31 +05:30

40 lines
963 B
TypeScript

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);
}