Skip to content

Commit

Permalink
Modal: Close is a promise + onClickOutside
Browse files Browse the repository at this point in the history
Make the modal closing function a promise as it's done asynchronously.
Add another optional callback that's called only in the case when clicking outside the modal.
  • Loading branch information
estib-vega committed Oct 28, 2024
1 parent a4a41c6 commit 7bcb7e9
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions packages/ui/src/lib/Modal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,17 @@
type?: 'info' | 'warning' | 'error' | 'success';
title?: string;
noPadding?: boolean;
/**
* Callback to be called when the modal is closed.
*
* Whether closing by clicking outside the modal, subtmitting the form or calling the `close` function.
* This is called after the closing animation is finished.
*/
onClose?: () => void;
/**
* Callback to be called when the modal is closed by clicking outside the modal.
*/
onClickOutside?: () => void;
onSubmit?: (close: () => void) => void;
onKeyDown?: (e: KeyboardEvent) => void;
children: Snippet<[item: any, close: () => void]>;
Expand All @@ -23,6 +33,7 @@
title,
type = 'info',
onClose,
onClickOutside,
children,
controls,
onSubmit,
Expand Down Expand Up @@ -52,14 +63,20 @@
window.addEventListener('keydown', handleKeyDown);
}
export function close() {
export function close(): Promise<void> {
if (isClosing) return Promise.resolve();
if (!open) return Promise.resolve();
isClosing = true;
setTimeout(() => {
item = undefined;
open = false;
isClosing = false;
onClose?.();
}, 100); // This should match the duration of the closing animation
return new Promise((resolve) => {
setTimeout(() => {
item = undefined;
open = false;
isClosing = false;
onClose?.();
resolve();
}, 100); // This should match the duration of the closing animation
});
}
export const imports = {
Expand All @@ -79,6 +96,7 @@
e.stopPropagation();

if (e.target === e.currentTarget) {
onClickOutside?.();
close();
}
}}
Expand Down

0 comments on commit 7bcb7e9

Please sign in to comment.