Skip to content

Commit 1889137

Browse files
reddysteadygemini-code-assist[bot]afc163
authored
fix: keep onChange target mounted when value does not need cloning (#175)
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Co-authored-by: Ed Stead <edward.stead.com> Co-authored-by: afc163 <afc163@gmail.com>
1 parent cb2f305 commit 1889137

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

src/utils/commonUtils.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,16 @@ function cloneEvent<
4545
return newEvent;
4646
}
4747

48+
function cloneEventWithTarget<
49+
EventType extends React.SyntheticEvent<any, any>,
50+
Element extends HTMLInputElement | HTMLTextAreaElement,
51+
>(event: EventType, target: Element): EventType {
52+
return Object.create(event, {
53+
target: { value: target },
54+
currentTarget: { value: target },
55+
});
56+
}
57+
4858
export function resolveOnChange<
4959
E extends HTMLInputElement | HTMLTextAreaElement,
5060
>(
@@ -84,7 +94,11 @@ export function resolveOnChange<
8494
// https://github.com/ant-design/ant-design/issues/45737
8595
// https://github.com/ant-design/ant-design/issues/46598
8696
if (target.type !== 'file' && targetValue !== undefined) {
87-
event = cloneEvent(e, target, targetValue);
97+
if (target.value !== targetValue) {
98+
event = cloneEvent(e, target, targetValue);
99+
} else {
100+
event = cloneEventWithTarget(e, target);
101+
}
88102
onChange(event as React.ChangeEvent<E>);
89103
return;
90104
}

tests/index.test.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,19 @@ describe('Input ref', () => {
439439
expect(spySetSelectionRange).toHaveBeenCalledWith(1, 2);
440440
});
441441

442+
it('onChange target should be the mounted input when value is unchanged by formatter', () => {
443+
const onChange = jest.fn();
444+
const { container } = render(<Input onChange={onChange} />);
445+
const inputEl = container.querySelector('input')!;
446+
447+
fireEvent.change(inputEl, { target: { value: 'test' } });
448+
449+
const event = onChange.mock.calls[0][0];
450+
expect(event.target).toBe(inputEl);
451+
expect(event.currentTarget).toBe(inputEl);
452+
expect(document.contains(event.target)).toBe(true);
453+
});
454+
442455
it('email type not support selection', () => {
443456
const onChange = jest.fn();
444457
const { container } = render(<Input type="email" onChange={onChange} />);

0 commit comments

Comments
 (0)