1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-10 13:56:47 +01:00
immich/web/src/lib/utils/click-outside.ts
Jason Rasmussen f55b3add80
chore(web): prettier (#2821)
Co-authored-by: Thomas Way <thomas@6f.io>
2023-06-30 23:50:47 -05:00

30 lines
841 B
TypeScript

import type { ActionReturn } from 'svelte/action';
interface Attributes {
'on:outclick'?: (e: CustomEvent) => void;
}
export function clickOutside(node: HTMLElement): ActionReturn<void, Attributes> {
const handleClick = (event: MouseEvent) => {
const targetNode = event.target as Node | null;
if (!node.contains(targetNode)) {
node.dispatchEvent(new CustomEvent('outclick'));
}
};
const handleKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
node.dispatchEvent(new CustomEvent('outclick'));
}
};
document.addEventListener('click', handleClick, true);
document.addEventListener('keydown', handleKey, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
document.removeEventListener('keydown', handleKey, true);
},
};
}