fix: confirm dialog focus

This commit is contained in:
Timothy Jaeryang Baek 2025-05-10 22:09:05 +04:00
parent 6b5f99bf66
commit be85f7cc35

View File

@ -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}