import { useRef , useContext , createContext , useState , useEffect } from 'react' ; import type { DialogProps } from '@mui/material' ; const StackingScopeEnabled = createContext < boolean > ( false ) ; const Stack = createContext ( { level : - 1 , onHideChange ( shouldHide ) { } } ) ; example export function useDialogStackActor ( open ) { const selfID = useRef ( Math . random ( ) ) ; const featureEnabled = useContext ( StackingScopeEnabled ) ; const { level : upperLevel , onHideChange } = useContext ( Stack ) ; const [ hide , setHide ] = useState < Record < number , boolean > > ( { } ) ; const LatestOnHideChange = useRef < ( hide : boolean ) => void > ( onHideChange ) ; LatestOnHideChange . current = onHideChange ; const Increase = useRef < React . ComponentType < React . PropsWithChildren < { } > > > ( null ! ) ; if ( ! Increase . current ) { Increase . current = function IncreaseStackLevel ( props ) { return ( < Stack . Provider children = { props . children } value = { { level : upperLevel + 1 , onHideChange : ( hide ) => { setHide ( ( val ) => ( { ... val , [ selfID . current ] : hide } ) ) ; } , } } / > ) ; } ; } useEffect ( ( ) => { if ( ! featureEnabled ) return LatestOnHideChange . current ( false ) ; LatestOnHideChange . current ( open ) ; } , [ featureEnabled , open ] ) ; useEffect ( ( ) => { return ( ) => LatestOnHideChange . current ( false ) ; } , [ ] ) ; const returnVal = { shouldReplaceExitWithBack : upperLevel !== - 1 , extraProps : { open } , IncreaseStack : Increase . current , } ; if ( ! featureEnabled || ! open ) return returnVal ; if ( returnVal . shouldReplaceExitWithBack ) { returnVal . extraProps . transitionDuration = 0 ; } if ( Object . values ( hide ) . some ( Boolean ) ) { returnVal . extraProps = { ... returnVal . extraProps , disableEscapeKeyDown : true , disableScrollLock : true , hideBackdrop : true , style : { visibility : 'hidden' } , 'aria-hidden' : true , } ; } return returnVal ; } export interface useDialogStackActorReturn { shouldReplaceExitWithBack : boolean ; extraProps : DialogProps ; IncreaseStack : React . ComponentType < React . PropsWithChildren < { } > > ; } export interface DialogStackingProviderProps extends React . PropsWithChildren < { } > { disabled ? : boolean ; } /**
 * This Provider can turn any `MaskDialog` or `InjectedDialog` in the subtree into a unified dialog.
 *
 * For example:
 *
 * ```tsx
 * <DialogStackingProvider>
 *    <Dialog1>
 *        <Dialog2></Dialog2>
 *    </Dialog1>
 * </DialogStackingProvider>
 * ```
 *
 * When Dialog1 and Dialog2 both opened, only Dialog2 will be visible and the left top button
 * becomes "BackArrow".
 */ export function DialogStackingProvider ( props ) { return < StackingScopeEnabled . Provider children = { props . children } value = { ! props . disabled } />; }