styled-hook-form
Version:
React form library for styled-components based on grommet and react-hook-form
75 lines (74 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumericBox = exports.formatNumbericValue = exports.parseNumericValue = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const grommet_1 = require("grommet");
const context_1 = require("../../../context");
const locale_1 = require("../../utils/locale");
function parseNumericValue(value, fractionSep) {
return parseFloat(value.replace(fractionSep, "."));
}
exports.parseNumericValue = parseNumericValue;
function formatNumbericValue(value, fractionSep) {
if (!value) {
return "";
}
return value.toString().replace(".", fractionSep);
}
exports.formatNumbericValue = formatNumbericValue;
const NumericBox = (props) => {
const { onChange, value } = props;
const ref = react_1.useRef(null);
const [localValue, updateLocalValue] = react_1.useState(value);
const { locale } = context_1.useFormBuilderContext();
react_1.useEffect(() => {
if (value !== null && value !== undefined) {
updateLocalValue(value);
}
}, [value]);
const fractionSep = locale_1.getLocaleFractionSeparator(locale);
const validValueRef = react_1.useRef("");
const handleKeyup = react_1.useCallback(function (e) {
// eslint-disable-next-line no-eval
const numericRegex = eval(`/^\\-?\\d*\\${fractionSep}?\\d*$/g`);
const nextValue = e.target && e.target.value;
if (nextValue && nextValue !== "-" && !numericRegex.test(nextValue)) {
const validValue = validValueRef.current;
updateLocalValue(validValue);
onChange && onChange(validValue);
}
else {
validValueRef.current = nextValue;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fractionSep]);
const handleBlur = react_1.useCallback(() => {
if (ref.current) {
let value = ref.current.value;
if (value.endsWith(fractionSep)) {
onChange(value.slice(0, -1));
}
}
}, [fractionSep, onChange]);
react_1.useEffect(() => {
const box = ref.current;
if (box) {
box.addEventListener("keyup", handleKeyup, false);
box.addEventListener("blur", handleBlur, false);
}
return () => {
if (box) {
box.removeEventListener("keyup", handleKeyup, false);
box.removeEventListener("blur", handleBlur, false);
}
};
}, [handleBlur, handleKeyup, ref]);
const handleChange = (e) => {
const value = e.target.value;
updateLocalValue(value);
onChange && onChange(value);
};
return (jsx_runtime_1.jsx(grommet_1.TextInput, Object.assign({}, props, { onChange: handleChange, value: localValue, ref: ref }), void 0));
};
exports.NumericBox = NumericBox;