Add curtain context in a curtain instance.

This commit is contained in:
Madeorsk 2024-07-14 14:52:11 +02:00
parent b0905b4a4f
commit c4423bf772
Signed by: Madeorsk
SSH key fingerprint: SHA256:J9G0ofIOLKf7kyS2IfrMqtMaPdfsk1W02+oGueZzDDU

View file

@ -50,6 +50,8 @@ export function useCurtains(): CurtainsContextState
return useContext(CurtainsContext); return useContext(CurtainsContext);
} }
/** /**
* Page curtains system. * Page curtains system.
*/ */
@ -117,20 +119,78 @@ function CurtainsPortal({curtains}: {
}) })
{ {
return ReactDOM.createPortal(Object.entries(curtains).map(([uuid, curtainContent]) => ( return ReactDOM.createPortal(Object.entries(curtains).map(([uuid, curtainContent]) => (
<CurtainInstance key={uuid}> <CurtainInstance key={uuid} uuid={uuid}>
{curtainContent} {curtainContent}
</CurtainInstance> </CurtainInstance>
)), document.body); )), document.body);
} }
/**
* Current curtain data and functions.
*/
export interface CurtainContextState
{
/**
* Curtain UUID.
*/
uuid: CurtainUuidType;
/**
* Close the curtain.
*/
close: () => void;
}
/**
* Current curtain context.
*/
const CurtainContext = React.createContext<CurtainContextState>({
// Empty values.
uuid: "",
close: () => {},
});
/**
* Hook to access current curtain data and functions.
*/
export function useCurtain(): CurtainContextState
{
return useContext(CurtainContext);
}
/** /**
* Component of an opened curtain instance. * Component of an opened curtain instance.
*/ */
function CurtainInstance({children}: React.PropsWithChildren<{}>) function CurtainInstance({uuid, children}: React.PropsWithChildren<{
/**
* Curtain UUID.
*/
uuid: string;
}>)
{ {
// Get close curtain function.
const {close} = useCurtains();
// Initialize close curtain function.
const closeCurtain = useRef<() => void>();
closeCurtain.current = useCallback(() => {
// Close the current curtain.
close(uuid);
}, [uuid, close]);
// Initialize context state from action functions.
const contextState = useMemo(() => ({
uuid: uuid,
close: () => closeCurtain.current(),
}), [uuid, closeCurtain]);
return ( return (
<div className={"curtain"}> <CurtainContext.Provider value={contextState}>
{children} <div className={"curtain"}>
</div> {children}
</div>
</CurtainContext.Provider>
); );
} }