feat: close model on esc

This commit is contained in:
Timothy J. Baek 2024-04-07 00:57:23 -07:00
parent 073aecd427
commit 4207f80ce9

View file

@ -7,6 +7,7 @@
export let show = true; export let show = true;
export let size = 'md'; export let size = 'md';
let modalElement = null;
let mounted = false; let mounted = false;
const sizeToWidth = (size) => { const sizeToWidth = (size) => {
@ -19,14 +20,23 @@
} }
}; };
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
console.log('Escape');
show = false;
}
};
onMount(() => { onMount(() => {
mounted = true; mounted = true;
}); });
$: if (mounted) { $: if (mounted) {
if (show) { if (show) {
window.addEventListener('keydown', handleKeyDown);
document.body.style.overflow = 'hidden'; document.body.style.overflow = 'hidden';
} else { } else {
window.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = 'unset'; document.body.style.overflow = 'unset';
} }
} }
@ -36,6 +46,7 @@
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions --> <!-- svelte-ignore a11y-no-static-element-interactions -->
<div <div
bind:this={modalElement}
class=" fixed top-0 right-0 left-0 bottom-0 bg-black/60 w-full min-h-screen h-screen flex justify-center z-50 overflow-hidden overscroll-contain" class=" fixed top-0 right-0 left-0 bottom-0 bg-black/60 w-full min-h-screen h-screen flex justify-center z-50 overflow-hidden overscroll-contain"
in:fade={{ duration: 10 }} in:fade={{ duration: 10 }}
on:click={() => { on:click={() => {