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
feat(ckeditor5): localize the admonition types through editor.t()
Elian Doraneeac941b670c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fa5d1eb41a..8f84e1c04c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3605,7 +3605,12 @@"checkbox-tooltip-state-label": "Task state:","checkbox-tooltip-state-unknown-suffix": "(missing definition)","ck": {- "admonition": "Admonition"+ "admonition": "Admonition",+ "caution": "Caution",+ "important": "Important",+ "note": "Note",+ "tip": "Tip",+ "warning": "Warning"},"collapsible-body-placeholder": "Type the content here...","collapsible-button-label": "Collapsible block",diff --git a/apps/client/src/translations/ro/translation.json b/apps/client/src/translations/ro/translation.jsonindex 0077eb548b..4715c9af8d 100644--- a/apps/client/src/translations/ro/translation.json+++ b/apps/client/src/translations/ro/translation.json@@ -2690,7 +2690,12 @@"text-editor": {"checkbox-tooltip": "Clic dreapta pentru mai multe stări ale sarcinii.\nApăsați {{shortcut}} pentru a comuta între stări.","ck": {- "admonition": "Casetă de avertizare"+ "admonition": "Casetă de avertizare",+ "caution": "Atenție",+ "important": "Important",+ "note": "Notă",+ "tip": "Sfat",+ "warning": "Avertisment"},"collapsible-body-placeholder": "Scrieți conținutul aici...","collapsible-button-label": "Bloc pliabil",diff --git a/packages/ckeditor5/src/extra_slash_commands.spec.ts b/packages/ckeditor5/src/extra_slash_commands.spec.tsindex 3147836ad2..6be4cf5e10 100644--- a/packages/ckeditor5/src/extra_slash_commands.spec.ts+++ b/packages/ckeditor5/src/extra_slash_commands.spec.ts@@ -259,9 +259,21 @@ describe("buildExtraCommands", () => {expect(cmd?.icon).toBeTruthy();expect(cmd?.description).toBe("slash_commands.admonition_description");expect(cmd?.aliases).toContain("box");+ // `t` echoes the key here, so the title falls back to the English message id.+ expect(cmd?.title).toBe(ADMONITION_TYPES[keyword as keyof typeof ADMONITION_TYPES].title);}});+ // Built before any editor exists, so the titles go through `translateMessage()` rather than+ // `editor.t()` — same message ids, same derived keys.+ it("translates the titles through the host translator", async () => {+ const { ADMONITION_TYPES } = await import("./plugins/admonition/admonition_ui.js");+ const commands = buildExtraCommands((key) => (key === "text-editor.ck.warning" ? "Avertisment" : key));++ expect(commands.find((c) => c.id === "warning")?.title).toBe("Avertisment");+ expect(commands.find((c) => c.id === "note")?.title).toBe(ADMONITION_TYPES.note.title);+ });+it("admonition execute calls editor.execute('admonition') with the keyword", async () => {const { ADMONITION_TYPES } = await import("./plugins/admonition/admonition_ui.js");const commands = buildExtraCommands(t);diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.tsindex 16f14f5d33..9c073860a0 100644--- a/packages/ckeditor5/src/extra_slash_commands.ts+++ b/packages/ckeditor5/src/extra_slash_commands.ts@@ -12,6 +12,7 @@ import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from './plugins/includenote.js';import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from './plugins/markdownimport.js';import { ADMONITION_TYPES } from "./plugins/admonition/admonition_ui.js";import type { AdmonitionType } from "./plugins/admonition/admonition_command.js";+import { translateMessage } from "./messages.js";import collapsibleIcon from './icons/collapsible.svg?raw';import dateTimeIcon from './icons/date-time.svg?raw';import internalLinkIcon from './icons/trilium.svg?raw';@@ -217,7 +218,9 @@ function buildAdmonitionExtraCommands(t: SlashTranslateFn): SlashCommandDefinitifor (const [ keyword, definition ] of Object.entries(ADMONITION_TYPES)) {commands.push({id: keyword,- title: definition.title,+ // Built before any editor exists, so the message goes through the host translator+ // directly rather than `editor.t()` — same message ids, same fallback to English.+ title: translateMessage(t, definition.title),description: t("slash_commands.admonition_description"),icon: admonitionIcons[keyword as AdmonitionType],execute: (editor: Editor) => editor.execute("admonition", { forceValue: keyword as AdmonitionType }),diff --git a/packages/ckeditor5/src/i18n.spec.ts b/packages/ckeditor5/src/i18n.spec.tsindex c90586777f..1cfcf1fe5e 100644--- a/packages/ckeditor5/src/i18n.spec.ts+++ b/packages/ckeditor5/src/i18n.spec.ts@@ -1,7 +1,49 @@import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";+import { Essentials, Paragraph, SplitButtonView } from "ckeditor5";import { describe, expect, it } from "vitest";+import { createTestEditor } from "../test/editor-kit.js";import getCkLocale from "./i18n.js";+import { MESSAGE_KEY_PREFIX } from "./messages.js";+import Admonition from "./plugins/admonition/admonition.js";+import AdmonitionUI from "./plugins/admonition/admonition_ui.js";++/**+ * A translator that resolves only the admonition button, echoing every other key back the way+ * i18next does for a missing entry — so the assertions below pin one dictionary entry rather than+ * tracking the whole message list.+ */+function translateAdmonitionOnly(translation: string) {+ return (key: string) => (key === "text-editor.ck.admonition" ? translation : key);+}++interface AdmonitionDropdown {+ isOpen: boolean;+ buttonView: SplitButtonView;+ panelView: {+ children: {+ get(index: number): {+ items: { length: number; get(index: number): { children: { get(index: number): { label?: string } } } };+ } | null;+ };+ };+}++/**+ * Open the dropdown — `addListToDropdown` only populates the panel on first open — and read the+ * label of every admonition type entry.+ */+function readTypeLabels(dropdown: AdmonitionDropdown): string[] {+ dropdown.isOpen = true;+ const listView = dropdown.panelView.children.get(0);+ if (!listView) throw new Error("expected the type list to be populated");++ const labels: string[] = [];+ for (let index = 0; index < listView.items.length; index++) {+ labels.push(listView.items.get(index).children.get(0).label ?? "");+ }+ return labels;+}describe("getCkLocale", () => {// "en" needs no translation at all, while "en_rtl" (a dev-only pseudo-locale) and "ga" have no@@ -20,7 +62,7 @@ describe("getCkLocale", () => {});it("appends the Trilium dictionary after the core translations", async () => {- const { language, translations } = await getCkLocale("de", () => "Ermahnung");+ const { language, translations } = await getCkLocale("de", translateAdmonitionOnly("Ermahnung"));expect(language).toBe("de");if (!Array.isArray(translations)) throw new Error("expected an array of translations");@@ -38,7 +80,7 @@ describe("getCkLocale", () => {if (!Array.isArray(before.translations)) throw new Error("expected an array of translations");const coreEntry = before.translations[1] as Record<string, { dictionary: Record<string, string> }>;- await getCkLocale("de", () => "Ermahnung");+ await getCkLocale("de", translateAdmonitionOnly("Ermahnung"));expect(coreEntry.de.dictionary).not.toHaveProperty("Admonition");});@@ -46,7 +88,7 @@ describe("getCkLocale", () => {// A locale with no CKEditor translation still needs the dictionary, since it also carries any// rewording of the editor's built-in English strings.it("supplies a dictionary keyed 'en' for locales with no core translation", async () => {- const { language, translations } = await getCkLocale("ga", () => "Rabhadh");+ const { language, translations } = await getCkLocale("ga", translateAdmonitionOnly("Rabhadh"));expect(language).toBeUndefined();expect(translations).toEqual([ {}, { en: { dictionary: { Admonition: "Rabhadh" } } } ]);@@ -58,6 +100,46 @@ describe("getCkLocale", () => {expect(await getCkLocale("ga", (key) => key)).toEqual({});});+ // End-to-end over a real editor: `AdmonitionUI` localizes with plain `editor.t("Admonition")`,+ // knowing nothing about translation keys or the host, and the only thing that makes it Romanian+ // is the dictionary configured here.+ describe("applied to an editor", () => {+ const RO_MESSAGES: Record<string, string> = {+ admonition: "Casetă de avertizare",+ caution: "Atenție",+ important: "Important",+ note: "Notă",+ tip: "Sfat",+ warning: "Avertisment"+ };+ const translateToRomanian = (key: string) => RO_MESSAGES[key.replace(MESSAGE_KEY_PREFIX, "")] ?? key;++ async function createAdmonitionDropdown(localeConfig: Awaited<ReturnType<typeof getCkLocale>>) {+ const editor = await createTestEditor([ Essentials, Paragraph, Admonition, AdmonitionUI ], localeConfig);+ return editor.ui.componentFactory.create("admonition") as unknown as AdmonitionDropdown;+ }++ it("translates the button and every type entry through the host translator", async () => {+ const dropdown = await createAdmonitionDropdown(await getCkLocale("ro", translateToRomanian));++ expect(dropdown.buttonView.label).toBe("Casetă de avertizare");+ expect(readTypeLabels(dropdown)).toEqual([ "Notă", "Sfat", "Important", "Atenție", "Avertisment" ]);+ });++ // What makes the mechanism seamless: with no host attached the editor still renders correct+ // English, because the message id passed to `t()` *is* the English text. Same for a+ // configured translator that cannot resolve the key.+ it.each([+ [ "no translator is configured", undefined ],+ [ "the translation is missing", (key: string) => key ]+ ])("falls back to the English message ids when %s", async (_case, translate) => {+ const dropdown = await createAdmonitionDropdown(await getCkLocale("ro", translate));++ expect(dropdown.buttonView.label).toBe("Admonition");+ expect(readTypeLabels(dropdown)).toEqual([ "Note", "Tip", "Important", "Caution", "Warning" ]);+ });+ });+// The CKEditor language code often differs from Trilium's locale id, so pin the mapping for// every locale rather than only the ones that happen to match.it.each<[DISPLAYABLE_LOCALE_IDS, string]>([diff --git a/packages/ckeditor5/src/messages.spec.ts b/packages/ckeditor5/src/messages.spec.tsindex 19293f1c17..dd287fa431 100644--- a/packages/ckeditor5/src/messages.spec.ts+++ b/packages/ckeditor5/src/messages.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { buildMessageDictionary, MESSAGE_KEY_PREFIX, MESSAGES, slugify } from "./messages.js";+import { buildMessageDictionary, MESSAGE_KEY_PREFIX, MESSAGES, slugify, translateMessage } from "./messages.js";describe("slugify", () => {// The punctuation cases matter: `.` separates key paths in i18next, and `"`/`%0` would be@@ -20,9 +20,9 @@ describe("buildMessageDictionary", () => {it("maps each message id to its translation", () => {const dictionary = buildMessageDictionary((key) => `translated:${key}`);- expect(dictionary).toEqual({- Admonition: `translated:${MESSAGE_KEY_PREFIX}admonition`- });+ expect(dictionary.Admonition).toBe(`translated:${MESSAGE_KEY_PREFIX}admonition`);+ expect(dictionary.Warning).toBe(`translated:${MESSAGE_KEY_PREFIX}warning`);+ expect(Object.keys(dictionary)).toHaveLength(MESSAGES.length);});// i18next echoes the key back when an entry is missing. Putting that in the dictionary would@@ -33,6 +33,10 @@ describe("buildMessageDictionary", () => {expect(buildMessageDictionary(() => "")).toEqual({});});+ it("has no duplicate message ids", () => {+ expect(new Set(MESSAGES).size).toBe(MESSAGES.length);+ });+it("covers every message id, keyed by its slug", () => {const dictionary = buildMessageDictionary((key) => key.slice(MESSAGE_KEY_PREFIX.length));@@ -42,3 +46,17 @@ describe("buildMessageDictionary", () => {}});});++describe("translateMessage", () => {+ it("resolves a message id through the host translator", () => {+ expect(translateMessage((key) => `translated:${key}`, "Warning"))+ .toBe(`translated:${MESSAGE_KEY_PREFIX}warning`);+ });++ // The counterpart of `editor.t()`'s fallback, for the code that has no editor: an unresolved+ // key must render the English message id, never `text-editor.ck.…`.+ it("falls back to the English message id", () => {+ expect(translateMessage((key) => key, "Warning")).toBe("Warning");+ expect(translateMessage(() => "", "Warning")).toBe("Warning");+ });+});diff --git a/packages/ckeditor5/src/messages.ts b/packages/ckeditor5/src/messages.tsindex 76ff3ff627..b49e6959cb 100644--- a/packages/ckeditor5/src/messages.ts+++ b/packages/ckeditor5/src/messages.ts@@ -24,11 +24,19 @@ export const MESSAGE_KEY_PREFIX = "text-editor.ck.";* Every English message id the editor package owns, i.e. each distinct string passed to* `editor.t()` by a Trilium plugin (plus any upstream string we deliberately reword).*- * Draft scope: only the admonition button. The remaining plugins still localize through the older+ * Current scope: the admonition feature. The remaining plugins still localize through the older* `config.translate` bridge and are migrated separately.*/export const MESSAGES = [- "Admonition"+ "Admonition",+ // The admonition types, declared as titles in `ADMONITION_TYPES` and rendered by the toolbar+ // dropdown, the type dropdown and the slash commands. `admonition_messages.spec.ts` keeps this+ // list and that map in sync.+ "Note",+ "Tip",+ "Important",+ "Caution",+ "Warning"] as const;/**@@ -46,6 +54,20 @@ export function slugify(message: string): string {.replace(/^-+|-+$/g, "");}+/**+ * Translate a single message id outside an editor, for code that builds editor content before an+ * editor exists — the slash-command definitions, for instance. Inside a plugin use `editor.t()`+ * instead; this is the same lookup, minus the editor.+ *+ * Falls back to the message id, which is the English text, so a missing entry renders English+ * rather than a raw key.+ */+export function translateMessage(translate: (key: string) => string, message: string): string {+ const key = MESSAGE_KEY_PREFIX + slugify(message);+ const translated = translate(key);+ return translated && translated !== key ? translated : message;+}+/*** Build the CKEditor dictionary for {@link MESSAGES} using the host's translator.*diff --git a/packages/ckeditor5/src/messages_integration.spec.ts b/packages/ckeditor5/src/messages_integration.spec.tsdeleted file mode 100644index 12fce0f814..0000000000--- a/packages/ckeditor5/src/messages_integration.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { Essentials, Paragraph, SplitButtonView } from "ckeditor5";-import { describe, expect, it } from "vitest";--import { createTestEditor } from "../test/editor-kit.js";-import getCkLocale from "./i18n.js";-import Admonition from "./plugins/admonition/admonition.js";-import AdmonitionUI from "./plugins/admonition/admonition_ui.js";--/**- * End-to-end check of the localization bridge against a real editor: `AdmonitionUI` localizes its- * button with plain `editor.t("Admonition")`, and the only thing that makes it German is the- * dictionary `getCkLocale()` appends to the editor config. The plugin itself knows nothing about- * translation keys or the host.- */-async function createAdmonitionEditor(localeConfig: Awaited<ReturnType<typeof getCkLocale>>) {- const editor = await createTestEditor([ Essentials, Paragraph, Admonition, AdmonitionUI ], localeConfig);- const button = editor.ui.componentFactory.create("admonition");- if (!(button instanceof SplitButtonView) && !("buttonView" in button)) {- throw new Error("expected the admonition dropdown");- }- return (button as unknown as { buttonView: SplitButtonView }).buttonView;-}--describe("editor.t() localization bridge", () => {- it("translates a plugin's button through the host translator", async () => {- const buttonView = await createAdmonitionEditor(await getCkLocale("de", () => "Ermahnung"));-- expect(buttonView.label).toBe("Ermahnung");- });-- // The property that makes the bridge seamless: with no host attached the editor still renders- // correct English, because the message id passed to `t()` *is* the English text.- it("falls back to the English message id when no translator is configured", async () => {- const buttonView = await createAdmonitionEditor(await getCkLocale("de"));-- expect(buttonView.label).toBe("Admonition");- });-- it("renders English rather than a raw key when the translation is missing", async () => {- const buttonView = await createAdmonitionEditor(await getCkLocale("de", (key) => key));-- expect(buttonView.label).toBe("Admonition");- });-});diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.tsindex d4d5ad54f2..56d886dff8 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts@@ -30,7 +30,9 @@ export default class AdmonitionTypeDropdown extends Plugin {dropdownView.buttonView.bind("label").to(command, "value", (value) => {if (!value) return "";const typeDef = ADMONITION_TYPES[value as AdmonitionType];- return typeDef?.title ?? value;+ // The title is an English message id; an unknown type has none, so its raw value+ // is shown as-is rather than run through `t()`.+ return typeDef ? editor.t(typeDef.title) : value;});dropdownView.on("execute", evt => {const source = evt.source as any;@@ -54,7 +56,7 @@ export default class AdmonitionTypeDropdown extends Plugin {type: "button",model: new ViewModel({commandParam: type,- label: typeDef.title,+ label: editor.t(typeDef.title),class: `ck-tn-admonition-option ck-tn-admonition-${type}`,role: "menuitemradio",withText: truediff --git a/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.ts b/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.tsindex 91a7a6b77d..961716ae87 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.ts@@ -2,6 +2,7 @@ import { _setModelData as setModelData, ClassicEditor, Essentials, Paragraph, Spimport { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import { MESSAGES } from "../../messages.js";import Admonition from "./admonition.js";import type AdmonitionCommand from "./admonition_command.js";import AdmonitionUI, { ADMONITION_TYPES } from "./admonition_ui.js";@@ -113,11 +114,25 @@ describe("AdmonitionUI", () => {expect(types).toContain(button.commandParam);if (type) {+ // No dictionary is configured here, so `t()` renders the message id, which is+ // the English title.expect(button.label).toBe(ADMONITION_TYPES[type].title);}}});+ // The titles are localized by passing them to `t()` as message ids, which only resolves if+ // each is declared in `MESSAGES` — that list is what builds the dictionary. A type added to+ // `ADMONITION_TYPES` alone would silently stay English in every locale.+ it("declares every type title as a message id", () => {+ const titles = Object.values(ADMONITION_TYPES).map((definition) => definition.title);++ expect(titles).not.toHaveLength(0);+ for (const title of titles) {+ expect(MESSAGES, `"${title}" is missing from MESSAGES`).toContain(title);+ }+ });+it("applies the picked type when a dropdown item is executed", () => {setModelData(editor.model, "<paragraph>foo[]</paragraph>");diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts b/packages/ckeditor5/src/plugins/admonition/admonition_ui.tsindex 28625c28bc..4a563749e5 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts@@ -109,12 +109,16 @@ export default class AdmonitionUI extends Plugin {return itemDefinitions;}+ // The titles are English message ids; `t()` translates them where a dictionary is+ // configured and returns them unchanged otherwise.+ const t = this.editor.t;+for (const [type, admonition] of Object.entries(ADMONITION_TYPES)) {const definition: ListDropdownItemDefinition = {type: "button",model: new ViewModel({commandParam: type,- label: admonition.title,+ label: t(admonition.title),class: `ck-tn-admonition-option ck-tn-admonition-${type}`,role: "menuitemradio",withText: true