network-resurrector-frontend/src/utils/i18n.js

102 lines
3.0 KiB
JavaScript
Raw Normal View History

2020-12-23 02:24:38 +02:00
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import moment from "moment";
import "moment/locale/ro.js";
import "moment/locale/de.js";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next) // passes i18n down to react-i18next
.init(
{
fallbackLng: "en",
debug: true,
ns: ["translations"],
defaultNS: "translations",
//whitelist: ["en", "ro"],
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: function (value, format, lng) {
if (format === "uppercase") return value.toUpperCase();
if (format === "intlDate") {
if (value && moment(value).isValid()) {
return moment(value).format("L");
}
return "";
}
if (format === "intlLongDate") {
if (value && moment(value).isValid()) {
return moment(value).format("LLLL");
}
return "";
}
if (format === "intlTimeFromX") {
if (value && moment(value.start).isValid()) {
let startDate = moment(value.start);
let endDate = moment(value.end);
return moment(endDate).from(startDate, true);
}
return "";
}
if (format === "intlHoursFromX") {
if (value && moment(value.start).isValid()) {
let startDate = moment(value.start);
let endDate = moment(value.end);
let span = moment.duration(endDate - startDate);
return `${parseInt(span.asHours(), 10)}h ${parseInt(
span.asMinutes() % 60,
10
)}m`;
}
return "";
}
if (format === "intlNumber")
return new Intl.NumberFormat(lng).format(value);
if (format === "intlDecimal")
return new Intl.NumberFormat(lng, {
minimumFractionDigits: 2
}).format(value);
if (format === "intlDecimal2")
return new Intl.NumberFormat(lng, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
//dateformat
if (value && value.format) {
if (value.value && moment(value).isValid()) {
return moment(value.value).format(value.format);
}
return "";
}
return value;
}
},
backend: {
2020-12-23 02:32:17 +02:00
loadPath: `${process.env.PUBLIC_URL || ""}/locales/{{lng}}/{{ns}}.json`
2020-12-23 02:24:38 +02:00
}
},
() => {
const currentLang = i18n.language;
if (!currentLang || !currentLang.startsWith("ro")) {
i18n.changeLanguage("en");
} else {
i18n.changeLanguage("ro");
}
}
);
i18n.on("languageChanged", function (lng) {
moment.locale(lng);
});
export default i18n;