forked from ephemeraHQ/xmtp-inbox-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.js
59 lines (51 loc) · 1.81 KB
/
i18n.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
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import backend from "i18next-http-backend";
import { format as formatDate, isDate, formatDistanceStrict } from "date-fns";
import * as locales from "date-fns/locale"; // import all locales we need
// Get translated JSON files from locales folder so we don't need to import here individually
const webpackContext = require.context("./locales", false, /\.json$/);
const filenames = webpackContext.keys(); // => ['./de_DE.json, './en_US.json']
const key_value_pairs = filenames.map((name) => [
name?.match(/\/(\w+)\.json$/)?.[1],
webpackContext(name),
]);
// Create object with languages and corresponding file mappings
const messages = Object.fromEntries(key_value_pairs);
// Populate mapping of language to locale file resources
export let resourceMap = {};
Object.keys(messages).forEach((locale) => {
const lang = locale?.split("_")?.[0];
resourceMap[lang] = { translation: messages[locale] };
});
i18next
.use(initReactI18next)
.use(LanguageDetector)
.use(backend)
.init({
fallbackLng: "en",
resources: resourceMap,
interpolation: {
format: (value, format, lng) => {
if (isDate(value)) {
const locale = locales[lng];
if (format === "long_date") {
return formatDate(value, "PPP", { locale });
}
if (format === "time") {
return formatDate(value, "h:mm a", { locale });
}
if (format === "ago")
return formatDistanceStrict(value, new Date(), {
locale,
addSuffix: true,
});
return formatDate(value, format, { locale });
} else {
return "";
}
},
},
});
export default i18next;