UNPKG

@keycloakify/keycloak-admin-ui

Version:
54 lines 2.98 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { Button, ButtonVariant, InputGroup, TextInput, InputGroupItem, } from "@patternfly/react-core"; import { MinusCircleIcon, PlusCircleIcon } from "@patternfly/react-icons"; import { Fragment, useEffect, useMemo } from "react"; import { useFormContext, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; function stringToMultiline(value) { return typeof value === "string" ? value.split("##") : [value || ""]; } function toStringValue(formValue) { return formValue.join("##"); } export const MultiLineInput = ({ name, addButtonLabel, isDisabled = false, defaultValue, stringify = false, id, ...rest }) => { const { t } = useTranslation(); const { register, setValue, control } = useFormContext(); const value = useWatch({ name, control, defaultValue: defaultValue || "", }); const fields = useMemo(() => { let values = stringify ? stringToMultiline(Array.isArray(value) && value.length === 1 ? value[0] : value) : Array.isArray(value) ? value : [value]; if (!Array.isArray(values) || values.length === 0) { values = (stringify ? stringToMultiline(defaultValue) : defaultValue) || [""]; } return values; }, [value]); const remove = (index) => { update([...fields.slice(0, index), ...fields.slice(index + 1)]); }; const append = () => { update([...fields, ""]); }; const updateValue = (index, value) => { update([...fields.slice(0, index), value, ...fields.slice(index + 1)]); }; const update = (values) => { const fieldValue = values.flatMap((field) => field); setValue(name, stringify ? toStringValue(fieldValue) : fieldValue, { shouldDirty: true, }); }; useEffect(() => { register(name); }, [register]); return (_jsx("div", { id: id, children: fields.map((value, index) => (_jsxs(Fragment, { children: [_jsxs(InputGroup, { children: [_jsx(InputGroupItem, { isFill: true, children: _jsx(TextInput, { "data-testid": name + index, onChange: (_event, value) => updateValue(index, value), name: `${name}.${index}.value`, value: value, isDisabled: isDisabled, ...rest }) }), _jsx(InputGroupItem, { children: _jsx(Button, { "data-testid": "remove" + index, variant: ButtonVariant.link, onClick: () => remove(index), tabIndex: -1, "aria-label": t("remove"), isDisabled: fields.length === 1 || isDisabled, children: _jsx(MinusCircleIcon, {}) }) })] }), index === fields.length - 1 && (_jsxs(Button, { variant: ButtonVariant.link, onClick: append, tabIndex: -1, "aria-label": t("add"), "data-testid": "addValue", isDisabled: !value || isDisabled, children: [_jsx(PlusCircleIcon, {}), " ", t(addButtonLabel || "add")] }))] }, index))) })); }; //# sourceMappingURL=MultiLineInput.js.map