Improve amount input

This commit is contained in:
2025-04-21 16:31:38 +02:00
parent 3fe3e20f51
commit 8d72175e51
2 changed files with 56 additions and 3 deletions

View 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);
}}
/>
);
}