Browse Source

fix: confirm dialog focus

Timothy Jaeryang Baek 1 month ago
parent
commit
be85f7cc35
1 changed files with 19 additions and 1 deletions
  1. 19 1
      src/lib/components/common/ConfirmDialog.svelte

+ 19 - 1
src/lib/components/common/ConfirmDialog.svelte

@@ -1,7 +1,9 @@
 <script lang="ts">
 	import DOMPurify from 'dompurify';
 
-	import { onMount, getContext, createEventDispatcher } from 'svelte';
+	import { onMount, getContext, createEventDispatcher, onDestroy } from 'svelte';
+	import * as FocusTrap from 'focus-trap';
+
 	const i18n = getContext('i18n');
 	const dispatch = createEventDispatcher();
 
@@ -26,6 +28,8 @@
 	let modalElement = null;
 	let mounted = false;
 
+	let focusTrap: FocusTrap.FocusTrap | null = null;
+
 	const handleKeyDown = (event: KeyboardEvent) => {
 		if (event.key === 'Escape') {
 			console.log('Escape');
@@ -51,16 +55,30 @@
 	$: if (mounted) {
 		if (show && modalElement) {
 			document.body.appendChild(modalElement);
+			focusTrap = FocusTrap.createFocusTrap(modalElement);
+			focusTrap.activate();
 
 			window.addEventListener('keydown', handleKeyDown);
 			document.body.style.overflow = 'hidden';
 		} else if (modalElement) {
+			focusTrap.deactivate();
+
 			window.removeEventListener('keydown', handleKeyDown);
 			document.body.removeChild(modalElement);
 
 			document.body.style.overflow = 'unset';
 		}
 	}
+
+	onDestroy(() => {
+		show = false;
+		if (focusTrap) {
+			focusTrap.deactivate();
+		}
+		if (modalElement) {
+			document.body.removeChild(modalElement);
+		}
+	});
 </script>
 
 {#if show}