From 5a4030ca1276ac30f2ad6211ec752a562b278511 Mon Sep 17 00:00:00 2001 From: Sudhanshu Date: Sun, 17 Mar 2024 23:11:14 +0530 Subject: [PATCH] Fix caret position not getting corrected when there is selection in the input. #780 --- package.json | 2 +- src/number_format_base.tsx | 22 ++++++++++++++++------ test/library/keypress_and_caret.spec.js | 12 ++++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 322fa6a..68a7cdb 100755 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "react-number-format", "description": "React component to format number in an input or as a text.", - "version": "5.3.3", + "version": "5.3.4", "main": "dist/react-number-format.cjs.js", "module": "dist/react-number-format.es.js", "types": "types/index.d.ts", diff --git a/src/number_format_base.tsx b/src/number_format_base.tsx index 12a232b..45838b5 100644 --- a/src/number_format_base.tsx +++ b/src/number_format_base.tsx @@ -345,14 +345,24 @@ export default function NumberFormatBase( * NOTE: we have to give default value for value as in case when custom input is provided * value can come as undefined when nothing is provided on value prop. */ - const { selectionStart, selectionEnd, value = '' } = el; - if (selectionStart === selectionEnd) { - const caretPosition = correctCaretPosition(value, selectionStart as number); - if (caretPosition !== selectionStart) { - setPatchedCaretPosition(el, caretPosition, value); + const correctCaretPositionIfRequired = () => { + const { selectionStart, selectionEnd, value = '' } = el; + if (selectionStart === selectionEnd) { + const caretPosition = correctCaretPosition(value, selectionStart as number); + if (caretPosition !== selectionStart) { + setPatchedCaretPosition(el, caretPosition, value); + } } - } + }; + + correctCaretPositionIfRequired(); + + // try to correct after selection has updated by browser + // this case is required when user clicks on some position while a text is selected on input + requestAnimationFrame(() => { + correctCaretPositionIfRequired(); + }); onMouseUp(e); }; diff --git a/test/library/keypress_and_caret.spec.js b/test/library/keypress_and_caret.spec.js index 0a6843b..163c835 100644 --- a/test/library/keypress_and_caret.spec.js +++ b/test/library/keypress_and_caret.spec.js @@ -679,5 +679,17 @@ describe('Test keypress and caret position changes', () => { jasmine.clock().tick(1); expect(caretPos).toEqual(0); }); + + it('should correct caret position after user click on input while it has selection #780', async () => { + const { input } = await render(); + + input.setSelectionRange(0, 3); + + // this simulates browser mouse up on already selected text + userEvent.click(input); + input.setSelectionRange(0, 0); + await wait(500); + expect(input.selectionStart).toEqual(1); + }); }); });