Skip to content

Commit

Permalink
click outside for deletion confirmation
Browse files Browse the repository at this point in the history
  • Loading branch information
moostoet committed Jan 29, 2023
1 parent 7be3fd7 commit 7a87c2b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/components/DeleteButton.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { ActionReturn } from 'svelte/action';
import { clickOutside } from '../utils/clickOutside';
import type { Session } from '../types/session';
export let session: Session;
const dispatch = createEventDispatcher();
let confirmation: boolean = false;
const confirm = (): void => {
confirmation = true;
};
const handleClick = () => {
confirmation = false;
}
const deleteSession = (session: Session) => async () => {
if (!confirmation) return;
const res = await fetch('http://localhost:8000/sessions', {
method: 'DELETE',
body: JSON.stringify(session._id)
Expand All @@ -19,9 +32,20 @@
</script>

<div class="ml-auto">
<button
on:click={deleteSession(session)}
class="bg-red-500 p-[10px] text-white font-semibold rounded-sm hover:bg-red-600 transition"
>Delete Session</button
>
{#if !confirmation}
<button
on:click={() => {
confirm();
}}
class="bg-red-500 p-[10px] text-white font-semibold rounded-sm hover:bg-red-600 transition"
>Delete Session</button
>
{:else}
<button
on:click={deleteSession(session)}
use:clickOutside on:click_outside={handleClick}
class="bg-red-500 p-[10px] text-white font-semibold rounded-sm hover:bg-red-600 transition"
>Are you sure?</button
>
{/if}
</div>
6 changes: 6 additions & 0 deletions src/typings/additional-svelte-typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare namespace svelteHTML {
// enhance attributes
interface HTMLAttributes {
'on:click_outside'?: () => void;
}
}
20 changes: 20 additions & 0 deletions src/utils/clickOutside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function clickOutside<T extends HTMLElement>(node: T) {
const handleClick = (event: MouseEvent) => {
if (
node &&
event.target instanceof Element &&
!node.contains(event.target) &&
!event.defaultPrevented
) {
node.dispatchEvent(new CustomEvent<T>('click_outside', { detail: node }))
}
}

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

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

0 comments on commit 7a87c2b

Please sign in to comment.