From dbcd429d27cf412821e3ebec421941ead4b1f5be Mon Sep 17 00:00:00 2001 From: Sudhanshu Date: Sat, 1 Jun 2024 18:27:48 +0530 Subject: [PATCH] - Fix key press after selection over masked area. https://github.com/s-yadav/react-number-format/issues/839 --- src/number_format_base.tsx | 6 ++++-- test/library/keypress_and_caret.spec.jsx | 9 ++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/number_format_base.tsx b/src/number_format_base.tsx index b3c5ec9..64f1287 100644 --- a/src/number_format_base.tsx +++ b/src/number_format_base.tsx @@ -319,9 +319,11 @@ export default function NumberFormatBase( 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 @@ -331,7 +333,7 @@ export default function NumberFormatBase( 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 diff --git a/test/library/keypress_and_caret.spec.jsx b/test/library/keypress_and_caret.spec.jsx index 48bebfb..628a634 100644 --- a/test/library/keypress_and_caret.spec.jsx +++ b/test/library/keypress_and_caret.spec.jsx @@ -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 { @@ -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(); + input.setSelectionRange(3, 7); + fireEvent.keyDown(input, { key: 'ArrowRight' }); + expect(input.selectionEnd).toEqual(1); + }); }); });