import * as React from 'react'; import { FormGroup } from '@patternfly/react-core'; import { useField, useFormikContext, FormikValues } from 'formik'; import compact from 'lodash/compact'; import isEmpty from 'lodash/isEmpty'; import { BasicNameValueEditor } from '../../name-value-editor'; import { KeyValueFieldProps } from '../field-types'; import { getFieldId } from '../field-utils'; import FieldHelperText from '../FieldHelperText'; const areNameValuePairsEqual = ( current: (string | number)[][], next: (string | number)[][], ): boolean => current.length === next.length && current.every((pair, index) => pair[0] === next[index][0] && pair[1] === next[index][1]); const KeyValueField: React.FC> = ({ label, helpText, description, labelIcon, required, entries, readOnly = false, ...props }) => { const { setFieldValue, values } = useFormikContext(); const [field] = useField<{ key: string; value: string }[]>(props.name); const fieldId = getFieldId(props.name, 'key-value-input'); const nameValuePairs = React.useMemo(() => { const source = field.value?.length ? field.value : (entries ?? []); if (isEmpty(source)) { return [['', '']]; } return source.map(({ key, value }) => [key, value]); }, [field.value, entries]); const [keyValue, setKeyValue] = React.useState(nameValuePairs); React.useEffect(() => { setKeyValue((current) => areNameValuePairsEqual(current, nameValuePairs) ? current : nameValuePairs, ); }, [nameValuePairs]); const onChangeKeyValuePair = React.useCallback( ({ nameValuePairs: keyValuePairs }: { nameValuePairs: string[][] }) => { if (keyValuePairs) { const updatedNameValuePairs = compact( keyValuePairs.map(([key, value]) => (key.length || value.length ? { key, value } : null)), ); setKeyValue(keyValuePairs); void setFieldValue(props.name, updatedNameValuePairs); } }, [props.name, setFieldValue], ); React.useEffect(() => { if (values.formReloadCount) { setKeyValue(nameValuePairs); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [values.formReloadCount]); return ( {description &&
{description}
}
); }; export default KeyValueField;