Skip to content

Commit

Permalink
feat: use click outside action
Browse files Browse the repository at this point in the history
  • Loading branch information
threedalpeng committed Feb 21, 2024
1 parent 670b593 commit 05dd986
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/routes/practice/(practice)/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { clickoutside } from '$/utils/hooks/click-outside';
import { base } from '$app/paths';
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from '@steeze-ui/heroicons';
import { Icon } from '@steeze-ui/svelte-icon';
Expand Down Expand Up @@ -59,7 +60,11 @@
class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
on:click={() => (practiceListOpen = !practiceListOpen)}
>
<div class="absolute -top-[30px] left-[50%] h-[40px] w-auto -translate-x-[50%]">
<div
use:clickoutside
on:clickoutside={() => (practiceListOpen = false)}
class="absolute -top-[30px] left-[50%] h-[40px] w-auto -translate-x-[50%]"
>
<Icon
class="opacity-25% hover:opacity-100% h-[20px] w-auto cursor-pointer transition-opacity"
src={practiceListOpen ? ChevronDown : ChevronUp}
Expand Down
25 changes: 25 additions & 0 deletions src/utils/hooks/click-outside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { Action, ActionReturn } from 'svelte/action';

export const clickoutside: Action<
Element,
unknown,
{ 'on:clickoutside'?: (event: CustomEvent<MouseEvent>) => any }
> = (node) => {
const handleClick = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (!event.target) {
return;
}
if (node && !node.contains(target) && !event.defaultPrevented) {
node.dispatchEvent(new CustomEvent('clickoutside', { detail: CustomEvent<MouseEvent> }));
}
};

document.addEventListener('click', handleClick, true);

return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
};

0 comments on commit 05dd986

Please sign in to comment.