svelte-modals icon indicating copy to clipboard operation
svelte-modals copied to clipboard

Make `openModal` a promise that resolves when the modal closes

Open c00 opened this issue 2 years ago • 4 comments

Is your feature request related to a problem? Please describe. Consider a confirmation dialog. A user gets a message "Are you sure?" and clicks yes or no. Currently you'd have to do this with callback props, they would have to exist on any modal component you'd want to wait for or have a return value for.

This works, but isn't optimal.

Describe the solution you'd like Have the openModal function return a promise. This promise will resolve once the modal is closed.

This could be done by extending the StoredModal interface with a promise, and then on pop() just resolve the promises of the modals you're popping.

Then update closeModal() to accept a parameter returnValue?: unknown. That value will be handed to the eventual pop function so it can be used to resolve the Promise. (To be helpful, add a generic to openModal so we know what to expect when it resolves)

Now what a user could do is:

const confirmation = await openModal(MyFancyConfirmationDialog);
if (confirmation) doStuff();

And in the modal itself, no extra callbacks or boilerplatey stuff would be required, just calling the close method would be sufficient:

    <button type="button" on:click={() => closeModal(false)}> Cancel </button>
    <button type="button" on:click={() => closeModal(true)}> Confirm </button>

Describe alternatives you've considered Rather than returning the promise from openModal directly, it could also return an object with the promise, so in the future we could add more stuff to it. Either way is fine.

I'd be very willing to make a PR for this. Just let me know if you'd be willing to accept such a PR.

c00 avatar Aug 06 '22 07:08 c00