Skip to content

Commit 5a4030c

Browse files
committed
Fix caret position not getting corrected when there is selection in the input. #780
1 parent 2910b57 commit 5a4030c

File tree

3 files changed

+29
-7
lines changed

3 files changed

+29
-7
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "react-number-format",
33
"description": "React component to format number in an input or as a text.",
4-
"version": "5.3.3",
4+
"version": "5.3.4",
55
"main": "dist/react-number-format.cjs.js",
66
"module": "dist/react-number-format.es.js",
77
"types": "types/index.d.ts",

src/number_format_base.tsx

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -345,14 +345,24 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
345345
* NOTE: we have to give default value for value as in case when custom input is provided
346346
* value can come as undefined when nothing is provided on value prop.
347347
*/
348-
const { selectionStart, selectionEnd, value = '' } = el;
349348

350-
if (selectionStart === selectionEnd) {
351-
const caretPosition = correctCaretPosition(value, selectionStart as number);
352-
if (caretPosition !== selectionStart) {
353-
setPatchedCaretPosition(el, caretPosition, value);
349+
const correctCaretPositionIfRequired = () => {
350+
const { selectionStart, selectionEnd, value = '' } = el;
351+
if (selectionStart === selectionEnd) {
352+
const caretPosition = correctCaretPosition(value, selectionStart as number);
353+
if (caretPosition !== selectionStart) {
354+
setPatchedCaretPosition(el, caretPosition, value);
355+
}
354356
}
355-
}
357+
};
358+
359+
correctCaretPositionIfRequired();
360+
361+
// try to correct after selection has updated by browser
362+
// this case is required when user clicks on some position while a text is selected on input
363+
requestAnimationFrame(() => {
364+
correctCaretPositionIfRequired();
365+
});
356366

357367
onMouseUp(e);
358368
};

test/library/keypress_and_caret.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,5 +679,17 @@ describe('Test keypress and caret position changes', () => {
679679
jasmine.clock().tick(1);
680680
expect(caretPos).toEqual(0);
681681
});
682+
683+
it('should correct caret position after user click on input while it has selection #780', async () => {
684+
const { input } = await render(<NumericFormat prefix="$" value="$123" />);
685+
686+
input.setSelectionRange(0, 3);
687+
688+
// this simulates browser mouse up on already selected text
689+
userEvent.click(input);
690+
input.setSelectionRange(0, 0);
691+
await wait(500);
692+
expect(input.selectionStart).toEqual(1);
693+
});
682694
});
683695
});

0 commit comments

Comments
 (0)