immich/web/src/lib/utils/click-outside.ts
martin f63d6d5b67
fix(web): escape shortcut (#3753)
* fix: escape shortcut

* feat: more escape scenarios

* feat: more escape shortcuts

---------

Co-authored-by: Jason Rasmussen <jrasm91@gmail.com>
2023-09-26 02:53:26 +00:00

31 lines
881 B
TypeScript

import type { ActionReturn } from 'svelte/action';
interface Attributes {
'on:outclick'?: (e: CustomEvent) => void;
'on:escape'?: (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('escape'));
}
};
document.addEventListener('click', handleClick, true);
document.addEventListener('keydown', handleKey, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
document.removeEventListener('keydown', handleKey, true);
},
};
}