| 1 |
import { useEffect, useState } from '@wordpress/element' |
| 2 |
import { InstallStandaloneModal } from '@library/components/modals/InstallStandaloneModal' |
| 3 |
import { useGlobalStore } from '@library/state/GlobalState' |
| 4 |
import { useUserStore } from '@library/state/User' |
| 5 |
|
| 6 |
/** Return any pending modals and check if any need to show */ |
| 7 |
export const useModal = () => { |
| 8 |
const [modal, setModal] = useState(null) |
| 9 |
const open = useGlobalStore((state) => state.open) |
| 10 |
const pushModal = useGlobalStore((state) => state.pushModal) |
| 11 |
const removeAllModals = useGlobalStore((state) => state.removeAllModals) |
| 12 |
|
| 13 |
// Watches modals added anywhere |
| 14 |
useEffect( |
| 15 |
() => |
| 16 |
useGlobalStore.subscribe( |
| 17 |
(state) => state.modals, |
| 18 |
(value) => setModal(value?.length > 0 ? value[0] : null), |
| 19 |
), |
| 20 |
[], |
| 21 |
) |
| 22 |
|
| 23 |
// Checks for modals that need to be shown on load |
| 24 |
useEffect(() => { |
| 25 |
if (!open) { |
| 26 |
removeAllModals() |
| 27 |
return |
| 28 |
} |
| 29 |
const ModalNoticesByPriority = { |
| 30 |
standalone: InstallStandaloneModal, |
| 31 |
} |
| 32 |
const componentKey = |
| 33 |
Object.keys(ModalNoticesByPriority).find((key) => { |
| 34 |
if (key === 'standalone') { |
| 35 |
return ( |
| 36 |
!window.extendifyData.standalone && |
| 37 |
!useUserStore.getState().modalNoticesDismissedAt[key] |
| 38 |
) |
| 39 |
} |
| 40 |
return !useUserStore.getState().modalNoticesDismissedAt[key] |
| 41 |
}) ?? null |
| 42 |
|
| 43 |
const Modal = ModalNoticesByPriority[componentKey] |
| 44 |
if (Modal) pushModal(<Modal />) |
| 45 |
}, [open, pushModal, removeAllModals]) |
| 46 |
|
| 47 |
return modal |
| 48 |
} |
| 49 |
|