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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
import React, { createContext, useContext } from 'react';
import usePersistedState from './common/usePersistedState';
import en from '../../web/l10n/en.json';
import es from '../../web/l10n/es.json';
const languages = {
en: { data: en, name: 'English' },
es: { data: es, name: 'Español' },
};
const getDefaultLanguage = () => {
const browserLanguages = window.navigator.languages ? window.navigator.languages.slice() : [];
const browserLanguage = window.navigator.userLanguage || window.navigator.language;
browserLanguages.push(browserLanguage);
browserLanguages.push(browserLanguage.substring(0, 2));
for (let i = 0; i < browserLanguages.length; i += 1) {
let language = browserLanguages[i].replace('-', '');
if (language in languages) {
return language;
}
if (language.length > 2) {
language = language.substring(0, 2);
if (language in languages) {
return language;
}
}
}
return 'es';
};
const LocalizationContext = createContext({
languages,
language: 'es',
setLanguage: () => {},
});
export const LocalizationProvider = ({ children }) => {
const [language, setLanguage] = usePersistedState('language', getDefaultLanguage());
return (
<LocalizationContext.Provider value={{ languages, language, setLanguage }}>
{children}
</LocalizationContext.Provider>
);
};
export const useLocalization = () => useContext(LocalizationContext);
export const useTranslation = () => {
const context = useContext(LocalizationContext);
const { data } = context.languages[context.language];
return (key, args = {}) => {
if (Object.keys(args).length) {
let str = data[key];
Object.keys(args).forEach(k => {
str = str.replace(new RegExp(`\\{${k}\\}`, 'gi'), args[k].toString());
});
return str;
} else {
return data[key];
}
}
};
export const useTranslationKeys = (predicate) => {
const context = useContext(LocalizationContext);
const { data } = context.languages[context.language];
return Object.keys(data).filter(predicate);
};
|