-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseOverlayModal.tsx
More file actions
43 lines (34 loc) · 1.19 KB
/
useOverlayModal.tsx
File metadata and controls
43 lines (34 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import React, { useRef } from 'react';
import type { ReactElement, ReactNode } from 'react';
import { overlay } from 'overlay-kit';
import Modal from '@/common/component/Modal/Modal';
type Closeable = { onClose: () => void };
type OpenOptions = { withWrapper?: boolean };
export const useOverlayModal = () => {
const idsRef = useRef<string[]>([]);
const openModal = (node: ReactNode, options: OpenOptions = {}) => {
const { withWrapper = true } = options;
const id = overlay.open(({ unmount }) => {
const handleClose = () => unmount();
const content = React.isValidElement(node)
? React.cloneElement(node as ReactElement<Partial<Closeable>>, { onClose: handleClose })
: node;
return withWrapper ? <Modal onClose={handleClose}>{content}</Modal> : <>{content}</>;
});
idsRef.current.push(id);
return { id, close: () => overlay.unmount(id) };
};
const closeModal = () => {
const id = idsRef.current.pop();
if (id) {
overlay.unmount(id);
}
};
const closeAll = () => {
while (idsRef.current.length) {
const id = idsRef.current.pop()!;
overlay.unmount(id);
}
};
return { openModal, closeModal, closeAll };
};