Improve amount input
This commit is contained in:
52
moneymgr_web/src/widgets/forms/AmountInput.tsx
Normal file
52
moneymgr_web/src/widgets/forms/AmountInput.tsx
Normal file
@ -0,0 +1,52 @@
|
||||
import React from "react";
|
||||
import { TextInput } from "./TextInput";
|
||||
|
||||
enum InputState {
|
||||
Normal,
|
||||
StartNeg,
|
||||
StartDecimal,
|
||||
}
|
||||
|
||||
export function AmountInput(p: {
|
||||
editable: boolean;
|
||||
type: string;
|
||||
placeholder: string;
|
||||
style: React.CSSProperties;
|
||||
value: number;
|
||||
onValueChange: (val: number) => {};
|
||||
}): React.ReactElement {
|
||||
const [state, setState] = React.useState(InputState.Normal);
|
||||
|
||||
let value = "";
|
||||
|
||||
if (state === InputState.StartNeg) {
|
||||
value = "-";
|
||||
} else if (state === InputState.StartDecimal) {
|
||||
value = String(p.value) + ".";
|
||||
} else if (!Number.isNaN(p.value)) {
|
||||
value = String(p.value);
|
||||
}
|
||||
|
||||
return (
|
||||
<TextInput
|
||||
{...p}
|
||||
value={value}
|
||||
onValueChange={(a) => {
|
||||
if (a === "-") return setState(InputState.StartNeg);
|
||||
|
||||
if (a?.endsWith(".")) {
|
||||
setState(InputState.StartDecimal);
|
||||
} else if (state !== InputState.Normal) {
|
||||
setState(InputState.Normal);
|
||||
}
|
||||
const parsed = Number(a);
|
||||
|
||||
// Empty field
|
||||
if (a?.length === 0) p.onValueChange(NaN);
|
||||
// Input number
|
||||
else if ((a?.length ?? 0 > 0) && !Number.isNaN(parsed))
|
||||
p.onValueChange(parsed);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
Reference in New Issue
Block a user