Skip to content

Commit

Permalink
feat: Prevent long press of enter (#72)
Browse files Browse the repository at this point in the history
* feat: Prevent long press of enter

* feat: test

* feat: 优化 if

* feat: keyLockRef
  • Loading branch information
crazyair authored Jul 18, 2024
1 parent 31ebcec commit e9d6848
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
onBlur,
onPressEnter,
onKeyDown,
onKeyUp,
prefixCls = 'rc-input',
disabled,
htmlSize,
Expand All @@ -42,6 +43,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {

const [focused, setFocused] = useState<boolean>(false);
const compositionRef = useRef(false);
const keyLockRef = useRef(false);

const inputRef = useRef<HTMLInputElement>(null);
const holderRef = useRef<HolderRef>(null);
Expand Down Expand Up @@ -155,10 +157,17 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
};

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (onPressEnter && e.key === 'Enter') {
onKeyDown?.(e);
if (onPressEnter && e.key === 'Enter' && !keyLockRef.current) {
keyLockRef.current = true;
onPressEnter(e);
}
onKeyDown?.(e);
};
const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyUp?.(e);
if (e.key === 'Enter') {
keyLockRef.current = false;
}
};

const handleFocus: React.FocusEventHandler<HTMLInputElement> = (e) => {
Expand Down Expand Up @@ -215,6 +224,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
onFocus={handleFocus}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
className={clsx(
prefixCls,
{
Expand Down
20 changes: 20 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,26 @@ describe('Input', () => {
expect(onPressEnter).toHaveBeenCalled();
});

it('should prevent long press of enter', () => {
const onKeyDown = jest.fn();
const onPressEnter = jest.fn();
const onKeyUp = jest.fn();
const { container } = render(
<Input
onKeyDown={onKeyDown}
onPressEnter={onPressEnter}
onKeyUp={onKeyUp}
/>,
);
const inputEl = container.querySelector('input')!;
fireEvent.keyDown(inputEl, { key: 'Enter' });
fireEvent.keyDown(inputEl, { key: 'Enter' });
fireEvent.keyUp(inputEl, { key: 'Enter' });
expect(onKeyDown).toBeCalledTimes(2);
expect(onPressEnter).toBeCalledTimes(1);
expect(onKeyUp).toBeCalledTimes(1);
});

it('should trigger onChange', () => {
const onChange = jest.fn();
const { container } = render(<Input onChange={onChange} />);
Expand Down

0 comments on commit e9d6848

Please sign in to comment.