Skip to content

Commit dbcd429

Browse files
committed
- Fix key press after selection over masked area.
#839
1 parent 38ce3ba commit dbcd429

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/number_format_base.tsx

+4-2
Original file line numberDiff line numberDiff line change
@@ -319,9 +319,11 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
319319
endOffset = 1;
320320
}
321321

322+
const isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';
323+
322324
//if expectedCaretPosition is not set it means we don't want to Handle keyDown
323325
// also if multiple characters are selected don't handle
324-
if (expectedCaretPosition === undefined || selectionStart !== selectionEnd) {
326+
if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {
325327
onKeyDown(e);
326328
// keep information of what was the caret position before keyDown
327329
// set it after onKeyDown, in case parent updates the position manually
@@ -331,7 +333,7 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
331333

332334
let newCaretPosition = expectedCaretPosition;
333335

334-
if (key === 'ArrowLeft' || key === 'ArrowRight') {
336+
if (isArrowKey) {
335337
const direction = key === 'ArrowLeft' ? 'left' : 'right';
336338
newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);
337339
// arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually

test/library/keypress_and_caret.spec.jsx

+8-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import React, { useState } from 'react';
33
import NumericFormat from '../../src/numeric_format';
44
import PatternFormat from '../../src/pattern_format';
55
import NumberFormatBase from '../../src/number_format_base';
6-
import { waitFor } from '@testing-library/react';
6+
import { waitFor, fireEvent } from '@testing-library/react';
77
import userEvent from '@testing-library/user-event';
88

99
import {
@@ -689,5 +689,12 @@ describe('Test keypress and caret position changes', () => {
689689
input.setSelectionRange(0, 0);
690690
waitFor(() => expect(input.selectionStart).toEqual(1));
691691
});
692+
693+
it('should correct caret position after user select masked area and then clicks or press key #839', async () => {
694+
const { input } = await render(<PatternFormat format="##/##/####" value="1" mask="_" />);
695+
input.setSelectionRange(3, 7);
696+
fireEvent.keyDown(input, { key: 'ArrowRight' });
697+
expect(input.selectionEnd).toEqual(1);
698+
});
692699
});
693700
});

0 commit comments

Comments
 (0)