UNPKG

styled-hook-form

Version:

React form library for styled-components based on grommet and react-hook-form

52 lines (51 loc) 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NumericEditor = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const react_hook_form_1 = require("react-hook-form"); const extension_1 = require("../../../../components/extension"); const context_1 = require("../../../../context"); const numeric_box_1 = require("../../../extension/numeric-box/numeric-box"); const locale_1 = require("../../../utils/locale"); const endsWithFractionZero = (rawValue, fractionSep) => // eslint-disable-next-line no-eval eval(`/.*${fractionSep}0+$/g`).test(rawValue); const NumericEditor = react_1.forwardRef((props, ref) => { let vrules = props.validationRules || {}; const { translate: T, locale } = context_1.useFormBuilderContext(); let { name, label, defaultValue: initialValue, shouldUnregister, min, max, required, methods, inputProps, } = props; let control = methods === null || methods === void 0 ? void 0 : methods.control; if (required) { vrules.required = { value: required, message: T("required-msg", { name: label }), }; } if (min) { vrules.min = { value: min, message: T("numeric-input-min-msg", { name: label, value: min }), }; } if (max) { vrules.max = { value: max, message: T("numeric-input-max-msg", { name: label, value: max }), }; } const fractionSep = locale_1.getLocaleFractionSeparator(locale); return (jsx_runtime_1.jsx(react_hook_form_1.Controller, { name: name, defaultValue: initialValue, shouldUnregister: shouldUnregister, rules: vrules, control: control, render: ({ field }) => { return (jsx_runtime_1.jsx(extension_1.NumericBox, Object.assign({}, inputProps, { ref: ref, onChange: (rawValue) => { var transformedValue = rawValue ? rawValue.endsWith(fractionSep) || rawValue === "-" || endsWithFractionZero(rawValue, fractionSep) ? rawValue : numeric_box_1.parseNumericValue(rawValue, fractionSep) : ""; field.onChange(isNaN(transformedValue) ? null : transformedValue); }, value: numeric_box_1.formatNumbericValue(field.value, fractionSep) }), void 0)); } }, void 0)); }); exports.NumericEditor = NumericEditor;