import { useRecoilState, useResetRecoilState } from 'recoil' import { contextPopupState, popupState } from '@/store/popupAtom' import { useEffect } from 'react' import { commonUtilsState } from '@/store/commonUtilsAtom' /** * 팝업 관리 훅 * @returns */ export function usePopup() { const [popup, setPopup] = useRecoilState(popupState) const [contextMenuPopup, setContextMenuPopup] = useRecoilState(contextPopupState) /** * 팝업 추가 * @param {*} id 팝업 아이디 * @param {*} depth 팝업 깊이 * @param {*} component 팝업 컴포넌트 * @param {*} isConfig 팝업 타입 */ 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], }) } /** * 팝업 닫기 * @param {*} id 팝업 아이디 * @param {*} isConfig 팝업 타입 */ 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)], }) } } /** * 팝업 필터 * @param {*} depth 팝업 깊이 */ const filterPopup = (depth) => { setPopup({ config: [...filterDepth(depth)], other: [], }) } /** * 팝업 자식 필터 * @param {*} id 팝업 아이디 * @param {*} isConfig 팝업 타입 * @returns */ 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 } } } /** * 팝업 여러개 닫기 * @param {*} ids 팝업 아이디 배열 */ 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: [], }) } /** * 팝업 깊이 필터 * @param {*} depth 팝업 깊이 * @param {*} isConfig 팝업 타입 * @returns */ const filterDepth = (depth, isConfig) => { if (isConfig) { return [...popup?.config.filter((child) => child.depth < depth)] } else { return [...popup?.other.filter((child) => child.depth < depth)] } } const targetClose = (type) => { popup[type] = [] setPopup({ ...popup, [type]: [] }) } return { popup, addPopup, closePopup, closePopups, closeAll, targetClose, } }