Would an option for a JS confirmation dialog on closing a modal be useful?

As one edits a Phoenix LiveView form in a modal, it’s very easy to accidentally press ‘Esc’ and lose all the edits.

Similar to data-confirm for links, I’d like to suggest a new modal attr (close_confirm?) that would accept the confirmation message to be displayed in a JS confirmation dialog on an attempt to close a modal.

I’d be willing to submit a PR if it looks useful. My POC implementation (along with possible usage) is in this gist: LiveView modal close confirmation on dirty form · GitHub

1 Like

Hi Max! I find that indeed interesting. Have you seen what ArthurClemens has recently done at Modal component in CoreComponents closes when clicked outside, may result in data loss · Issue #5660 · phoenixframework/phoenix · GitHub and Add opt-in modal behaviour to dialogs by ArthurClemens · Pull Request #5661 · phoenixframework/phoenix · GitHub?

1 Like

Hey Rodolfo, thanks for the pointers, wasn’t aware of a similar discussion ongoing!

I suggest keeping things as simple and decoupled as possible, by enabling the modal to warn on close when requested. The rest of the logic should go elsewhere, as I showed in my gist.

I’ve made this before:

It works in live and dead views. IIRC it may not work with all form elements (maybe radio buttons? I don’t remember).

If you want a demo, check out:

The login form is the easiest way to try it out, but if you make an account, then a quiz, then create/edit a question, then you can see it in action in a live view popup.

EDIT: There’s some Alpine.js mixed in there (Escape key functionality) but you should be able to add it to the hook with minimal hassle if you know what you’re doing.

3 Likes