refactor(server): async import without side effects

This commit is contained in:
Elian Doran 2025-05-25 14:09:51 +03:00
parent e07a7d291b
commit fa9d0be651
No known key found for this signature in database
2 changed files with 25 additions and 18 deletions

View File

@ -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<string, string> = {
cn: "zh-cn",
tw: "zh-tw"
};
let dayjsLocale: string;
const DAYJS_LOADER: Record<LOCALE_IDS, () => Promise<typeof import("dayjs/locale/en.js")>> = {
"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) {

View File

@ -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"];