Meet npm Pro: unlimited public & private packages + package-based permissions.Learn more »

@ackee/jerome

3.0.0 • Public • Published

ackee|Jerome

GitHub license CI Status PRs Welcome Dependency Status

Jerome

Localization module useful mainly for frontend development in Ackee.

Name of package refers to Saint Jerome the patron of all translators.

Table of contents

Installation

Using yarn:

yarn add @ackee/jerome

Using npm:

npm i -s @ackee/jerome

Usage

All parts are independent, but best works all together. Don't forget that for correct usage of selectors your reducer have to be stored with translate key (as in example).

Used APIs

Jerome uses react-intl@3 which relies on some native browser APIs so if you're going to use components for plurals or relative time format, be sure that your minimal supported browsers implement those APIs or use polyfills as described bellow

For polyfilling plurals, use intl-pluralrules package.

if (!Intl.PluralRules) {
  require('intl-pluralrules');
}

For polyfilling plurals, use intl-relativetimeformat package.

if (!Intl.RelativeTimeFormat) {
  require('@formatjs/intl-relativetimeformat/polyfill');
  require('@formatjs/intl-relativetimeformat/dist/locale-data/de'); // Add locale data for de
}

API

HOC

Important To make HOCs works properly, you must have react-intl installed just once! So be sure your dependencies structure is flat.

translatableFactory(intlLocaleData): (ContentComponent) => TranslatableContentComponent

It provides reac-intl localization context, so you first have to provide localization messages to the factory that will return the actual HOC.

intlLocaleData - object with messages keyed by locale name, eg.

const messages = {
    cs: {
        hello: 'Dobry den',
        ...
    },
    en: {
        hello: 'Hello',
        ...
    },
}

The factory returns function that receives ContentComponent and return it wrapped with IntlProvider which receives locale from the store.translate.locale store path.

Example

import { FormattedMessage, addLocaleData } from 'react-intl';
import { translatableFactory } from '@ackee/jerome';
 
const ContentComponent = () => (
    <div id="app">
        <h1><FormattedMessage id="hello" /></h1>
        <h2><FormattedMessage id="bye.instant" /></h2>
        <h3><FormattedMessage id="bye.forever" /></h3>
    </div>
);
 
const messages = {
    cs: {
        hello: 'Cau',
        'bye.instant': 'Nashledanou',
        'bye.forever': 'Sbohem',
    },
    en: {
        hello: 'Hello',
        'bye.instant': 'See you later',
        'bye.forever': 'Goodbye',
    },
};
 
const store = createStore((state = initialState) => ({
    translate: { locale: 'cs' },
}));
 
TranslatableComponent = translatableFactory(messages)(ContentComponent);
 
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));

translatableWithAntdFactory(intlLocaleData, antdLocaleData): (ContentComponent) => TranslatableContentComponent

If you use Ant design components library, you can use this HOC, which extends the translatableFactory to add antd localization context. Only difference (except the name) is that you have to provide antLocaleData as a second argument to the factory.

intlLocaleData - object with antd locales keyed by locale name. eg.

import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
 
const messages = {
    cs: cs_CZ,
    en: en_US,
}

Returns the same HOC as a translatableFactory, look at the usage example below.

import { FormattedMessage, addLocaleData } from 'react-intl';
 
import { Pagination } from 'antd';
import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
 
import { translatableWithAntdFactory } from '@ackee/jerome';
 
const ContentComponent = () => (
    <div id="app">
        <h1><FormattedMessage id="hello" /></h1>
        <Pagination defaultCurrent={1} total={50} showSizeChanger />
    </div>
);
 
const messages = {
    cs: {
        hello: 'Cau',
    },
    en: {
        hello: 'Hello',
    },
};
 
const antdMessages = {
    cs: cs_CZ,
    en: en_US,
}
 
const store = createStore((state = initialState) => ({
    translate: { locale: 'cs' },
}));
 
TranslatableComponent = translatableWithAntdFactory(messages, antdMessages)(ContentComponent);
 
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));

Actions

setLocale(locale: string)

Example

import { setLocale } from '@ackee/jerome';
 
dispatch(setLocale('cs'));

getLocale

Example

import { getLocale } from '@ackee/jerome';
 
dispatch(getLocale());

Action types

import { actionTypes } from '@ackee/jerome'

Reducer

Reducer is actually reducer factory since you must provide default locale first.

reducer(locale: string): TranslateReducer

Example

import { reducer as translateFactory } from '@ackee/jerome';
 
const translate = translateFactory('cs');
 
const appReducers = combineReducers({
    translate,
    ...
});

Selectors

translateSelector(state: State): { locale: string }

Select translate part of store.

Example

import { translateSelector } from '@ackee/jerome';
 
translateSelector(state); // { locale: 'cs' }

Sagas

saga()

The saga has two purposes, both related to handling persistent storing of locale.

  • It saves locale on every SET_LOCALE action into the persistent storage.
  • It loads locale from persistent storage when app load and set it up.

Example

import { saga as localization } from '@ackee/jerome';
 
const rootSaga = function* () {
    yield all([
        localization(), // plug it into root saga
        ...
    ]);
};
 
function configureStore(initialState) {
    const sagaMiddleware = createSagaMiddleware();
    const middlewares = [sagaMiddleware];
 
    const middleware = applyMiddleware(...middlewares);
 
    const store = createStore(reducer, initialState, enhancer);
    sagaMiddleware.run(rootSaga);
 
    return store;
}

getIntl(): ReactIntl

The getIntl saga returns an intl object that exactly corresponds to the intlShape.

Example

import { getIntl } from '@ackee/jerome';
 
function* mySaga() {
    const intl = yield getIntl();
 
    const translatedMessage = intl.formatMessage({
        id: 'hello'
    });
}

Utilities

saveLocale(locale: string)

Used for persistent store of locale setting.

Example

import { saveLocale } from '@ackee/jerome';
 
saveLocale('cs');

loadLocale(): string

Used for getting locale setting from persistent storage.

Example

import { loadLocale } from '@ackee/jerome';
 
loadLocale(); // 'cs'

localStorageHandlers

Covers both utilities mentioned above.

Example

import { localStorageHandlers } from '@ackee/jerome';
 
localStorageHandlers.saveLocale('en');
localStorageHandlers.loadLocale(); // 'en'

Keywords

none

Install

npm i @ackee/jerome

DownloadsWeekly Downloads

31

Version

3.0.0

License

MIT

Unpacked Size

151 kB

Total Files

64

Last publish

Collaborators

  • avatar
  • avatar
  • avatar