UNPKG

@root-systems/redux-form-validators

Version:
1,505 lines (1,160 loc) 207 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReduxFormValidators"] = factory(require("react")); else root["ReduxFormValidators"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_ALLOW_BLANK = exports.REG_URL = exports.url = exports.required = exports.presence = exports.numericality = exports.length = exports.inclusion = exports.format = exports.exclusion = exports.REG_EMAIL = exports.email = exports.formatDate = exports.parseDate = exports.date = exports.confirmation = exports.addValidator = exports.acceptance = exports.absence = undefined; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _absence = __webpack_require__(13); var _absence2 = _interopRequireDefault(_absence); var _acceptance = __webpack_require__(14); var _acceptance2 = _interopRequireDefault(_acceptance); var _addValidator = __webpack_require__(15); var _addValidator2 = _interopRequireDefault(_addValidator); var _confirmation = __webpack_require__(16); var _confirmation2 = _interopRequireDefault(_confirmation); var _date = __webpack_require__(17); var _date2 = _interopRequireDefault(_date); var _email = __webpack_require__(18); var _email2 = _interopRequireDefault(_email); var _format = __webpack_require__(5); var _format2 = _interopRequireDefault(_format); var _inclusion = __webpack_require__(9); var _inclusion2 = _interopRequireDefault(_inclusion); var _exclusion = __webpack_require__(19); var _exclusion2 = _interopRequireDefault(_exclusion); var _length = __webpack_require__(20); var _length2 = _interopRequireDefault(_length); var _numericality = __webpack_require__(21); var _numericality2 = _interopRequireDefault(_numericality); var _presence = __webpack_require__(22); var _presence2 = _interopRequireDefault(_presence); var _url = __webpack_require__(23); var _url2 = _interopRequireDefault(_url); var _helpers = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var required = _presence2.default; // alias exports.absence = _absence2.default; exports.acceptance = _acceptance2.default; exports.addValidator = _addValidator2.default; exports.confirmation = _confirmation2.default; exports.date = _date2.default; exports.parseDate = _date.parseDate; exports.formatDate = _date.formatDate; exports.email = _email2.default; exports.REG_EMAIL = _email.REG_EMAIL; exports.exclusion = _exclusion2.default; exports.format = _format2.default; exports.inclusion = _inclusion2.default; exports.length = _length2.default; exports.numericality = _numericality2.default; exports.presence = _presence2.default; exports.required = required; exports.url = _url2.default; exports.REG_URL = _url.REG_URL; exports.DEFAULT_ALLOW_BLANK = _helpers.DEFAULT_ALLOW_BLANK; /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_ALLOW_BLANK = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.regFormat = regFormat; exports.prepare = prepare; exports.trunc = trunc; exports.isNumber = isNumber; exports.formatMessage = formatMessage; exports.memoize = memoize; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactIntl = __webpack_require__(3); var _format = __webpack_require__(5); var _format2 = _interopRequireDefault(_format); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DEFAULT_ALLOW_BLANK = exports.DEFAULT_ALLOW_BLANK = false; function regFormat(options, reg, messageId) { options.msg = options.msg || options.message || messageId; options.with = reg; return (0, _format2.default)(options); } function prepare(ifCond, unlessCond, allowBlank, func) { return function () { var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var allValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; value = '' + value; if (allowBlank && !value.trim()) { return; } if (('function' !== typeof ifCond || ifCond(allValues, value)) && ('function' !== typeof unlessCond || !unlessCond(allValues, value))) { return func(value, allValues); } }; } function trunc(num) { return Math.trunc ? Math.trunc(num) : num < 0 ? Math.ceil(num) : Math.floor(num); } function isNumber(num) { return !isNaN(num) && '' !== ('' + num).trim(); } function formatMessage(msg) { if (null == msg) return null; return 'string' === typeof msg ? _react2.default.createElement(_reactIntl.FormattedMessage, { id: msg }) : _react2.default.createElement(_reactIntl.FormattedMessage, msg.props || msg); } function memoize(func) { if (!func.cache) { func.cache = {}; } return function (options) { var key = stringify(options); return HAS_PROP.call(func.cache, key) ? func.cache[key] : func.cache[key] = func(options); }; } // private var HAS_PROP = {}.hasOwnProperty; var TO_STRING = {}.toString; function stringify(options) { var arr = []; var value = void 0; for (var k in options) { if (HAS_PROP.call(options, k)) { value = options[k]; arr.push(k, _react2.default.isValidElement(value) ? stringify(value.props) : isObject(value) ? stringify(value) : value); } } return arr.toString(); } function isObject(obj) { return 'object' === (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) && '[object Object]' === TO_STRING.call(obj) && null !== obj; } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/* * Copyright 2017, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var allLocaleData = _interopDefault(__webpack_require__(47)); var IntlMessageFormat = _interopDefault(__webpack_require__(11)); var IntlRelativeFormat = _interopDefault(__webpack_require__(34)); var PropTypes = _interopDefault(__webpack_require__(44)); var React = __webpack_require__(1); var React__default = _interopDefault(React); var invariant = _interopDefault(__webpack_require__(40)); var memoizeIntlConstructor = _interopDefault(__webpack_require__(24)); // GENERATED FILE var defaultLocaleData = { "locale": "en", "pluralRuleFunction": function pluralRuleFunction(n, ord) { var s = String(n).split("."), v0 = !s[1], t0 = Number(s[0]) == n, n10 = t0 && s[0].slice(-1), n100 = t0 && s[0].slice(-2);if (ord) return n10 == 1 && n100 != 11 ? "one" : n10 == 2 && n100 != 12 ? "two" : n10 == 3 && n100 != 13 ? "few" : "other";return n == 1 && v0 ? "one" : "other"; }, "fields": { "year": { "displayName": "year", "relative": { "0": "this year", "1": "next year", "-1": "last year" }, "relativeTime": { "future": { "one": "in {0} year", "other": "in {0} years" }, "past": { "one": "{0} year ago", "other": "{0} years ago" } } }, "month": { "displayName": "month", "relative": { "0": "this month", "1": "next month", "-1": "last month" }, "relativeTime": { "future": { "one": "in {0} month", "other": "in {0} months" }, "past": { "one": "{0} month ago", "other": "{0} months ago" } } }, "day": { "displayName": "day", "relative": { "0": "today", "1": "tomorrow", "-1": "yesterday" }, "relativeTime": { "future": { "one": "in {0} day", "other": "in {0} days" }, "past": { "one": "{0} day ago", "other": "{0} days ago" } } }, "hour": { "displayName": "hour", "relativeTime": { "future": { "one": "in {0} hour", "other": "in {0} hours" }, "past": { "one": "{0} hour ago", "other": "{0} hours ago" } } }, "minute": { "displayName": "minute", "relativeTime": { "future": { "one": "in {0} minute", "other": "in {0} minutes" }, "past": { "one": "{0} minute ago", "other": "{0} minutes ago" } } }, "second": { "displayName": "second", "relative": { "0": "now" }, "relativeTime": { "future": { "one": "in {0} second", "other": "in {0} seconds" }, "past": { "one": "{0} second ago", "other": "{0} seconds ago" } } } } }; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ function addLocaleData() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var locales = Array.isArray(data) ? data : [data]; locales.forEach(function (localeData) { if (localeData && localeData.locale) { IntlMessageFormat.__addLocaleData(localeData); IntlRelativeFormat.__addLocaleData(localeData); } }); } function hasLocaleData(locale) { var localeParts = (locale || '').split('-'); while (localeParts.length > 0) { if (hasIMFAndIRFLocaleData(localeParts.join('-'))) { return true; } localeParts.pop(); } return false; } function hasIMFAndIRFLocaleData(locale) { var normalizedLocale = locale && locale.toLowerCase(); return !!(IntlMessageFormat.__localeData__[normalizedLocale] && IntlRelativeFormat.__localeData__[normalizedLocale]); } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var bool = PropTypes.bool; var number = PropTypes.number; var string = PropTypes.string; var func = PropTypes.func; var object = PropTypes.object; var oneOf = PropTypes.oneOf; var shape = PropTypes.shape; var any = PropTypes.any; var localeMatcher = oneOf(['best fit', 'lookup']); var narrowShortLong = oneOf(['narrow', 'short', 'long']); var numeric2digit = oneOf(['numeric', '2-digit']); var funcReq = func.isRequired; var intlConfigPropTypes = { locale: string, formats: object, messages: object, textComponent: any, defaultLocale: string, defaultFormats: object }; var intlFormatPropTypes = { formatDate: funcReq, formatTime: funcReq, formatRelative: funcReq, formatNumber: funcReq, formatPlural: funcReq, formatMessage: funcReq, formatHTMLMessage: funcReq }; var intlShape = shape(_extends({}, intlConfigPropTypes, intlFormatPropTypes, { formatters: object, now: funcReq })); var messageDescriptorPropTypes = { id: string.isRequired, description: string, defaultMessage: string }; var dateTimeFormatPropTypes = { localeMatcher: localeMatcher, formatMatcher: oneOf(['basic', 'best fit']), timeZone: string, hour12: bool, weekday: narrowShortLong, era: narrowShortLong, year: numeric2digit, month: oneOf(['numeric', '2-digit', 'narrow', 'short', 'long']), day: numeric2digit, hour: numeric2digit, minute: numeric2digit, second: numeric2digit, timeZoneName: oneOf(['short', 'long']) }; var numberFormatPropTypes = { localeMatcher: localeMatcher, style: oneOf(['decimal', 'currency', 'percent']), currency: string, currencyDisplay: oneOf(['symbol', 'code', 'name']), useGrouping: bool, minimumIntegerDigits: number, minimumFractionDigits: number, maximumFractionDigits: number, minimumSignificantDigits: number, maximumSignificantDigits: number }; var relativeFormatPropTypes = { style: oneOf(['best fit', 'numeric']), units: oneOf(['second', 'minute', 'hour', 'day', 'month', 'year']) }; var pluralFormatPropTypes = { style: oneOf(['cardinal', 'ordinal']) }; /* HTML escaping and shallow-equals implementations are the same as React's (on purpose.) Therefore, it has the following Copyright and Licensing: Copyright 2013-2014, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of React's source tree. */ var intlConfigPropNames = Object.keys(intlConfigPropTypes); var ESCAPED_CHARS = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var UNSAFE_CHARS_REGEX = /[&><"']/g; function escape(str) { return ('' + str).replace(UNSAFE_CHARS_REGEX, function (match) { return ESCAPED_CHARS[match]; }); } function filterProps(props, whitelist) { var defaults$$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return whitelist.reduce(function (filtered, name) { if (props.hasOwnProperty(name)) { filtered[name] = props[name]; } else if (defaults$$1.hasOwnProperty(name)) { filtered[name] = defaults$$1[name]; } return filtered; }, {}); } function invariantIntlContext() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, intl = _ref.intl; invariant(intl, '[React Intl] Could not find required `intl` object. ' + '<IntlProvider> needs to exist in the component ancestry.'); } function shallowEquals(objA, objB) { if (objA === objB) { return true; } if ((typeof objA === 'undefined' ? 'undefined' : _typeof(objA)) !== 'object' || objA === null || (typeof objB === 'undefined' ? 'undefined' : _typeof(objB)) !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function shouldIntlComponentUpdate(_ref2, nextProps, nextState) { var props = _ref2.props, state = _ref2.state, _ref2$context = _ref2.context, context = _ref2$context === undefined ? {} : _ref2$context; var nextContext = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var _context$intl = context.intl, intl = _context$intl === undefined ? {} : _context$intl; var _nextContext$intl = nextContext.intl, nextIntl = _nextContext$intl === undefined ? {} : _nextContext$intl; return !shallowEquals(nextProps, props) || !shallowEquals(nextState, state) || !(nextIntl === intl || shallowEquals(filterProps(nextIntl, intlConfigPropNames), filterProps(intl, intlConfigPropNames))); } /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ // Inspired by react-redux's `connect()` HOC factory function implementation: // https://github.com/rackt/react-redux function getDisplayName(Component$$1) { return Component$$1.displayName || Component$$1.name || 'Component'; } function injectIntl(WrappedComponent) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$intlPropName = options.intlPropName, intlPropName = _options$intlPropName === undefined ? 'intl' : _options$intlPropName, _options$withRef = options.withRef, withRef = _options$withRef === undefined ? false : _options$withRef; var InjectIntl = function (_Component) { inherits(InjectIntl, _Component); function InjectIntl(props, context) { classCallCheck(this, InjectIntl); var _this = possibleConstructorReturn(this, (InjectIntl.__proto__ || Object.getPrototypeOf(InjectIntl)).call(this, props, context)); invariantIntlContext(context); return _this; } createClass(InjectIntl, [{ key: 'getWrappedInstance', value: function getWrappedInstance() { invariant(withRef, '[React Intl] To access the wrapped instance, ' + 'the `{withRef: true}` option must be set when calling: ' + '`injectIntl()`'); return this.refs.wrappedInstance; } }, { key: 'render', value: function render() { return React__default.createElement(WrappedComponent, _extends({}, this.props, defineProperty({}, intlPropName, this.context.intl), { ref: withRef ? 'wrappedInstance' : null })); } }]); return InjectIntl; }(React.Component); InjectIntl.displayName = 'InjectIntl(' + getDisplayName(WrappedComponent) + ')'; InjectIntl.contextTypes = { intl: intlShape }; InjectIntl.WrappedComponent = WrappedComponent; return InjectIntl; } /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ function defineMessages(messageDescriptors) { // This simply returns what's passed-in because it's meant to be a hook for // babel-plugin-react-intl. return messageDescriptors; } /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ // This is a "hack" until a proper `intl-pluralformat` package is created. function resolveLocale(locales) { // IntlMessageFormat#_resolveLocale() does not depend on `this`. return IntlMessageFormat.prototype._resolveLocale(locales); } function findPluralFunction(locale) { // IntlMessageFormat#_findPluralFunction() does not depend on `this`. return IntlMessageFormat.prototype._findPluralRuleFunction(locale); } var IntlPluralFormat = function IntlPluralFormat(locales) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, IntlPluralFormat); var useOrdinal = options.style === 'ordinal'; var pluralFn = findPluralFunction(resolveLocale(locales)); this.format = function (value) { return pluralFn(value, useOrdinal); }; }; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var DATE_TIME_FORMAT_OPTIONS = Object.keys(dateTimeFormatPropTypes); var NUMBER_FORMAT_OPTIONS = Object.keys(numberFormatPropTypes); var RELATIVE_FORMAT_OPTIONS = Object.keys(relativeFormatPropTypes); var PLURAL_FORMAT_OPTIONS = Object.keys(pluralFormatPropTypes); var RELATIVE_FORMAT_THRESHOLDS = { second: 60, // seconds to minute minute: 60, // minutes to hour hour: 24, // hours to day day: 30, // days to month month: 12 }; function updateRelativeFormatThresholds(newThresholds) { var thresholds = IntlRelativeFormat.thresholds; thresholds.second = newThresholds.second; thresholds.minute = newThresholds.minute; thresholds.hour = newThresholds.hour; thresholds.day = newThresholds.day; thresholds.month = newThresholds.month; } function getNamedFormat(formats, type, name) { var format = formats && formats[type] && formats[type][name]; if (format) { return format; } if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] No ' + type + ' format named: ' + name); } } function formatDate(config, state, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale, formats = config.formats; var format = options.format; var date = new Date(value); var defaults$$1 = format && getNamedFormat(formats, 'date', format); var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults$$1); try { return state.getDateTimeFormat(locale, filteredOptions).format(date); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting date.\n' + e); } } return String(date); } function formatTime(config, state, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale, formats = config.formats; var format = options.format; var date = new Date(value); var defaults$$1 = format && getNamedFormat(formats, 'time', format); var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults$$1); if (!filteredOptions.hour && !filteredOptions.minute && !filteredOptions.second) { // Add default formatting options if hour, minute, or second isn't defined. filteredOptions = _extends({}, filteredOptions, { hour: 'numeric', minute: 'numeric' }); } try { return state.getDateTimeFormat(locale, filteredOptions).format(date); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting time.\n' + e); } } return String(date); } function formatRelative(config, state, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale, formats = config.formats; var format = options.format; var date = new Date(value); var now = new Date(options.now); var defaults$$1 = format && getNamedFormat(formats, 'relative', format); var filteredOptions = filterProps(options, RELATIVE_FORMAT_OPTIONS, defaults$$1); // Capture the current threshold values, then temporarily override them with // specific values just for this render. var oldThresholds = _extends({}, IntlRelativeFormat.thresholds); updateRelativeFormatThresholds(RELATIVE_FORMAT_THRESHOLDS); try { return state.getRelativeFormat(locale, filteredOptions).format(date, { now: isFinite(now) ? now : state.now() }); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting relative time.\n' + e); } } finally { updateRelativeFormatThresholds(oldThresholds); } return String(date); } function formatNumber(config, state, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale, formats = config.formats; var format = options.format; var defaults$$1 = format && getNamedFormat(formats, 'number', format); var filteredOptions = filterProps(options, NUMBER_FORMAT_OPTIONS, defaults$$1); try { return state.getNumberFormat(locale, filteredOptions).format(value); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting number.\n' + e); } } return String(value); } function formatPlural(config, state, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale; var filteredOptions = filterProps(options, PLURAL_FORMAT_OPTIONS); try { return state.getPluralFormat(locale, filteredOptions).format(value); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting plural.\n' + e); } } return 'other'; } function formatMessage(config, state) { var messageDescriptor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var locale = config.locale, formats = config.formats, messages = config.messages, defaultLocale = config.defaultLocale, defaultFormats = config.defaultFormats; var id = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage; // `id` is a required field of a Message Descriptor. invariant(id, '[React Intl] An `id` must be provided to format a message.'); var message = messages && messages[id]; var hasValues = Object.keys(values).length > 0; // Avoid expensive message formatting for simple messages without values. In // development messages will always be formatted in case of missing values. if (!hasValues && process.env.NODE_ENV === 'production') { return message || defaultMessage || id; } var formattedMessage = void 0; if (message) { try { var formatter = state.getMessageFormat(message, locale, formats); formattedMessage = formatter.format(values); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting message: "' + id + '" for locale: "' + locale + '"' + (defaultMessage ? ', using default message as fallback.' : '') + ('\n' + e)); } } } else { if (process.env.NODE_ENV !== 'production') { // This prevents warnings from littering the console in development // when no `messages` are passed into the <IntlProvider> for the // default locale, and a default message is in the source. if (!defaultMessage || locale && locale.toLowerCase() !== defaultLocale.toLowerCase()) { console.error('[React Intl] Missing message: "' + id + '" for locale: "' + locale + '"' + (defaultMessage ? ', using default message as fallback.' : '')); } } } if (!formattedMessage && defaultMessage) { try { var _formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats); formattedMessage = _formatter.format(values); } catch (e) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Error formatting the default message for: "' + id + '"' + ('\n' + e)); } } } if (!formattedMessage) { if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Cannot format message: "' + id + '", ' + ('using message ' + (message || defaultMessage ? 'source' : 'id') + ' as fallback.')); } } return formattedMessage || message || defaultMessage || id; } function formatHTMLMessage(config, state, messageDescriptor) { var rawValues = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; // Process all the values before they are used when formatting the ICU // Message string. Since the formatted message might be injected via // `innerHTML`, all String-based values need to be HTML-escaped. var escapedValues = Object.keys(rawValues).reduce(function (escaped, name) { var value = rawValues[name]; escaped[name] = typeof value === 'string' ? escape(value) : value; return escaped; }, {}); return formatMessage(config, state, messageDescriptor, escapedValues); } var format = Object.freeze({ formatDate: formatDate, formatTime: formatTime, formatRelative: formatRelative, formatNumber: formatNumber, formatPlural: formatPlural, formatMessage: formatMessage, formatHTMLMessage: formatHTMLMessage }); /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var intlConfigPropNames$1 = Object.keys(intlConfigPropTypes); var intlFormatPropNames = Object.keys(intlFormatPropTypes); // These are not a static property on the `IntlProvider` class so the intl // config values can be inherited from an <IntlProvider> ancestor. var defaultProps = { formats: {}, messages: {}, textComponent: 'span', defaultLocale: 'en', defaultFormats: {} }; var IntlProvider = function (_Component) { inherits(IntlProvider, _Component); function IntlProvider(props) { var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, IntlProvider); var _this = possibleConstructorReturn(this, (IntlProvider.__proto__ || Object.getPrototypeOf(IntlProvider)).call(this, props, context)); invariant(typeof Intl !== 'undefined', '[React Intl] The `Intl` APIs must be available in the runtime, ' + 'and do not appear to be built-in. An `Intl` polyfill should be loaded.\n' + 'See: http://formatjs.io/guides/runtime-environments/'); var intlContext = context.intl; // Used to stabilize time when performing an initial rendering so that // all relative times use the same reference "now" time. var initialNow = void 0; if (isFinite(props.initialNow)) { initialNow = Number(props.initialNow); } else { // When an `initialNow` isn't provided via `props`, look to see an // <IntlProvider> exists in the ancestry and call its `now()` // function to propagate its value for "now". initialNow = intlContext ? intlContext.now() : Date.now(); } // Creating `Intl*` formatters is expensive. If there's a parent // `<IntlProvider>`, then its formatters will be used. Otherwise, this // memoize the `Intl*` constructors and cache them for the lifecycle of // this IntlProvider instance. var _ref = intlContext || {}, _ref$formatters = _ref.formatters, formatters = _ref$formatters === undefined ? { getDateTimeFormat: memoizeIntlConstructor(Intl.DateTimeFormat), getNumberFormat: memoizeIntlConstructor(Intl.NumberFormat), getMessageFormat: memoizeIntlConstructor(IntlMessageFormat), getRelativeFormat: memoizeIntlConstructor(IntlRelativeFormat), getPluralFormat: memoizeIntlConstructor(IntlPluralFormat) } : _ref$formatters; _this.state = _extends({}, formatters, { // Wrapper to provide stable "now" time for initial render. now: function now() { return _this._didDisplay ? Date.now() : initialNow; } }); return _this; } createClass(IntlProvider, [{ key: 'getConfig', value: function getConfig() { var intlContext = this.context.intl; // Build a whitelisted config object from `props`, defaults, and // `context.intl`, if an <IntlProvider> exists in the ancestry. var config = filterProps(this.props, intlConfigPropNames$1, intlContext); // Apply default props. This must be applied last after the props have // been resolved and inherited from any <IntlProvider> in the ancestry. // This matches how React resolves `defaultProps`. for (var propName in defaultProps) { if (config[propName] === undefined) { config[propName] = defaultProps[propName]; } } if (!hasLocaleData(config.locale)) { var _config = config, locale = _config.locale, defaultLocale = _config.defaultLocale, defaultFormats = _config.defaultFormats; if (process.env.NODE_ENV !== 'production') { console.error('[React Intl] Missing locale data for locale: "' + locale + '". ' + ('Using default locale: "' + defaultLocale + '" as fallback.')); } // Since there's no registered locale data for `locale`, this will // fallback to the `defaultLocale` to make sure things can render. // The `messages` are overridden to the `defaultProps` empty object // to maintain referential equality across re-renders. It's assumed // each <FormattedMessage> contains a `defaultMessage` prop. config = _extends({}, config, { locale: defaultLocale, formats: defaultFormats, messages: defaultProps.messages }); } return config; } }, { key: 'getBoundFormatFns', value: function getBoundFormatFns(config, state) { return intlFormatPropNames.reduce(function (boundFormatFns, name) { boundFormatFns[name] = format[name].bind(null, config, state); return boundFormatFns; }, {}); } }, { key: 'getChildContext', value: function getChildContext() { var config = this.getConfig(); // Bind intl factories and current config to the format functions. var boundFormatFns = this.getBoundFormatFns(config, this.state); var _state = this.state, now = _state.now, formatters = objectWithoutProperties(_state, ['now']); return { intl: _extends({}, config, boundFormatFns, { formatters: formatters, now: now }) }; } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, next = Array(_len), _key = 0; _key < _len; _key++) { next[_key] = arguments[_key]; } return shouldIntlComponentUpdate.apply(undefined, [this].concat(next)); } }, { key: 'componentDidMount', value: function componentDidMount() { this._didDisplay = true; } }, { key: 'render', value: function render() { return React.Children.only(this.props.children); } }]); return IntlProvider; }(React.Component); IntlProvider.displayName = 'IntlProvider'; IntlProvider.contextTypes = { intl: intlShape }; IntlProvider.childContextTypes = { intl: intlShape.isRequired }; process.env.NODE_ENV !== "production" ? IntlProvider.propTypes = _extends({}, intlConfigPropTypes, { children: PropTypes.element.isRequired, initialNow: PropTypes.any }) : void 0; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var FormattedDate = function (_Component) { inherits(FormattedDate, _Component); function FormattedDate(props, context) { classCallCheck(this, FormattedDate); var _this = possibleConstructorReturn(this, (FormattedDate.__proto__ || Object.getPrototypeOf(FormattedDate)).call(this, props, context)); invariantIntlContext(context); return _this; } createClass(FormattedDate, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, next = Array(_len), _key = 0; _key < _len; _key++) { next[_key] = arguments[_key]; } return shouldIntlComponentUpdate.apply(undefined, [this].concat(next)); } }, { key: 'render', value: function render() { var _context$intl = this.context.intl, formatDate = _context$intl.formatDate, Text = _context$intl.textComponent; var _props = this.props, value = _props.value, children = _props.children; var formattedDate = formatDate(value, this.props); if (typeof children === 'function') { return children(formattedDate); } return React__default.createElement( Text, null, formattedDate ); } }]); return FormattedDate; }(React.Component); FormattedDate.displayName = 'FormattedDate'; FormattedDate.contextTypes = { intl: intlShape }; process.env.NODE_ENV !== "production" ? FormattedDate.propTypes = _extends({}, dateTimeFormatPropTypes, { value: PropTypes.any.isRequired, format: PropTypes.string, children: PropTypes.func }) : void 0; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var FormattedTime = function (_Component) { inherits(FormattedTime, _Component); function FormattedTime(props, context) { classCallCheck(this, FormattedTime); var _this = possibleConstructorReturn(this, (FormattedTime.__proto__ || Object.getPrototypeOf(FormattedTime)).call(this, props, context)); invariantIntlContext(context); return _this; } createClass(FormattedTime, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, next = Array(_len), _key = 0; _key < _len; _key++) { next[_key] = arguments[_key]; } return shouldIntlComponentUpdate.apply(undefined, [this].concat(next)); } }, { key: 'render', value: function render() { var _context$intl = this.context.intl, formatTime = _context$intl.formatTime, Text = _context$intl.textComponent; var _props = this.props, value = _props.value, children = _props.children; var formattedTime = formatTime(value, this.props); if (typeof children === 'function') { return children(formattedTime); } return React__default.createElement( Text, null, formattedTime ); } }]); return FormattedTime; }(React.Component); FormattedTime.displayName = 'FormattedTime'; FormattedTime.contextTypes = { intl: intlShape }; process.env.NODE_ENV !== "production" ? FormattedTime.propTypes = _extends({}, dateTimeFormatPropTypes, { value: PropTypes.any.isRequired, format: PropTypes.string, children: PropTypes.func }) : void 0; /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ var SECOND = 1000; var MINUTE = 1000 * 60; var HOUR = 1000 * 60 * 60; var DAY = 1000 * 60 * 60 * 24; // The maximum timer delay value is a 32-bit signed integer. // See: https://mdn.io/setTimeout var MAX_TIMER_DELAY = 2147483647; function selectUnits(delta) { var absDelta = Math.abs(delta); if (absDelta < MINUTE) { return 'second'; } if (absDelta < HOUR) { return 'minute'; } if (absDelta < DAY) { return 'hour'; } // The maximum scheduled delay will be measured in days since the maximum // timer delay is less than the number of milliseconds in 25 days. return 'day'; } function getUnitDelay(units) { switch (units) { case 'second': return SECOND; case 'minute': return MINUTE; case 'hour': return HOUR; case 'day': return DAY; default: return MAX_TIMER_DELAY; } } function isSameDate(a, b) { if (a === b) { return true; } var aTime = new Date(a).getTime(); var bTime = new Date(b).getTime(); return isFinite(aTime) && isFinite(bTime) && aTime === bTime; } var FormattedRelative = function (_Component) { inherits(FormattedRelative, _Component); function FormattedRelative(props, context) { classCallCheck(this, FormattedRelative); var _this = possibleConstructorReturn(this, (FormattedRelative.__proto__ || Object.getPrototypeOf(FormattedRelative)).call(this, props, context)); invariantIntlContext(context); var now = isFinite(props.initialNow) ? Number(props.initialNow) : context.intl.now(); // `now` is stored as state so that `render()` remains a function of // props + state, instead of accessing `Date.now()` inside `render()`. _this.state = { now: now }; return _this; } createClass(FormattedRelative, [{ key: 'scheduleNextUpdate', value: function scheduleNextUpdate(props, state) { var _this2 = this; // Cancel and pending update because we're scheduling a new update. clearTimeout(this._timer); var value = props.value, units = props.units, updateInterval = props.updateInterval; var time = new Date(value).getTime(); // If the `updateInterval` is falsy, including `0` or we don't have a // valid date, then auto updates have been turned off, so we bail and // skip scheduling an update. if (!updateInterval || !isFinite(time)) { return; } var delta = time - state.now; var unitDelay = getUnitDelay(units || selectUnits(delta)); var unitRemainder = Math.abs(delta % unitDelay); // We want the largest possible timer delay which will still display // accurate information while reducing unnecessary re-renders. The delay // should be until the next "interesting" moment, like a tick from // "1 minute ago" to "2 minutes ago" when the delta is 120,000ms. var delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder); this._timer = setTimeout(function () { _this2.setState({ now: _this2.context.intl.now() }); }, delay); } }, { key: 'componentDidMount', value: function componentDidMount() { this.scheduleNextUpdate(this.props, this.state); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(_ref) { var nextValue = _ref.value; // When the `props.value` date changes, `state.now` needs to be updated, // and the next update can be rescheduled. if (!isSameDate(nextValue, this.props.value)) { this.setState({ now: this.context.intl.now() }); } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, next = Array(_len), _key = 0; _key < _len; _key++) { next[_key] = arguments[_key]; } return shouldIntlComponentUpdate.apply(undefined, [this].concat(next)); } }, { key: 'componentWillUpdate', value: function componentWillUpdate(nextProps, nextState) { this.scheduleNextUpdate(nextProps, nextState); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this._timer); } }, { key: 'render', value: function render() { var _context$intl = this.context.intl, formatRelative = _context$intl.formatRelative, Text = _context$intl.textComponent; var _props = this.props, value = _props.value, children = _props.children; var formattedRelative = formatRelative(value, _extends({}, this.props, this.state)); if (typeof children === 'function') { return children(formattedRelative); } return React__default.createElement( Text, null, formattedRelative ); } }]); return FormattedRelative; }(React.Component); FormattedRelative.displayName = 'FormattedRelative'; FormattedRelative.contextTypes = { intl: intlShape }; FormattedRelative.defaultProps = { updateInterval: 1000 * 10 }; process.env.NODE_ENV !== "production" ? FormattedRelative.propTypes = _extends({}, relativeFormatPropTypes, { value: PropTypes.any.isRequired, format: PropTypes.string, updateInterval: PropTypes.number, initialNow: PropTypes.any,