Skip to content

Commit

Permalink
fix: cursor position when formatter appends characters on empty string (
Browse files Browse the repository at this point in the history
#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 <pierluigi.giancola@moltiplygroup.com>
Co-authored-by: afc163 <afc163@gmail.com>
  • Loading branch information
3 people authored Jul 4, 2024
1 parent fdaef5a commit e1f7727
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/hooks/useCursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ export default function useCursor(

let startPos = value.length;

if (value.endsWith(afterTxt)) {
startPos = value.length - selectionRef.current.afterTxt.length;
} else if (value.startsWith(beforeTxt)) {
if (value.startsWith(beforeTxt)) {
startPos = beforeTxt.length;
} else if (value.endsWith(afterTxt)) {
startPos = value.length - selectionRef.current.afterTxt.length;
} else {
const beforeLastChar = beforeTxt[start - 1];
const newIndex = value.indexOf(beforeLastChar, start - 1);
Expand Down
10 changes: 10 additions & 0 deletions tests/cursor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,14 @@ describe('InputNumber.Cursor', () => {
});
});
});

describe('append string', () => {
it('position caret before appended characters', () => {
const { container } = render(<InputNumber formatter={(value) => `${value}%`} parser={(value) => value.replace('%', '')} />);
const input = container.querySelector('input');
fireEvent.focus(input);
fireEvent.change(input,{ target: { value: '5' } });
expect(cursorInput(input)).toEqual(1);
});
});
});

0 comments on commit e1f7727

Please sign in to comment.