import { useRecoilState } from 'recoil' import { contextPopupState, popupState } from '@/store/popupAtom' export function usePopup() { const [popup, setPopup] = useRecoilState(popupState) const [contextMenuPopup, setContextMenuPopup] = useRecoilState(contextPopupState) const addPopup = (id, depth, component, isConfig = false) => { setPopup({ config: isConfig ? [...filterDepth(depth, isConfig), { id, depth, component, isConfig }] : [...popup.config], other: !isConfig ? [...filterDepth(depth, isConfig), { id, depth, component, isConfig }] : [...popup.other], }) } const closePopup = (id, isConfig = false) => { if (contextMenuPopup) setContextMenuPopup(null) if (isConfig) { setPopup({ config: [...filterChildrenPopup(id, isConfig).filter((child) => child.id !== id)], other: popup.other, }) } else { setPopup({ config: popup.config, other: [...filterChildrenPopup(id, isConfig).filter((child) => child.id !== id)], }) } } const filterPopup = (depth) => { setPopup({ config: [...filterDepth(depth)], other: [], }) } const filterChildrenPopup = (id, isConfig) => { let target = [] if (isConfig) { target = popup?.config.filter((child) => child.id === id) } else { target = popup?.other.filter((child) => child.id === id) } if (target.length !== 0) { if (isConfig) { return popup?.config.filter((child) => child.depth <= target[0].depth) } else { return popup?.other.filter((child) => child.depth <= target[0].depth) } } else { if (isConfig) { return popup.config } else { return popup.other } } } const closePopups = (ids) => { setPopup({ config: [...popup?.config.filter((child) => !ids.includes(child.id))], other: [...popup?.other.filter((child) => !ids.includes(child.id))], }) } const closeAll = () => { setPopup({ other: [], config: [], }) } const closePrevPopup = () => { setPopup({ config: [...popup?.slice(popup?.length - 1)], other: [], }) } const filterDepth = (depth, isConfig) => { if (isConfig) { return [...popup?.config.filter((child) => child.depth < depth)] } else { return [...popup?.other.filter((child) => child.depth < depth)] } } return { popup, addPopup, closePopup, closePopups, closeAll, } }