swup / fragment-plugin

A swup plugin for dynamically replacing containers based on rules 🧩
https://swup-fragment-plugin.netlify.app
MIT License
15 stars 1 forks source link

Think about a way to handle `Escape` key presses when in a `<dialog>` element #61

Closed hirasso closed 10 months ago

hirasso commented 10 months ago

Describe the problem

The HTMLDialogElement has the default behavior of closing itself as soon as the user presses the Escape key. This event is not cancelable. This poses problems for when the dialog is being used as a "full page" with it's own URL as we are suggesting for fragment-plugin. The URL will just stay the same. It's easily possible to implement custom logic to navigate back to any URL when the modal closes – but maybe there is a chance for some clever automatic behavior here?

How important is this feature to you?

hirasso commented 10 months ago

Maybe preventDeftault()ing Escape presses on these modals would be enough already. It's a special modal, after all:

function showDialogs({ logger }: FragmentPlugin): void {
    document
        .querySelectorAll<HTMLDialogElement & FragmentElement>('dialog[data-swup-fragment]')
        .forEach((el) => {
            if (!el.__swupFragment) {
                if (__DEV__) logger?.warn(`fragment properties missing on element:`, el);
                return;
            }
            if (el.__swupFragment.modalShown) return;
            el.__swupFragment.modalShown = true;
            el.removeAttribute('open');
            el.showModal?.();
+           el.addEventListener('keydown', (e) => e.key === 'Escape' && e.preventDefault());
        });
}

Just tested this in my playground, it's working well. Escape won't close the modal anymore. It's not the most ideal solution, but a simple one.

@daun, any thoughts?

hirasso commented 10 months ago

Thinking about this further, I am more and more convinced that we should do this anyway, even if we find a way to actually handle Escape presses more elegantly down the road by navigating somehow.