Skip to content

Commit

Permalink
Call onRequestClose for nested modal when outer modal unmounts
Browse files Browse the repository at this point in the history
  • Loading branch information
stokesman committed Sep 29, 2023
1 parent 06161c4 commit ecd0a43
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions packages/components/src/modal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,20 @@ function UnforwardedModal(

const dismissers = useContext( context );
const isLevel0 = dismissers === level0Dismissers;
const nestedDismissers = useRef< typeof level0Dismissers >( [] );

// Updates the stack tracking open modals at this level and calls
// onRequestClose for the prior modal if applicable.
// onRequestClose for any prior and/or nested modals as applicable.
useEffect( () => {
dismissers.push( refOnRequestClose );
const [ first, second ] = dismissers;
if ( second ) first?.current?.();
return () => void dismissers.shift();

const nested = nestedDismissers.current;
return () => {
nested[ 0 ]?.current?.();
dismissers.shift();
};
}, [ dismissers ] );

// Adds/removes the value of bodyOpenClassName to body element.
Expand Down Expand Up @@ -338,10 +344,8 @@ function UnforwardedModal(
</div>
);

const nextLevelDismissers = useRef( [] );

return createPortal(
<context.Provider value={ nextLevelDismissers.current }>
<context.Provider value={ nestedDismissers.current }>
{ modal }
</context.Provider>,
document.body
Expand Down

0 comments on commit ecd0a43

Please sign in to comment.