import { FC, ReactElement, ReactNode, useMemo } from 'react'; import FlexBox from './FlexBox'; import InputWithRef from './InputWithRef'; import OutlinedInputWithLabel from './OutlinedInputWithLabel'; import { ExpandablePanel } from './Panels'; import SelectWithLabel from './SelectWithLabel'; import SwitchWithLabel from './SwitchWithLabel'; const CHECKED_STATES: Array = ['1', 'on']; const MAP_TO_INPUT_BUILDER: MapToInputBuilder = { boolean: ({ id, isChecked = false, label }) => ( } valueType="boolean" /> ), select: ({ id, isRequired, label, selectOptions = [], value = '' }) => ( } required={isRequired} /> ), string: ({ id, isRequired, label = '', value }) => ( } required={isRequired} /> ), }; const CommonFenceInputGroup: FC = ({ fenceId, fenceTemplate, }) => { const fenceParameterElements = useMemo(() => { let result: ReactNode; if (fenceTemplate && fenceId) { const { parameters: fenceParameters } = fenceTemplate[fenceId]; const { optional: optionalInputs, required: requiredInputs } = Object.entries(fenceParameters).reduce<{ optional: ReactElement[]; required: ReactElement[]; }>( ( previous, [ parameterId, { content_type: contentType, default: parameterDefault, options: parameterSelectOptions, required: isRequired, }, ], ) => { const { optional, required } = previous; const buildInput = MAP_TO_INPUT_BUILDER[contentType] ?? MAP_TO_INPUT_BUILDER.string; const fenceJoinParameterId = `${fenceId}-${parameterId}`; const parameterIsRequired = isRequired === '1'; const parameterInput = buildInput({ id: fenceJoinParameterId, isChecked: CHECKED_STATES.includes(parameterDefault), isRequired: parameterIsRequired, label: parameterId, selectOptions: parameterSelectOptions, value: parameterDefault, }); if (parameterIsRequired) { required.push(parameterInput); } else { optional.push(parameterInput); } return previous; }, { optional: [], required: [ MAP_TO_INPUT_BUILDER.string({ id: `${fenceId}-name`, isRequired: true, label: 'Fence device name', }), ], }, ); result = ( <> {requiredInputs} {optionalInputs} ); } return result; }, [fenceId, fenceTemplate]); return <>{fenceParameterElements}; }; export default CommonFenceInputGroup;