import { equals } from 'ramda'; import { type ReactElement, useCallback, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { number, object, type Schema, 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 GlobalRefreshFieldOption from './GlobalRefreshFieldOption'; import { labelCharacters, labelMustBeAtLeast, labelMustBeMost, labelRequired } from './translatedLabels'; export type DashboardFormProps = { labels: DashboardFormLabels; onSubmit?: FormProps['submit']; resource?: DashboardResource; showRefreshIntervalFields?: boolean; variant?: FormVariant; } & Pick; export type DashboardFormLabels = { actions: FormActionsProps['labels']; entity: Required; }; const DashboardForm = ({ variant = 'create', resource, labels, onSubmit, onCancel, showRefreshIntervalFields }: DashboardFormProps): ReactElement => { const { classes } = useStyles(); const { t } = useTranslation(); const formProps = useMemo>( () => ({ initialValues: resource ?? { description: null, name: '' }, inputs: [ { fieldName: 'name', group: 'main', label: labels?.entity?.name, required: true, type: InputType.Text }, { fieldName: 'description', group: 'main', label: labels?.entity?.description || '', text: { multilineRows: 3 }, type: InputType.Text }, { fieldName: 'refresh.type', group: 'main', hideInput: () => !showRefreshIntervalFields, label: labels?.entity?.globalRefreshInterval?.title, radio: { options: [ { label: , value: 'global' }, { label: labels?.entity?.globalRefreshInterval?.manual, value: 'manual' } ], row: false }, type: InputType.Radio } ], submit: (values, bag) => onSubmit?.(values, bag), validationSchema: object({ description: string() .label(labels?.entity?.description || '') .max( 180, (p) => `${p.label} ${t(labelMustBeMost)} ${p.max} ${t(labelCharacters)}` ) .nullable(), globalRefreshInterval: object({ interval: number().when('type', ([type], schema) => { if (equals(type, 'manual')) { schema .min(1, ({ min }) => t(labelMustBeAtLeast, { min })) .required(t(labelRequired) as string); } return schema.nullable(); }), type: string() }), 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) }) as unknown as Schema }), [resource, labels, onSubmit, showRefreshIntervalFields, t] ); const Actions = useCallback( () => ( labels={labels?.actions} onCancel={onCancel} variant={variant} /> ), [labels, onCancel, variant] ); return (
{...formProps} Buttons={Actions} />
); }; export { DashboardForm };