From ea682998a8e6640376f856fb45749f9e493bf0f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Z=C3=ADpek?= Date: Sun, 28 Aug 2022 13:06:44 +0200 Subject: [PATCH] Preparation of confirm modal context --- client/src/contexts/ConfirmModalContext.tsx | 85 +++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 client/src/contexts/ConfirmModalContext.tsx diff --git a/client/src/contexts/ConfirmModalContext.tsx b/client/src/contexts/ConfirmModalContext.tsx new file mode 100644 index 0000000..b18dc1c --- /dev/null +++ b/client/src/contexts/ConfirmModalContext.tsx @@ -0,0 +1,85 @@ +import { Modal } from '@/components/Modal' +import { ComponentChild, createContext } from 'preact' +import { useCallback, useContext, useMemo, useState } from 'preact/hooks' + +type Props = { + children: ComponentChild +} + +type ShowModalProps = { + content: ComponentChild + onConfirm: () => void + onCancel: () => void +} + +type ShowModelResult = { + show: () => void +} + +type ConfirmModalContext = { + createModal: (props: ShowModalProps) => ShowModelResult +} + +type ModalState = { + id: string + props: ShowModalProps +} + +const ConfirmModalContext = createContext(null) + +export const ConfirmModalContextProvider = ({ children }: Props) => { + const [modals, setModals] = useState([] as ModalState[]) + + const createModal = useCallback((props: ShowModalProps) => { + return { + show: () => + setModals((p) => [ + ...p, + { id: new Date().getTime().toString(), props }, + ]), + } + }, []) + + const handleClose = (modal: ModalState) => { + setModals((p) => p.filter((m) => m.id !== modal.id)) + + modal.props.onCancel() + } + + const handleConfirm = (modal: ModalState) => { + setModals((p) => p.filter((m) => m.id !== modal.id)) + + modal.props.onConfirm() + } + + const value = useMemo(() => ({ createModal }), [createModal]) + + return ( + + {children} + {modals.map((m) => ( + handleClose(m)}> + {m.props.content} + + + + ))} + + ) +} + +export const useConfirmModalContext = () => { + const ctx = useContext(ConfirmModalContext) + + if (!ctx) { + throw new Error('useConfirmModalContext used outside context') + } + + return ctx +} + +export const useConfirmModal = (modal: ShowModalProps) => { + const ctx = useConfirmModalContext() + + return ctx.createModal(modal) +}