UNPKG

wix-style-react

Version:
68 lines 2.91 kB
import isValidDate from 'date-fns/isValid'; import isBefore from 'date-fns/isBefore'; import parse from 'date-fns/parse'; import { fullDateFormats, longDateFormats, mediumDateFormats, shortDateFormats, } from './constants'; import { MAX_DATE, MIN_DATE, SHORT_SEPARATORS_REGEX } from '../constants'; export function isValid(date, minDate, maxDate) { minDate = minDate ?? MIN_DATE; maxDate = maxDate ?? MAX_DATE; return (isValidDate(date) && !isBefore(date, minDate) && isBefore(date, maxDate)); } export function isInvalidValue(value) { return value === '0'; } function getDateFormat(dateStyle, locale, isOtherFormat) { if ((dateStyle === 'short' && isOtherFormat) || (dateStyle === 'medium' && !isOtherFormat)) { return mediumDateFormats[locale]; } return shortDateFormats[locale]; } function parseLongerFormats(value, format, locale) { let parsedDate = parse(value, format, Date.now()); if (!isValid(parsedDate)) { parsedDate = parse(value, longDateFormats[locale], Date.now()); } if (!isValid(parsedDate)) { parsedDate = parse(value, fullDateFormats[locale], Date.now()); } return parsedDate; } function parseShortFormat(value, format) { if (!SHORT_SEPARATORS_REGEX.test(value)) { return null; } const invalidSeparator = value.match(/\W/)[0]; const validSeparator = format.match(/\W/)[0]; const newValue = value.split(invalidSeparator).join(validSeparator); return parse(newValue, format, Date.now()); } export function parseStrictInputValue(value, dateStyle, locale) { const dateFormat = getDateFormat(dateStyle, locale); const otherDateFormat = getDateFormat(dateStyle, locale, true); let parsedDate = parseShortFormat(value, dateStyle === 'short' ? dateFormat : otherDateFormat); if (!isValid(parsedDate)) { parsedDate = parseLongerFormats(value, dateStyle === 'short' ? otherDateFormat : dateFormat, locale); } return isValid(parsedDate) ? { parsedDate, dateFormat } : { dateFormat }; } export function parseDate(value, dateStyle, locale) { if (isInvalidValue(value)) { return null; } const dateFormat = getDateFormat(dateStyle, locale); const slicedDateFormat = dateFormat.slice(0, value.length); const otherDateFormat = getDateFormat(dateStyle, locale, true).slice(0, value.length); let parsedDate = parse(value, dateFormat, Date.now()); if (!isValid(parsedDate)) { parsedDate = parse(value, slicedDateFormat, Date.now()); } if (!isValid(parsedDate)) { parsedDate = parseShortFormat(value, dateStyle === 'short' ? slicedDateFormat : otherDateFormat); } if (!isValid(parsedDate)) { parsedDate = parseLongerFormats(value, dateStyle === 'short' ? otherDateFormat : slicedDateFormat, locale); } return isValid(parsedDate) ? parsedDate : null; } //# sourceMappingURL=utils.js.map