Skip to content

Commit

Permalink
- Fix key press after selection over masked area.
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yadav committed Jun 1, 2024
1 parent 38ce3ba commit dbcd429
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/number_format_base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,11 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
endOffset = 1;
}

const isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';

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

let newCaretPosition = expectedCaretPosition;

if (key === 'ArrowLeft' || key === 'ArrowRight') {
if (isArrowKey) {
const direction = key === 'ArrowLeft' ? 'left' : 'right';
newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);
// arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually
Expand Down
9 changes: 8 additions & 1 deletion test/library/keypress_and_caret.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useState } from 'react';
import NumericFormat from '../../src/numeric_format';
import PatternFormat from '../../src/pattern_format';
import NumberFormatBase from '../../src/number_format_base';
import { waitFor } from '@testing-library/react';
import { waitFor, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import {
Expand Down Expand Up @@ -689,5 +689,12 @@ describe('Test keypress and caret position changes', () => {
input.setSelectionRange(0, 0);
waitFor(() => expect(input.selectionStart).toEqual(1));
});

it('should correct caret position after user select masked area and then clicks or press key #839', async () => {
const { input } = await render(<PatternFormat format="##/##/####" value="1" mask="_" />);
input.setSelectionRange(3, 7);
fireEvent.keyDown(input, { key: 'ArrowRight' });
expect(input.selectionEnd).toEqual(1);
});
});
});

0 comments on commit dbcd429

Please sign in to comment.