Comparing version 0.1.0 to 0.1.1-alpha.31
@@ -6,1 +6,5 @@ export { default as IntlProvider } from './IntlProvider'; | ||
export { default as useIntl } from './useIntl'; | ||
export { default as useNow } from './useNow'; | ||
export { default as Formats } from './Formats'; | ||
export { default as DateTimeFormatOptions } from './DateTimeFormatOptions'; | ||
export { default as IntlError, IntlErrorCode } from './IntlError'; |
/// <reference types="react" /> | ||
import Formats from './Formats'; | ||
import IntlError from './IntlError'; | ||
import IntlMessages from './IntlMessages'; | ||
declare const IntlContext: import("react").Context<{ | ||
messages: IntlMessages; | ||
export declare type IntlContextShape = { | ||
messages?: IntlMessages; | ||
locale: string; | ||
} | undefined>; | ||
formats?: Partial<Formats>; | ||
timeZone?: string; | ||
onError(error: IntlError): void; | ||
getMessageFallback(info: { | ||
error: IntlError; | ||
key: string; | ||
namespace?: string; | ||
}): string; | ||
now?: Date; | ||
}; | ||
declare const IntlContext: import("react").Context<IntlContextShape | undefined>; | ||
export default IntlContext; |
import { ReactNode } from 'react'; | ||
import Formats from './Formats'; | ||
import IntlMessages from './IntlMessages'; | ||
import { IntlError } from '.'; | ||
declare type Props = { | ||
/** All messages that will be available in your components. */ | ||
messages?: IntlMessages; | ||
/** A valid Unicode locale tag (e.g. "en" or "en-GB"). */ | ||
locale: string; | ||
/** Global formats can be provided to achieve consistent | ||
* formatting across components. */ | ||
formats?: Partial<Formats>; | ||
/** A time zone as defined in [the tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) which will be applied when formatting dates and times. If this is absent, the user time zone will be used. You can override this by supplying an explicit time zone to `formatDateTime`. */ | ||
timeZone?: string; | ||
/** This callback will be invoked when an error is encountered during | ||
* resolving a message or formatting it. This defaults to `console.error` to | ||
* keep your app running. You can customize the handling by taking | ||
* `error.code` into account. */ | ||
onError?(error: IntlError): void; | ||
/** Will be called when a message couldn't be resolved or formatting it led to | ||
* an error. This defaults to `${namespace}.${key}` You can use this to | ||
* customize what will be rendered in this case. */ | ||
getMessageFallback?(info: { | ||
namespace?: string; | ||
key: string; | ||
error: IntlError; | ||
}): string; | ||
/** All components that use the provided hooks should be within this tree. */ | ||
children: ReactNode; | ||
messages: IntlMessages; | ||
locale: string; | ||
/** | ||
* Providing this value will have two effects: | ||
* 1. It will be used as the default for the `now` argument of | ||
* `useIntl().formatRelativeTime` if no explicit value is provided. | ||
* 2. It will be returned as a static value from the `useNow` hook. Note | ||
* however that when `updateInterval` is configured on the `useNow` hook, | ||
* the global `now` value will only be used for the initial render, but | ||
* afterwards the current date will be retunred continuously. | ||
*/ | ||
now?: Date; | ||
}; | ||
export default function IntlProvider({ children, locale, messages }: Props): JSX.Element; | ||
export default function IntlProvider({ children, onError, getMessageFallback, ...contextValues }: Props): JSX.Element; | ||
export {}; |
@@ -11,16 +11,198 @@ 'use strict'; | ||
function _extends() { | ||
_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; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
var IntlContext = /*#__PURE__*/React.createContext(undefined); | ||
function IntlProvider(_ref) { | ||
var children = _ref.children, | ||
locale = _ref.locale, | ||
messages = _ref.messages; | ||
function defaultGetMessageFallback(_ref) { | ||
var key = _ref.key, | ||
namespace = _ref.namespace; | ||
return [namespace, key].filter(function (part) { | ||
return part != null; | ||
}).join('.'); | ||
} | ||
function IntlProvider(_ref2) { | ||
var children = _ref2.children, | ||
_ref2$onError = _ref2.onError, | ||
onError = _ref2$onError === void 0 ? console.error : _ref2$onError, | ||
_ref2$getMessageFallb = _ref2.getMessageFallback, | ||
getMessageFallback = _ref2$getMessageFallb === void 0 ? defaultGetMessageFallback : _ref2$getMessageFallb, | ||
contextValues = _objectWithoutPropertiesLoose(_ref2, ["children", "onError", "getMessageFallback"]); | ||
return React__default.createElement(IntlContext.Provider, { | ||
value: { | ||
messages: messages, | ||
locale: locale | ||
} | ||
value: _extends({}, contextValues, { | ||
onError: onError, | ||
getMessageFallback: getMessageFallback | ||
}) | ||
}, children); | ||
} | ||
(function (IntlErrorCode) { | ||
IntlErrorCode["MISSING_MESSAGE"] = "MISSING_MESSAGE"; | ||
IntlErrorCode["MISSING_FORMAT"] = "MISSING_FORMAT"; | ||
IntlErrorCode["INSUFFICIENT_PATH"] = "INSUFFICIENT_PATH"; | ||
IntlErrorCode["INVALID_MESSAGE"] = "INVALID_MESSAGE"; | ||
IntlErrorCode["FORMATTING_ERROR"] = "FORMATTING_ERROR"; | ||
})(exports.IntlErrorCode || (exports.IntlErrorCode = {})); | ||
var IntlError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(IntlError, _Error); | ||
function IntlError(code, originalMessage) { | ||
var _this; | ||
var message = code; | ||
if (originalMessage) { | ||
message += ': ' + originalMessage; | ||
} | ||
_this = _Error.call(this, message) || this; | ||
_this.code = code; | ||
if (originalMessage) { | ||
_this.originalMessage = originalMessage; | ||
} | ||
return _this; | ||
} | ||
return IntlError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* `intl-messageformat` uses separate keys for `date` and `time`, but there's | ||
* only one native API: `Intl.DateTimeFormat`. Additionally you might want to | ||
* include both a time and a date in a value, therefore the separation doesn't | ||
* seem so useful. We offer a single `dateTime` namespace instead, but we have | ||
* to convert the format before `intl-messageformat` can be used. | ||
*/ | ||
function convertFormatsToIntlMessageFormat(formats) { | ||
return _extends({}, formats, { | ||
date: formats == null ? void 0 : formats.dateTime, | ||
time: formats == null ? void 0 : formats.dateTime | ||
}); | ||
} | ||
function useIntlContext() { | ||
@@ -30,5 +212,3 @@ var context = React.useContext(IntlContext); | ||
if (!context) { | ||
{ | ||
throw new Error('No context found. Have you configured the provider?'); | ||
} | ||
throw new Error( 'No intl context found. Have you configured the provider?' ); | ||
} | ||
@@ -39,8 +219,7 @@ | ||
function useLocale() { | ||
var context = useIntlContext(); | ||
return context.locale; | ||
} | ||
function resolvePath(messages, idPath, namespace) { | ||
if (!messages) { | ||
throw new Error( "No messages available at `" + namespace + "`." ); | ||
} | ||
function resolvePath(messages, idPath) { | ||
var message = messages; | ||
@@ -50,6 +229,4 @@ idPath.split('.').forEach(function (part) { | ||
{ | ||
if (part == null || next == null) { | ||
throw new Error("Could not resolve `" + idPath + "` in `" + JSON.stringify(messages, null, 2) + "`."); | ||
} | ||
if (part == null || next == null) { | ||
throw new Error( "Could not resolve `" + idPath + "` in " + (namespace ? "`" + namespace + "`" : 'messages') + "." ); | ||
} | ||
@@ -86,29 +263,38 @@ | ||
/** | ||
* Translates messages from the given path by using the ICU syntax. | ||
* Translates messages from the given namespace by using the ICU syntax. | ||
* See https://formatjs.io/docs/core-concepts/icu-syntax. | ||
* | ||
* If no path is provided, all available messages are returned. | ||
* | ||
* The path can also indicate nesting by using a dot (e.g. `namespace.Component`). | ||
* If no namespace is provided, all available messages are returned. | ||
* The namespace can also indicate nesting by using a dot | ||
* (e.g. `namespace.Component`). | ||
*/ | ||
function useTranslations(path) { | ||
var context = useIntlContext(); | ||
var locale = useLocale(); | ||
function useTranslations(namespace) { | ||
var _useIntlContext = useIntlContext(), | ||
globalFormats = _useIntlContext.formats, | ||
getMessageFallback = _useIntlContext.getMessageFallback, | ||
locale = _useIntlContext.locale, | ||
allMessages = _useIntlContext.messages, | ||
onError = _useIntlContext.onError; | ||
var cachedFormatsByLocaleRef = React.useRef({}); | ||
var allMessages = context.messages; | ||
var messages = React.useMemo(function () { | ||
return path ? resolvePath(allMessages, path) : allMessages; | ||
}, [allMessages, path]); | ||
var messagesOrError = React.useMemo(function () { | ||
try { | ||
var retrievedMessages = namespace ? resolvePath(allMessages, namespace) : allMessages; | ||
{ | ||
if (!messages) { | ||
throw new Error("No messages for component `" + path + "` found."); | ||
if (!retrievedMessages) { | ||
throw new Error("development" !== "production" ? "No messages for namespace `" + namespace + "` found." : undefined); | ||
} | ||
return retrievedMessages; | ||
} catch (error) { | ||
var intlError = new IntlError(exports.IntlErrorCode.MISSING_MESSAGE, error.message); | ||
onError(intlError); | ||
return intlError; | ||
} | ||
} | ||
function translate( | ||
}, [allMessages, namespace, onError]); | ||
var translate = React.useCallback(function ( | ||
/** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */ | ||
idPath, | ||
key, | ||
/** Key value pairs for values to interpolate into the message. */ | ||
@@ -121,16 +307,45 @@ values, | ||
var cachedFormatsByLocale = cachedFormatsByLocaleRef.current; | ||
function getFallbackFromError(code, message) { | ||
var error = new IntlError(code, message); | ||
onError(error); | ||
return getMessageFallback({ | ||
error: error, | ||
key: key, | ||
namespace: namespace | ||
}); | ||
} | ||
if (messagesOrError instanceof IntlError) { | ||
// We have already warned about this during render | ||
return getMessageFallback({ | ||
error: messagesOrError, | ||
key: key, | ||
namespace: namespace | ||
}); | ||
} | ||
var messages = messagesOrError; | ||
var messageFormat; | ||
if ((_cachedFormatsByLocal = cachedFormatsByLocale[locale]) != null && _cachedFormatsByLocal[idPath]) { | ||
messageFormat = cachedFormatsByLocale[locale][idPath]; | ||
if ((_cachedFormatsByLocal = cachedFormatsByLocale[locale]) != null && _cachedFormatsByLocal[key]) { | ||
messageFormat = cachedFormatsByLocale[locale][key]; | ||
} else { | ||
var message = resolvePath(messages, idPath); | ||
var message; | ||
try { | ||
message = resolvePath(messages, key, namespace); | ||
} catch (error) { | ||
return getFallbackFromError(exports.IntlErrorCode.MISSING_MESSAGE, error.message); | ||
} | ||
if (typeof message === 'object') { | ||
{ | ||
throw new Error("Insufficient path specified for `" + idPath + "` in `" + path + "`."); | ||
} | ||
return getFallbackFromError(exports.IntlErrorCode.INSUFFICIENT_PATH, "Insufficient path specified for `" + key + "` in `" + namespace + "`." ); | ||
} | ||
messageFormat = new IntlMessageFormat(message, locale, formats); | ||
try { | ||
messageFormat = new IntlMessageFormat(message, locale, convertFormatsToIntlMessageFormat(_extends({}, globalFormats, formats))); | ||
} catch (error) { | ||
return getFallbackFromError(exports.IntlErrorCode.INVALID_MESSAGE, error.message); | ||
} | ||
@@ -141,16 +356,17 @@ if (!cachedFormatsByLocale[locale]) { | ||
cachedFormatsByLocale[locale][idPath] = messageFormat; | ||
cachedFormatsByLocale[locale][key] = messageFormat; | ||
} | ||
var formattedMessage = messageFormat.format(prepareTranslationValues(values)); | ||
try { | ||
var formattedMessage = messageFormat.format(prepareTranslationValues(values)); | ||
{ | ||
if (formattedMessage === undefined) { | ||
throw new Error("Unable to format " + path + "." + idPath); | ||
if (formattedMessage == null) { | ||
throw new Error("development" !== "production" ? "Unable to format " + [namespace, key].join('.') : undefined); | ||
} | ||
return formattedMessage; | ||
} catch (error) { | ||
return getFallbackFromError(exports.IntlErrorCode.FORMATTING_ERROR, error.message); | ||
} | ||
return formattedMessage; | ||
} | ||
}, [getMessageFallback, globalFormats, locale, messagesOrError, namespace, onError]); | ||
return translate; | ||
@@ -202,26 +418,101 @@ } | ||
function useIntl() { | ||
var locale = useLocale(); | ||
var _useIntlContext = useIntlContext(), | ||
formats = _useIntlContext.formats, | ||
locale = _useIntlContext.locale, | ||
globalNow = _useIntlContext.now, | ||
onError = _useIntlContext.onError, | ||
timeZone = _useIntlContext.timeZone; | ||
function formatDateTime(value, options) { | ||
return new Intl.DateTimeFormat(locale, options).format(value); | ||
function resolveFormatOrOptions(typeFormats, formatOrOptions) { | ||
var options; | ||
if (typeof formatOrOptions === 'string') { | ||
var formatName = formatOrOptions; | ||
options = typeFormats == null ? void 0 : typeFormats[formatName]; | ||
if (!options) { | ||
var error = new IntlError(exports.IntlErrorCode.MISSING_FORMAT, "Format `" + formatName + "` is not available. You can configure it on the provider or provide custom options." ); | ||
onError(error); | ||
throw error; | ||
} | ||
} else { | ||
options = formatOrOptions; | ||
} | ||
return options; | ||
} | ||
function formatNumber(value, options) { | ||
return new Intl.NumberFormat(locale, options).format(value); | ||
function getFormattedValue(value, formatOrOptions, typeFormats, formatter) { | ||
var options; | ||
try { | ||
options = resolveFormatOrOptions(typeFormats, formatOrOptions); | ||
} catch (error) { | ||
return String(value); | ||
} | ||
try { | ||
return formatter(options); | ||
} catch (error) { | ||
onError(new IntlError(exports.IntlErrorCode.FORMATTING_ERROR, error.message)); | ||
return String(value); | ||
} | ||
} | ||
function formatRelativeTime(date, now) { | ||
var dateDate = date instanceof Date ? date : new Date(date); | ||
var nowDate = now instanceof Date ? now : new Date(now); | ||
var seconds = (dateDate.getTime() - nowDate.getTime()) / 1000; | ||
function formatDateTime( | ||
/** If a number is supplied, this is interpreted as a UTC timestamp. */ | ||
value, | ||
/** If a time zone is supplied, the `value` is converted to that time zone. | ||
* Otherwise the user time zone will be used. */ | ||
formatOrOptions) { | ||
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.dateTime, function (options) { | ||
var _options; | ||
var _getRelativeTimeForma = getRelativeTimeFormatConfig(seconds), | ||
unit = _getRelativeTimeForma.unit, | ||
value = _getRelativeTimeForma.value; | ||
if (timeZone && !((_options = options) != null && _options.timeZone)) { | ||
options = _extends({}, options, { | ||
timeZone: timeZone | ||
}); | ||
} | ||
return new Intl.RelativeTimeFormat(locale, { | ||
numeric: 'auto' | ||
}).format(value, unit); | ||
return new Intl.DateTimeFormat(locale, options).format(value); | ||
}); | ||
} | ||
function formatNumber(value, formatOrOptions) { | ||
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.number, function (options) { | ||
return new Intl.NumberFormat(locale, options).format(value); | ||
}); | ||
} | ||
function formatRelativeTime( | ||
/** The date time that needs to be formatted. */ | ||
date, | ||
/** The reference point in time to which `date` will be formatted in relation to. */ | ||
now) { | ||
try { | ||
if (!now) { | ||
if (globalNow) { | ||
now = globalNow; | ||
} else { | ||
throw new Error("development" !== "production" ? "The `now` parameter wasn't provided to `formatRelativeTime` and there was no global fallback configured on the provider." : undefined); | ||
} | ||
} | ||
var dateDate = date instanceof Date ? date : new Date(date); | ||
var nowDate = now instanceof Date ? now : new Date(now); | ||
var seconds = (dateDate.getTime() - nowDate.getTime()) / 1000; | ||
var _getRelativeTimeForma = getRelativeTimeFormatConfig(seconds), | ||
unit = _getRelativeTimeForma.unit, | ||
value = _getRelativeTimeForma.value; | ||
return new Intl.RelativeTimeFormat(locale, { | ||
numeric: 'auto' | ||
}).format(value, unit); | ||
} catch (error) { | ||
onError(new IntlError(exports.IntlErrorCode.FORMATTING_ERROR, error.message)); | ||
return String(date); | ||
} | ||
} | ||
return { | ||
@@ -234,5 +525,52 @@ formatDateTime: formatDateTime, | ||
function getNow() { | ||
return new Date(); | ||
} | ||
/** | ||
* Reading the current date via `new Date()` in components should be avoided, as | ||
* it causes components to be impure and can lead to flaky tests. Instead, this | ||
* hook can be used. | ||
* | ||
* By default, it returns the time when the component mounts. If `updateInterval` | ||
* is specified, the value will be updated based on the interval. | ||
* | ||
* You can however also return a static value from this hook, if you | ||
* configure the `now` parameter on the context provider. Note however, | ||
* that if `updateInterval` is configured in this case, the component | ||
* will initialize with the global value, but will afterwards update | ||
* continuously based on the interval. | ||
* | ||
* For unit tests, this can be mocked to a constant value. For end-to-end | ||
* testing, an environment parameter can be passed to the `now` parameter | ||
* of the provider to mock this to a static value. | ||
*/ | ||
function useNow(options) { | ||
var updateInterval = options == null ? void 0 : options.updateInterval; | ||
var _useIntlContext = useIntlContext(), | ||
globalNow = _useIntlContext.now; | ||
var _useState = React.useState(globalNow || getNow()), | ||
now = _useState[0], | ||
setNow = _useState[1]; | ||
React.useEffect(function () { | ||
if (!updateInterval) return; | ||
var intervalId = setInterval(function () { | ||
setNow(getNow()); | ||
}); | ||
return function () { | ||
clearInterval(intervalId); | ||
}; | ||
}, [globalNow, updateInterval]); | ||
return now; | ||
} | ||
exports.IntlError = IntlError; | ||
exports.IntlProvider = IntlProvider; | ||
exports.useIntl = useIntl; | ||
exports.useNow = useNow; | ||
exports.useTranslations = useTranslations; | ||
//# sourceMappingURL=use-intl.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"),r=e(t),n=e(require("intl-messageformat")),o=t.createContext(void 0);function a(){var e=t.useContext(o);if(!e)throw new Error;return e}function u(){return a().locale}function i(e,t){var r=e;return t.split(".").forEach((function(e){r=r[e]})),r}exports.IntlProvider=function(e){return r.createElement(o.Provider,{value:{messages:e.messages,locale:e.locale}},e.children)},exports.useIntl=function(){var e=u();return{formatDateTime:function(t,r){return new Intl.DateTimeFormat(e,r).format(t)},formatNumber:function(t,r){return new Intl.NumberFormat(e,r).format(t)},formatRelativeTime:function(t,r){var n=t instanceof Date?t:new Date(t),o=r instanceof Date?r:new Date(r),a=function(e){var t,r,n=Math.abs(e);return n<60?(r="second",t=Math.round(e)):n<3600?(r="minute",t=Math.round(e/60)):n<86400?(r="hour",t=Math.round(e/3600)):n<604800?(r="day",t=Math.round(e/86400)):n<2628e3?(r="week",t=Math.round(e/604800)):n<31536e3?(r="month",t=Math.round(e/2628e3)):(r="year",t=Math.round(e/31536e3)),{value:t,unit:r}}((n.getTime()-o.getTime())/1e3),u=a.unit,i=a.value;return new Intl.RelativeTimeFormat(e,{numeric:"auto"}).format(i,u)}}},exports.useTranslations=function(e){var r=a(),o=u(),f=t.useRef({}),c=r.messages,s=t.useMemo((function(){return e?i(c,e):c}),[c,e]);return function(e,r,a){var u,c,l=f.current;if(null!=(u=l[o])&&u[e])c=l[o][e];else{var m=i(s,e);if("object"==typeof m)throw new Error;c=new n(m,o,a),l[o]||(l[o]={}),l[o][e]=c}return c.format(function(e){if(!e)return e;var r={};return Object.keys(e).forEach((function(n){var o=e[n];r[n]="function"==typeof o?function(e){var r=o(e);return t.isValidElement(r)?t.cloneElement(r,{key:r.key||n+String(e)}):r}:o})),r}(r))}}; | ||
"use strict";function r(r){return r&&"object"==typeof r&&"default"in r?r.default:r}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"),e=r(t),n=r(require("intl-messageformat"));function o(){return(o=Object.assign||function(r){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n])}return r}).apply(this,arguments)}function u(r){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)})(r)}function a(r,t){return(a=Object.setPrototypeOf||function(r,t){return r.__proto__=t,r})(r,t)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(r){return!1}}function c(r,t,e){return(c=i()?Reflect.construct:function(r,t,e){var n=[null];n.push.apply(n,t);var o=new(Function.bind.apply(r,n));return e&&a(o,e.prototype),o}).apply(null,arguments)}function f(r){var t="function"==typeof Map?new Map:void 0;return(f=function(r){if(null===r||-1===Function.toString.call(r).indexOf("[native code]"))return r;if("function"!=typeof r)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(r))return t.get(r);t.set(r,e)}function e(){return c(r,arguments,u(this).constructor)}return e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),a(e,r)})(r)}var l,s=t.createContext(void 0);function p(r){return[r.namespace,r.key].filter((function(r){return null!=r})).join(".")}(l=exports.IntlErrorCode||(exports.IntlErrorCode={})).MISSING_MESSAGE="MISSING_MESSAGE",l.MISSING_FORMAT="MISSING_FORMAT",l.INSUFFICIENT_PATH="INSUFFICIENT_PATH",l.INVALID_MESSAGE="INVALID_MESSAGE",l.FORMATTING_ERROR="FORMATTING_ERROR";var v=function(r){var t,e;function n(t,e){var n,o=t;return e&&(o+=": "+e),(n=r.call(this,o)||this).code=t,e&&(n.originalMessage=e),n}return e=r,(t=n).prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e,n}(f(Error));function d(){var r=t.useContext(s);if(!r)throw new Error(void 0);return r}function I(r,t,e){if(!r)throw new Error(void 0);var n=r;return t.split(".").forEach((function(r){var t=n[r];if(null==r||null==t)throw new Error(void 0);n=t})),n}function E(){return new Date}exports.IntlError=v,exports.IntlProvider=function(r){var t=r.children,n=r.onError,u=void 0===n?console.error:n,a=r.getMessageFallback,i=void 0===a?p:a,c=function(r,t){if(null==r)return{};var e,n,o={},u=Object.keys(r);for(n=0;n<u.length;n++)t.indexOf(e=u[n])>=0||(o[e]=r[e]);return o}(r,["children","onError","getMessageFallback"]);return e.createElement(s.Provider,{value:o({},c,{onError:u,getMessageFallback:i})},t)},exports.useIntl=function(){var r=d(),t=r.formats,e=r.locale,n=r.now,u=r.onError,a=r.timeZone;function i(r,t,e,n){var o;try{o=function(r,t){var e;if("string"==typeof t){if(!(e=null==r?void 0:r[t])){var n=new v(exports.IntlErrorCode.MISSING_FORMAT,void 0);throw u(n),n}}else e=t;return e}(e,t)}catch(t){return String(r)}try{return n(o)}catch(t){return u(new v(exports.IntlErrorCode.FORMATTING_ERROR,t.message)),String(r)}}return{formatDateTime:function(r,n){return i(r,n,null==t?void 0:t.dateTime,(function(t){var n;return!a||null!=(n=t)&&n.timeZone||(t=o({},t,{timeZone:a})),new Intl.DateTimeFormat(e,t).format(r)}))},formatNumber:function(r,n){return i(r,n,null==t?void 0:t.number,(function(t){return new Intl.NumberFormat(e,t).format(r)}))},formatRelativeTime:function(r,t){try{if(!t){if(!n)throw new Error(void 0);t=n}var o=r instanceof Date?r:new Date(r),a=t instanceof Date?t:new Date(t),i=function(r){var t,e,n=Math.abs(r);return n<60?(e="second",t=Math.round(r)):n<3600?(e="minute",t=Math.round(r/60)):n<86400?(e="hour",t=Math.round(r/3600)):n<604800?(e="day",t=Math.round(r/86400)):n<2628e3?(e="week",t=Math.round(r/604800)):n<31536e3?(e="month",t=Math.round(r/2628e3)):(e="year",t=Math.round(r/31536e3)),{value:t,unit:e}}((o.getTime()-a.getTime())/1e3),c=i.unit,f=i.value;return new Intl.RelativeTimeFormat(e,{numeric:"auto"}).format(f,c)}catch(t){return u(new v(exports.IntlErrorCode.FORMATTING_ERROR,t.message)),String(r)}}}},exports.useNow=function(r){var e=null==r?void 0:r.updateInterval,n=d().now,o=t.useState(n||E()),u=o[0],a=o[1];return t.useEffect((function(){if(e){var r=setInterval((function(){a(E())}));return function(){clearInterval(r)}}}),[n,e]),u},exports.useTranslations=function(r){var e=d(),u=e.formats,a=e.getMessageFallback,i=e.locale,c=e.messages,f=e.onError,l=t.useRef({}),s=t.useMemo((function(){try{var t=r?I(c,r):c;if(!t)throw new Error(void 0);return t}catch(r){var e=new v(exports.IntlErrorCode.MISSING_MESSAGE,r.message);return f(e),e}}),[c,r,f]);return t.useCallback((function(e,c,p){var d,E=l.current;function m(t,n){var o=new v(t,n);return f(o),a({error:o,key:e,namespace:r})}if(s instanceof v)return a({error:s,key:e,namespace:r});var y,h=s;if(null!=(d=E[i])&&d[e])y=E[i][e];else{var M;try{M=I(h,e)}catch(r){return m(exports.IntlErrorCode.MISSING_MESSAGE,r.message)}if("object"==typeof M)return m(exports.IntlErrorCode.INSUFFICIENT_PATH,void 0);try{y=new n(M,i,function(r){return o({},r,{date:null==r?void 0:r.dateTime,time:null==r?void 0:r.dateTime})}(o({},u,p)))}catch(r){return m(exports.IntlErrorCode.INVALID_MESSAGE,r.message)}E[i]||(E[i]={}),E[i][e]=y}try{var S=y.format(function(r){if(!r)return r;var e={};return Object.keys(r).forEach((function(n){var o=r[n];e[n]="function"==typeof o?function(r){var e=o(r);return t.isValidElement(e)?t.cloneElement(e,{key:e.key||n+String(r)}):e}:o})),e}(c));if(null==S)throw new Error(void 0);return S}catch(r){return m(exports.IntlErrorCode.FORMATTING_ERROR,r.message)}}),[a,u,i,s,r,f])}; | ||
//# sourceMappingURL=use-intl.cjs.production.min.js.map |
@@ -1,18 +0,202 @@ | ||
import React, { createContext, useContext, useRef, useMemo, isValidElement, cloneElement } from 'react'; | ||
import React, { createContext, useContext, useRef, useMemo, useCallback, isValidElement, cloneElement, useState, useEffect } from 'react'; | ||
import IntlMessageFormat from 'intl-messageformat'; | ||
function _extends() { | ||
_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; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
var IntlContext = /*#__PURE__*/createContext(undefined); | ||
function IntlProvider(_ref) { | ||
var children = _ref.children, | ||
locale = _ref.locale, | ||
messages = _ref.messages; | ||
function defaultGetMessageFallback(_ref) { | ||
var key = _ref.key, | ||
namespace = _ref.namespace; | ||
return [namespace, key].filter(function (part) { | ||
return part != null; | ||
}).join('.'); | ||
} | ||
function IntlProvider(_ref2) { | ||
var children = _ref2.children, | ||
_ref2$onError = _ref2.onError, | ||
onError = _ref2$onError === void 0 ? console.error : _ref2$onError, | ||
_ref2$getMessageFallb = _ref2.getMessageFallback, | ||
getMessageFallback = _ref2$getMessageFallb === void 0 ? defaultGetMessageFallback : _ref2$getMessageFallb, | ||
contextValues = _objectWithoutPropertiesLoose(_ref2, ["children", "onError", "getMessageFallback"]); | ||
return React.createElement(IntlContext.Provider, { | ||
value: { | ||
messages: messages, | ||
locale: locale | ||
} | ||
value: _extends({}, contextValues, { | ||
onError: onError, | ||
getMessageFallback: getMessageFallback | ||
}) | ||
}, children); | ||
} | ||
var IntlErrorCode; | ||
(function (IntlErrorCode) { | ||
IntlErrorCode["MISSING_MESSAGE"] = "MISSING_MESSAGE"; | ||
IntlErrorCode["MISSING_FORMAT"] = "MISSING_FORMAT"; | ||
IntlErrorCode["INSUFFICIENT_PATH"] = "INSUFFICIENT_PATH"; | ||
IntlErrorCode["INVALID_MESSAGE"] = "INVALID_MESSAGE"; | ||
IntlErrorCode["FORMATTING_ERROR"] = "FORMATTING_ERROR"; | ||
})(IntlErrorCode || (IntlErrorCode = {})); | ||
var IntlError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(IntlError, _Error); | ||
function IntlError(code, originalMessage) { | ||
var _this; | ||
var message = code; | ||
if (originalMessage) { | ||
message += ': ' + originalMessage; | ||
} | ||
_this = _Error.call(this, message) || this; | ||
_this.code = code; | ||
if (originalMessage) { | ||
_this.originalMessage = originalMessage; | ||
} | ||
return _this; | ||
} | ||
return IntlError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* `intl-messageformat` uses separate keys for `date` and `time`, but there's | ||
* only one native API: `Intl.DateTimeFormat`. Additionally you might want to | ||
* include both a time and a date in a value, therefore the separation doesn't | ||
* seem so useful. We offer a single `dateTime` namespace instead, but we have | ||
* to convert the format before `intl-messageformat` can be used. | ||
*/ | ||
function convertFormatsToIntlMessageFormat(formats) { | ||
return _extends({}, formats, { | ||
date: formats == null ? void 0 : formats.dateTime, | ||
time: formats == null ? void 0 : formats.dateTime | ||
}); | ||
} | ||
function useIntlContext() { | ||
@@ -22,7 +206,3 @@ var context = useContext(IntlContext); | ||
if (!context) { | ||
if (process.env.NODE_ENV !== "production") { | ||
throw new Error('No context found. Have you configured the provider?'); | ||
} else { | ||
throw new Error(); | ||
} | ||
throw new Error(process.env.NODE_ENV !== "production" ? 'No intl context found. Have you configured the provider?' : undefined); | ||
} | ||
@@ -33,8 +213,7 @@ | ||
function useLocale() { | ||
var context = useIntlContext(); | ||
return context.locale; | ||
} | ||
function resolvePath(messages, idPath, namespace) { | ||
if (!messages) { | ||
throw new Error(process.env.NODE_ENV !== "production" ? "No messages available at `" + namespace + "`." : undefined); | ||
} | ||
function resolvePath(messages, idPath) { | ||
var message = messages; | ||
@@ -44,6 +223,4 @@ idPath.split('.').forEach(function (part) { | ||
if (process.env.NODE_ENV !== "production") { | ||
if (part == null || next == null) { | ||
throw new Error("Could not resolve `" + idPath + "` in `" + JSON.stringify(messages, null, 2) + "`."); | ||
} | ||
if (part == null || next == null) { | ||
throw new Error(process.env.NODE_ENV !== "production" ? "Could not resolve `" + idPath + "` in " + (namespace ? "`" + namespace + "`" : 'messages') + "." : undefined); | ||
} | ||
@@ -80,29 +257,38 @@ | ||
/** | ||
* Translates messages from the given path by using the ICU syntax. | ||
* Translates messages from the given namespace by using the ICU syntax. | ||
* See https://formatjs.io/docs/core-concepts/icu-syntax. | ||
* | ||
* If no path is provided, all available messages are returned. | ||
* | ||
* The path can also indicate nesting by using a dot (e.g. `namespace.Component`). | ||
* If no namespace is provided, all available messages are returned. | ||
* The namespace can also indicate nesting by using a dot | ||
* (e.g. `namespace.Component`). | ||
*/ | ||
function useTranslations(path) { | ||
var context = useIntlContext(); | ||
var locale = useLocale(); | ||
function useTranslations(namespace) { | ||
var _useIntlContext = useIntlContext(), | ||
globalFormats = _useIntlContext.formats, | ||
getMessageFallback = _useIntlContext.getMessageFallback, | ||
locale = _useIntlContext.locale, | ||
allMessages = _useIntlContext.messages, | ||
onError = _useIntlContext.onError; | ||
var cachedFormatsByLocaleRef = useRef({}); | ||
var allMessages = context.messages; | ||
var messages = useMemo(function () { | ||
return path ? resolvePath(allMessages, path) : allMessages; | ||
}, [allMessages, path]); | ||
var messagesOrError = useMemo(function () { | ||
try { | ||
var retrievedMessages = namespace ? resolvePath(allMessages, namespace) : allMessages; | ||
if (process.env.NODE_ENV !== "production") { | ||
if (!messages) { | ||
throw new Error("No messages for component `" + path + "` found."); | ||
if (!retrievedMessages) { | ||
throw new Error(process.env.NODE_ENV !== "production" ? "No messages for namespace `" + namespace + "` found." : undefined); | ||
} | ||
return retrievedMessages; | ||
} catch (error) { | ||
var intlError = new IntlError(IntlErrorCode.MISSING_MESSAGE, error.message); | ||
onError(intlError); | ||
return intlError; | ||
} | ||
} | ||
function translate( | ||
}, [allMessages, namespace, onError]); | ||
var translate = useCallback(function ( | ||
/** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */ | ||
idPath, | ||
key, | ||
/** Key value pairs for values to interpolate into the message. */ | ||
@@ -115,18 +301,45 @@ values, | ||
var cachedFormatsByLocale = cachedFormatsByLocaleRef.current; | ||
function getFallbackFromError(code, message) { | ||
var error = new IntlError(code, message); | ||
onError(error); | ||
return getMessageFallback({ | ||
error: error, | ||
key: key, | ||
namespace: namespace | ||
}); | ||
} | ||
if (messagesOrError instanceof IntlError) { | ||
// We have already warned about this during render | ||
return getMessageFallback({ | ||
error: messagesOrError, | ||
key: key, | ||
namespace: namespace | ||
}); | ||
} | ||
var messages = messagesOrError; | ||
var messageFormat; | ||
if ((_cachedFormatsByLocal = cachedFormatsByLocale[locale]) != null && _cachedFormatsByLocal[idPath]) { | ||
messageFormat = cachedFormatsByLocale[locale][idPath]; | ||
if ((_cachedFormatsByLocal = cachedFormatsByLocale[locale]) != null && _cachedFormatsByLocal[key]) { | ||
messageFormat = cachedFormatsByLocale[locale][key]; | ||
} else { | ||
var message = resolvePath(messages, idPath); | ||
var message; | ||
try { | ||
message = resolvePath(messages, key, namespace); | ||
} catch (error) { | ||
return getFallbackFromError(IntlErrorCode.MISSING_MESSAGE, error.message); | ||
} | ||
if (typeof message === 'object') { | ||
if (process.env.NODE_ENV !== "production") { | ||
throw new Error("Insufficient path specified for `" + idPath + "` in `" + path + "`."); | ||
} else { | ||
throw new Error(); | ||
} | ||
return getFallbackFromError(IntlErrorCode.INSUFFICIENT_PATH, process.env.NODE_ENV !== "production" ? "Insufficient path specified for `" + key + "` in `" + namespace + "`." : undefined); | ||
} | ||
messageFormat = new IntlMessageFormat(message, locale, formats); | ||
try { | ||
messageFormat = new IntlMessageFormat(message, locale, convertFormatsToIntlMessageFormat(_extends({}, globalFormats, formats))); | ||
} catch (error) { | ||
return getFallbackFromError(IntlErrorCode.INVALID_MESSAGE, error.message); | ||
} | ||
@@ -137,16 +350,17 @@ if (!cachedFormatsByLocale[locale]) { | ||
cachedFormatsByLocale[locale][idPath] = messageFormat; | ||
cachedFormatsByLocale[locale][key] = messageFormat; | ||
} | ||
var formattedMessage = messageFormat.format(prepareTranslationValues(values)); | ||
try { | ||
var formattedMessage = messageFormat.format(prepareTranslationValues(values)); | ||
if (process.env.NODE_ENV !== "production") { | ||
if (formattedMessage === undefined) { | ||
throw new Error("Unable to format " + path + "." + idPath); | ||
if (formattedMessage == null) { | ||
throw new Error(process.env.NODE_ENV !== "production" ? "Unable to format " + [namespace, key].join('.') : undefined); | ||
} | ||
return formattedMessage; | ||
} catch (error) { | ||
return getFallbackFromError(IntlErrorCode.FORMATTING_ERROR, error.message); | ||
} | ||
return formattedMessage; | ||
} | ||
}, [getMessageFallback, globalFormats, locale, messagesOrError, namespace, onError]); | ||
return translate; | ||
@@ -198,26 +412,101 @@ } | ||
function useIntl() { | ||
var locale = useLocale(); | ||
var _useIntlContext = useIntlContext(), | ||
formats = _useIntlContext.formats, | ||
locale = _useIntlContext.locale, | ||
globalNow = _useIntlContext.now, | ||
onError = _useIntlContext.onError, | ||
timeZone = _useIntlContext.timeZone; | ||
function formatDateTime(value, options) { | ||
return new Intl.DateTimeFormat(locale, options).format(value); | ||
function resolveFormatOrOptions(typeFormats, formatOrOptions) { | ||
var options; | ||
if (typeof formatOrOptions === 'string') { | ||
var formatName = formatOrOptions; | ||
options = typeFormats == null ? void 0 : typeFormats[formatName]; | ||
if (!options) { | ||
var error = new IntlError(IntlErrorCode.MISSING_FORMAT, process.env.NODE_ENV !== "production" ? "Format `" + formatName + "` is not available. You can configure it on the provider or provide custom options." : undefined); | ||
onError(error); | ||
throw error; | ||
} | ||
} else { | ||
options = formatOrOptions; | ||
} | ||
return options; | ||
} | ||
function formatNumber(value, options) { | ||
return new Intl.NumberFormat(locale, options).format(value); | ||
function getFormattedValue(value, formatOrOptions, typeFormats, formatter) { | ||
var options; | ||
try { | ||
options = resolveFormatOrOptions(typeFormats, formatOrOptions); | ||
} catch (error) { | ||
return String(value); | ||
} | ||
try { | ||
return formatter(options); | ||
} catch (error) { | ||
onError(new IntlError(IntlErrorCode.FORMATTING_ERROR, error.message)); | ||
return String(value); | ||
} | ||
} | ||
function formatRelativeTime(date, now) { | ||
var dateDate = date instanceof Date ? date : new Date(date); | ||
var nowDate = now instanceof Date ? now : new Date(now); | ||
var seconds = (dateDate.getTime() - nowDate.getTime()) / 1000; | ||
function formatDateTime( | ||
/** If a number is supplied, this is interpreted as a UTC timestamp. */ | ||
value, | ||
/** If a time zone is supplied, the `value` is converted to that time zone. | ||
* Otherwise the user time zone will be used. */ | ||
formatOrOptions) { | ||
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.dateTime, function (options) { | ||
var _options; | ||
var _getRelativeTimeForma = getRelativeTimeFormatConfig(seconds), | ||
unit = _getRelativeTimeForma.unit, | ||
value = _getRelativeTimeForma.value; | ||
if (timeZone && !((_options = options) != null && _options.timeZone)) { | ||
options = _extends({}, options, { | ||
timeZone: timeZone | ||
}); | ||
} | ||
return new Intl.RelativeTimeFormat(locale, { | ||
numeric: 'auto' | ||
}).format(value, unit); | ||
return new Intl.DateTimeFormat(locale, options).format(value); | ||
}); | ||
} | ||
function formatNumber(value, formatOrOptions) { | ||
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.number, function (options) { | ||
return new Intl.NumberFormat(locale, options).format(value); | ||
}); | ||
} | ||
function formatRelativeTime( | ||
/** The date time that needs to be formatted. */ | ||
date, | ||
/** The reference point in time to which `date` will be formatted in relation to. */ | ||
now) { | ||
try { | ||
if (!now) { | ||
if (globalNow) { | ||
now = globalNow; | ||
} else { | ||
throw new Error(process.env.NODE_ENV !== "production" ? "The `now` parameter wasn't provided to `formatRelativeTime` and there was no global fallback configured on the provider." : undefined); | ||
} | ||
} | ||
var dateDate = date instanceof Date ? date : new Date(date); | ||
var nowDate = now instanceof Date ? now : new Date(now); | ||
var seconds = (dateDate.getTime() - nowDate.getTime()) / 1000; | ||
var _getRelativeTimeForma = getRelativeTimeFormatConfig(seconds), | ||
unit = _getRelativeTimeForma.unit, | ||
value = _getRelativeTimeForma.value; | ||
return new Intl.RelativeTimeFormat(locale, { | ||
numeric: 'auto' | ||
}).format(value, unit); | ||
} catch (error) { | ||
onError(new IntlError(IntlErrorCode.FORMATTING_ERROR, error.message)); | ||
return String(date); | ||
} | ||
} | ||
return { | ||
@@ -230,3 +519,48 @@ formatDateTime: formatDateTime, | ||
export { IntlProvider, useIntl, useTranslations }; | ||
function getNow() { | ||
return new Date(); | ||
} | ||
/** | ||
* Reading the current date via `new Date()` in components should be avoided, as | ||
* it causes components to be impure and can lead to flaky tests. Instead, this | ||
* hook can be used. | ||
* | ||
* By default, it returns the time when the component mounts. If `updateInterval` | ||
* is specified, the value will be updated based on the interval. | ||
* | ||
* You can however also return a static value from this hook, if you | ||
* configure the `now` parameter on the context provider. Note however, | ||
* that if `updateInterval` is configured in this case, the component | ||
* will initialize with the global value, but will afterwards update | ||
* continuously based on the interval. | ||
* | ||
* For unit tests, this can be mocked to a constant value. For end-to-end | ||
* testing, an environment parameter can be passed to the `now` parameter | ||
* of the provider to mock this to a static value. | ||
*/ | ||
function useNow(options) { | ||
var updateInterval = options == null ? void 0 : options.updateInterval; | ||
var _useIntlContext = useIntlContext(), | ||
globalNow = _useIntlContext.now; | ||
var _useState = useState(globalNow || getNow()), | ||
now = _useState[0], | ||
setNow = _useState[1]; | ||
useEffect(function () { | ||
if (!updateInterval) return; | ||
var intervalId = setInterval(function () { | ||
setNow(getNow()); | ||
}); | ||
return function () { | ||
clearInterval(intervalId); | ||
}; | ||
}, [globalNow, updateInterval]); | ||
return now; | ||
} | ||
export { IntlError, IntlErrorCode, IntlProvider, useIntl, useNow, useTranslations }; | ||
//# sourceMappingURL=use-intl.esm.js.map |
@@ -0,5 +1,6 @@ | ||
import DateTimeFormatOptions from './DateTimeFormatOptions'; | ||
export default function useIntl(): { | ||
formatDateTime: (value: number | Date, options?: Intl.DateTimeFormatOptions | undefined) => string; | ||
formatNumber: (value: number, options?: Intl.NumberFormatOptions | undefined) => string; | ||
formatRelativeTime: (date: number | Date, now: number | Date) => string; | ||
formatDateTime: (value: Date | number, formatOrOptions?: string | DateTimeFormatOptions | undefined) => string; | ||
formatNumber: (value: number, formatOrOptions?: string | Intl.NumberFormatOptions | undefined) => string; | ||
formatRelativeTime: (date: number | Date, now?: number | Date | undefined) => string; | ||
}; |
@@ -1,4 +0,1 @@ | ||
export default function useIntlContext(): { | ||
messages: import("./IntlMessages").default; | ||
locale: string; | ||
}; | ||
export default function useIntlContext(): import("./IntlContext").IntlContextShape; |
@@ -1,11 +0,11 @@ | ||
import { Formats } from 'intl-messageformat'; | ||
import { ReactNode } from 'react'; | ||
import Formats from './Formats'; | ||
/** | ||
* Translates messages from the given path by using the ICU syntax. | ||
* Translates messages from the given namespace by using the ICU syntax. | ||
* See https://formatjs.io/docs/core-concepts/icu-syntax. | ||
* | ||
* If no path is provided, all available messages are returned. | ||
* | ||
* The path can also indicate nesting by using a dot (e.g. `namespace.Component`). | ||
* If no namespace is provided, all available messages are returned. | ||
* The namespace can also indicate nesting by using a dot | ||
* (e.g. `namespace.Component`). | ||
*/ | ||
export default function useTranslations(path?: string): (idPath: string, values?: Record<string, string | number | boolean | Date | ((children: ReactNode) => ReactNode) | null | undefined> | undefined, formats?: Partial<Formats> | undefined) => string | number | boolean | {} | import("react").ReactElement<any, string | ((props: any) => import("react").ReactElement<any, string | any | (new (props: any) => import("react").Component<any, any, any>)> | null) | (new (props: any) => import("react").Component<any, any, any>)> | import("react").ReactNodeArray | import("react").ReactPortal | (string | number | boolean | {} | import("react").ReactElement<any, string | ((props: any) => import("react").ReactElement<any, string | any | (new (props: any) => import("react").Component<any, any, any>)> | null) | (new (props: any) => import("react").Component<any, any, any>)> | import("react").ReactNodeArray | import("react").ReactPortal | null)[] | null; | ||
export default function useTranslations(namespace?: string): (key: string, values?: Record<string, string | number | boolean | Date | ((children: ReactNode) => ReactNode) | null | undefined> | undefined, formats?: Partial<Formats> | undefined) => {}; |
{ | ||
"name": "use-intl", | ||
"version": "0.1.0", | ||
"version": "0.1.1-alpha.31+dfafd51", | ||
"sideEffects": false, | ||
@@ -36,2 +36,3 @@ "author": "Jan Amann <jan@amann.me>", | ||
"@types/react": "^16.9.56", | ||
"date-fns": "^2.16.1", | ||
"eslint": "7.4.0", | ||
@@ -47,3 +48,4 @@ "eslint-config-molindo": "5.0.1", | ||
"node": ">=10" | ||
} | ||
}, | ||
"gitHead": "dfafd51e5f6297114eeb3266a4d731447ff7ddb7" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
154704
37
1780
10
9
2