import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useFormContext } from "react-hook-form"; import { ActionList, ActionListItem, Button, Flex, FlexItem, FormGroup, TextInput, } from "@patternfly/react-core"; import { MinusCircleIcon, PlusCircleIcon } from "@patternfly/react-icons"; import type { ComponentProps } from "./components"; import { HelpItem } from "../help-enabler/HelpItem"; import { convertToName } from "./DynamicComponents"; import { KeyValueType } from "../key-value-form/key-value-convert"; type IdKeyValueType = KeyValueType & { id: number; }; const generateId = () => Math.floor(Math.random() * 100); export const MapComponent = ({ name, label, helpText }: ComponentProps) => { const { t } = useTranslation("dynamic"); const { getValues, setValue, register } = useFormContext(); const [map, setMap] = useState([]); const fieldName = convertToName(name!); useEffect(() => { register(fieldName); const values: KeyValueType[] = JSON.parse(getValues(fieldName) || "[]"); if (!values.length) { values.push({ key: "", value: "" }); } setMap(values.map((value) => ({ ...value, id: generateId() }))); }, [register, getValues]); const update = (val = map) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars setValue(fieldName, JSON.stringify(val.map(({ id, ...entry }) => entry))); }; const updateKey = (index: number, key: string) => { updateEntry(index, { ...map[index], key }); }; const updateValue = (index: number, value: string) => { updateEntry(index, { ...map[index], value }); }; const updateEntry = (index: number, entry: IdKeyValueType) => setMap([...map.slice(0, index), entry, ...map.slice(index + 1)]); const remove = (index: number) => { const value = [...map.slice(0, index), ...map.slice(index + 1)]; setMap(value); update(value); }; return ( } fieldId={name!} > {t("common:key")} {t("common:value")} {map.map((attribute, index) => ( updateKey(index, value)} onBlur={() => update()} /> updateValue(index, value)} onBlur={() => update()} /> ))} ); };