UNPKG

@wix/design-system

Version:

@wix/design-system

51 lines 2.19 kB
const isEmptyValue = (value) => value === null || value === undefined || value === ''; const isInvalidNumber = (value) => isEmptyValue(value) || !/[0-9]$/.test(String(value)); export const defaultValueToNullIfEmpty = (value, defaultValue) => { if (!isEmptyValue(value)) { return String(value); } return !isEmptyValue(defaultValue) ? Number(defaultValue) : ''; }; export const defaultValueToNullIfInvalidNumber = (value) => (isInvalidNumber(value) ? null : Number(value)); const normalizeStringValue = (value) => { const valueWithDotDecimalSeparator = value.replace(',', '.'); if (isInvalidNumber(valueWithDotDecimalSeparator)) { return valueWithDotDecimalSeparator; } // Preserve minus sign when typing '-00'. return valueWithDotDecimalSeparator.startsWith('-') ? valueWithDotDecimalSeparator.replace(/^-0+(?!\.|,|$)/, '-') : valueWithDotDecimalSeparator.replace(/^0+(?!\.|,|$)/, ''); }; export const normalizeValues = (value) => { const stringValue = normalizeStringValue(String(value)); const numberValue = stringValue === '' ? null : Number(stringValue); return { numberValue, stringValue, }; }; export const isInRange = ({ value, minValue, maxValue, }) => !(!Number.isNaN(minValue) && value < Number(minValue)) && !(!Number.isNaN(maxValue) && value > Number(maxValue)); export const validateValue = ({ value, minValue, maxValue, }) => { if (isEmptyValue(value)) { return { hasError: false }; } if (isInvalidNumber(value)) { return { hasError: true, validationType: 'formatError' }; } if (!isInRange({ value: Number(value), minValue, maxValue, })) { return { hasError: true, validationType: 'outOfBoundsError' }; } return { hasError: false }; }; export const getClosestValue = (currentValue, options, direction) => { const sortedOptions = [...options]; sortedOptions.sort((a, b) => (direction === 'up' ? a - b : b - a)); return (sortedOptions.find(v => direction === 'up' ? v > currentValue : v < currentValue) ?? sortedOptions[sortedOptions.length - 1]); }; //# sourceMappingURL=index.js.map