From e1f772709e73d8d1d3408fcdfa06b74d681399c8 Mon Sep 17 00:00:00 2001 From: pierluigigiancola Date: Thu, 4 Jul 2024 05:21:04 +0200 Subject: [PATCH] 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 Co-authored-by: afc163 --- src/hooks/useCursor.ts | 6 +++--- tests/cursor.test.tsx | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/hooks/useCursor.ts b/src/hooks/useCursor.ts index c5d33f60..10d7c503 100644 --- a/src/hooks/useCursor.ts +++ b/src/hooks/useCursor.ts @@ -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); diff --git a/tests/cursor.test.tsx b/tests/cursor.test.tsx index 87023771..83003b83 100644 --- a/tests/cursor.test.tsx +++ b/tests/cursor.test.tsx @@ -107,4 +107,14 @@ describe('InputNumber.Cursor', () => { }); }); }); + + describe('append string', () => { + it('position caret before appended characters', () => { + const { container } = render( `${value}%`} parser={(value) => value.replace('%', '')} />); + const input = container.querySelector('input'); + fireEvent.focus(input); + fireEvent.change(input,{ target: { value: '5' } }); + expect(cursorInput(input)).toEqual(1); + }); + }); });