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
3 changes: 2 additions & 1 deletion src/useEscKeyDown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { type EscCallback } from './Portal';
import useId from '@rc-component/util/lib/hooks/useId';
import { useEvent } from '@rc-component/util';

let stack: string[] = [];
export let stack: string[] = []; // export for testing

export default function useEscKeyDown(open: boolean, onEsc?: EscCallback) {
const id = useId();
Expand Down Expand Up @@ -31,6 +31,7 @@ export default function useEscKeyDown(open: boolean, onEsc?: EscCallback) {
window.addEventListener('keydown', handleEscKeyDown);

return () => {
stack = stack.filter(item => item !== id);
Copy link

Copilot AI Dec 23, 2025

Choose a reason for hiding this comment

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

The stack cleanup on component unmount lacks test coverage. Consider adding a test that verifies the stack is properly cleaned up when a Portal component unmounts while still open (not just when open changes to false). This would ensure the fix works correctly and prevent regressions.

Copilot uses AI. Check for mistakes.
window.removeEventListener('keydown', handleEscKeyDown);
};
}, [open, id]);
Expand Down
13 changes: 13 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { render, fireEvent } from '@testing-library/react';
import React from 'react';
import Portal from '../src';
import { stack } from '../src/useEscKeyDown';
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

考虑测试隔离问题。

直接导入内部实现的 stack 用于测试会造成测试与实现的紧耦合。更重要的是,由于 stack 是模块级别的可变状态,如果没有在测试之间正确重置,可能会导致测试相互影响。

建议在 beforeEach 中添加清理逻辑:

beforeEach(() => {
  global.isOverflow = true;
  stack.length = 0; // 清空 stack 以确保测试隔离
});
🤖 Prompt for AI Agents
In tests/index.test.tsx around line 4, the test currently imports the internal
mutable "stack" which tightly couples tests to implementation and can leak state
between tests; add a beforeEach block that resets global.isOverflow to true and
clears the stack (set its length to 0) to ensure test isolation, and preferably
update tests to use the public API rather than importing the internal stack
directly.


global.isOverflow = true;

Expand Down Expand Up @@ -355,5 +356,17 @@ describe('Portal', () => {
);
expect(onEscB).not.toHaveBeenCalled();
});

it('should clear stack when unmount', () => {
const { unmount } = render(
<Portal open>
<div />
</Portal>,
);

expect(stack).toHaveLength(1);
unmount();
expect(stack).toHaveLength(0);
});
});
});