better click outside detection

This commit is contained in:
Nikita Galaiko 2023-05-11 10:57:16 +02:00
parent 90f475d7e5
commit 37f74e9ff9
3 changed files with 25 additions and 21 deletions

View File

@ -1,8 +1,8 @@
<script lang="ts">
import { scale } from 'svelte/transition';
import clickOutside from './click_outside';
let dialog: HTMLDialogElement;
let content: HTMLDivElement | null = null;
let open = false;
@ -18,26 +18,11 @@
dialog.close();
open = false;
};
const handleClick = (event: Event) => {
if (event.defaultPrevented) return;
if (!dialog?.open) return;
const isClickInside = !content || content.contains(event.target as Node | null);
if (isClickInside) return;
close();
};
</script>
<dialog
on:click={handleClick}
on:keydown={handleClick}
class="bg-transparent"
in:scale={{ duration: 150 }}
bind:this={dialog}
on:close={close}
>
<dialog class="bg-transparent" in:scale={{ duration: 150 }} bind:this={dialog} on:close={close}>
{#if open}
<div bind:this={content} class="flex">
<div use:clickOutside on:outclick={close} class="flex">
<slot {close} isOpen={open} />
</div>
{/if}

View File

@ -0,0 +1,21 @@
import type { ActionReturn } from 'svelte/action';
interface Attributes {
'on:outclick': (e: CustomEvent<void>) => void;
}
export default (node: HTMLElement): ActionReturn<any, Attributes> => {
const handleClick = (event: Event) => {
if (event.target && !node.contains(event.target as Node | null)) {
node.dispatchEvent(new CustomEvent('outclick'));
}
};
document.addEventListener('click', handleClick, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
};

View File

@ -33,9 +33,7 @@
hotkeys.on('Meta+T', () => goto(`/projects/${$project.id}/terminal/`)),
hotkeys.on('Meta+P', () => goto(`/projects/${$project.id}/`)),
hotkeys.on('Meta+Shift+,', () => goto(`/projects/${$project.id}/settings/`)),
hotkeys.on('Meta+R', () =>
goto(`/projects/${$project.id}/player/`)
),
hotkeys.on('Meta+R', () => goto(`/projects/${$project.id}/player/`)),
hotkeys.on('a i p', () => goto(`/projects/${$project.id}/aiplayground/`))
)
);