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 EditFenceDeviceInputGroup: FC = ({ fenceDeviceId, fenceDeviceTemplate, }) => { const fenceParameterElements = useMemo(() => { let result: ReactNode; if (fenceDeviceTemplate && fenceDeviceId) { const { parameters: fenceDeviceParameters } = fenceDeviceTemplate[fenceDeviceId]; const { optional: optionalInputs, required: requiredInputs } = Object.entries(fenceDeviceParameters).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 = `${fenceDeviceId}-${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: `${fenceDeviceId}-name`, isRequired: true, label: 'Fence device name', }), ], }, ); result = ( <> {requiredInputs} {optionalInputs} ); } return result; }, [fenceDeviceId, fenceDeviceTemplate]); return <>{fenceParameterElements}; }; export default EditFenceDeviceInputGroup;