import React, { useCallback } from "react"; import { EnumType, FieldProps, ResolvedProperty } from "../../types"; import { FieldHelperText, LabelWithIcon } from "../components"; import { EnumValuesChip } from "../../preview"; import { enumToObjectEntries, getIconForProperty, getLabelOrConfigFrom } from "../../util"; import { CloseIcon, MultiSelect, MultiSelectItem } from "@firecms/ui"; import { useClearRestoreValue } from "../useClearRestoreValue"; /** * This fields renders a dropdown with multiple selection. * * This is one of the internal components that get mapped natively inside forms * and tables to the specified properties. * @group Form fields */ export function MultiSelectBinding({ propertyKey, value, setValue, error, showError, disabled, property, includeDescription, autoFocus }: FieldProps) { const of: ResolvedProperty | ResolvedProperty[] = property.of; if (!of) { throw Error("Using wrong component ArrayEnumSelect"); } if (Array.isArray(of)) { throw Error("Using array properties instead of single one in `of` in ArrayProperty"); } if (of.dataType !== "string" && of.dataType !== "number") { throw Error("Field misconfiguration: array field of type string or number"); } const enumValues = enumToObjectEntries(of.enumValues); if (!enumValues) { console.error(property); throw Error("Field misconfiguration: array field of type string or number needs to have enumValues"); } useClearRestoreValue({ property, value, setValue }); const validValue = !!value && Array.isArray(value); const renderValue = useCallback((enumKey: string, list: boolean) => { const enumValue = enumKey !== undefined ? getLabelOrConfigFrom(enumValues, enumKey) : undefined; return {enumValue?.label ?? enumKey} {!list && } ; }, [enumValues, setValue, value]); return (
v.toString()) : []} disabled={disabled} label={} renderValue={useCallback((v: string) => renderValue(v, false), [renderValue])} onMultiValueChange={(updatedValue: string[]) => { let newValue: EnumType[] | null; if (of && (of as ResolvedProperty)?.dataType === "number") { newValue = updatedValue ? (updatedValue as string[]).map((e) => parseFloat(e)) : []; } else { newValue = updatedValue; } return setValue(newValue); }}> {enumValues.map((enumValue) => String(enumValue.id)).map((enumKey) => ( {renderValue(enumKey, true)} ))}
); }