From 0a2018ed93b8e65b7a5619995adf2b165429a5b4 Mon Sep 17 00:00:00 2001 From: Cesar S Date: Wed, 22 Nov 2023 02:13:20 +0000 Subject: [PATCH] refactor: clean up updateValueAndCaretPosition --- src/number_format_base.tsx | 36 +++++++++++------------------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/src/number_format_base.tsx b/src/number_format_base.tsx index 682f64d4..0eebd8a5 100644 --- a/src/number_format_base.tsx +++ b/src/number_format_base.tsx @@ -155,46 +155,33 @@ export default function NumberFormatBase( | React.FocusEvent | React.KeyboardEvent; source: SourceType; - caretPos?: number; - setCaretPosition?: Boolean; }) => { const { formattedValue: newFormattedValue = '', input, - setCaretPosition = true, source, event, numAsString, } = params; - let { caretPos } = params; + let caretPos; if (input) { - //calculate caret position if not defined - if (caretPos === undefined && setCaretPosition) { - const inputValue = params.inputValue || input.value; + const inputValue = params.inputValue || input.value; - const currentCaretPosition = geInputCaretPosition(input); - - /** - * set the value imperatively, this is required for IE fix - * This is also required as if new caret position is beyond the previous value. - * Caret position will not be set correctly - */ - input.value = newFormattedValue; - - //get the caret position - caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition); - } + const currentCaretPosition = geInputCaretPosition(input); /** - * set the value imperatively, as we set the caret position as well imperatively. - * This is to keep value and caret position in sync + * set the value imperatively, this is required for IE fix + * This is also required as if new caret position is beyond the previous value. + * Caret position will not be set correctly */ input.value = newFormattedValue; - //set caret position, and value imperatively when element is provided - if (setCaretPosition && caretPos !== undefined) { - //set caret position + //get the caret position + caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition); + + //set caret position imperatively + if (caretPos !== undefined) { setPatchedCaretPosition(input, caretPos, newFormattedValue); } } @@ -287,7 +274,6 @@ export default function NumberFormatBase( inputValue, event, source, - setCaretPosition: true, input: event.target as HTMLInputElement, });