UNPKG

@baseplate-dev/ui-components

Version:

Shared UI component library

44 lines 2.82 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { notEmpty } from '@baseplate-dev/utils'; import { useControllerMerged } from '#src/hooks/use-controller-merged.js'; import { cn } from '#src/utils/cn.js'; import { genericForwardRef } from '#src/utils/generic-forward-ref.js'; import { FormDescription, FormItem, FormLabel, FormMessage, } from '../form-item/form-item.js'; import { SwitchField } from '../switch-field/switch-field.js'; /** * Field with label and error states that wraps multiple SwitchField components. */ const MultiSwitchFieldRoot = genericForwardRef(function MultiSwitchField({ label, description, error, value, options, onChange, getOptionLabel = (val) => val.label, getOptionValue = (val) => val.value, className, disabled, }, ref) { const selectedOptions = value ?.map((val) => options.find((option) => getOptionValue(option) === val)) .filter(notEmpty); const selectedValues = selectedOptions?.map((option) => ({ label: getOptionLabel(option), value: getOptionValue(option), })); return (_jsxs(FormItem, { error: error, className: cn('space-y-3', className), children: [_jsx(FormLabel, { children: label }), _jsx("div", { className: "flex flex-wrap gap-4", ref: ref, children: options.map((option) => { const optionValue = getOptionValue(option); const optionLabel = getOptionLabel(option); const checked = selectedValues?.some((selectedValue) => selectedValue.value === optionValue); return (_jsx(SwitchField, { value: checked, label: optionLabel, disabled: disabled, onChange: (isChecked) => { if (isChecked) { onChange?.(options .map(getOptionValue) .filter((val) => (val === optionValue || value?.includes(val)) ?? false)); } else { onChange?.(value?.filter((val) => val !== optionValue) ?? []); } } }, optionValue)); }) }), _jsx(FormDescription, { children: description }), _jsx(FormMessage, {})] })); }); const MultiSwitchFieldController = genericForwardRef(function MultiSwitchFieldController({ name, control, ...rest }, ref) { const { field, fieldState: { error }, } = useControllerMerged({ name, control }, rest, ref); const restProps = rest; return (_jsx(MultiSwitchFieldRoot, { error: error?.message, ...restProps, ...field })); }); export const MultiSwitchField = Object.assign(MultiSwitchFieldRoot, { Controller: MultiSwitchFieldController, }); //# sourceMappingURL=multi-switch-field.js.map