import { type ReactElement, useCallback, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { object, string } from 'yup'; import { Form, type FormProps } from '../../../Form'; import { InputType } from '../../../Form/Inputs/models'; import type { FormVariant } from '../Form.models'; import { FormActions, type FormActionsProps } from '../FormActions'; import type { DashboardResource } from './Dashboard.resource'; import { useStyles } from './DashboardForm.styles'; import { labelMustBeAtLeast, labelMustBeMost, labelRequired } from './translatedLabels'; type DashboardFormProps = { labels: DashboardFormLabels; name: string; onSubmit?: FormProps['submit']; variant?: FormVariant; } & Pick; type DashboardFormLabels = { actions: FormActionsProps['labels']; entity: Required; }; const DashboardDuplicationForm = ({ variant = 'create', labels, onSubmit, onCancel, name }: DashboardFormProps): ReactElement => { const { classes } = useStyles(); const { t } = useTranslation(); const formProps = useMemo>( () => ({ initialValues: { name }, inputs: [ { autoFocus: true, fieldName: 'name', group: 'main', label: labels?.entity?.name, required: true, type: InputType.Text } ], submit: (values, bag) => onSubmit?.(values, bag), validationSchema: object({ name: string() .label(labels?.entity?.name) .min(3, ({ min, label }) => t(labelMustBeAtLeast, { label, min })) .max(50, ({ max, label }) => t(labelMustBeMost, { label, max })) .required(t(labelRequired) as string) }) }), [labels, onSubmit, name, t] ); const Actions = useCallback( () => ( enableSubmitWhenNotDirty labels={labels?.actions} onCancel={onCancel} variant={variant} /> ), [labels, onCancel, variant] ); return (
{...formProps} Buttons={Actions} />
); }; export { DashboardDuplicationForm };