UNPKG

@nish1896/rhf-mui-components

Version:

A suite of 20+ production-ready react-hook-form components built with material-ui. Fully typed, tree-shakable, and optimized for enterprise-grade forms.

45 lines (44 loc) 1.91 kB
//#region src/utils/object.ts function isKeyValueOption(option, labelKey, valueKey) { if (typeof option !== "object" || option === null || !labelKey || !valueKey) return false; const obj = option; return typeof obj[labelKey] === "string" && (typeof obj[valueKey] === "string" || typeof obj[valueKey] === "number"); } /** * Utility to cast string values from form element onChange event to either * string or number based on the typeof item of its options prop. */ function coerceValue(raw, example) { return typeof example === "number" ? Number(raw) : raw; } /** * Get the value of an option based on the valueKey. If valueKey is not provided, * return the option itself. */ function getOptionValue(option, valueKey) { if (valueKey && typeof option === "object" && option !== null) return option[valueKey]; return option; } /** * Normalize the raw value(s) from select input to match the type of option values. */ function normalizeSelectValue(raw, options, labelKey, valueKey) { const normalizeOne = (val) => { const match = options.find((op) => isKeyValueOption(op, labelKey, valueKey) ? String(op[valueKey]) === val : String(op) === val); if (!match) return val; if (isKeyValueOption(match, labelKey, valueKey)) return match[valueKey]; return match; }; return Array.isArray(raw) ? raw.map(normalizeOne) : normalizeOne(raw); } function getDisplayLabelForSelectValue(rawValue, options, labelKey, valueKey) { const match = options.find((op) => isKeyValueOption(op, labelKey, valueKey) ? op[valueKey] === rawValue : op === rawValue); if (match === void 0) { if (rawValue === null || rawValue === void 0 || rawValue === "") return ""; return String(rawValue); } if (isKeyValueOption(match, labelKey, valueKey)) return match[labelKey]; return String(match); } //#endregion export { coerceValue, getDisplayLabelForSelectValue, getOptionValue, isKeyValueOption, normalizeSelectValue };