UNPKG

@navinc/base-react-components

Version:
64 lines 3.21 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { jsx as _jsx } from "react/jsx-runtime"; import { StringInput } from '../input/index.js'; import { useEffect, useRef, forwardRef } from 'react'; import { toUsdMoney, toNumber, dollarsToCents, centsToDollars } from '@navinc/utils'; import { useFormField } from '../use-form-field.js'; import { InputWrapper } from '../input-components/index.js'; import { styledBackwardsCompatibility } from '../../styled-backwards-compatibility.js'; const negativeNumberRegExp = /^(\$ )?0?-0?$/; const { abs, trunc } = Math; export const UsdInput = styledBackwardsCompatibility(forwardRef((_a, forwardedRef) => { var { className, allowNegatives = false, label, optional, helperText, name } = _a, props = __rest(_a, ["className", "allowNegatives", "label", "optional", "helperText", "name"]); const isNegativeRef = useRef(false); const { value: ogValue, error, onBlur, helpers } = useFormField(name); const { setValue } = helpers; const toNumberOrZero = (input) => { const number = toNumber(input) || 0; return trunc(allowNegatives ? number : abs(number)); }; useEffect(() => { // Ensure initial value stored in parent form is a number setValue(toNumberOrZero(ogValue), false); // eslint-disable-next-line react-hooks/exhaustive-deps -- only run on mount }, []); const value = allowNegatives && isNegativeRef.current && ogValue === 0 ? '$ -' : toUsdMoney(centsToDollars(ogValue)); const updateValue = (value) => { setValue(value); }; const onKeyUp = (e) => { // keyCode is deprecated but this is a fallback for older browsers const keyCode = e.keyCode; const code = e.code; const valAsNum = Number(ogValue); if (code === 'ArrowUp' || keyCode === 38) { const newVal = valAsNum + 100; updateValue(newVal); } if (code === 'ArrowDown' || keyCode === 40) { const newVal = valAsNum - 100; updateValue(newVal); } }; return (_jsx(InputWrapper, Object.assign({ className: className, label: label, optional: optional, errorText: error, helperText: helperText }, props, { children: _jsx(StringInput, { name: name, value: value, "$error": error, onChange: (e) => { const { target } = e; const { value } = target; isNegativeRef.current = negativeNumberRegExp.test(value); const newVal = dollarsToCents(toNumberOrZero(value)); updateValue(newVal); }, onBlur: (e) => { isNegativeRef.current = false; onBlur(e); }, onKeyUp: onKeyUp, ref: forwardedRef }) }))); })); //# sourceMappingURL=index.js.map