@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.
241 lines (240 loc) • 10.3 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, sanitizePastedNumber } from "../../utils/text-transform.js";
import { useFieldIds } from "../../utils/useFieldIds.js";
import { forwardRef, useCallback, useContext, useMemo } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { Controller } from "react-hook-form";
import TextField from "@mui/material/TextField";
//#region src/mui/number-input/index.tsx
function setInputValueAndNotify(input, value) {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
function getSteppedInputValue(input, step, direction, nonNegative) {
const currentValue = Number(input.value);
const nextValue = (Number.isNaN(currentValue) ? 0 : currentValue) + step * direction;
return String(nonNegative ? Math.max(0, nextValue) : nextValue);
}
function isNativeNumberMarkerClick(input, event) {
const rect = input.getBoundingClientRect();
const markerWidth = Math.min(24, rect.width);
return event.clientX >= rect.right - markerWidth;
}
/**
* Builds a pattern for in-progress typing: optional leading `-` when
* `nonNegative` is false; digits; optional decimal with length limit.
* @param nonNegative - When `true`, only non-negative values (including 0) match
* while typing. When `false` or omitted, `-` and negative numbers are allowed.
* @param maxDecimalPlaces - The maximum number of decimal places allowed.
* @returns A RegExp pattern for in-progress typing.
*/
function buildNumberInputDecimalPattern(nonNegative, onlyIntegers, maxDecimalPlaces) {
const sign = nonNegative ? "" : "-?";
if (onlyIntegers) return new RegExp(`^${sign}\\d+$`);
if (maxDecimalPlaces !== void 0) return new RegExp(`^${sign}\\d*(\\.\\d{0,${Math.max(0, Math.floor(maxDecimalPlaces))}})?$`);
return new RegExp(`^${sign}\\d*(\\.\\d*)?$`);
}
const RHFNumberInput = forwardRef(function RHFNumberInput({ fieldName, control, registerOptions, customOnChange, onValueChange, disabled: muiDisabled, label, showLabelAboveFormField, formLabelProps, hideLabel, showMarkers, onlyIntegers = false, nonNegative = false, maxDecimalPlaces, stepAmount = 1, required, helperText, errorMessage, hideErrorMessage, formHelperTextProps, sx: muiSx, onBlur: muiOnBlur, autoComplete = "off", slotProps: muiSlotProps, customIds, onKeyDown, onMouseDown, onPaste, ...otherNumberInputProps }, 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 decimalPattern = useMemo(() => buildNumberInputDecimalPattern(nonNegative, onlyIntegers, maxDecimalPlaces), [
nonNegative,
onlyIntegers,
maxDecimalPlaces
]);
const resolvedStepAmount = onlyIntegers ? Math.max(1, Math.floor(stepAmount)) : stepAmount;
const handleMouseDown = useCallback((e) => {
const input = e.target instanceof HTMLInputElement ? e.target : null;
if (showMarkers && input && isNativeNumberMarkerClick(input, e)) {
const rect = input.getBoundingClientRect();
e.preventDefault();
input.focus();
setInputValueAndNotify(input, getSteppedInputValue(input, resolvedStepAmount, e.clientY < rect.top + rect.height / 2 ? 1 : -1, nonNegative));
}
onMouseDown?.(e);
}, [
nonNegative,
onMouseDown,
resolvedStepAmount,
showMarkers
]);
if (onlyIntegers && maxDecimalPlaces !== void 0) console.warn("RHFNumberInput: \"onlyIntegers\" and \"maxDecimalPlaces\" props cannot be used together");
const handleKeyDown = useCallback((e) => {
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
const input = e.target instanceof HTMLInputElement ? e.target : null;
if (input) {
e.preventDefault();
setInputValueAndNotify(input, getSteppedInputValue(input, resolvedStepAmount, e.key === "ArrowUp" ? 1 : -1, nonNegative));
}
}
if (onlyIntegers && (e.key === "." || e.code === "Period" || e.code === "NumpadDecimal")) e.preventDefault();
if (e.key === "e" || e.key === "E" || e.key === "+") e.preventDefault();
if (nonNegative) {
if (e.key === "-" || e.key === "Subtract" || e.code === "Minus" || e.code === "NumpadSubtract") e.preventDefault();
}
if (e.key === "-" || e.code === "Minus" || e.code === "NumpadSubtract") {
/**
* Allow only one leading minus.
* Note: selectionStart is always null for type="number" (MDN spec),
* so cursor-position checks are unavailable. We use two proxy checks:
* • input.value !== '' → a valid numeric value already occupies
* the field; a minus at any position would be invalid
* • input.validity.badInput → the field is in a partial/invalid
* in-progress state (e.g. user has only typed "-"); a second
* minus would produce "--" or "-23-"
*/
const input = e.target;
if (input.value !== "" || input.validity.badInput) e.preventDefault();
}
onKeyDown?.(e);
}, [
nonNegative,
onlyIntegers,
onKeyDown,
resolvedStepAmount
]);
const handlePaste = useCallback((e) => {
const paste = e.clipboardData.getData("text").trim();
if (paste !== "" && !decimalPattern.test(paste)) {
e.preventDefault();
const sanitized = sanitizePastedNumber(paste, nonNegative, onlyIntegers, maxDecimalPlaces);
if (sanitized !== null) {
const input = e.target instanceof HTMLInputElement ? e.target : null;
if (input) setInputValueAndNotify(input, sanitized);
}
}
onPaste?.(e);
}, [
decimalPattern,
maxDecimalPlaces,
nonNegative,
onlyIntegers,
onPaste
]);
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);
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(TextField, {
...otherNumberInputProps,
id: fieldId,
name: rhfFieldName,
type: "number",
inputRef: mergeRefs(rhfRef, ref),
autoComplete,
label: !hideLabel && !isLabelAboveFormField ? /* @__PURE__ */ jsx(FormLabelText, {
label: fieldLabel,
required
}) : void 0,
value: rhfValue === null || rhfValue === void 0 || Number.isNaN(rhfValue) ? "" : rhfValue,
disabled: isDisabled,
onChange: (event) => {
const changeEvent = event;
const { value: inputValue, validity } = changeEvent.target;
/**
* type="number" reports value="" for ANY invalid input
* (e.g. "2.3.4", "-23-", partial states). validity.badInput
* is the only reliable way to tell "user typed something wrong"
* apart from "user intentionally cleared the field" (MDN).
* Returning early protects form state from being wiped to null
* when the browser silently discards an invalid intermediate value.
*/
if (validity.badInput) return;
const safeInputValue = inputValue === "" || decimalPattern.test(inputValue) ? inputValue : sanitizePastedNumber(inputValue, nonNegative, onlyIntegers, maxDecimalPlaces);
if (safeInputValue !== null && (safeInputValue === "" || decimalPattern.test(safeInputValue))) {
const parsed = safeInputValue === "" ? null : onlyIntegers ? parseInt(safeInputValue, 10) : Number(safeInputValue);
const safeValue = Number.isNaN(parsed) ? null : parsed;
if (customOnChange) {
customOnChange({
rhfOnChange,
newValue: safeValue,
event: changeEvent
});
return;
}
rhfOnChange(safeValue);
onValueChange?.({
newValue: safeValue,
event: changeEvent
});
}
},
onBlur: (blurEvent) => {
rhfOnBlur();
muiOnBlur?.(blurEvent);
},
onKeyDown: handleKeyDown,
onMouseDown: handleMouseDown,
onPaste: handlePaste,
slotProps: {
...muiSlotProps,
htmlInput: {
...muiSlotProps?.htmlInput,
"aria-labelledby": !hideLabel && isLabelAboveFormField ? labelId : void 0,
"aria-label": hideLabel ? accessibleFieldLabel : void 0,
"aria-describedby": showHelperTextElement ? isError ? errorId : helperTextId : void 0,
"aria-required": required,
...nonNegative ? { min: 0 } : {},
step: resolvedStepAmount
}
},
error: isError,
sx: {
...muiSx,
...!showMarkers && { "& input[type=number]": {
MozAppearance: "textfield",
"&::-webkit-outer-spin-button": { display: "none" },
"&::-webkit-inner-spin-button": { display: "none" }
} }
},
multiline: false
}),
/* @__PURE__ */ jsx(FormHelperText, {
error: isError,
errorMessage: fieldErrorMessage,
hideErrorMessage,
helperText,
showHelperTextElement,
formHelperTextProps: {
...formHelperTextProps,
id: isError ? errorId : helperTextId
}
})
]
});
}
});
});
//#endregion
export { RHFNumberInput as default };