Skip to content

Commit e1f7727

Browse files
pierluigigiancolaPierluigi Giancolaafc163
authored
fix: cursor position when formatter appends characters on empty string (#652)
* fix: cursor position when formatter appends characters on empty string * revert: fix * test(useCursor): position caret before appended characters * fix cursor position when formatter appends characters on empty string * Update tests/cursor.test.tsx * Update tests/cursor.test.tsx --------- Co-authored-by: Pierluigi Giancola <[email protected]> Co-authored-by: afc163 <[email protected]>
1 parent fdaef5a commit e1f7727

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/hooks/useCursor.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ export default function useCursor(
5050

5151
let startPos = value.length;
5252

53-
if (value.endsWith(afterTxt)) {
54-
startPos = value.length - selectionRef.current.afterTxt.length;
55-
} else if (value.startsWith(beforeTxt)) {
53+
if (value.startsWith(beforeTxt)) {
5654
startPos = beforeTxt.length;
55+
} else if (value.endsWith(afterTxt)) {
56+
startPos = value.length - selectionRef.current.afterTxt.length;
5757
} else {
5858
const beforeLastChar = beforeTxt[start - 1];
5959
const newIndex = value.indexOf(beforeLastChar, start - 1);

tests/cursor.test.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,4 +107,14 @@ describe('InputNumber.Cursor', () => {
107107
});
108108
});
109109
});
110+
111+
describe('append string', () => {
112+
it('position caret before appended characters', () => {
113+
const { container } = render(<InputNumber formatter={(value) => `${value}%`} parser={(value) => value.replace('%', '')} />);
114+
const input = container.querySelector('input');
115+
fireEvent.focus(input);
116+
fireEvent.change(input,{ target: { value: '5' } });
117+
expect(cursorInput(input)).toEqual(1);
118+
});
119+
});
110120
});

0 commit comments

Comments
 (0)