Skip to content

Build your personal knowledge base with Trilium Notes

feat(ai-assistant): offer the enabled content languages under Translate

Elian Doran589427a7de4b
diff --git a/apps/client/src/services/i18n.ts b/apps/client/src/services/i18n.ts
index 7c4e2b9cab..447739b53a 100644
--- a/apps/client/src/services/i18n.ts
+++ b/apps/client/src/services/i18n.ts
@@ -1,4 +1,4 @@
-import { type Locale, LOCALE_IDS, LOCALES, setDayjsLocale } from "@triliumnext/commons";
+import { getEnglishName, type Locale, LOCALE_IDS, LOCALES, setDayjsLocale } from "@triliumnext/commons";
import i18next from "i18next";
import i18nextHttpBackend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
@@ -84,33 +84,3 @@ function withEnglishName(locale: Locale, englishNames: Intl.DisplayNames): strin
: locale.name;
}
-/**
- * The English name of a locale, or `null` when there is none worth showing: the English entries are
- * named in English already, and anything `Intl` does not recognize has nothing to offer.
- */
-function getEnglishName(localeId: string, englishNames: Intl.DisplayNames): string | null {
- const tag = ENGLISH_NAME_TAGS[localeId] ?? localeId.replaceAll("_", "-");
-
- // Covers `en_rtl` too, which is not even a well-formed tag — `Intl` would throw on it.
- if (tag === "en" || tag.startsWith("en-")) return null;
-
- try {
- return englishNames.of(tag) ?? null;
- } catch {
- // A malformed tag is a RangeError rather than an empty result.
- return null;
- }
-}
-
-/**
- * Locale ids that are not BCP-47 tags, mapped to one.
- *
- * The Chinese pair deliberately resolves through the script subtags rather than the regions
- * `normalizeLocale` (in `utils/formatters`) maps them to: `zh-Hans` reads as "Simplified Chinese",
- * whereas `zh-CN` would say "Chinese (China)" — the wrong distinction for entries differing by
- * script.
- */
-const ENGLISH_NAME_TAGS: Record<string, string> = {
- cn: "zh-Hans",
- tw: "zh-Hant"
-};
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 89f5b995d1..e2f85a62a0 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2871,13 +2871,7 @@
"reformat_diagram": "Diagram",
"reformat_callout": "Callout",
"reformat_collapsible": "Collapsible",
- "reformat_action_items": "Action items",
- "lang_english": "English",
- "lang_german": "German",
- "lang_spanish": "Spanish",
- "lang_french": "French",
- "lang_romanian": "Romanian",
- "lang_chinese": "Simplified Chinese"
+ "reformat_action_items": "Action items"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
index 99fd8e3b4e..2174a4d977 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
@@ -6,13 +6,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
// Keys stand in for their translations; a key with interpolation renders as `key(name=value)`, so
// a composed label shows both the key it went through and what was substituted into it.
-vi.mock("../../../services/i18n.js", () => ({
- t: (key: string, values?: Record<string, string>) => (values
- ? `${key}(${Object.entries(values).map(([name, value]) => `${name}=${value}`).join(",")})`
- : key)
-}));
+vi.mock("../../../services/i18n.js", async () => {
+ // The real catalogue, which is what the function returns in a production build: the languages
+ // the Translate submenu offers are exactly the ones out of it the user enabled.
+ const { LOCALES } = await import("@triliumnext/commons");
+ return {
+ t: (key: string, values?: Record<string, string>) => (values
+ ? `${key}(${Object.entries(values).map(([name, value]) => `${name}=${value}`).join(",")})`
+ : key),
+ getAvailableLocales: () => LOCALES
+ };
+});
vi.mock("../../../services/options.js", () => ({
- default: { getJson: () => storedProviders }
+ default: { getJson: (key: string) => (key === "languages" ? storedLanguages : storedProviders) }
}));
vi.mock("../../../services/llm_chat.js", () => ({
streamChatCompletion: vi.fn(async (messages, config, callbacks) => {
@@ -34,6 +40,8 @@ import buildAiAssistantStream, { buildAiAssistantQuickActions, stripMarkdownFenc
/** The `llmProviders` option as the mocked `options.getJson` will return it. */
let storedProviders: unknown = null;
+/** The `languages` option — the locale ids enabled as content languages. */
+let storedLanguages: unknown = null;
/** The config each `streamChatCompletion` call was made with, in order. */
let requestedConfigs: LlmChatConfig[] = [];
/** The messages each `streamChatCompletion` call was made with, in order. */
@@ -47,6 +55,7 @@ const PROVIDER = [{ id: "cfg-openai", provider: "openai", selectedModels: [{ id:
beforeEach(() => {
storedProviders = null;
+ storedLanguages = null;
requestedConfigs = [];
requestedMessages = [];
responseChunks = ["done"];
@@ -246,13 +255,42 @@ describe("buildAiAssistantQuickActions", () => {
expect(direct?.label).toBe("ai_assistant.tone_direct");
expect(direct?.commandLabel).toBe("ai_assistant.command_tone(tone=ai_assistant.tone_direct)");
- const romanian = actions("translate").find((action) => action.id === "translateRomanian");
- expect(romanian?.label).toBe("ai_assistant.lang_romanian");
- expect(romanian?.commandLabel).toBe("ai_assistant.command_translate(language=ai_assistant.lang_romanian)");
+ const romanian = actions("translate").find((action) => action.id === "translate:ro");
+ expect(romanian?.label).toBe("Română");
+ expect(romanian?.commandLabel).toBe("ai_assistant.command_translate(language=Română)");
// The instruction is not translated: it is addressed to the model, not to the user.
expect(romanian?.prompt).toBe("Translate the content to Romanian.");
});
+ // The list is the user's own — the languages they enabled as content languages, the same ones a
+ // note's language is picked from — rather than a fixed six that suit nobody in particular.
+ it("offers the enabled content languages, naming each in itself but to the model in English", () => {
+ storedLanguages = ["ja", "cn", "pt_br", "en-GB", "ar"];
+
+ // Ordered as the catalogue is — by native name — so the submenu reads the same way as the
+ // language picker the list was configured in.
+ expect(actions("translate").map((action) => [action.id, action.label, action.prompt])).toEqual([
+ ["translate:en-GB", "English (United Kingdom)", "Translate the content to English (United Kingdom)."],
+ ["translate:pt_br", "Português (Brasil)", "Translate the content to Brazilian Portuguese."],
+ ["translate:ar", "اَلْعَرَبِيَّةُ", "Translate the content to Arabic."],
+ ["translate:ja", "日本語", "Translate the content to Japanese."],
+ // `zh-Hans`, not the `zh-CN` the locale maps to elsewhere: the pair differs by script,
+ // so "Simplified Chinese" is the name that tells them apart and "Chinese (China)" is not.
+ ["translate:cn", "简体中文", "Translate the content to Simplified Chinese."]
+ ]);
+ });
+
+ // Nothing is enabled on a fresh install, and an empty Translate submenu would say the feature
+ // was broken rather than unconfigured.
+ it("falls back to the original six when no content language is enabled", () => {
+ for (const empty of [null, []]) {
+ storedLanguages = empty;
+ expect(actions("translate").map((action) => action.id)).toEqual([
+ "translate:de", "translate:en", "translate:es", "translate:fr", "translate:ro", "translate:cn"
+ ]);
+ }
+ });
+
// "Make shorter" against "Simplify language", "Turn into a table" against "Extract action
// items": no single phrase composes either pair, so both labels are translated as a pair.
it("spells out both labels for the adjustments and the reformats", () => {
@@ -331,8 +369,7 @@ describe("buildAiAssistantQuickActions", () => {
expect([ ...reviewViews ].filter(([, view]) => view === "result").map(([id]) => id))
.toEqual([
"summarize", "explain", "continue", "table", "diagram", "actionItems",
- "translateEnglish", "translateGerman", "translateSpanish", "translateFrench",
- "translateRomanian", "translateChinese"
+ "translate:de", "translate:en", "translate:es", "translate:fr", "translate:ro", "translate:cn"
]);
for (const id of ["fixTypos", "improveWriting", "makeShorter", "professional", "callout"]) {
expect(reviewViews.get(id), id).toBeUndefined();
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
index c5a329cdaf..b0bc44c682 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
@@ -1,7 +1,7 @@
import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";
-import type { LlmChatConfig, LlmMessage, LlmModelInfo, LlmUsage, ToMarkdownResponse } from "@triliumnext/commons";
+import { getEnglishName, type LlmChatConfig, type LlmMessage, type LlmModelInfo, type LlmUsage, type Locale, type ToMarkdownResponse } from "@triliumnext/commons";
-import { t } from "../../../services/i18n.js";
+import { getAvailableLocales, t } from "../../../services/i18n.js";
import { streamChatCompletion } from "../../../services/llm_chat.js";
import options from "../../../services/options.js";
import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";
@@ -167,14 +167,7 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
id: "translate",
label: t("ai_assistant.group_translate"),
submenu: true,
- actions: [
- translateAction("translateEnglish", t("ai_assistant.lang_english"), "Translate the content to English."),
- translateAction("translateGerman", t("ai_assistant.lang_german"), "Translate the content to German."),
- translateAction("translateSpanish", t("ai_assistant.lang_spanish"), "Translate the content to Spanish."),
- translateAction("translateFrench", t("ai_assistant.lang_french"), "Translate the content to French."),
- translateAction("translateRomanian", t("ai_assistant.lang_romanian"), "Translate the content to Romanian."),
- translateAction("translateChinese", t("ai_assistant.lang_chinese"), "Translate the content to Simplified Chinese.")
- ]
+ actions: buildTranslateActions()
}
]);
}
@@ -276,9 +269,50 @@ function toneAction(id: string, tone: string, prompt: string): AiQuickAction {
return { id, label: tone, commandLabel: t("ai_assistant.command_tone", { tone }), prompt };
}
-/** The prompt stays English and spelled out: the label is translated, the instruction is not. */
-function translateAction(id: string, language: string, prompt: string): AiQuickAction {
- return { id, label: language, commandLabel: t("ai_assistant.command_translate", { language }), prompt };
+/**
+ * The languages the Translate submenu offers: the ones enabled as content languages, which is the
+ * list a note's own language is picked from and the closest thing Trilium has to a record of the
+ * languages this user works in. macOS reads the system's preferred languages for its own Translate
+ * for the same reason, and Word offers a shortlist with the full picker behind it — a fixed six is
+ * the one shape nobody ships, because no six are right for everybody.
+ *
+ * Read when the editor is built, like the provider list: enabling a language in Options →
+ * Localization shows it after the editor is next rebuilt.
+ *
+ * A fresh install has none enabled, so the original six stand in — enough to show what the submenu
+ * is for, and the settings are where it is made the user's own.
+ */
+function buildTranslateActions(): AiQuickAction[] {
+ const available = getAvailableLocales();
+ const enabled = (options.getJson("languages") as string[] | null) ?? [];
+
+ const selected = available.filter((locale) => enabled.includes(locale.id));
+ const locales = selected.length
+ ? selected
+ : available.filter((locale) => FALLBACK_TRANSLATE_LOCALES.has(locale.id));
+
+ return locales.map((locale) => translateAction(locale));
+}
+
+const FALLBACK_TRANSLATE_LOCALES = new Set(["en", "de", "es", "fr", "ro", "cn"]);
+
+/**
+ * The label is the language's own name, as everywhere else a language is picked in Trilium — a
+ * speaker looking for their own language expects to find it written in it.
+ *
+ * The prompt is not: it addresses the model, and a model told to translate "to 简体中文" has to read
+ * the target out of the very script it is written in first. `Intl` has no English name for the
+ * English entries (their own name is already one) or for a tag it does not know, which is what the
+ * fallback covers.
+ */
+function translateAction(locale: Locale): AiQuickAction {
+ const language = locale.name;
+ return {
+ id: `translate:${locale.id}`,
+ label: language,
+ commandLabel: t("ai_assistant.command_translate", { language }),
+ prompt: `Translate the content to ${getEnglishName(locale.id) ?? locale.name}.`
+ };
}
/**
diff --git a/packages/commons/src/lib/i18n.ts b/packages/commons/src/lib/i18n.ts
index 9c225a18a1..83b04d2845 100644
--- a/packages/commons/src/lib/i18n.ts
+++ b/packages/commons/src/lib/i18n.ts
@@ -115,3 +115,43 @@ export function isDisplayableLocale(localeId: string | null | undefined): locale
if (!localeId) return false;
return LOCALES.some((l) => l.id === localeId && !l.contentOnly);
}
+
+/**
+ * The English name of a locale, or `null` when there is none worth showing: the English entries are
+ * named in English already, and anything `Intl` does not recognize has nothing to offer.
+ *
+ * Used both to annotate the locale list for a developer who cannot tell `한국어` from `हिन्दी`, and to
+ * name a language to something other than the user — an instruction to a language model, say, which
+ * would otherwise have to read its target out of the script that target is written in.
+ *
+ * @param englishNames a formatter to reuse, for a caller naming a whole list of locales at once.
+ */
+export function getEnglishName(
+ localeId: string,
+ englishNames = new Intl.DisplayNames([ "en" ], { type: "language" })
+): string | null {
+ const tag = ENGLISH_NAME_TAGS[localeId] ?? localeId.replaceAll("_", "-");
+
+ // Covers `en_rtl` too, which is not even a well-formed tag — `Intl` would throw on it.
+ if (tag === "en" || tag.startsWith("en-")) return null;
+
+ try {
+ return englishNames.of(tag) ?? null;
+ } catch {
+ // A malformed tag is a RangeError rather than an empty result.
+ return null;
+ }
+}
+
+/**
+ * Locale ids that are not BCP-47 tags, mapped to one.
+ *
+ * The Chinese pair deliberately resolves through the script subtags rather than the regions
+ * `normalizeLocale` (in the client's `utils/formatters`) maps them to: `zh-Hans` reads as
+ * "Simplified Chinese", whereas `zh-CN` would say "Chinese (China)" — the wrong distinction for
+ * entries differing by script.
+ */
+const ENGLISH_NAME_TAGS: Record<string, string> = {
+ cn: "zh-Hans",
+ tw: "zh-Hant"
+};