/
modalManager.ts
40 lines (35 loc) · 862 Bytes
/
modalManager.ts
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
import { Ref, useEffect } from 'react';
let modals: Ref<Element>[] = [];
/**
* Handle the order of the modals.
* Inspired by the material-ui implementation.
*/
export const modalManager = {
/**
* Register a new modal
*/
add: (newModal: Ref<Element>) => {
modals.push(newModal);
},
/**
* Remove a modal
*/
remove: (oldModal: Ref<Element>) => {
modals = modals.filter((modal) => modal !== oldModal);
},
/**
* When multiple modals are rendered will return true if current modal is the last one
*/
isTopModal: (modal: Ref<Element>) =>
!!modals.length && modals[modals.length - 1] === modal,
};
export function useModalManager(ref: Ref<Element>, open: boolean) {
useEffect(() => {
if (open) {
modalManager.add(ref);
}
return () => {
modalManager.remove(ref);
};
}, [open, ref]);
}