Skip to content

Build your personal knowledge base with Trilium Notes

feat(client-standalone): proper integration of server-side locale

Elian Doran7547371ba0e0
diff --git a/apps/client-standalone/src/i18n.ts b/apps/client-standalone/src/lightweight/translation_provider.ts
similarity index 72%
rename from apps/client-standalone/src/i18n.ts
rename to apps/client-standalone/src/lightweight/translation_provider.ts
index e2f63479e1..ee3a31f794 100644
--- a/apps/client-standalone/src/i18n.ts
+++ b/apps/client-standalone/src/lightweight/translation_provider.ts
@@ -1,11 +1,8 @@
+import { LOCALE_IDS } from "@triliumnext/commons";
import i18next from "i18next";
import I18NextHttpBackend from "i18next-http-backend";
-export default async function initTranslations() {
- // TODO: Use proper locale.
- const locale = "en";
-
- // Initialize translations.
+export default async function translationProvider(locale: LOCALE_IDS) {
await i18next.use(I18NextHttpBackend).init({
lng: locale,
fallbackLng: "en",
diff --git a/apps/client-standalone/src/local-server-worker.ts b/apps/client-standalone/src/local-server-worker.ts
index 786321585e..7f77525e28 100644
--- a/apps/client-standalone/src/local-server-worker.ts
+++ b/apps/client-standalone/src/local-server-worker.ts
@@ -2,13 +2,13 @@
// This will eventually import your core server and DB provider.
// import { createCoreServer } from "@trilium/core"; (bundled)
-import initTranslations from './i18n';
import { BrowserRouter } from './lightweight/browser_router';
import { createConfiguredRouter } from './lightweight/browser_routes';
import BrowserExecutionContext from './lightweight/cls_provider';
import BrowserCryptoProvider from './lightweight/crypto_provider';
import WorkerMessagingProvider from './lightweight/messaging_provider';
import BrowserSqlProvider from './lightweight/sql_provider';
+import translationProvider from './lightweight/translation_provider';
// Global error handlers - MUST be set up before any async imports
self.onerror = (message, source, lineno, colno, error) => {
@@ -101,12 +101,12 @@ async function initialize(): Promise<void> {
console.log("[Worker] Database loaded");
console.log("[Worker] Loading @triliumnext/core...");
- initTranslations();
coreModule = await import("@triliumnext/core");
coreModule.initializeCore({
executionContext: new BrowserExecutionContext(),
crypto: new BrowserCryptoProvider(),
messaging: messagingProvider,
+ translations: translationProvider,
dbConfig: {
provider: sqlProvider,
isReadOnly: false,
diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts
index 7dd11fa64b..ceb5fca437 100644
--- a/apps/server/src/main.ts
+++ b/apps/server/src/main.ts
@@ -43,10 +43,9 @@ async function startApplication() {
}
},
crypto: new NodejsCryptoProvider(),
- executionContext: new ClsHookedExecutionContext()
+ executionContext: new ClsHookedExecutionContext(),
+ translations: (await import("./services/i18n.js")).initializeTranslations
});
- const { initializeTranslations } = (await import("./services/i18n.js"));
- await initializeTranslations();
const startTriliumServer = (await import("./www.js")).default;
await startTriliumServer();
}
diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.ts
index e81b546448..4024bc9bd4 100644
--- a/apps/server/src/routes/index.ts
+++ b/apps/server/src/routes/index.ts
@@ -8,7 +8,6 @@ import appPath from "../services/app_path.js";
import assetPath from "../services/asset_path.js";
import attributeService from "../services/attributes.js";
import config from "../services/config.js";
-import { getCurrentLocale } from "../services/i18n.js";
import log from "../services/log.js";
import optionService from "../services/options.js";
import { isDev, isElectron, isWindows11 } from "../services/utils.js";
@@ -30,7 +29,6 @@ export function bootstrap(req: Request, res: Response) {
const themeNote = attributeService.getNoteWithLabel("appTheme", theme);
const nativeTitleBarVisible = options.nativeTitleBarVisible === "true";
const iconPacks = iconPackService.getIconPacks();
- const currentLocale = getCurrentLocale();
res.send({
...getSharedBootstrapItems(assetPath),
@@ -49,8 +47,6 @@ export function bootstrap(req: Request, res: Response) {
triliumVersion: packageJson.version,
appPath,
baseApiUrl: 'api/',
- currentLocale,
- isRtl: !!currentLocale.rtl,
iconPackCss: iconPacks
.map((p: iconPackService.ProcessedIconPack) => iconPackService.generateCss(p, p.builtin
? `${assetPath}/fonts/${p.fontAttachmentId}.${iconPackService.MIME_TO_EXTENSION_MAPPINGS[p.fontMime]}`
diff --git a/apps/server/src/services/i18n.ts b/apps/server/src/services/i18n.ts
index cc43a95005..a52367a18a 100644
--- a/apps/server/src/services/i18n.ts
+++ b/apps/server/src/services/i18n.ts
@@ -1,16 +1,12 @@
-import { type Dayjs, dayjs, type Locale, type LOCALE_IDS,LOCALES, setDayjsLocale } from "@triliumnext/commons";
+import { LOCALE_IDS, setDayjsLocale } from "@triliumnext/commons";
import i18next from "i18next";
import { join } from "path";
-import hidden_subtree from "./hidden_subtree.js";
-import options from "./options.js";
-import sql_init from "./sql_init.js";
-import { getResourceDir } from "./utils.js";
+import { getResourceDir } from "./utils";
-export async function initializeTranslations() {
+export async function initializeTranslations(locale: LOCALE_IDS) {
const resourceDir = getResourceDir();
const Backend = (await import("i18next-fs-backend/cjs")).default;
- const locale = getCurrentLanguage();
// Initialize translations
await i18next.use(Backend).init({
@@ -25,38 +21,3 @@ export async function initializeTranslations() {
// Initialize dayjs locale.
await setDayjsLocale(locale);
}
-
-export function ordinal(date: Dayjs) {
- return dayjs(date)
- .format("Do");
-}
-
-export function getLocales(): Locale[] {
- return LOCALES;
-}
-
-function getCurrentLanguage(): LOCALE_IDS {
- let language: string | null = null;
- if (sql_init.isDbInitialized()) {
- language = options.getOptionOrNull("locale");
- }
-
- if (!language) {
- console.info("Language option not found, falling back to en.");
- language = "en";
- }
-
- return language as LOCALE_IDS;
-}
-
-export async function changeLanguage(locale: string) {
- await i18next.changeLanguage(locale);
- hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });
-}
-
-export function getCurrentLocale() {
- const localeId = options.getOptionOrNull("locale") ?? "en";
- const currentLocale = LOCALES.find(l => l.id === localeId);
- if (!currentLocale) return LOCALES.find(l => l.id === "en")!;
- return currentLocale;
-}
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index fd2f90a18c..a575eb1c08 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -7,17 +7,18 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
- "@triliumnext/commons": "workspace:*",
- "sanitize-html": "2.17.0",
"@braintree/sanitize-url": "7.1.1",
- "sanitize-filename": "1.6.3",
+ "@triliumnext/commons": "workspace:*",
+ "escape-html": "1.0.3",
+ "i18next": "25.7.3",
"mime-types": "3.0.2",
- "unescape": "1.0.1",
- "escape-html": "1.0.3"
+ "sanitize-filename": "1.6.3",
+ "sanitize-html": "2.17.0",
+ "unescape": "1.0.1"
},
"devDependencies": {
- "@types/sanitize-html": "2.16.0",
+ "@types/escape-html": "1.0.4",
"@types/mime-types": "3.0.1",
- "@types/escape-html": "1.0.4"
+ "@types/sanitize-html": "2.16.0"
}
}
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 8544cd95fc..001e21c169 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -4,6 +4,7 @@ import { getLog, initLog } from "./services/log";
import { initSql } from "./services/sql/index";
import { SqlService, SqlServiceParams } from "./services/sql/sql";
import { initMessaging, MessagingProvider } from "./services/messaging/index";
+import { initTranslations, TranslationProvider } from "./services/i18n";
export type * from "./services/sql/types";
export * from "./services/sql/index";
@@ -24,6 +25,7 @@ export { default as hidden_subtree } from "./services/hidden_subtree";
export * as icon_packs from "./services/icon_packs";
export { getContext, type ExecutionContext } from "./services/context";
export * as cls from "./services/context";
+export * as i18n from "./services/i18n";
export * from "./errors";
export { default as getInstanceId } from "./services/instance_id";
export type { CryptoProvider } from "./services/encryption/crypto";
@@ -64,16 +66,18 @@ export type { NoteParams } from "./services/notes";
export * as sanitize from "./services/sanitizer";
export * as routes from "./routes";
-export function initializeCore({ dbConfig, executionContext, crypto, messaging }: {
+export function initializeCore({ dbConfig, executionContext, crypto, translations, messaging }: {
dbConfig: SqlServiceParams,
executionContext: ExecutionContext,
crypto: CryptoProvider,
+ translations: TranslationProvider,
messaging?: MessagingProvider
}) {
initLog();
initCrypto(crypto);
initSql(new SqlService(dbConfig, getLog()));
initContext(executionContext);
+ initTranslations(translations);
if (messaging) {
initMessaging(messaging);
}
diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.ts
index 18762caa2a..19fa1b81c1 100644
--- a/packages/trilium-core/src/services/bootstrap_utils.ts
+++ b/packages/trilium-core/src/services/bootstrap_utils.ts
@@ -3,10 +3,12 @@ import { getSql } from "./sql";
import protected_session from "./protected_session";
import { generateCss, generateIconRegistry, getIconPacks, MIME_TO_EXTENSION_MAPPINGS } from "./icon_packs";
import options from "./options";
+import { getCurrentLocale } from "./i18n";
-export default function getSharedBootstrapItems(assetPath: string): Pick<BootstrapDefinition, "assetPath" | "headingStyle" | "layoutOrientation" | "maxEntityChangeIdAtLoad" | "maxEntityChangeSyncIdAtLoad" | "isProtectedSessionAvailable" | "iconRegistry" | "iconPackCss"> {
+export default function getSharedBootstrapItems(assetPath: string): Pick<BootstrapDefinition, "assetPath" | "headingStyle" | "layoutOrientation" | "maxEntityChangeIdAtLoad" | "maxEntityChangeSyncIdAtLoad" | "isProtectedSessionAvailable" | "iconRegistry" | "iconPackCss" | "currentLocale" | "isRtl"> {
const sql = getSql();
const iconPacks = getIconPacks();
+ const currentLocale = getCurrentLocale();
return {
assetPath,
@@ -15,6 +17,8 @@ export default function getSharedBootstrapItems(assetPath: string): Pick<Bootstr
maxEntityChangeIdAtLoad: sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes"),
maxEntityChangeSyncIdAtLoad: sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1"),
isProtectedSessionAvailable: protected_session.isProtectedSessionAvailable(),
+ currentLocale,
+ isRtl: !!currentLocale.rtl,
iconRegistry: generateIconRegistry(iconPacks),
iconPackCss: iconPacks
.map(p => generateCss(p, p.builtin
diff --git a/packages/trilium-core/src/services/i18n.ts b/packages/trilium-core/src/services/i18n.ts
index 1cbf52ba85..c28c897787 100644
--- a/packages/trilium-core/src/services/i18n.ts
+++ b/packages/trilium-core/src/services/i18n.ts
@@ -1,10 +1,51 @@
-import { LOCALES } from "@triliumnext/commons";
+import { dayjs, Dayjs, Locale, LOCALE_IDS, LOCALES, setDayjsLocale } from "@triliumnext/commons";
+import sql_init from "./sql_init";
+import options from "./options";
+import i18next from "i18next";
+import hidden_subtree from "./hidden_subtree";
-// TODO: Real impl.
-export function changeLanguage(languageCode: string) {
- console.log("Got request to change language", languageCode);
+export type TranslationProvider = (locale: LOCALE_IDS) => Promise<void>;
+
+export async function initTranslations(translationProvider: TranslationProvider) {
+ const locale = getCurrentLanguage();
+
+ await translationProvider(locale);
+
+ // Initialize dayjs locale.
+ await setDayjsLocale(locale);
+}
+
+export function ordinal(date: Dayjs) {
+ return dayjs(date)
+ .format("Do");
+}
+
+export function getLocales(): Locale[] {
+ return LOCALES;
+}
+
+function getCurrentLanguage(): LOCALE_IDS {
+ let language: string | null = null;
+ if (sql_init.isDbInitialized()) {
+ language = options.getOptionOrNull("locale");
+ }
+
+ if (!language) {
+ console.info("Language option not found, falling back to en.");
+ language = "en";
+ }
+
+ return language as LOCALE_IDS;
+}
+
+export async function changeLanguage(locale: string) {
+ await i18next.changeLanguage(locale);
+ hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });
}
-export function getLocales() {
- return LOCALES;
+export function getCurrentLocale() {
+ const localeId = options.getOptionOrNull("locale") ?? "en";
+ const currentLocale = LOCALES.find(l => l.id === localeId);
+ if (!currentLocale) return LOCALES.find(l => l.id === "en")!;
+ return currentLocale;
}
diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.ts
index ec44193cb7..6d3b509c3c 100644
--- a/packages/trilium-core/src/services/sql_init.ts
+++ b/packages/trilium-core/src/services/sql_init.ts
@@ -6,3 +6,9 @@ export const dbReady = deferred<void>();
setTimeout(() => {
dbReady.resolve();
}, 850);
+
+function isDbInitialized() {
+ return true;
+}
+
+export default { isDbInitialized };
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fd9ba09627..e46ecc8a50 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1639,6 +1639,9 @@ importers:
escape-html:
specifier: 1.0.3
version: 1.0.3
+ i18next:
+ specifier: 25.7.3
+ version: 25.7.3([email protected])
mime-types:
specifier: 3.0.2
version: 3.0.2
@@ -15784,8 +15787,6 @@ snapshots:
'@ckeditor/ckeditor5-ui': 47.3.0
'@ckeditor/ckeditor5-utils': 47.3.0
ckeditor5: 47.3.0
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]':
dependencies:
@@ -15794,8 +15795,6 @@ snapshots:
'@ckeditor/ckeditor5-ui': 47.3.0
'@ckeditor/ckeditor5-utils': 47.3.0
ckeditor5: 47.3.0
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]':
dependencies:
@@ -15805,8 +15804,6 @@ snapshots:
'@ckeditor/ckeditor5-utils': 47.3.0
'@ckeditor/ckeditor5-widget': 47.3.0
ckeditor5: 47.3.0
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]':
dependencies:
@@ -15816,8 +15813,6 @@ snapshots:
'@ckeditor/ckeditor5-utils': 47.3.0
'@ckeditor/ckeditor5-widget': 47.3.0
ckeditor5: 47.3.0
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]':
dependencies:
@@ -15833,8 +15828,6 @@ snapshots:
'@ckeditor/ckeditor5-widget': 47.3.0
ckeditor5: 47.3.0
es-toolkit: 1.39.5
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]': {}
@@ -15875,8 +15868,6 @@ snapshots:
'@ckeditor/ckeditor5-ui': 47.3.0
'@ckeditor/ckeditor5-utils': 47.3.0
ckeditor5: 47.3.0
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]': {}
@@ -15979,6 +15970,8 @@ snapshots:
'@ckeditor/ckeditor5-utils': 47.3.0
ckeditor5: 47.3.0
es-toolkit: 1.39.5
+ transitivePeerDependencies:
+ - supports-color
'@ckeditor/[email protected]':
dependencies: