Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,16 @@


```js
import {createTranslations} from 'use-t';
const {Provider, useT, withT, Trans, Consumer, context} = createTranslations();
import {Provider, useT, withT, Trans, Consumer, context} from 'use-t';
```

- [`createTranslations()`](./docs/createTranslations.md)
- [`<Provider>`](./docs/Provider.md)
- [`useT()`](./docs/useT.md)
- [`withT()`](./docs/withT.md)
- [`<Trans>`](./docs/Trans.md)
- [`<Consumer>`](./docs/Consumer.md)
- [`context`](./docs/context.md)
- [`createTranslations()`](./docs/createTranslations.md)


<br />
Expand All @@ -48,9 +47,7 @@ const {Provider, useT, withT, Trans, Consumer, context} = createTranslations();
<h2 align="center">Example</h2>

```jsx
import {createTranslations} from 'use-t';

const {Provider, useT} = createTranslations();
import {Provider, useT} from 'use-t';

const Hello = (props) => {
const [t] = useT();
Expand Down
2 changes: 1 addition & 1 deletion docs/createTranslations.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Creates translation context, hook, higher order component, and render prop that
can use together to manage translations in your app.

```js
import {createTranslations} from 'use-t';
import createTranslations from 'use-t/lib/createTranslations';

const {
Provider,
Expand Down
2 changes: 1 addition & 1 deletion src/__stories__/Trans.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {createTranslations} from '..';
import createTranslations from '../createTranslations';

const {Provider, Trans} = createTranslations();

Expand Down
2 changes: 1 addition & 1 deletion src/__stories__/interpolations.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {createTranslations} from '..';
import createTranslations from '../createTranslations';

const {Provider, useT} = createTranslations();

Expand Down
57 changes: 57 additions & 0 deletions src/__stories__/precreated.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {Provider, useT} from '..';

const Demo = () => {
const [t, {setLocale}] = useT();
return (
<div>
{t('Hello')}, user! {t('welcome')}
<br />
<button onClick={() => setLocale('en')}>en</button>
<button onClick={() => setLocale('fr')}>fr</button>
</div>
);
};

storiesOf('useT precreated', module)
.add('Switch preloaded translations', () =>
<Provider map={{
en: {
main: {Hello: 'Hello', welcome: 'Welcome!'}
},
fr: {
main: {Hello: 'Bonjour', welcome: 'Lala!'}
},
}}>
<Demo/>
</Provider>
)
.add('Missing language', () =>
<Provider map={{
en: {
main: {Hello: 'Hello', welcome: 'Welcome!'}
},
}}>
<Demo/>
</Provider>
)
.add('Load translations dynamically, 2 sec delay', () =>
<Provider
map={{
en: {
main: {Hello: 'Hello', welcome: 'Welcome!'}
},
}}
loader={() => new Promise(resolve => {
setTimeout(() => {
resolve({Hello: 'Bonjour', welcome: 'Lala!'});
}, 2000);
})}
>
<Demo/>
</Provider>
)
.add('Without provider', () =>
<Demo/>
)
2 changes: 1 addition & 1 deletion src/__stories__/readme.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {createTranslations} from '..';
import createTranslations from '../createTranslations';

const {Provider, useT} = createTranslations();

Expand Down
2 changes: 1 addition & 1 deletion src/__stories__/useT.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {createTranslations} from '..';
import createTranslations from '../createTranslations';

const {Provider, useT, withT} = createTranslations();

Expand Down
2 changes: 1 addition & 1 deletion src/__stories__/withT.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import {storiesOf} from '@storybook/react';
import {createTranslations} from '..';
import createTranslations from '../createTranslations';

const {Provider, withT} = createTranslations();

Expand Down
142 changes: 142 additions & 0 deletions src/createTranslations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import * as React from 'react';
import {render} from 'react-universal-interface';
import {ProviderProps, ProviderState, TransProps, Result, UseT, TranslatorFn, WithT} from './types';
import invariant from 'tiny-invariant';

export * from './types';

const defaultInterpolate = (strs: TemplateStringsArray, args: any[]) => {
let str = '', i = 0;
for (; i < args.length; i++) str += strs![i] + args[i];
return str + strs![i];
};

export const createTranslations = (ns: string = 'main'): Result => {
const context = React.createContext<ProviderState>({} as any);
const {Consumer} = context;
const Provider = class extends React.Component<ProviderProps, ProviderState> {
static defaultProps = {
locale: 'en',
defaultLocale: 'en',
ns,
};

state: ProviderState;

constructor (props) {
super(props);
const {map = {}, locale, defaultLocale, ns} = props;

// Normalize translation map.
if (!map[defaultLocale]) map[defaultLocale] = {[ns]: {}};
else if (!map[defaultLocale][ns]) map[defaultLocale][ns] = {};
if (!map[locale]) map[locale] = {[ns]: {}};
else if (!map[locale][ns]) map[locale][ns] = {};

this.state = {
locale,
ns,
map,
load: this.load,
setLocale: this.setLocale,
createT: this.createT,
};
}

load = async (locale: string, ns: string) => {
if (!this.state.map[locale]) {
this.state.map[locale] = {};
}
if (!this.state.map[locale][ns]) {
this.state.map[locale][ns] = {};
this.setState({...this.state});
invariant(this.props.loader, 'use-t provider .loader() prop not set.');
const translations = await this.props.loader!(locale, ns);
this.state.map[locale][ns] = translations;
this.setState({...this.state});
}
};

setLocale = (locale: string) => {
if (!this.state.map[locale])
this.state.map[locale] = {};
this.setState({locale});
};

createT = (nss: string[] = []): TranslatorFn => {
const {locale} = this.state;
const translationsNamespaced = this.state.map[locale];
for (const ns of nss) {
if (!translationsNamespaced[ns]) {
this.load(locale, ns).catch(err => console.error(err));
}
}

const t: TranslatorFn = (key: string, ...args: any[]) => {
for (const currentLocale of [locale, this.props.defaultLocale]) {
if (!currentLocale) break;
const translationsNamespaced = this.state.map[currentLocale];
for (const namespace of nss) {
const translations = translationsNamespaced[namespace];
const value = translations[key];
if (value !== undefined) {
return typeof value === 'function'
? value(...args) : value || key;
}
}
}

return key;
};
t.t = key => (strs?: TemplateStringsArray, ...args: any[]) => {
const result = t(key, ...args);
if (result !== key) return result;
else return defaultInterpolate(strs!, args);
};

return t;
};

render () {
return React.createElement(context.Provider, {
value: this.state,
children: this.props.children,
});
}
};

const defaultT: TranslatorFn = k => k;
defaultT.t = key => (strs, ...args) => defaultInterpolate(strs!, args);
const useT: UseT = (namespaces?: string | string[]) => {
const nss: string[] = namespaces instanceof Array ? namespaces : [namespaces || ns];
const state = (React as any).useContext(context) as ProviderState;
return [state.createT ? state.createT(nss) : defaultT, state];
};

const withT: WithT = <P>(Comp, nss: string | string[] = ns) => {
if (!Array.isArray(nss)) nss = [nss];
const Enhanced: React.SFC<P> = props => {
const [t, T] = useT(nss as string[]);
return React.createElement(Comp, {...(props as any), t, T});
};
return Enhanced;
};

const Trans: React.SFC<TransProps> = (props) => {
const nss: string[] = props.ns instanceof Array
? props.ns : [props.ns || ns];
const [t, T] = useT(nss);
return render(props, {t, T});
};

return {
Consumer,
Provider,
context,
useT,
Trans,
withT,
};
};

export default createTranslations;
Loading