Skip to content

Commit

Permalink
fix: negative numeric input
Browse files Browse the repository at this point in the history
  • Loading branch information
Sampaio Leal committed Jun 9, 2022
1 parent 22b542f commit c921aa3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@euk-labs/componentz",
"version": "0.5.5",
"version": "0.5.6",
"main": "./cjs/index.js",
"module": "./index.js",
"types": "./index.d.ts",
Expand Down
33 changes: 22 additions & 11 deletions src/components/Inputs/NumericField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function NumericField(props: NumericInputProps) {

const hasValue = value !== undefined;
let inputDefaultValue;
let inputValue;
let inputValue: string | undefined;

if (hasValue) {
if (isNaN(defaultValue) || value === '') {
Expand All @@ -80,6 +80,9 @@ function NumericField(props: NumericInputProps) {
if (inputValue && !inputValue.includes('-')) {
inputValue = `-${inputValue}`;
}
} else {
inputValue = inputValue?.replace(/^-/, '');
inputDefaultValue = inputDefaultValue?.replace(/^-/, '');
}

function format(number: number) {
Expand All @@ -92,16 +95,16 @@ function NumericField(props: NumericInputProps) {
}

function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>): void {
if (
e.ctrlKey ||
e.shiftKey ||
e.key === 'Backspace' ||
e.key === 'Enter' ||
e.key === 'Tab' ||
e.key === 'ArrowRight' ||
e.key === 'ArrowLeft' ||
e.key === 'Delete'
) {
const allowedKeys = [
'Backspace',
'Enter',
'Delete',
'ArrowLeft',
'ArrowRight',
'Tab',
];

if (e.ctrlKey || e.shiftKey || allowedKeys.includes(e.key)) {
return;
}

Expand Down Expand Up @@ -170,6 +173,14 @@ function NumericField(props: NumericInputProps) {
}
}, [negative]);

useEffect(() => {
const { numberFormat } = verifyNumber(inputValue || '');

if (!inputValue || Math.abs(numberFormat || 0) === 0) {
setIsNegative(false);
}
}, [inputValue]);

return (
<TextField
defaultValue={inputDefaultValue}
Expand Down

0 comments on commit c921aa3

Please sign in to comment.