|
| 1 | +// @flow |
| 2 | + |
| 3 | +import * as React from 'react' |
| 4 | + |
| 5 | +type NumberNormalizer = (value: ?(string | number)) => ?(string | number) |
| 6 | +type Validator = (value: any, allValues: Object, props: Object) => ?any |
| 7 | +const WHITESPACE = /^\s*$/ |
| 8 | + |
| 9 | +function createNumericField<P: {validate?: Validator | Array<Validator>, normalizeOnBlur?: Function}>( |
| 10 | + Field: React.ComponentType<P> |
| 11 | +): React.ComponentType<P & {normalizeNumber?: NumberNormalizer}> { |
| 12 | + type Props = React.ElementProps<typeof Field> & {normalizeNumber?: NumberNormalizer} |
| 13 | + |
| 14 | + function defaultNormalize(value: ?(string | number)): ?(string | number) { |
| 15 | + if (value == null || typeof value === 'number' || WHITESPACE.test(value)) { |
| 16 | + return typeof value === 'string' ? value.trim() : value |
| 17 | + } |
| 18 | + const parsed = Number(value) |
| 19 | + return Number.isFinite(parsed) ? parsed : value.trim() |
| 20 | + } |
| 21 | + |
| 22 | + return class NumericField extends React.Component<Props> { |
| 23 | + normalizeOnBlur = (value: any): any => { |
| 24 | + const {normalizeOnBlur} = this.props |
| 25 | + const normalizeNumber = this.props.normalizeNumber || defaultNormalize |
| 26 | + const result = normalizeNumber(value) |
| 27 | + return normalizeOnBlur ? normalizeOnBlur(result) : result |
| 28 | + } |
| 29 | + |
| 30 | + validate = (value: any, allValues: Object, props: Object): ?string => { |
| 31 | + const normalizeNumber = this.props.normalizeNumber || defaultNormalize |
| 32 | + const normalized = normalizeNumber(value) |
| 33 | + if (typeof normalized === 'string') { |
| 34 | + if (WHITESPACE.test(normalized)) return |
| 35 | + return 'must be a number' |
| 36 | + } |
| 37 | + const {validate} = this.props |
| 38 | + if (Array.isArray(validate)) { |
| 39 | + for (let validator of validate) { |
| 40 | + const result = validator(normalized, allValues, props) |
| 41 | + if (result) return result |
| 42 | + } |
| 43 | + } else if (validate) { |
| 44 | + return validate(normalized, allValues, props) |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + render(): React.Node { |
| 49 | + const { |
| 50 | + normalizeNumber, // eslint-disable-line no-unused-vars |
| 51 | + ...props |
| 52 | + } = this.props |
| 53 | + return ( |
| 54 | + <Field |
| 55 | + {...props} |
| 56 | + validate={this.validate} |
| 57 | + normalizeOnBlur={this.normalizeOnBlur} |
| 58 | + /> |
| 59 | + ) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +module.exports = createNumericField |
0 commit comments