Skip to content

Commit f1b2385

Browse files
EmilyyyLiu刘欢
andauthored
feat: Add IME judgment (#125)
Co-authored-by: 刘欢 <[email protected]>
1 parent 1d77d2d commit f1b2385

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/Input.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,12 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
160160
};
161161

162162
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
163-
if (onPressEnter && e.key === 'Enter' && !keyLockRef.current) {
163+
if (
164+
onPressEnter &&
165+
e.key === 'Enter' &&
166+
!keyLockRef.current &&
167+
!e.nativeEvent.isComposing
168+
) {
164169
keyLockRef.current = true;
165170
onPressEnter(e);
166171
}

tests/index.test.tsx

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { fireEvent, render } from '@testing-library/react';
22
import userEvent from '@testing-library/user-event';
33
import { spyElementPrototypes } from '@rc-component/util/lib/test/domHook';
4-
import React from 'react';
4+
import React, { ElementType } from 'react';
55
import Input from '../src';
66
import type { InputRef } from '../src/interface';
77
import { resolveOnChange } from '../src/utils/commonUtils';
@@ -504,3 +504,40 @@ describe('resolveChange should work', () => {
504504
fireEvent.compositionEnd(container.querySelector('textarea')!);
505505
expect(onChange).toHaveBeenCalled();
506506
});
507+
508+
describe('Input IME behavior', () => {
509+
it('should ignore Enter during composition', () => {
510+
const onPressEnter = jest.fn();
511+
const { container } = render(<Input onPressEnter={onPressEnter} />);
512+
const input = container.querySelector('input')!;
513+
514+
fireEvent.compositionStart(input);
515+
516+
fireEvent.keyDown(input, {
517+
key: 'Enter',
518+
keyCode: 229,
519+
isComposing: true,
520+
nativeEvent: { isComposing: true },
521+
});
522+
523+
fireEvent.compositionUpdate(input, { data: '开始' });
524+
525+
expect(onPressEnter).not.toHaveBeenCalled();
526+
527+
fireEvent.compositionEnd(input);
528+
fireEvent.keyDown(input, {
529+
key: 'Enter',
530+
nativeEvent: { isComposing: false },
531+
});
532+
expect(onPressEnter).toHaveBeenCalledTimes(1);
533+
});
534+
535+
it('should work with actual IME input', async () => {
536+
const user = userEvent.setup();
537+
const onPressEnter = jest.fn();
538+
const { container } = render(<Input onPressEnter={onPressEnter} />);
539+
540+
await user.type(container.querySelector('input')!, 'abc{enter}');
541+
expect(onPressEnter).toHaveBeenCalled();
542+
});
543+
});

0 commit comments

Comments
 (0)