Farmbot-Web-App/frontend/i18n.ts

45 lines
1.4 KiB
TypeScript
Raw Normal View History

import axios from "axios";
2019-10-30 14:14:31 -06:00
import { InitOptions } from "i18next";
2019-02-28 16:31:42 -07:00
import { merge } from "lodash";
const translationFilePath = (lang: string): string =>
`/app-resources/languages/${lang}.json`;
2019-01-28 09:07:26 -07:00
2018-03-02 08:25:15 -07:00
/** @public */
2018-05-15 20:38:52 -06:00
export function generateUrl(langCode: string, host: string, port: string) {
const lang = langCode.slice(0, 2);
2018-11-30 21:59:18 -07:00
const baseUrl = `//${host.split(":")[0]}:${port}`;
2019-02-28 16:31:42 -07:00
const url = `${baseUrl}${translationFilePath(lang)}`;
2017-06-29 12:54:02 -06:00
return url;
}
2017-06-29 12:54:02 -06:00
2018-05-15 20:38:52 -06:00
export function getUserLang(
langCode = "en_us", host = location.host, port = location.port) {
return axios.get(generateUrl(langCode, host, port))
2018-11-30 21:59:18 -07:00
.then(() => langCode.slice(0, 2))
.catch(() => "en");
}
2017-06-29 12:54:02 -06:00
2019-02-28 16:31:42 -07:00
type TranslationFile = { [cat: string]: { [key: string]: string } };
type Translations = { [key: string]: string };
const parseTranslationData = (data: TranslationFile): Translations =>
merge(data["translated"], data["untranslated"], data["other_translations"]);
2019-10-30 14:14:31 -06:00
export function generateI18nConfig(lang: string): Promise<InitOptions> {
2019-01-28 09:07:26 -07:00
return axios
2019-02-28 16:31:42 -07:00
.get<TranslationFile>(translationFilePath(lang))
.then(response => {
const translation = parseTranslationData(response.data);
2019-01-28 09:07:26 -07:00
return {
nsSeparator: "",
keySeparator: "",
lng: lang,
2019-02-28 16:31:42 -07:00
resources: { [lang]: { translation } }
2019-01-28 09:07:26 -07:00
};
});
}
2017-10-12 12:47:29 -06:00
export const detectLanguage =
2018-01-23 13:07:50 -07:00
(lang = navigator.language) => getUserLang(lang).then(generateI18nConfig);