-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (64 loc) · 2.39 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
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
73
74
75
76
77
/**
* * * LOCALE INTL SETTINGS * * *
* */
const React = require("react")
const { IntlProvider, addLocaleData } = require("react-intl")
async function load() {
const [module1, module2, module3] = await Promise.all([
require("intl"),
require("intl/locale-data/jsonp/en"),
require("intl/locale-data/jsonp/it"),
require("intl/locale-data/jsonp/de")
])
return [module1, module2, module3]
}
/* needed in order to user nested translation objects */
const flattenMessages = (nestedMessages, prefix = "") => {
if (!nestedMessages) {
return {}
}
return Object.keys(nestedMessages).reduce((messages, key) => {
const value = nestedMessages[key] || ""
const prefixedKey = prefix ? `${prefix}.${key}` : key
if (typeof value === "string") {
Object.assign(messages, { [prefixedKey]: value })
} else {
Object.assign(messages, flattenMessages(value, prefixedKey))
}
return messages
}, {})
}
const IntlProviderHoc = props => {
// props.localeData is Our translated strings
const { localeData = {}, initialLocale = {} } = props
const localeToAdd = Object.keys(localeData).map(value => ({
locale: value,
fields: localeData[value],
pluralRuleFunction: () => {}
}))
addLocaleData(localeToAdd)
// Define user's language. Different browsers have the user locale defined
// on different fields on the `navigator` object, so we make sure to account
// for these different by checking all of them
const language = initialLocale.length
? initialLocale
: (navigator.languages && navigator.languages[0]) ||
navigator.language ||
navigator.userLanguage ||
"it"
// Split locales with a region code
const languageWithoutRegionCode = language.toLowerCase().split(/[_-]+/)[0]
// Try full locale, try locale without region code, fallback to 'en'
const messages = localeData[languageWithoutRegionCode] || localeData[language] || localeData.en
// If browser doesn't support Intl (i.e. Safari), then we manually import
// the intl polyfill and locale data.
if (!window.Intl) {
load()
}
return (
<IntlProvider locale={language} key={language} messages={flattenMessages(messages)}>
{props.children}
</IntlProvider>
)
}
module.exports = IntlProviderHoc