Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/useEscKeyDown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export default function useEscKeyDown(open: boolean, onEsc?: EscCallback) {
}, [open, id]);

useEffect(() => {
if (open && !stack.includes(id)) {
stack.push(id);
}

if (!open) {
return;
}
Expand Down
44 changes: 44 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -381,5 +381,49 @@ describe('Portal', () => {
unmount();
expect(stack).toHaveLength(0);
});

it('onEsc should treat first mounted portal as top in StrictMode', () => {
const onEsc = jest.fn();

const Demo = ({ visible }: { visible: boolean }) =>
visible ? (
<Portal open onEsc={onEsc}>
<div />
</Portal>
) : null;

render(<Demo visible />, { wrapper: React.StrictMode });

expect(stack).toHaveLength(1);

fireEvent.keyDown(window, { key: 'Escape' });

expect(onEsc).toHaveBeenCalledWith(expect.objectContaining({ top: true }));
});

it('nested portals should trigger in correct order', () => {
const onEsc = jest.fn();
const onEsc2 = jest.fn();
const onEsc3 = jest.fn();

render(
<Portal open onEsc={onEsc}>
<div />
<Portal open onEsc={onEsc2}>
<div />
<Portal open onEsc={onEsc3}>
<div />
</Portal>
</Portal>
</Portal>
);

fireEvent.keyDown(window, { key: 'Escape' });

expect(onEsc).toHaveBeenCalledWith(expect.objectContaining({ top: false }));
expect(onEsc2).toHaveBeenCalledWith(expect.objectContaining({ top: false }));
expect(onEsc3).toHaveBeenCalledWith(expect.objectContaining({ top: true }));
});
Comment on lines +404 to +426
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

顺带补了一下嵌套Portal下的case


});
});