I have a Modal component, which uses Bulma CSS' modal:
<script>
import { createEventDispatcher } from 'svelte';
export let active;
export let closeable = true;
const dispatch = createEventDispatcher();
const closeModal = () => {
active = false;
dispatch("closeModal");
};
const closeModalSoft = () => {
if (closeable) {
closeModal();
}
};
const closeModalKeyboard = (event) => {
if (event.key === "Escape" && closeable) {
closeModal();
}
};
</script>
<svelte:window on:keydown={closeModalKeyboard}/>
<div class="modal is-clipped" class:is-active={active}>
<div class="modal-background" on:click={closeModalSoft}/>
<div class="modal-content">
<div class="container">
<slot />
</div>
</div>
{#if closeable}
<button class="is-large modal-close" aria-label="close" on:click={closeModal}/>
{/if}
</div>
It should allow for arbitrary nesting, so you can for example have a modal over a modal over the rest of the website.
I would like to allow for modals be closed by pressing the close button, clicking outside of the modal or using the escape key. I would like this to operate like a stack: the topmost modal gets closed first. (Note: If a modal is not closeable as shown in my code, it just means that the modal can only be closed by manipulating active externally).
Currently, the close button and clicking outside the modal work with nested modals. However, escape will always close all modals, instead of just the topmost one. But, given the code, I think this is to be expected.
What would I need to change such that only the topmost (closeable=true) modal gets closed?
I have thought about the following approaches, but I feel like there must be better ways:
modal and is-active classes. If so, ignore the keypress.:focus or other modifiers on the topmost element and then a similar approach as the one above.Adding the event on the window is the wrong approach which leads to this issue.
Modals should not allow focus to leave it, that being the case you should be able to handle the Escape press on the Modal itself. The easiest way to get the focus trap "for free" would be to use a native dialog element (though it getting support is still relatively recent).
A manual focus trap would have to steer focus on opening/closing and on any Tab press. There might be libraries that already implement this. Actually, I would not recommend implementing such generic components anyway and suggest the use of a component library instead. It is easy to get accessibility and things like keyboard interactions very wrong.
Guidelines for Modals: https://www.w3.org/WAI/ARIA/apg/patterns/dialogmodal/