Skip to content

Commit

Permalink
[fix] Correct timing of <Modal> onDismiss callback
Browse files Browse the repository at this point in the history
Close #2558
  • Loading branch information
bernhardoj authored and necolas committed Aug 24, 2023
1 parent ef95fc0 commit d8f1b58
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/react-native-web/src/exports/Modal/ModalAnimation.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function ModalAnimation(props: ModalAnimationProps): React.Node {

const [isRendering, setIsRendering] = React.useState(false);
const wasVisible = React.useRef(false);
const wasRendering = React.useRef(false);

const isAnimated = animationType && animationType !== 'none';

Expand All @@ -54,14 +55,18 @@ function ModalAnimation(props: ModalAnimationProps): React.Node {
}
} else {
setIsRendering(false);
if (onDismiss) {
onDismiss();
}
}
},
[onDismiss, onShow, visible]
[onShow, visible]
);

React.useEffect(() => {
if (wasRendering.current && !isRendering && onDismiss) {
onDismiss();
}
wasRendering.current = isRendering;
}, [isRendering, onDismiss]);

React.useEffect(() => {
if (visible) {
setIsRendering(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,32 @@ describe('components/Modal', () => {
expect(document.activeElement).toBe(insideElement);
});

test('focus is not trapped after closing modal', () => {
const { rerender } = render(
<>
<a data-testid={'outside'} href={'#outside'}>
Outside
</a>
<Modal visible={true} />
</>
);

const outsideElement = document.querySelector('[data-testid="outside"]');
const onDismissCallback = jest.fn(() => outsideElement.focus());

rerender(
<>
<a data-testid={'outside'} href={'#outside'}>
Outside
</a>
<Modal onDismiss={onDismissCallback} visible={false} />
</>
);

expect(onDismissCallback).toBeCalledTimes(1);
expect(document.activeElement).toBe(outsideElement);
});

test('focus is brought back to the element that triggered modal after closing', () => {
const { rerender } = render(
<>
Expand Down

0 comments on commit d8f1b58

Please sign in to comment.