Skip to content

Commit

Permalink
Fix #711
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yadav committed Jan 10, 2023
1 parent cf0b3ba commit 29fb422
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/numeric_format.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -330,17 +330,22 @@ export function useNumericFormat<BaseType = InputAttributes>(
}

// don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set
const { decimalSeparator } = getSeparators(props);
const { decimalSeparator, allowedDecimalSeparators } = getSeparators(props);
if (
key === 'Backspace' &&
value[(selectionStart as number) - 1] === decimalSeparator &&
value[selectionStart - 1] === decimalSeparator &&
decimalScale &&
fixedDecimalScale
) {
setCaretPosition(el, (selectionStart as number) - 1);
setCaretPosition(el, selectionStart - 1);
e.preventDefault();
}

// if user presses the allowed decimal separator before the separator, move the cursor after the separator
if (allowedDecimalSeparators?.includes(key) && value[selectionStart] === decimalSeparator) {
setCaretPosition(el, selectionStart + 1);
}

const _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;

// move cursor when delete or backspace is pressed before/after thousand separator
Expand Down
19 changes: 19 additions & 0 deletions test/library/keypress_and_caret.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,25 @@ describe('Test keypress and caret position changes', () => {
expect(input.selectionStart).toEqual(2);
});

it('should update caret position when any of the decimal separator is pressed just before the decimal separator #711', async () => {
const { input } = await render(
<NumericFormat
value={12}
allowedDecimalSeparators={[',', '.']}
decimalSeparator=","
thousandSeparator="."
decimalScale={3}
fixedDecimalScale
/>,
);

simulateNativeKeyInput(input, ',', 2, 2);
expect(input.selectionStart).toEqual(3);

simulateNativeKeyInput(input, '.', 2, 2);
expect(input.selectionStart).toEqual(3);
});

describe('Test character insertion', () => {
it('should add any number properly when input is empty without format prop passed', () => {
const wrapper = mount(<NumericFormat thousandSeparator={true} prefix={'$'} />);
Expand Down

0 comments on commit 29fb422

Please sign in to comment.