frontPanel/src/ui_kit/CustomNumberField.tsx

55 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-09-12 14:36:22 +00:00
import CustomTextField from "./CustomTextField";
import type { ChangeEvent, KeyboardEvent, FocusEvent } from "react";
import type { SxProps, Theme } from "@mui/material";
interface CustomNumberFieldProps {
placeholder: string;
onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
2023-09-12 15:57:48 +00:00
error?: string;
2023-09-12 15:23:56 +00:00
value: string;
2023-09-12 14:36:22 +00:00
sx?: SxProps<Theme>;
min?: number;
max?: number;
}
export default function CustomNumberField({
placeholder,
2023-09-12 15:23:56 +00:00
value,
2023-09-12 14:36:22 +00:00
sx,
2023-09-12 15:57:48 +00:00
error,
2023-09-12 14:36:22 +00:00
onChange,
onKeyDown,
onBlur,
min = -999999999,
max = 999999999,
}: CustomNumberFieldProps) {
const onInputChange = (event: ChangeEvent<HTMLInputElement>) => {
const inputValue = event.target.value;
if (
Number(inputValue) >= min &&
Number(inputValue) <= max &&
(inputValue === "" ||
inputValue.match(/^\d*$/) ||
(inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/)))
) {
onChange?.({ ...event, target: { ...event.target, value: inputValue } });
}
};
return (
<CustomTextField
placeholder={placeholder}
sx={sx}
2023-09-12 15:57:48 +00:00
error={error}
2023-09-12 14:36:22 +00:00
onChange={onInputChange}
onKeyDown={onKeyDown}
onBlur={onBlur}
value={value}
/>
);
}