Files
Trilium/apps/client/src/services/i18n.ts

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-08-11 08:12:01 +03:00
import options from "./options.js";
2025-02-28 08:26:48 +01:00
import i18next from "i18next";
import i18nextHttpBackend from "i18next-http-backend";
import server from "./server.js";
import type { Locale } from "@triliumnext/commons";
import { initReactI18next } from "react-i18next";
let locales: Locale[] | null;
/**
* A deferred promise that resolves when translations are initialized.
*/
2025-07-28 18:58:26 +03:00
export let translationsInitializedPromise = $.Deferred();
2024-08-11 08:12:01 +03:00
export async function initLocale() {
2024-12-19 20:52:43 +02:00
const locale = (options.get("locale") as string) || "en";
2024-08-11 08:12:01 +03:00
locales = await server.get<Locale[]>("options/locales");
i18next.use(initReactI18next);
2025-01-09 18:07:02 +02:00
await i18next.use(i18nextHttpBackend).init({
lng: locale,
fallbackLng: "en",
backend: {
loadPath: `${window.glob.assetPath}/translations/{{lng}}/{{ns}}.json`
},
returnEmptyString: false
});
translationsInitializedPromise.resolve();
2024-08-11 08:12:01 +03:00
}
2024-07-20 09:42:55 +03:00
export function getAvailableLocales() {
if (!locales) {
throw new Error("Tried to load list of locales, but localization is not yet initialized.")
}
return locales;
}
/**
* Finds the given locale by ID.
*
* @param localeId the locale ID to search for.
* @returns the corresponding {@link Locale} or `null` if it was not found.
*/
export function getLocaleById(localeId: string | null | undefined) {
if (!localeId) return null;
return locales?.find((l) => l.id === localeId) ?? null;
}
export const t = i18next.t;
export const getCurrentLanguage = () => i18next.language;