-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
45 lines (32 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import {createElement, createContext, useContext} from 'react';
const pickLanguage = require('picklanguage');
const TranslatorContext = createContext(()=>{});
export function Localize(props) {
// language tag or language header string
const language = props.lang || (!props.ignoreBrowser && navigator.language);
const avail = Array.isArray(props.avail) ? props.avail : [props.avail];
const { langTag, translate } = pickLanguage(avail, language, {
strict: !!props.strict,
flagMissing: props.flagMissing,
fallback: props.fallback,
silent: props.silent
});
return createElement(TranslatorContext.Provider, {value: translate}, props.children);
}
export function useTranslate(MessageOrMessages) {
const Translate = useContext(TranslatorContext);
if (typeof MessageOrMessages === 'undefined') return useTranslate;
if (typeof MessageOrMessages === 'string') return MessageOrMessages;
const Translated = {};
let foundObject;
for (const message in MessageOrMessages) {
if (typeof MessageOrMessages[message] === 'object') {
foundObject = true;
Translated[message] = Translate(MessageOrMessages[message]);
} else {
if (foundObject) throw new Error('Translation target had mixed strings and sub-objects');
else return Translate(MessageOrMessages);
}
}
return Translated;
}