@nish1896/rhf-mui-components
Version:
A suite of 25+ production-ready react-hook-form components built with material-ui. Fully typed, tree-shakable, and optimized for enterprise-grade forms.
162 lines (161 loc) • 7.01 kB
JavaScript
"use client";
import { RHFMuiConfigContext } from "../../config/ConfigProvider.js";
import { keepLabelAboveFormField, mergeRefs } from "../../utils/control.js";
import { generateLargeOptionsErrMsg } from "../../utils/errors.js";
import FormControl from "../../common/FormControl.js";
import FormHelperText from "../../common/FormHelperText.js";
import FormLabel from "../../common/FormLabel.js";
import FormLabelText from "../../common/FormLabelText.js";
import { getDisplayLabelForSelectValue, getOptionValue, isKeyValueOption, normalizeSelectValue } from "../../utils/object.js";
import { fieldNameToLabel } from "../../utils/text-transform.js";
import { useFieldIds } from "../../utils/useFieldIds.js";
import { Fragment, forwardRef, useContext } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { Controller } from "react-hook-form";
import MenuItem from "@mui/material/MenuItem";
import InputLabel from "@mui/material/InputLabel";
import MuiSelect from "@mui/material/Select";
//#region src/mui/select/index.tsx
const componentName = "RHFSelect";
const RHFSelect = forwardRef(function RHFSelect({ fieldName, control, registerOptions, options, labelKey, valueKey, renderOptionLabel, getOptionDisabled, multiple, showDefaultOption, defaultOptionText, customOnChange, onValueChange, disabled: muiDisabled, label, showLabelAboveFormField, formLabelProps, hideLabel, required, helperText, errorMessage, hideErrorMessage, formHelperTextProps, onBlur, autoComplete = "off", renderValue, placeholder, customIds, inputProps: muiSelectInputProps, ...otherSelectProps }, ref) {
const { allLabelsAboveFields } = useContext(RHFMuiConfigContext);
if (options.length > 40) console.warn(generateLargeOptionsErrMsg(componentName, options.length));
const { fieldId, labelId, helperTextId, errorId } = useFieldIds(fieldName, customIds);
const isLabelAboveFormField = keepLabelAboveFormField(showLabelAboveFormField, allLabelsAboveFields);
const defaultFieldLabel = fieldNameToLabel(fieldName);
const fieldLabelText = fieldNameToLabel(fieldName);
const fieldLabel = label ?? defaultFieldLabel;
const accessibleFieldLabel = typeof fieldLabel === "string" ? fieldLabel : defaultFieldLabel;
const SelectFormLabel = /* @__PURE__ */ jsx(FormLabelText, {
label: fieldLabel,
required
});
return /* @__PURE__ */ jsx(Controller, {
name: fieldName,
control,
rules: registerOptions,
render: ({ field: { name: rhfFieldName, value: rhfValue, onChange: rhfOnChange, onBlur: rhfOnBlur, ref: rhfRef, disabled: rhfDisabled }, fieldState: { error: fieldStateError } }) => {
const isValueEmpty = rhfValue === void 0 || rhfValue === null || rhfValue === "" || multiple && Array.isArray(rhfValue) && !rhfValue.length;
const showPlaceholder = isValueEmpty && !!placeholder;
const selectLabelValue = hideLabel || isLabelAboveFormField || showPlaceholder || isValueEmpty ? void 0 : SelectFormLabel;
const selectLabelId = isLabelAboveFormField || hideLabel ? void 0 : labelId;
const isDisabled = muiDisabled || rhfDisabled;
const fieldErrorMessage = fieldStateError?.message?.toString() ?? errorMessage;
const isError = !!fieldErrorMessage;
const showHelperTextElement = !!(helperText || isError && !hideErrorMessage);
return /* @__PURE__ */ jsxs(FormControl, {
error: isError,
disabled: isDisabled,
children: [
!hideLabel && /* @__PURE__ */ jsx(FormLabel, {
label: fieldLabel,
isVisible: isLabelAboveFormField,
required,
error: isError,
disabled: isDisabled,
formLabelProps: {
...formLabelProps,
id: labelId,
htmlFor: fieldId
}
}),
!hideLabel && !isLabelAboveFormField && !showPlaceholder && /* @__PURE__ */ jsx(InputLabel, {
id: labelId,
htmlFor: fieldId,
shrink: !isValueEmpty,
disabled: isDisabled,
children: SelectFormLabel
}),
/* @__PURE__ */ jsxs(MuiSelect, {
...otherSelectProps,
inputProps: {
...muiSelectInputProps,
id: fieldId
},
name: rhfFieldName,
autoComplete,
inputRef: mergeRefs(rhfRef, ref),
labelId: selectLabelId,
"aria-required": required,
"aria-invalid": isError,
"aria-describedby": showHelperTextElement ? isError ? errorId : helperTextId : void 0,
"aria-label": hideLabel ? accessibleFieldLabel : void 0,
label: selectLabelValue,
value: rhfValue ?? (multiple ? [] : ""),
error: isError,
multiple,
displayEmpty: isValueEmpty,
disabled: isDisabled,
onChange: (event, child) => {
const selectEvent = event;
const selectedValue = selectEvent.target.value;
const normalizedValue = normalizeSelectValue(selectedValue, options, labelKey, valueKey);
if (customOnChange) {
customOnChange({
rhfOnChange,
newValue: normalizedValue,
event: selectEvent,
child
});
return;
}
rhfOnChange(normalizedValue);
onValueChange?.({
newValue: normalizedValue,
event: selectEvent,
child
});
},
onBlur: (blurEvent) => {
rhfOnBlur();
onBlur?.(blurEvent);
},
renderValue: (value) => {
if (showPlaceholder) return /* @__PURE__ */ jsx("span", {
"aria-hidden": "true",
style: {
opacity: .6,
color: "inherit"
},
children: placeholder
});
if (Array.isArray(value)) {
const labels = value.map((val) => getDisplayLabelForSelectValue(val, options, labelKey, valueKey)).filter((node) => node !== "" && node !== null && node !== void 0);
return /* @__PURE__ */ jsx(Fragment, { children: renderValue?.(value) ?? labels.join(", ") });
}
const optionLabel = getDisplayLabelForSelectValue(value, options, labelKey, valueKey);
return /* @__PURE__ */ jsx(Fragment, { children: renderValue?.(value) ?? optionLabel });
},
children: [showDefaultOption && /* @__PURE__ */ jsx(MenuItem, {
value: "",
disabled: required,
children: defaultOptionText ?? `Select ${fieldLabelText}`
}), options.map((option, index) => {
const isObject = isKeyValueOption(option, labelKey, valueKey);
const opnValue = getOptionValue(option, valueKey);
const opnLabel = isObject ? String(option[labelKey]) : String(option);
return /* @__PURE__ */ jsx(MenuItem, {
value: opnValue,
disabled: getOptionDisabled?.(option) ?? false,
children: renderOptionLabel?.(option) ?? opnLabel
}, `${opnValue}-${index}`);
})]
}),
/* @__PURE__ */ jsx(FormHelperText, {
error: isError,
errorMessage: fieldErrorMessage,
hideErrorMessage,
helperText,
showHelperTextElement,
formHelperTextProps: {
...formHelperTextProps,
id: isError ? errorId : helperTextId
}
})
]
});
}
});
});
//#endregion
export { RHFSelect as default };