diff --git a/apps/server/src/services/i18n.ts b/apps/server/src/services/i18n.ts index e4488ef06..c060f80fd 100644 --- a/apps/server/src/services/i18n.ts +++ b/apps/server/src/services/i18n.ts @@ -4,15 +4,22 @@ import sql_init from "./sql_init.js"; import { join } from "path"; import { getResourceDir } from "./utils.js"; import hidden_subtree from "./hidden_subtree.js"; -import { LOCALES, type Locale } from "@triliumnext/commons"; +import { LOCALES, type Locale, type LOCALE_IDS } from "@triliumnext/commons"; import dayjs, { Dayjs } from "dayjs"; -const DAYJS_LOCALE_MAP: Record = { - cn: "zh-cn", - tw: "zh-tw" -}; - -let dayjsLocale: string; +const DAYJS_LOADER: Record Promise> = { + "ar": () => import("dayjs/locale/ar.js"), + "cn": () => import("dayjs/locale/zh-cn.js"), + "de": () => import("dayjs/locale/de.js"), + "en": () => import("dayjs/locale/en.js"), + "es": () => import("dayjs/locale/es.js"), + "fa": () => import("dayjs/locale/fa.js"), + "fr": () => import("dayjs/locale/fr.js"), + "he": () => import("dayjs/locale/he.js"), + "ku": () => import("dayjs/locale/ku.js"), + "ro": () => import("dayjs/locale/ro.js"), + "tw": () => import("dayjs/locale/tw.js") +} export async function initializeTranslations() { const resourceDir = getResourceDir(); @@ -30,12 +37,7 @@ export async function initializeTranslations() { }); // Initialize dayjs locale. - dayjsLocale = DAYJS_LOCALE_MAP[locale] ?? locale; - try { - await import(`dayjs/locale/${dayjsLocale}.js`); - } catch (err) { - console.warn(`Could not load locale ${dayjsLocale}`, err); - } + const dayjsLocale = await DAYJS_LOADER[locale](); dayjs.locale(dayjsLocale); } @@ -48,8 +50,8 @@ export function getLocales(): Locale[] { return LOCALES; } -function getCurrentLanguage() { - let language; +function getCurrentLanguage(): LOCALE_IDS { + let language: string; if (sql_init.isDbInitialized()) { language = options.getOptionOrNull("locale"); } @@ -59,7 +61,7 @@ function getCurrentLanguage() { language = "en"; } - return language; + return language as LOCALE_IDS; } export async function changeLanguage(locale: string) { diff --git a/packages/commons/src/lib/i18n.ts b/packages/commons/src/lib/i18n.ts index 5967a1275..bfb5caac1 100644 --- a/packages/commons/src/lib/i18n.ts +++ b/packages/commons/src/lib/i18n.ts @@ -9,7 +9,7 @@ export interface Locale { electronLocale?: string; } -export const LOCALES: Locale[] = [ +const UNSORTED_LOCALES = [ { id: "en", name: "English", @@ -75,4 +75,9 @@ export const LOCALES: Locale[] = [ rtl: true, contentOnly: true } -].sort((a, b) => a.name.localeCompare(b.name)); +] as const; + +export const LOCALES: Locale[] = Array.from(UNSORTED_LOCALES) + .sort((a, b) => a.name.localeCompare(b.name)); + +export type LOCALE_IDS = typeof UNSORTED_LOCALES[number]["id"];