@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.
179 lines (178 loc) • 7.6 kB
JavaScript
"use client";
import { RHFMuiConfigContext } from "../../config/ConfigProvider.js";
import { keepLabelAboveFormField, mergeRefs } from "../../utils/control.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 { fieldNameToLabel } from "../../utils/text-transform.js";
import { useFieldIds } from "../../utils/useFieldIds.js";
import CountryMenuItem from "./CountryMenuItem.js";
import { countryList } from "./countries.js";
import { forwardRef, useContext, useMemo } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { Controller } from "react-hook-form";
import Box from "@mui/material/Box";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
//#region src/mui/country-select/index.tsx
const RHFCountrySelect = forwardRef(function RHFCountrySelect({ fieldName, control, registerOptions, countries, preferredCountries, valueKey, disabled: muiDisabled, autoHighlight = true, customOnChange, onValueChange, label, showLabelAboveFormField, formLabelProps, hideLabel, renderOptionLabel, required, helperText, errorMessage, hideErrorMessage, formHelperTextProps, multiple, textFieldProps, slotProps, ChipProps, onBlur: muiOnBlur, disableClearable, customIds, limitTags = 2, getLimitTagsText, getOptionKey, ...otherCountrySelectProps }, ref) {
const { fieldId, labelId, helperTextId, errorId } = useFieldIds(fieldName, customIds);
const { allLabelsAboveFields } = useContext(RHFMuiConfigContext);
const isLabelAboveFormField = keepLabelAboveFormField(showLabelAboveFormField, allLabelsAboveFields);
const defaultFieldLabel = fieldNameToLabel(fieldName);
const fieldLabel = label ?? defaultFieldLabel;
const accessibleFieldLabel = typeof fieldLabel === "string" ? fieldLabel : defaultFieldLabel;
const countryOptions = countries ?? countryList;
const countrySelectOptions = useMemo(() => {
let countriesToList = countryOptions;
let countriesToListAtTop = [];
if (preferredCountries?.length) {
countriesToListAtTop = countryOptions.filter((country) => preferredCountries.includes(country.iso));
countriesToListAtTop.sort((a, b) => preferredCountries.indexOf(a.iso) - preferredCountries.indexOf(b.iso));
countriesToList = countryOptions.filter((country) => !preferredCountries.includes(country.iso));
}
return [...countriesToListAtTop, ...countriesToList];
}, [countryOptions, preferredCountries]);
const countryMap = useMemo(() => {
if (!valueKey) return null;
const map = /* @__PURE__ */ new Map();
countrySelectOptions.forEach((country) => {
map.set(country[valueKey], country);
});
return map;
}, [countrySelectOptions, valueKey]);
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 isDisabled = muiDisabled || rhfDisabled;
const fieldErrorMessage = fieldStateError?.message?.toString() ?? errorMessage;
const isError = !!fieldErrorMessage;
const showHelperTextElement = !!(helperText || isError && !hideErrorMessage);
const fieldValue = rhfValue;
const selectedCountries = multiple ? Array.isArray(fieldValue) ? valueKey && countryMap ? fieldValue.map((val) => countryMap.get(val)).filter((country) => !!country) : fieldValue : [] : valueKey && countryMap ? countryMap.get(fieldValue) ?? null : fieldValue ?? null;
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
}
}),
/* @__PURE__ */ jsx(Autocomplete, {
...otherCountrySelectProps,
id: fieldId,
options: countrySelectOptions,
multiple,
freeSolo: false,
value: selectedCountries,
disabled: isDisabled,
onChange: (event, newValue, reason, details) => {
const storedValue = multiple ? Array.isArray(newValue) ? valueKey ? newValue.map((item) => item[valueKey]) : newValue : [] : !Array.isArray(newValue) && newValue !== null ? valueKey ? newValue[valueKey] : newValue : null;
if (customOnChange) {
customOnChange({
rhfOnChange,
newValue: storedValue,
event,
reason,
details
});
return;
}
rhfOnChange(storedValue);
onValueChange?.({
newValue: storedValue,
event,
reason,
details
});
},
onBlur: (blurEvent) => {
rhfOnBlur();
muiOnBlur?.(blurEvent);
},
autoHighlight,
blurOnSelect: !multiple,
disableCloseOnSelect: multiple,
disableClearable,
fullWidth: true,
limitTags,
getLimitTagsText: (more) => getLimitTagsText?.(more) ?? (more === 1 ? "+1 Country" : `+${more} Countries`),
getOptionKey: getOptionKey ?? ((option) => String(valueKey ? option[valueKey] : option.iso)),
getOptionLabel: (option) => option.name,
isOptionEqualToValue: (option, value) => valueKey ? option[valueKey] === value[valueKey] : option.iso === value.iso,
renderInput: (params) => {
const { InputProps, inputProps, disabled: paramsDisabled, ...otherInputParams } = params ?? {};
const { autoComplete = "off", ...otherTextFieldProps } = textFieldProps ?? {};
const textFieldInputProps = {
...inputProps,
"aria-required": required,
"aria-invalid": isError,
"aria-labelledby": !hideLabel && isLabelAboveFormField ? labelId : void 0,
"aria-label": hideLabel ? accessibleFieldLabel : void 0,
"aria-describedby": showHelperTextElement ? isError ? errorId : helperTextId : void 0,
autoComplete
};
return /* @__PURE__ */ jsx(TextField, {
name: rhfFieldName,
inputRef: mergeRefs(rhfRef, ref),
disabled: paramsDisabled,
...otherTextFieldProps,
...otherInputParams,
label: !isLabelAboveFormField ? /* @__PURE__ */ jsx(FormLabelText, {
label: fieldLabel,
required
}) : void 0,
error: isError,
slotProps: {
...textFieldProps?.slotProps,
input: {
...InputProps,
...textFieldProps?.slotProps?.input
},
htmlInput: textFieldInputProps
}
});
},
renderOption: ({ key, ...optionProps }, option) => /* @__PURE__ */ jsx(Box, {
component: "li",
sx: {
display: "flex",
alignItems: "center"
},
...optionProps,
children: renderOptionLabel?.(option) ?? /* @__PURE__ */ jsx(CountryMenuItem, { countryInfo: option })
}, key),
slotProps: {
...slotProps,
chip: ChipProps
}
}),
/* @__PURE__ */ jsx(FormHelperText, {
error: isError,
errorMessage: fieldErrorMessage,
hideErrorMessage,
helperText,
showHelperTextElement,
formHelperTextProps: {
...formHelperTextProps,
id: isError ? errorId : helperTextId
}
})
]
});
}
});
});
//#endregion
export { countryList, RHFCountrySelect as default };