Skip to content

Commit

Permalink
Fix caret position not getting corrected when there is selection in t…
Browse files Browse the repository at this point in the history
…he input. #780
  • Loading branch information
s-yadav committed Mar 17, 2024
1 parent 2910b57 commit 5a4030c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
22 changes: 16 additions & 6 deletions src/number_format_base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -345,14 +345,24 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
* 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);
};
Expand Down
12 changes: 12 additions & 0 deletions test/library/keypress_and_caret.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(<NumericFormat prefix="$" value="$123" />);

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);
});
});
});

0 comments on commit 5a4030c

Please sign in to comment.