Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

use-intl

Package Overview
Dependencies
Maintainers
1
Versions
241
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-intl - npm Package Compare versions

Comparing version 0.1.0 to 0.2.0

dist/IntlError.d.ts

1

dist/index.d.ts

@@ -6,1 +6,2 @@ export { default as IntlProvider } from './IntlProvider';

export { default as useIntl } from './useIntl';
export { default as IntlError, IntlErrorCode } from './IntlError';
/// <reference types="react" />
import IntlError from './IntlError';
import IntlMessages from './IntlMessages';
declare const IntlContext: import("react").Context<{
export declare type IntlContextShape = {
messages: IntlMessages;
locale: string;
} | undefined>;
onError(error: IntlError): void;
getMessageFallback(info: {
error: IntlError;
key: string;
namespace?: string;
}): string;
};
declare const IntlContext: import("react").Context<IntlContextShape | undefined>;
export default IntlContext;
import { ReactNode } from 'react';
import IntlMessages from './IntlMessages';
import { IntlError } from '.';
declare type Props = {
children: ReactNode;
/** All messages that will be available in your components. */
messages: IntlMessages;
/** A valid Unicode locale tag (e.g. "en" or "en-GB"). */
locale: 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;
};
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,176 @@ '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);
}
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));
function useIntlContext() {

@@ -30,5 +190,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?' );
}

@@ -44,3 +202,3 @@

function resolvePath(messages, idPath) {
function resolvePath(messages, idPath, namespace) {
var message = messages;

@@ -50,6 +208,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,12 +242,12 @@

/**
* 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) {
function useTranslations(namespace) {
var context = useIntlContext();

@@ -101,15 +257,23 @@ var locale = useLocale();

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("MISSING_MESSAGE"
/* MISSING_MESSAGE */
, error.message);
context.onError(intlError);
return intlError;
}
}
}, [allMessages, context, namespace]);
function translate(
/** 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. */

@@ -122,16 +286,51 @@ values,

var cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
function getFallbackFromError(code, message) {
var error = new IntlError(code, message);
context.onError(error);
return context.getMessageFallback({
error: error,
key: key,
namespace: namespace
});
}
if (messagesOrError instanceof IntlError) {
// We have already warned about this during render
return context.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("MISSING_MESSAGE"
/* MISSING_MESSAGE */
, error.message);
}
if (typeof message === 'object') {
{
throw new Error("Insufficient path specified for `" + idPath + "` in `" + path + "`.");
}
return getFallbackFromError("INSUFFICIENT_PATH"
/* INSUFFICIENT_PATH */
, "Insufficient path specified for `" + key + "` in `" + namespace + "`." );
}
messageFormat = new IntlMessageFormat(message, locale, formats);
try {
messageFormat = new IntlMessageFormat(message, locale, formats);
} catch (error) {
return getFallbackFromError("INVALID_MESSAGE"
/* INVALID_MESSAGE */
, error.message);
}

@@ -142,14 +341,18 @@ 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("FORMATTING_ERROR"
/* FORMATTING_ERROR */
, error.message);
}
return formattedMessage;
}

@@ -234,2 +437,3 @@

exports.IntlError = IntlError;
exports.IntlProvider = IntlProvider;

@@ -236,0 +440,0 @@ exports.useIntl = useIntl;

2

dist/use-intl.cjs.production.min.js

@@ -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 e=require("react"),t=r(e),n=r(require("intl-messageformat"));function o(){return(o=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[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,e){return(a=Object.setPrototypeOf||function(r,e){return r.__proto__=e,r})(r,e)}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,e,t){return(c=i()?Reflect.construct:function(r,e,t){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(r,n));return t&&a(o,t.prototype),o}).apply(null,arguments)}function f(r){var e="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!==e){if(e.has(r))return e.get(r);e.set(r,t)}function t(){return c(r,arguments,u(this).constructor)}return t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),a(t,r)})(r)}var l=e.createContext(void 0);function s(r){return[r.namespace,r.key].filter((function(r){return null!=r})).join(".")}var p=function(r){var e,t;function n(e,t){var n,o=e;return t&&(o+=": "+t),(n=r.call(this,o)||this).code=e,t&&(n.originalMessage=t),n}return t=r,(e=n).prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t,n}(f(Error));function v(){var r=e.useContext(l);if(!r)throw new Error(void 0);return r}function y(){return v().locale}function m(r,e,t){var n=r;return e.split(".").forEach((function(r){var e=n[r];if(null==r||null==e)throw new Error(void 0);n=e})),n}exports.IntlError=p,exports.IntlProvider=function(r){var e=r.children,n=r.onError,u=void 0===n?console.error:n,a=r.getMessageFallback,i=void 0===a?s:a,c=function(r,e){if(null==r)return{};var t,n,o={},u=Object.keys(r);for(n=0;n<u.length;n++)e.indexOf(t=u[n])>=0||(o[t]=r[t]);return o}(r,["children","onError","getMessageFallback"]);return t.createElement(l.Provider,{value:o({},c,{onError:u,getMessageFallback:i})},e)},exports.useIntl=function(){var r=y();return{formatDateTime:function(e,t){return new Intl.DateTimeFormat(r,t).format(e)},formatNumber:function(e,t){return new Intl.NumberFormat(r,t).format(e)},formatRelativeTime:function(e,t){var n=e instanceof Date?e:new Date(e),o=t instanceof Date?t:new Date(t),u=function(r){var e,t,n=Math.abs(r);return n<60?(t="second",e=Math.round(r)):n<3600?(t="minute",e=Math.round(r/60)):n<86400?(t="hour",e=Math.round(r/3600)):n<604800?(t="day",e=Math.round(r/86400)):n<2628e3?(t="week",e=Math.round(r/604800)):n<31536e3?(t="month",e=Math.round(r/2628e3)):(t="year",e=Math.round(r/31536e3)),{value:e,unit:t}}((n.getTime()-o.getTime())/1e3),a=u.unit,i=u.value;return new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(i,a)}}},exports.useTranslations=function(r){var t=v(),o=y(),u=e.useRef({}),a=t.messages,i=e.useMemo((function(){try{var e=r?m(a,r):a;if(!e)throw new Error(void 0);return e}catch(r){var n=new p("MISSING_MESSAGE",r.message);return t.onError(n),n}}),[a,t,r]);return function(a,c,f){var l,s=u.current;function v(e,n){var o=new p(e,n);return t.onError(o),t.getMessageFallback({error:o,key:a,namespace:r})}if(i instanceof p)return t.getMessageFallback({error:i,key:a,namespace:r});var y,d=i;if(null!=(l=s[o])&&l[a])y=s[o][a];else{var h;try{h=m(d,a)}catch(r){return v("MISSING_MESSAGE",r.message)}if("object"==typeof h)return v("INSUFFICIENT_PATH",void 0);try{y=new n(h,o,f)}catch(r){return v("INVALID_MESSAGE",r.message)}s[o]||(s[o]={}),s[o][a]=y}try{var g=y.format(function(r){if(!r)return r;var t={};return Object.keys(r).forEach((function(n){var o=r[n];t[n]="function"==typeof o?function(r){var t=o(r);return e.isValidElement(t)?e.cloneElement(t,{key:t.key||n+String(r)}):t}:o})),t}(c));if(null==g)throw new Error(void 0);return g}catch(r){return v("FORMATTING_ERROR",r.message)}}};
//# sourceMappingURL=use-intl.cjs.production.min.js.map
import React, { createContext, useContext, useRef, useMemo, isValidElement, cloneElement } 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 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));
function useIntlContext() {

@@ -22,7 +182,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);
}

@@ -38,3 +194,3 @@

function resolvePath(messages, idPath) {
function resolvePath(messages, idPath, namespace) {
var message = messages;

@@ -44,6 +200,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,12 +234,12 @@

/**
* 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) {
function useTranslations(namespace) {
var context = useIntlContext();

@@ -95,15 +249,23 @@ var locale = useLocale();

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("MISSING_MESSAGE"
/* MISSING_MESSAGE */
, error.message);
context.onError(intlError);
return intlError;
}
}
}, [allMessages, context, namespace]);
function translate(
/** 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. */

@@ -116,18 +278,51 @@ values,

var cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
function getFallbackFromError(code, message) {
var error = new IntlError(code, message);
context.onError(error);
return context.getMessageFallback({
error: error,
key: key,
namespace: namespace
});
}
if (messagesOrError instanceof IntlError) {
// We have already warned about this during render
return context.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("MISSING_MESSAGE"
/* 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("INSUFFICIENT_PATH"
/* 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, formats);
} catch (error) {
return getFallbackFromError("INVALID_MESSAGE"
/* INVALID_MESSAGE */
, error.message);
}

@@ -138,14 +333,18 @@ 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("FORMATTING_ERROR"
/* FORMATTING_ERROR */
, error.message);
}
return formattedMessage;
}

@@ -230,3 +429,3 @@

export { IntlProvider, useIntl, useTranslations };
export { IntlError, IntlProvider, useIntl, useTranslations };
//# sourceMappingURL=use-intl.esm.js.map
export default function useIntlContext(): {
messages: import("./IntlMessages").default;
locale: string;
onError(error: import("./IntlError").default): void;
};
import { Formats } from 'intl-messageformat';
import { ReactNode } from 'react';
/**
* 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.2.0",
"sideEffects": false,

@@ -5,0 +5,0 @@ "author": "Jan Amann <jan@amann.me>",

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc