import React, { useMemo, useEffect, useState } from 'react';
import { TextInput, Select, Field } from '@rocket.chat/fuselage';
import { useSetting } from '../contexts/SettingsContext';
import { useForm } from '../hooks/useForm';
import { useTranslation } from '../contexts/TranslationContext';
import { capitalize } from '../helpers/capitalize';
const CustomTextInput = ({ name, required, minLength, maxLength, setState, state, className }) => {
const t = useTranslation();
const verify = useMemo(() => {
const error = [];
if (!state && required) { error.push(t('Field_required')); }
if (state.length < minLength && state.length > 0) { error.push(t('Min_length_is', minLength)); }
return error.join(', ');
}, [state, required, minLength, t]);
return useMemo(() =>
{t(name)}
setState(e.currentTarget.value)}/>
{verify}
, [name, verify, maxLength, state, required, setState, className]);
};
const CustomSelect = ({ name, required, options, setState, state, className }) => {
const t = useTranslation();
const mappedOptions = useMemo(() => Object.values(options).map((value) => [value, value]), [options]);
const verify = useMemo(() => (!state.length && required ? t('Field_required') : ''), [required, state.length, t]);
return useMemo(() =>
{t(name)}
{verify}
, [name, verify, state, mappedOptions, required, setState, className]);
};
const CustomFieldsAssembler = ({ formValues, formHandlers, customFields, ...props }) => Object.entries(customFields).map(([key, value]) => {
const extraProps = {
key,
name: key,
setState: formHandlers[`handle${ capitalize(key) }`],
state: formValues[key],
...value,
};
if (value.type === 'select') {
return ;
}
if (value.type === 'text') {
return ;
}
return null;
});
export default function CustomFieldsForm({ customFieldsData, setCustomFieldsData, onLoadFields = () => {}, ...props }) {
const customFieldsJson = useSetting('Accounts_CustomFields');
const [customFields] = useState(() => {
try {
return JSON.parse(customFieldsJson || '{}');
} catch {
return {};
}
});
const hasCustomFields = Boolean(Object.values(customFields).length);
const defaultFields = useMemo(() => Object.entries(customFields).reduce((data, [key, value]) => { data[key] = value.defaultValue ?? ''; return data; }, {}), []);
const { values, handlers } = useForm({ ...defaultFields, ...customFieldsData });
useEffect(() => {
onLoadFields(hasCustomFields);
if (hasCustomFields) {
setCustomFieldsData(values);
}
// TODO: remove stringify. Is needed to avoid infinite rendering
}, [JSON.stringify(values)]);
if (!hasCustomFields) {
return null;
}
return ;
}