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

react-i18nify

Package Overview
Dependencies
Maintainers
2
Versions
131
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-i18nify - npm Package Compare versions

Comparing version 2.0.0-1 to 2.0.0-2

build/lib/core.js

30

build/index.js

@@ -7,11 +7,2 @@ 'use strict';

var _I18n = require('./lib/I18n');
Object.defineProperty(exports, 'I18n', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_I18n).default;
}
});
var _Translate = require('./lib/Translate');

@@ -35,2 +26,23 @@

var _I18n = require('./lib/I18n');
Object.defineProperty(exports, 'I18n', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_I18n).default;
}
});
var _core = require('./lib/core');
Object.keys(_core).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _core[key];
}
});
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -7,9 +7,4 @@ 'use strict';

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; }; /* eslint global-require: "off" */
/* eslint no-console: "off" */
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 _intl = require('intl');
var _intl2 = _interopRequireDefault(_intl);
var _react = require('react');

@@ -19,14 +14,6 @@

var _parse = require('date-fns/parse');
var _propTypes = require('prop-types');
var _parse2 = _interopRequireDefault(_parse);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _format = require('date-fns/format');
var _format2 = _interopRequireDefault(_format);
var _locale = require('date-fns/locale');
var _locale2 = _interopRequireDefault(_locale);
var _Base = require('./Base');

@@ -38,152 +25,32 @@

exports.default = {
_localeKey: 'en',
_localeObject: _locale2.default.enUS,
_translationsObject: {},
_getTranslations: null,
_getLocale: null,
_handleMissingTranslation: function _handleMissingTranslation(text) {
return text.split('.').pop();
},
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
get _translations() {
return this._getTranslations ? this._getTranslations() : this._translationsObject;
},
function _possibleConstructorReturn(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; }
set _translations(translations) {
this._translationsObject = translations;
},
function _inherits(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; }
get _locale() {
return this._getLocale ? this._getLocale() : this._localeKey;
},
var I18n = function (_BaseComponent) {
_inherits(I18n, _BaseComponent);
set _locale(locale) {
this._localeKey = locale;
this._localeObject = _locale2.default[locale] || _locale2.default.enUS;
},
function I18n() {
_classCallCheck(this, I18n);
setLocale: function setLocale(locale) {
var rerenderComponents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return _possibleConstructorReturn(this, (I18n.__proto__ || Object.getPrototypeOf(I18n)).apply(this, arguments));
}
this._locale = locale;
if (rerenderComponents) {
this.forceComponentsUpdate();
}
},
setTranslations: function setTranslations(translations) {
var rerenderComponents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
this._translations = translations;
if (rerenderComponents) {
this.forceComponentsUpdate();
}
},
setTranslationsGetter: function setTranslationsGetter(fn) {
if (typeof fn !== 'function') {
throw new Error('Translations getter must be a function');
}
this._getTranslations = fn;
},
setLocaleGetter: function setLocaleGetter(fn) {
if (typeof fn !== 'function') {
throw new Error('Locale getter must be a function');
}
this._getLocale = fn;
},
setHandleMissingTranslation: function setHandleMissingTranslation(fn) {
if (typeof fn !== 'function') {
throw new Error('Handle missing translation must be a function');
}
this._handleMissingTranslation = fn;
},
t: function t(key) {
var replacements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this._translate(key, replacements);
},
l: function l(value, options) {
return this._localize(value, options);
},
_replace: function _replace(translation, replacements) {
var _this = this;
if (typeof translation === 'string') {
var result = translation;
Object.keys(replacements).forEach(function (replacement) {
result = result.split('%{' + replacement + '}').join(replacements[replacement]);
_createClass(I18n, [{
key: 'render',
value: function render() {
return _react2.default.Children.map(this.props.children, function (child) {
return _react2.default.cloneElement(child);
});
return result;
}
if (_react2.default.isValidElement(translation)) {
return translation;
}
if ((typeof translation === 'undefined' ? 'undefined' : _typeof(translation)) === 'object') {
var _result = {};
Object.keys(translation).forEach(function (translationKey) {
_result[translationKey] = _this._replace(translation[translationKey], replacements);
});
return _result;
}
return null;
},
_translate: function _translate(key) {
var replacements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
}]);
var translation = '';
try {
var translationLocale = this._translations[this._locale] ? this._locale : this._locale.split('-')[0];
translation = this._fetchTranslation(this._translations, translationLocale + '.' + key, replacements.count);
} catch (err) {
return this._handleMissingTranslation(key, replacements);
}
return this._replace(translation, replacements);
},
_localize: function _localize(value) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return I18n;
}(_Base2.default);
if (options.dateFormat) {
var parsedDate = options.parseFormat ? (0, _parse2.default)(value, options.parseFormat, new Date(), { locale: this._localeObject }) : value;
return (0, _format2.default)(parsedDate, this.t(options.dateFormat), { locale: this._localeObject });
}
if (typeof value === 'number') {
if (global.Intl) {
if (!(Intl.NumberFormat && Intl.NumberFormat.supportedLocalesOf(this._locale).length === 1)) {
Intl.NumberFormat = _intl2.default.NumberFormat;
}
} else {
global.Intl = _intl2.default;
}
return new Intl.NumberFormat(this._locale, options).format(value);
}
return value;
},
_fetchTranslation: function _fetchTranslation(translations, key) {
var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var _index = key.indexOf('.');
if (typeof translations === 'undefined') {
throw new Error('not found');
}
if (_index > -1) {
return this._fetchTranslation(translations[key.substring(0, _index)], key.substr(_index + 1), count);
}
if (count !== null) {
if (translations[key + '_' + count]) {
// when key = 'items_3' if count is 3
return translations[key + '_' + count];
}
if (count !== 1 && translations[key + '_plural']) {
// when count is not simply singular, return _plural
return translations[key + '_plural'];
}
}
if (translations[key]) {
return translations[key];
}
throw new Error('not found');
},
forceComponentsUpdate: function forceComponentsUpdate() {
_Base2.default.rerenderAll();
}
};
I18n.propTypes = {
children: _propTypes2.default.node
};
exports.default = I18n;

@@ -19,6 +19,4 @@ 'use strict';

var _I18n = require('./I18n');
var _ = require('../');
var _I18n2 = _interopRequireDefault(_I18n);
var _Base = require('./Base');

@@ -55,3 +53,3 @@

var localization = _I18n2.default._localize(value, _extends({}, options, { dateFormat: dateFormat, parseFormat: parseFormat }));
var localization = (0, _.l)(value, _extends({}, options, { dateFormat: dateFormat, parseFormat: parseFormat }));

@@ -71,6 +69,6 @@ return _react2.default.createElement(

value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.object]).isRequired,
options: _propTypes2.default.object,
dateFormat: _propTypes2.default.string,
parseFormat: _propTypes2.default.string
parseFormat: _propTypes2.default.string,
options: _propTypes2.default.object
};
exports.default = Localize;

@@ -17,6 +17,4 @@ 'use strict';

var _I18n = require('./I18n');
var _ = require('../');
var _I18n2 = _interopRequireDefault(_I18n);
var _Base = require('./Base');

@@ -52,3 +50,3 @@

var translation = _I18n2.default._translate(value, otherProps);
var translation = (0, _.t)(value, otherProps);

@@ -55,0 +53,0 @@ return _react2.default.createElement(

@@ -12,5 +12,7 @@ const React = require('react');

const { I18n, Translate, Localize } = ReactI18nfiy;
const {
setTranslations, setLocale, setHandleMissingTranslation, t, l, Translate, Localize, I18n,
} = ReactI18nfiy;
I18n.setTranslations({
setTranslations({
en: {

@@ -44,12 +46,12 @@ application: {

I18n.setLocale('nl');
setLocale('nl');
console.log(I18n.t('application.title'));
console.log(I18n.t('application.hello', { name: 'Aad' }));
console.log(I18n.t('export', { count: 0 }));
console.log(I18n.t('application.unknown_translation'));
console.log(I18n.t('application', { name: 'Aad' }));
console.log(t('application.title'));
console.log(t('application.hello', { name: 'Aad' }));
console.log(t('export', { count: 0 }));
console.log(t('application.unknown_translation'));
console.log(t('application', { name: 'Aad' }));
console.log(I18n.l(1385856000000, { dateFormat: 'date.long' }));
console.log(I18n.l(Math.PI, { maximumFractionDigits: 2 }));
console.log(l(1385856000000, { dateFormat: 'date.long' }));
console.log(l(Math.PI, { maximumFractionDigits: 2 }));

@@ -60,5 +62,5 @@ function myHandleMissingTranslation(key, replacements) {

I18n.setHandleMissingTranslation(myHandleMissingTranslation);
setHandleMissingTranslation(myHandleMissingTranslation);
console.log(I18n.t('application.unknown_translation'));
console.log(t('application.unknown_translation'));

@@ -65,0 +67,0 @@ function AwesomeComponent() {

{
"name": "react-i18nify",
"version": "2.0.0-1",
"version": "2.0.0-2",
"description": "Simple i18n translation and localization components and helpers for React applications.",
"main": "./build/index.js",
"scripts": {
"test": "jest --colors --env=jsdom",
"test": "jest --verbose",
"test:watch": "npm test -- --watch",

@@ -16,5 +16,2 @@ "lint": "eslint src/**/*.jsx src/**/*.js __tests__/**/*.js",

},
"jest": {
"verbose": true
},
"files": [

@@ -21,0 +18,0 @@ "build",

@@ -31,5 +31,5 @@ # react-i18nify

```javascript
const { I18n } = require('react-i18nify');
const { setTranslations, setLocale } = require('react-i18nify');
I18n.setTranslations({
setTranslations({
en: {

@@ -63,3 +63,3 @@ application: {

I18n.setLocale('nl');
setLocale('nl');
```

@@ -97,54 +97,65 @@

If for some reason, you cannot use the components, you can use the `I18n.t` and `I18n.l` helpers instead.
These helpers however will not be re-rendered automatically in any way, so if you use those, it's up to you to handle state change.
If for some reason, you cannot use the components, you can use the `t` and `l` helpers instead.
```javascript
const { I18n } = require('react-i18nify');
const { t, l } = require('react-i18nify');
I18n.t('application.title');
t('application.title');
// => Toffe app met i18n!
I18n.t('application.hello', {name: 'Aad'});
t('application.hello', {name: 'Aad'});
// => Hallo, Aad!'
I18n.t('export', {count: 0});
t('export', {count: 0});
// => Niks te exporteren
I18n.t('application.unknown_translation');
t('application.unknown_translation');
// => unknown_translation
I18n.t('application', {name: 'Aad'});
t('application', {name: 'Aad'});
// => {hello: 'Hallo, Aad!', title: 'Toffe app met i18n!'}
I18n.l(1385856000000, { dateFormat: 'date.long' });
l(1385856000000, { dateFormat: 'date.long' });
// => 1 december 2013
I18n.l(Math.PI, { maximumFractionDigits: 2 });
l(Math.PI, { maximumFractionDigits: 2 });
// => 3,14
```
## API Reference
If you want these helpers to be re-rendered automatically when the locale or translations change, you have to wrap them in a `<I18n>` component.
### `I18n`
```javascript
const { I18n, t } = require('react-i18nify');
Main module for handling all configurations and translations, with the following functions:
<I18n><input placeholder={t("application.title")} /></I18n>
```
#### `setLocale(locale, rerenderComponents = true)`
## API Reference
### `setLocale(locale, rerenderComponents = true)`
The used locale can be set with this function. By default, changing the locale will re-render all components.
This behavior can be prevented by providing `false` as a second argument.
#### `setTranslations(translations, rerenderComponents = true)`
### `getLocale()`
Get the currently used locale.
### `setTranslations(translations, rerenderComponents = true)`
The used translations can be set with this function. By default, changing the translations will re-render all components.
This behavior can be prevented by providing `false` as a second argument.
#### `setLocaleGetter(fn)`
### `getTranslations()`
Get the currently used translations.
### `setLocaleGetter(fn)`
Alternatively to using `setLocale`, you can provide a callback to return the locale with `setLocaleGetter`:
```javascript
const { I18n } = require('react-i18nify');
const { setLocaleGetter } = require('react-i18nify');
const locale = () => 'nl';
I18n.setLocaleGetter(locale);
setLocaleGetter(locale);
```
#### `setTranslationsGetter(fn)`
### `setTranslationsGetter(fn)`

@@ -154,3 +165,3 @@ Alternatively to using `setTranslations`, you can provide a callback to return the translations with `setTranslationsGetter`:

```javascript
const { I18n } = require('react-i18nify');
const { setTranslationsGetter } = require('react-i18nify');

@@ -162,27 +173,27 @@ const translation = () => ({

I18n.setTranslationsGetter(translation);
setTranslationsGetter(translation);
```
#### `setHandleMissingTranslation(fn)`
### `setHandleMissingTranslation(fn)`
By default, when a translation is missing, the translation key will be returned in a slightly formatted way,
as can be seen in the `I18n.t('application.unknown_translation');` example above.
as can be seen in the `t('application.unknown_translation');` example above.
You can however overwrite this behavior by setting a function to handle missing translations.
```javascript
const { I18n } = require('react-i18nify');
const { setHandleMissingTranslation, t } = require('react-i18nify');
const myHandleMissingTranslation = (key, replacements) => `Missing translation: ${key}`;
I18n.setHandleMissingTranslation(myHandleMissingTranslation);
setHandleMissingTranslation(myHandleMissingTranslation);
I18n.t('application.unknown_translation');
t('application.unknown_translation');
// => Missing translation: application.unknown_translation
```
#### `t(key, replacements = {})`
### `t(key, replacements = {})`
Helper function to translate a `key`, given an optional set of `replacements`. See the above Helpers section for examples.
#### `l(value, options)`
### `l(value, options)`

@@ -199,3 +210,3 @@ Helper function to localize a `value`, given a set of `options`. See the above Helpers section for examples.

#### `forceComponentsUpdate()`
### `forceComponentsUpdate()`

@@ -239,2 +250,11 @@ This function can be called to force a re-render of all I18n components.

### `<I18n>`
React I18n wrapper component, with the following prop:
#### `children` (node)
The children to automatically re-render when the locale or translations change.
[version-image]: https://img.shields.io/npm/v/react-i18nify.svg

@@ -241,0 +261,0 @@ [downloads-image]: https://img.shields.io/npm/dm/react-i18nify.svg

@@ -1,3 +0,4 @@

export { default as I18n } from './lib/I18n';
export { default as Translate } from './lib/Translate';
export { default as Localize } from './lib/Localize';
export { default as I18n } from './lib/I18n';
export * from './lib/core';
import React from 'react';
import PropTypes from 'prop-types';
import I18n from './I18n';
import { l } from '../';
import BaseComponent from './Base';

@@ -12,5 +12,5 @@

PropTypes.object]).isRequired,
options: PropTypes.object,
dateFormat: PropTypes.string,
parseFormat: PropTypes.string,
options: PropTypes.object,
};

@@ -22,3 +22,3 @@

} = this.props;
const localization = I18n._localize(value, { ...options, dateFormat, parseFormat });
const localization = l(value, { ...options, dateFormat, parseFormat });

@@ -25,0 +25,0 @@ return <React.Fragment>{localization}</React.Fragment>;

import React from 'react';
import PropTypes from 'prop-types';
import I18n from './I18n';
import { t } from '../';
import BaseComponent from './Base';

@@ -13,3 +14,3 @@

const { value, ...otherProps } = this.props;
const translation = I18n._translate(value, otherProps);
const translation = t(value, otherProps);

@@ -16,0 +17,0 @@ return <React.Fragment>{translation}</React.Fragment>;

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