import React, { useMemo, useState } from "react"; import { TextField, TextFieldProps } from "@mui/material"; import { Dictionary } from "@types"; export type TextFieldCustomProps = { onFix?: () => void; onChangeValue?: (val: string) => void; messages?: Dictionary; readonly?: boolean; } & TextFieldProps; export default function TextFieldCustom({ onFix, onChangeValue, messages, readonly, ...others }: TextFieldCustomProps) { const [oldValue, setOldValue] = useState(null); const inputProps = useMemo(() => { if (readonly) { return { style: { color: "rgb(50, 50, 50)" }, disabled: true, }; } else { return undefined; } }, [readonly]); const fix = (newValue: string) => { if (oldValue !== newValue) { setOldValue(newValue); if (onFix) { onFix(); } } }; const handleEnter = (e: React.KeyboardEvent) => { if (e.key === "Enter") { if (e.target instanceof HTMLInputElement) { fix(e.target.value); } } }; const handleBlur = (e: React.FocusEvent) => { if (!others.select) { fix(e.target.value); } }; const handleChange = (e: React.ChangeEvent) => { if (onChangeValue) { onChangeValue(e.target.value); } if (others.select) { fix(e.target.value); } }; const message = useMemo(() => { if (messages && others.name) { return messages[others.name] ?? ""; } else { return ""; } }, [messages]); const error = useMemo(() => { if (messages && others.name) { return ( messages[others.name] !== undefined && messages[others.name].length !== 0 ); } else { return false; } }, [messages]); return ( ); }