import React, { useContext, useEffect, useState } from "react"; import { useSideDialogsController } from "../hooks"; import { SideDialogPanelProps } from "../types"; import { Sheet } from "@firecms/ui"; import { UnsavedChangesDialog, useNavigationUnsavedChangesDialog } from "../internal/useUnsavedChangesDialog"; import { ErrorBoundary } from "../components"; export type SideDialogContextProps = { blocked: boolean, setBlocked: (blocked: boolean) => void, setBlockedNavigationMessage: (message?: React.ReactNode) => void, width?: string, close: (force?: boolean) => void } const SideDialogContext = React.createContext({ width: "", blocked: false, setBlocked: (blocked: boolean) => { }, setBlockedNavigationMessage: (message?: React.ReactNode) => { }, close: () => { } }); /** * This hook is used to access the properties of a particular side dialog, * in contrast with {@link useSideDialogsController} which handles the * state of all the dialogs. */ export const useSideDialogContext = () => useContext(SideDialogContext); /** * This is the component in charge of rendering the side dialogs used * for editing entities. Use the {@link useSideEntityController} to open * and control the dialogs. * This component needs a parent {@link FireCMS} * {@link useSideDialogsController} * @group Components */ export function SideDialogs() { const sideDialogsController = useSideDialogsController(); const sidePanels = sideDialogsController.sidePanels; const panels: (SideDialogPanelProps | undefined)[] = [...sidePanels]; panels.push(undefined); return <> { panels.map((panel, index) => ) } ; } function SideDialogView({ offsetPosition, panel }: { offsetPosition: number, panel?: SideDialogPanelProps }) { // was the closing of the dialog requested by the drawer const [drawerCloseRequested, setDrawerCloseRequested] = useState(false); const [blocked, setBlocked] = useState(false); const [blockedNavigationMessage, setBlockedNavigationMessage] = useState(); const widthRef = React.useRef(panel?.width); const width = widthRef.current; const sideDialogsController = useSideDialogsController(); const { navigationWasBlocked, handleOk: handleNavigationOk, handleCancel: handleNavigationCancel } = useNavigationUnsavedChangesDialog( blocked && !drawerCloseRequested, () => setBlocked(false) ); useEffect(() => { if (panel) widthRef.current = panel.width; }, [panel]) const handleDrawerCloseOk = () => { setBlocked(false); setDrawerCloseRequested(false); sideDialogsController.close(); panel?.onClose?.(); }; const handleDrawerCloseCancel = () => { setDrawerCloseRequested(false); }; const onCloseRequest = (force?: boolean) => { if (blocked && !force) { setDrawerCloseRequested(true); } else { sideDialogsController.close(); panel?.onClose?.(); } }; // const offsetClass = offsetPosition > 0 ? `transform translate-x-${offsetPosition}` : ""; return ( !open && onCloseRequest()} > {panel &&
{panel.component}
} {!panel &&
} ); }