2022-04-06 16:26:46 +10:00
|
|
|
import { useEffect } from "react";
|
|
|
|
|
import { useWatch } from "react-hook-form";
|
2022-05-04 19:10:19 +10:00
|
|
|
import { startCase } from "lodash-es";
|
2022-04-06 16:26:46 +10:00
|
|
|
import {
|
|
|
|
|
ShortTextComponent,
|
|
|
|
|
IShortTextComponentProps,
|
|
|
|
|
} from "@rowy/form-builder";
|
|
|
|
|
|
|
|
|
|
export interface ITableNameProps extends IShortTextComponentProps {
|
|
|
|
|
watchedField?: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default function TableName({ watchedField, ...props }: ITableNameProps) {
|
|
|
|
|
const {
|
2023-04-06 11:17:47 +05:30
|
|
|
field: { onChange, value },
|
2022-04-06 16:26:46 +10:00
|
|
|
useFormMethods: { control },
|
|
|
|
|
disabled,
|
|
|
|
|
} = props;
|
|
|
|
|
|
|
|
|
|
const watchedValue = useWatch({ control, name: watchedField } as any);
|
|
|
|
|
useEffect(() => {
|
2023-04-06 11:17:47 +05:30
|
|
|
if (!disabled) {
|
2023-06-28 23:55:31 +08:00
|
|
|
const touched = control.getFieldState(props.name).isTouched;
|
|
|
|
|
|
|
|
|
|
if (!touched && typeof watchedValue === "string" && !!watchedValue) {
|
|
|
|
|
// if table name field is not touched, and watched value is valid, set table name to watched value
|
2023-04-06 11:17:47 +05:30
|
|
|
onChange(startCase(watchedValue));
|
2023-06-28 23:55:31 +08:00
|
|
|
} else if (typeof value === "string") {
|
|
|
|
|
// otherwise if table name is valid, set watched value to table name
|
|
|
|
|
onChange(value.trim());
|
2023-04-06 11:17:47 +05:30
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, [watchedValue, disabled, onChange, value]);
|
2022-04-06 16:26:46 +10:00
|
|
|
|
|
|
|
|
return <ShortTextComponent {...props} />;
|
|
|
|
|
}
|