Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(spreadsheet): inherit UI language from Trilium settings (closes #10104)
Elian Doran3ad1f713a592
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsxindex 9f98a8244f..5287024cd5 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx@@ -10,31 +10,24 @@ import "@univerjs/preset-sheets-data-validation/lib/index.css";import { DEFAULT_STYLES } from '@univerjs/core';import { UniverSheetsConditionalFormattingPreset } from '@univerjs/preset-sheets-conditional-formatting';-import UniverPresetSheetsConditionalFormattingEnUS from '@univerjs/preset-sheets-conditional-formatting/locales/en-US';import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core';-import sheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US';import { UniverSheetsDataValidationPreset } from '@univerjs/preset-sheets-data-validation';-import UniverPresetSheetsDataValidationEnUS from '@univerjs/preset-sheets-data-validation/locales/en-US';import { UniverSheetsFilterPreset } from '@univerjs/preset-sheets-filter';-import UniverPresetSheetsFilterEnUS from '@univerjs/preset-sheets-filter/locales/en-US';import { UniverSheetsFindReplacePreset } from '@univerjs/preset-sheets-find-replace';-import sheetsFindReplaceEnUS from '@univerjs/preset-sheets-find-replace/locales/en-US';import { UniverSheetsHyperLinkPreset } from '@univerjs/preset-sheets-hyper-link';-import UniverPresetSheetsHyperLinkEnUS from '@univerjs/preset-sheets-hyper-link/locales/en-US';import { UniverSheetsNotePreset } from '@univerjs/preset-sheets-note';-import sheetsNoteEnUS from '@univerjs/preset-sheets-note/locales/en-US';import { UniverSheetsSortPreset } from '@univerjs/preset-sheets-sort';-import UniverPresetSheetsSortEnUS from '@univerjs/preset-sheets-sort/locales/en-US';-import { createUniver, FUniver, LocaleType, mergeLocales } from '@univerjs/presets';+import { createUniver, FUniver, mergeLocales } from '@univerjs/presets';import { CalculationMode } from '@univerjs/sheets-formula';import { IDialogService, IShortcutService, ISidebarService } from '@univerjs/ui';-import { MutableRef, useEffect, useRef } from "preact/hooks";+import { MutableRef, useEffect, useRef, useState } from "preact/hooks";import type NoteContext from "../../../components/note_context";import { t } from "../../../services/i18n";import { useColorScheme, useEffectiveReadOnly, useTriliumEvent, useTriliumEvents } from "../../react/hooks";import { TypeWidgetProps } from "../type_widget";import useSpreadsheetExport from "./export";+import { loadUniverLocale, UniverLocale } from "./locales";import usePersistence from "./persistence";function buildReadOnlyLocaleOverrides() {@@ -63,16 +56,38 @@ function buildReadOnlyLocaleOverrides() {export default function Spreadsheet(props: TypeWidgetProps) {const readOnly = useEffectiveReadOnly(props.note, props.noteContext);+ const locale = useUniverLocale();++ // Wait for the locale bundle before mounting the editor so Univer can be created synchronously+ // with the right language (the dependent hooks below rely on the API being ready immediately).+ if (!locale) {+ return <div className="spreadsheet" />;+ }// Use readOnly as key to force full remount (and data reload) when it changes.- return <SpreadsheetEditor key={String(readOnly)} {...props} readOnly={readOnly} />;+ return <SpreadsheetEditor key={String(readOnly)} {...props} readOnly={readOnly} locale={locale} />;+}++/** Loads the Univer locale matching Trilium's UI language once, on mount. */+function useUniverLocale() {+ const [locale, setLocale] = useState<UniverLocale>();+ useEffect(() => {+ let cancelled = false;+ void loadUniverLocale().then((loaded) => {+ if (!cancelled) setLocale(loaded);+ });+ return () => {+ cancelled = true;+ };+ }, []);+ return locale;}-function SpreadsheetEditor({ note, noteContext, readOnly }: TypeWidgetProps & { readOnly: boolean }) {+function SpreadsheetEditor({ note, noteContext, readOnly, locale }: TypeWidgetProps & { readOnly: boolean; locale: UniverLocale }) {const containerRef = useRef<HTMLDivElement>(null);const apiRef = useRef<FUniver>();- useInitializeSpreadsheet(containerRef, apiRef, readOnly);+ useInitializeSpreadsheet(containerRef, apiRef, readOnly, locale);useReleaseFillShortcuts(apiRef);useDarkMode(apiRef);usePersistence(note, noteContext, apiRef, containerRef);@@ -187,7 +202,7 @@ function useReleaseFillShortcuts(apiRef: MutableRef<FUniver | undefined>) {}, [ apiRef ]);}-function useInitializeSpreadsheet(containerRef: MutableRef<HTMLDivElement | null>, apiRef: MutableRef<FUniver | undefined>, readOnly: boolean) {+function useInitializeSpreadsheet(containerRef: MutableRef<HTMLDivElement | null>, apiRef: MutableRef<FUniver | undefined>, readOnly: boolean, locale: UniverLocale) {useEffect(() => {if (!containerRef.current) return;@@ -198,17 +213,12 @@ function useInitializeSpreadsheet(containerRef: MutableRef<HTMLDivElement | null}const { univerAPI } = createUniver({- locale: LocaleType.EN_US,+ // Inherit the spreadsheet language (and locale-dependent defaults such as the currency+ // symbol) from Trilium's UI language instead of hardcoding US English.+ locale: locale.type,locales: {- [LocaleType.EN_US]: mergeLocales(- sheetsCoreEnUS,- sheetsFindReplaceEnUS,- sheetsNoteEnUS,- UniverPresetSheetsFilterEnUS,- UniverPresetSheetsSortEnUS,- UniverPresetSheetsDataValidationEnUS,- UniverPresetSheetsConditionalFormattingEnUS,- UniverPresetSheetsHyperLinkEnUS,+ [locale.type]: mergeLocales(+ locale.data,readOnly ? buildReadOnlyLocaleOverrides() : {},),},@@ -256,7 +266,7 @@ function useInitializeSpreadsheet(containerRef: MutableRef<HTMLDivElement | nullapiRef.current = univerAPI;return () => univerAPI.dispose();- }, [ apiRef, containerRef, readOnly ]);+ }, [ apiRef, containerRef, readOnly, locale ]);}function useDarkMode(apiRef: MutableRef<FUniver | undefined>) {diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/locales.spec.ts b/apps/client/src/widgets/type_widgets/spreadsheet/locales.spec.tsnew file mode 100644index 0000000000..856e525739--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/locales.spec.ts@@ -0,0 +1,64 @@+import { LOCALES } from "@triliumnext/commons";+import { LocaleType } from "@univerjs/presets";+import { describe, expect, it } from "vitest";++import { loadUniverLocale, resolveUniverLocaleSource, SPREADSHEET_PRESET_PACKAGES, UNIVER_LOCALES } from "./locales";++describe("UNIVER_LOCALES", () => {+ it("maps every displayable Trilium UI language (fails when a new language is added)", () => {+ // A newly introduced Trilium UI language must get an explicit entry (a source or null),+ // rather than silently defaulting.+ for (const locale of LOCALES) {+ if (locale.contentOnly) continue;+ expect(UNIVER_LOCALES, `No Univer mapping for Trilium locale "${locale.id}"`).toHaveProperty(locale.id);+ }+ });++ it("only maps locales that still exist as displayable Trilium languages", () => {+ const displayableIds = LOCALES.filter((locale) => !locale.contentOnly).map((locale) => locale.id);+ for (const mappedId of Object.keys(UNIVER_LOCALES)) {+ expect(displayableIds, `Stale mapping for removed locale "${mappedId}"`).toContain(mappedId);+ }+ });++ it("can physically import every mapped locale (and the English fallback) across every preset", async () => {+ // The English fallback isn't referenced by any entry (English variants map to null), so load+ // it through a null-mapped locale to confirm it imports too.+ const english = await loadUniverLocale("en");+ expect(english.type).toBe(LocaleType.EN_US);+ expect(Object.keys(english.data).length).toBeGreaterThan(0);++ for (const [id, source] of Object.entries(UNIVER_LOCALES)) {+ if (source === null) continue;+ const modules = await source.load();++ // Every preset bundle must resolve to a non-empty translation object.+ expect(modules, id).toHaveLength(SPREADSHEET_PRESET_PACKAGES.length);+ for (const module of modules) {+ expect(Object.keys(module.default).length, id).toBeGreaterThan(0);+ }+ }+ });++ it("loads and merges the locale matching the Trilium language", async () => {+ // "fr" maps to fr-FR, exercising the resolve -> import -> merge path end to end.+ const { type, data } = await loadUniverLocale("fr");+ expect(type).toBe(LocaleType.FR_FR);+ expect(Object.keys(data).length).toBeGreaterThan(0);+ });+});++describe("resolveUniverLocaleSource", () => {+ it("falls back to the base language before defaulting to English", () => {+ // Region-suffixed variants resolve to their base language's mapping.+ expect(resolveUniverLocaleSource("fr-CA").type).toBe(LocaleType.FR_FR);+ expect(resolveUniverLocaleSource("es_419").type).toBe(LocaleType.ES_ES);+ });++ it("falls back to English for locales without a Univer translation", () => {+ // German and Romanian have no Univer bundle, so English is the closest available option.+ expect(resolveUniverLocaleSource("de").type).toBe(LocaleType.EN_US);+ expect(resolveUniverLocaleSource("ro").type).toBe(LocaleType.EN_US);+ expect(resolveUniverLocaleSource("").type).toBe(LocaleType.EN_US);+ });+});diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/locales.ts b/apps/client/src/widgets/type_widgets/spreadsheet/locales.tsnew file mode 100644index 0000000000..d37ff398ce--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/locales.ts@@ -0,0 +1,184 @@+import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";+import { LocaleType, mergeLocales } from '@univerjs/presets';++import { getCurrentLanguage } from "../../../services/i18n";++export interface UniverLocale {+ /** The Univer {@link LocaleType} used both as the active locale and as the key of the locale data map. */+ type: LocaleType;+ /** The merged locale data, gathering the translations of every spreadsheet preset we load. */+ data: object;+}++interface UniverLocaleSource {+ /** The Univer {@link LocaleType} enum value (e.g. `enUS`), distinct from the on-disk code (`en-US`). */+ type: LocaleType;+ /** Lazily imports and returns the locale bundle of every preset in {@link SPREADSHEET_PRESET_PACKAGES}. */+ load: () => Promise<{ default: object }[]>;+}++/**+ * The spreadsheet presets used in {@link Spreadsheet}, each of which ships its own per-locale+ * translation bundle. Exposed so tests can assert each {@link UNIVER_LOCALES} source loads a bundle+ * for every preset. Keep this in sync with the preset list passed to `createUniver`.+ */+export const SPREADSHEET_PRESET_PACKAGES = [+ "@univerjs/preset-sheets-core",+ "@univerjs/preset-sheets-find-replace",+ "@univerjs/preset-sheets-note",+ "@univerjs/preset-sheets-filter",+ "@univerjs/preset-sheets-sort",+ "@univerjs/preset-sheets-data-validation",+ "@univerjs/preset-sheets-conditional-formatting",+ "@univerjs/preset-sheets-hyper-link"+] as const;++/**+ * English (`en-US`) is Univer's built-in default and the fallback for every UI language without a+ * dedicated translation. Kept standalone because no {@link UNIVER_LOCALES} entry references it+ * directly — the English variants map to `null` rather than to a bundle.+ */+const ENGLISH_LOCALE: UniverLocaleSource = {+ type: LocaleType.EN_US,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/en-US'),+ import('@univerjs/preset-sheets-find-replace/locales/en-US'),+ import('@univerjs/preset-sheets-note/locales/en-US'),+ import('@univerjs/preset-sheets-filter/locales/en-US'),+ import('@univerjs/preset-sheets-sort/locales/en-US'),+ import('@univerjs/preset-sheets-data-validation/locales/en-US'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/en-US'),+ import('@univerjs/preset-sheets-hyper-link/locales/en-US')+ ])+};++/**+ * Maps every Trilium UI language to the Univer locale that best matches it — the {@link LocaleType}+ * enum plus a lazy loader that merges the matching bundle of every preset — or `null` to use+ * Univer's built-in English ({@link ENGLISH_LOCALE}) default. `null` covers both the English+ * variants (English is the default, so there is nothing to switch to) and languages Univer does not+ * translate (German, Romanian, Arabic, …). So the non-null entries are exactly the languages for+ * which Univer ships a non-English UI; spelling out `null` keeps each fallback an explicit decision.+ * The bundles load lazily, so a user only pays for the locale they actually use.+ *+ * Keyed by {@link DISPLAYABLE_LOCALE_IDS}, so introducing a new Trilium UI language fails to compile+ * (and trips the `locales.spec.ts` guard) until its Univer mapping — a source or `null` — is decided+ * here.+ */+export const UNIVER_LOCALES: Record<DISPLAYABLE_LOCALE_IDS, UniverLocaleSource | null> = {+ cn: {+ type: LocaleType.ZH_CN,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/zh-CN'),+ import('@univerjs/preset-sheets-find-replace/locales/zh-CN'),+ import('@univerjs/preset-sheets-note/locales/zh-CN'),+ import('@univerjs/preset-sheets-filter/locales/zh-CN'),+ import('@univerjs/preset-sheets-sort/locales/zh-CN'),+ import('@univerjs/preset-sheets-data-validation/locales/zh-CN'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/zh-CN'),+ import('@univerjs/preset-sheets-hyper-link/locales/zh-CN')+ ])+ },+ cs: null,+ de: null,+ en: null,+ "en-GB": null,+ en_rtl: null,+ ar: null,+ es: {+ type: LocaleType.ES_ES,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/es-ES'),+ import('@univerjs/preset-sheets-find-replace/locales/es-ES'),+ import('@univerjs/preset-sheets-note/locales/es-ES'),+ import('@univerjs/preset-sheets-filter/locales/es-ES'),+ import('@univerjs/preset-sheets-sort/locales/es-ES'),+ import('@univerjs/preset-sheets-data-validation/locales/es-ES'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/es-ES'),+ import('@univerjs/preset-sheets-hyper-link/locales/es-ES')+ ])+ },+ fr: {+ type: LocaleType.FR_FR,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/fr-FR'),+ import('@univerjs/preset-sheets-find-replace/locales/fr-FR'),+ import('@univerjs/preset-sheets-note/locales/fr-FR'),+ import('@univerjs/preset-sheets-filter/locales/fr-FR'),+ import('@univerjs/preset-sheets-sort/locales/fr-FR'),+ import('@univerjs/preset-sheets-data-validation/locales/fr-FR'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/fr-FR'),+ import('@univerjs/preset-sheets-hyper-link/locales/fr-FR')+ ])+ },+ ga: null,+ id: null,+ it: null,+ hi: null,+ ja: {+ type: LocaleType.JA_JP,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/ja-JP'),+ import('@univerjs/preset-sheets-find-replace/locales/ja-JP'),+ import('@univerjs/preset-sheets-note/locales/ja-JP'),+ import('@univerjs/preset-sheets-filter/locales/ja-JP'),+ import('@univerjs/preset-sheets-sort/locales/ja-JP'),+ import('@univerjs/preset-sheets-data-validation/locales/ja-JP'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/ja-JP'),+ import('@univerjs/preset-sheets-hyper-link/locales/ja-JP')+ ])+ },+ pt_br: null,+ pt: null,+ pl: null,+ ro: null,+ ru: {+ type: LocaleType.RU_RU,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/ru-RU'),+ import('@univerjs/preset-sheets-find-replace/locales/ru-RU'),+ import('@univerjs/preset-sheets-note/locales/ru-RU'),+ import('@univerjs/preset-sheets-filter/locales/ru-RU'),+ import('@univerjs/preset-sheets-sort/locales/ru-RU'),+ import('@univerjs/preset-sheets-data-validation/locales/ru-RU'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/ru-RU'),+ import('@univerjs/preset-sheets-hyper-link/locales/ru-RU')+ ])+ },+ tw: {+ type: LocaleType.ZH_TW,+ load: () => Promise.all([+ import('@univerjs/preset-sheets-core/locales/zh-TW'),+ import('@univerjs/preset-sheets-find-replace/locales/zh-TW'),+ import('@univerjs/preset-sheets-note/locales/zh-TW'),+ import('@univerjs/preset-sheets-filter/locales/zh-TW'),+ import('@univerjs/preset-sheets-sort/locales/zh-TW'),+ import('@univerjs/preset-sheets-data-validation/locales/zh-TW'),+ import('@univerjs/preset-sheets-conditional-formatting/locales/zh-TW'),+ import('@univerjs/preset-sheets-hyper-link/locales/zh-TW')+ ])+ },+ uk: null+};++/** Resolves the Univer locale source for a Trilium UI language, falling back to {@link ENGLISH_LOCALE}. */+export function resolveUniverLocaleSource(triliumLocale = getCurrentLanguage()): UniverLocaleSource {+ const locales: Record<string, UniverLocaleSource | null | undefined> = UNIVER_LOCALES;+ // Fall back to the base language (e.g. an unexpected "de-DE" -> "de") before giving up on English.+ const baseLanguage = triliumLocale.split(/[-_]/)[0];+ return locales[triliumLocale] ?? locales[baseLanguage] ?? ENGLISH_LOCALE;+}++/**+ * Loads and merges the Univer locale bundles matching the user's Trilium language. The resulting+ * {@link UniverLocale.type} also drives Univer's locale-dependent defaults, most notably the+ * currency symbol applied by the toolbar (e.g. € for euro-zone locales).+ */+export async function loadUniverLocale(triliumLocale = getCurrentLanguage()): Promise<UniverLocale> {+ const { type, load } = resolveUniverLocaleSource(triliumLocale);+ const modules = await load();+ return {+ type,+ data: mergeLocales(...modules.map((module) => module.default))+ };+}