Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor5): localize plugin strings through editor.t()

Elian Dorancd365f6c5310
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 78ad5b4b96..fa5d1eb41a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3604,6 +3604,9 @@
"checkbox-tooltip": "Right-click or press {{- shortcut}} to change state.",
"checkbox-tooltip-state-label": "Task state:",
"checkbox-tooltip-state-unknown-suffix": "(missing definition)",
+ "ck": {
+ "admonition": "Admonition"
+ },
"collapsible-body-placeholder": "Type the content here...",
"collapsible-button-label": "Collapsible block",
"collapsible-handle-tooltip": "Drag to reposition the collapsible block",
diff --git a/apps/client/src/translations/ro/translation.json b/apps/client/src/translations/ro/translation.json
index 68e7b588f5..0077eb548b 100644
--- a/apps/client/src/translations/ro/translation.json
+++ b/apps/client/src/translations/ro/translation.json
@@ -2689,6 +2689,9 @@
},
"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"
+ },
"collapsible-body-placeholder": "Scrieți conținutul aici...",
"collapsible-button-label": "Bloc pliabil",
"collapsible-handle-tooltip": "Trageți pentru a repoziționa blocul pliabil",
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 4897f8d954..54263b6f17 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -129,9 +129,11 @@ describe("CK config", () => {
if (locale.id !== "en" && locale.id !== "ga") {
expect((config.language as unknown as { ui: string }).ui).toMatch(new RegExp(`^${expectedLocale}`));
expect(config.translations, locale.id).toBeDefined();
- // Only CKEditor's GPL core translations: the premium bundle used to contribute a
- // second entry, but no premium plugin is loaded any more.
- expect(config.translations, locale.id).toHaveLength(1);
+ // The merge seed and CKEditor's GPL core translations. The premium bundle used to
+ // contribute another entry, but no premium plugin is loaded any more; the Trilium
+ // message dictionary is absent because i18next is not initialized here, so every
+ // editor string falls back to the English message id.
+ expect(config.translations, locale.id).toHaveLength(2);
}
}
}, 20_000);
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 3c276dc15e..b4b6e95697 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -184,7 +184,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
allow: JSON.parse(options.get("allowedHtmlTags"))
},
removePlugins: getDisabledPlugins(),
- ...await getCkLocale(opts.uiLanguage)
+ // The locale's CKEditor translations, plus the dictionary of Trilium-authored editor
+ // strings resolved through the app's i18n (see `messages.ts` in the ckeditor5 package).
+ ...await getCkLocale(opts.uiLanguage, (key) => t(key))
};
// User-configurable todo task states (from the `_taskStates` hidden subtree).
diff --git a/packages/ckeditor5/src/i18n.spec.ts b/packages/ckeditor5/src/i18n.spec.ts
index 70b2e6eda7..c90586777f 100644
--- a/packages/ckeditor5/src/i18n.spec.ts
+++ b/packages/ckeditor5/src/i18n.spec.ts
@@ -10,6 +10,54 @@ describe("getCkLocale", () => {
expect(await getCkLocale(locale)).toEqual({});
});
+ // Without a host translator (a test, or a standalone editor) nothing is configured beyond
+ // CKEditor's own translations: plugins fall back to the English message ids they pass to `t()`.
+ it("adds no dictionary when no translator is given", async () => {
+ const { translations } = await getCkLocale("de");
+
+ // The merge seed plus CKEditor's own translations, and nothing of ours.
+ expect(translations).toHaveLength(2);
+ });
+
+ it("appends the Trilium dictionary after the core translations", async () => {
+ const { language, translations } = await getCkLocale("de", () => "Ermahnung");
+
+ expect(language).toBe("de");
+ if (!Array.isArray(translations)) throw new Error("expected an array of translations");
+ // Seed, core translations, ours — ours last, so it wins for any message id both define.
+ expect(translations).toHaveLength(3);
+ expect(translations[0]).toEqual({});
+ expect(translations[2]).toEqual({ de: { dictionary: { Admonition: "Ermahnung" } } });
+ });
+
+ // CKEditor merges the `translations` array in place via `reduce(merge)`, so a missing seed
+ // would write our dictionary into the shared `ckeditor5/translations/<lang>.js` module object
+ // and leak it into every other editor on the page.
+ it("does not mutate the imported core translations", async () => {
+ const before = await getCkLocale("de");
+ 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");
+
+ expect(coreEntry.de.dictionary).not.toHaveProperty("Admonition");
+ });
+
+ // 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");
+
+ expect(language).toBeUndefined();
+ expect(translations).toEqual([ {}, { en: { dictionary: { Admonition: "Rabhadh" } } } ]);
+ });
+
+ // An unresolved key yields an empty dictionary, which must not be pushed as a translations
+ // entry — an empty dictionary for a locale would otherwise shadow nothing but still allocate.
+ it("omits the dictionary when the translator resolves nothing", async () => {
+ expect(await getCkLocale("ga", (key) => key)).toEqual({});
+ });
+
// 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]>([
@@ -36,11 +84,12 @@ describe("getCkLocale", () => {
const result = await getCkLocale(locale);
expect(result.language).toBe(languageCode);
- // A single entry: the GPL core translations. The premium bundle used to add a second one,
- // but no premium plugin is loaded any more.
+ // The merge seed and the GPL core translations. The premium bundle used to add another
+ // entry, but no premium plugin is loaded any more; this call passes no translator, so the
+ // Trilium dictionary is absent too.
const translations = result.translations;
if (!Array.isArray(translations)) throw new Error("expected an array of translations");
- expect(translations).toHaveLength(1);
- expect(typeof translations[0]).toBe("object");
+ expect(translations).toHaveLength(2);
+ expect(typeof translations[1]).toBe("object");
});
});
diff --git a/packages/ckeditor5/src/i18n.ts b/packages/ckeditor5/src/i18n.ts
index 297e062ef6..b9c245f98d 100644
--- a/packages/ckeditor5/src/i18n.ts
+++ b/packages/ckeditor5/src/i18n.ts
@@ -1,6 +1,8 @@
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { EditorConfig, Translations } from "ckeditor5";
+import { buildMessageDictionary } from "./messages.js";
+
interface LocaleMapping {
languageCode: string;
coreTranslation: () => Promise<{ default: Translations }>;
@@ -88,13 +90,48 @@ const LOCALE_MAPPINGS: Record<DISPLAYABLE_LOCALE_IDS, LocaleMapping | null> = {
},
};
-export default async function getCkLocale(locale: DISPLAYABLE_LOCALE_IDS): Promise<Pick<EditorConfig, "language" | "translations">> {
+/**
+ * Build the editor's language configuration: CKEditor's own translations for the locale, plus the
+ * dictionary of Trilium-authored strings (see `messages.ts`).
+ *
+ * The two are separate entries in the `translations` array, and CKEditor merges them in order, so
+ * ours wins where both define a message id — which is how an upstream string can be reworded per
+ * locale.
+ *
+ * @param locale the Trilium locale to configure the editor for.
+ * @param translate the host's translator, resolving an i18next key to the localized string. Omit it
+ * (a test, a standalone editor) and every Trilium string falls back to the English
+ * message id passed to `editor.t()`.
+ */
+export default async function getCkLocale(
+ locale: DISPLAYABLE_LOCALE_IDS,
+ translate?: (key: string) => string
+): Promise<Pick<EditorConfig, "language" | "translations">> {
const mapping = LOCALE_MAPPINGS[locale];
- if (!mapping) return {};
+ const translations: Translations[] = [];
+
+ // `en`, the `en_rtl` pseudo-locale and `ga` have no CKEditor translation to load; they still get
+ // our dictionary, since it also carries any rewording of CKEditor's built-in English strings.
+ if (mapping) {
+ translations.push((await mapping.coreTranslation()).default);
+ }
+
+ if (translate) {
+ const dictionary = buildMessageDictionary(translate);
+ if (Object.keys(dictionary).length > 0) {
+ // Keyed by the language CKEditor will resolve messages under, which is the editor's
+ // default (`en`) whenever we pass no `language` below.
+ translations.push({ [mapping?.languageCode ?? "en"]: { dictionary } });
+ }
+ }
- const coreTranslation = (await (mapping.coreTranslation())).default;
return {
- language: mapping.languageCode,
- translations: [ coreTranslation ]
+ ...(mapping ? { language: mapping.languageCode } : {}),
+ // The empty leading entry is load-bearing. CKEditor merges `translations` with
+ // `array.reduce(merge)` and no initial value, so the *first* entry is mutated in place —
+ // without the seed our dictionary would be written into the imported
+ // `ckeditor5/translations/<lang>.js` module object, which is shared by every editor on the
+ // page and would keep applying to editors built with no dictionary at all.
+ ...(translations.length > 0 ? { translations: [ {}, ...translations ] } : {})
};
}
diff --git a/packages/ckeditor5/src/messages.spec.ts b/packages/ckeditor5/src/messages.spec.ts
new file mode 100644
index 0000000000..19293f1c17
--- /dev/null
+++ b/packages/ckeditor5/src/messages.spec.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+
+import { buildMessageDictionary, MESSAGE_KEY_PREFIX, MESSAGES, slugify } from "./messages.js";
+
+describe("slugify", () => {
+ // The punctuation cases matter: `.` separates key paths in i18next, and `"`/`%0` would be
+ // awkward in a catalog, so a message id must survive being written as natural English.
+ it.each([
+ [ "Admonition", "admonition" ],
+ [ "Insert a table.", "insert-a-table" ],
+ [ "Show all emoji...", "show-all-emoji" ],
+ [ "No templates were found matching \"%0\".", "no-templates-were-found-matching-0" ],
+ [ "Copy formatting", "copy-formatting" ]
+ ])("derives the key for %j", (message, expected) => {
+ expect(slugify(message)).toBe(expected);
+ });
+});
+
+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`
+ });
+ });
+
+ // i18next echoes the key back when an entry is missing. Putting that in the dictionary would
+ // render `text-editor.ck.admonition` at the user; skipping it lets CKEditor fall back to the
+ // English message id instead.
+ it("omits messages whose key the translator does not resolve", () => {
+ expect(buildMessageDictionary((key) => key)).toEqual({});
+ expect(buildMessageDictionary(() => "")).toEqual({});
+ });
+
+ it("covers every message id, keyed by its slug", () => {
+ const dictionary = buildMessageDictionary((key) => key.slice(MESSAGE_KEY_PREFIX.length));
+
+ expect(Object.keys(dictionary)).toEqual([ ...MESSAGES ]);
+ for (const message of MESSAGES) {
+ expect(dictionary[message]).toBe(slugify(message));
+ }
+ });
+});
diff --git a/packages/ckeditor5/src/messages.ts b/packages/ckeditor5/src/messages.ts
new file mode 100644
index 0000000000..76ff3ff627
--- /dev/null
+++ b/packages/ckeditor5/src/messages.ts
@@ -0,0 +1,69 @@
+/**
+ * Trilium-authored editor strings, and the bridge that gets them translated.
+ *
+ * Plugins localize with CKEditor's own `editor.t("English text")` — no host configuration, no
+ * translation keys in plugin code. When nothing supplies a dictionary (a test, a standalone
+ * editor), `t()` falls back to the message id itself, which *is* the English text, so the UI is
+ * always correct rather than showing a raw key.
+ *
+ * To actually translate those strings, the host hands {@link buildMessageDictionary} a translator
+ * (the client passes i18next's `t`) and the resulting dictionary is appended to the editor's
+ * `translations` config in `i18n.ts`. The i18next key is *derived* from the English text by
+ * {@link slugify}, so there is no message-id-to-key mapping to maintain: every string is written
+ * once, at the call site.
+ *
+ * The same mechanism can reword CKEditor's own strings — listing an upstream message id here
+ * overrides the built-in translation for every locale, because our dictionary is merged after the
+ * core one.
+ */
+
+/** Prefix for the i18next keys this package's messages resolve to. */
+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
+ * `config.translate` bridge and are migrated separately.
+ */
+export const MESSAGES = [
+ "Admonition"
+] as const;
+
+/**
+ * Derive the i18next key for a message id: lowercase, with every run of non-alphanumeric
+ * characters collapsed into a single dash. Punctuation that would otherwise be significant in an
+ * i18next key (`.` separates key paths) or awkward in a catalog (`"`, `%0`) disappears, so message
+ * ids can be written as natural English.
+ *
+ * `"Insert a table."` becomes `text-editor.ck.insert-a-table`.
+ */
+export function slugify(message: string): string {
+ return message
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+}
+
+/**
+ * Build the CKEditor dictionary for {@link MESSAGES} using the host's translator.
+ *
+ * A message is only included when the translator actually resolves its key. i18next echoes the key
+ * back for a missing entry, so an unresolved message would otherwise put `text-editor.ck.…` in the
+ * dictionary and render that key at the user; skipping it instead lets CKEditor fall back to the
+ * English message id.
+ */
+export function buildMessageDictionary(translate: (key: string) => string): Record<string, string> {
+ const dictionary: Record<string, string> = {};
+
+ for (const message of MESSAGES) {
+ const key = MESSAGE_KEY_PREFIX + slugify(message);
+ const translated = translate(key);
+ if (translated && translated !== key) {
+ dictionary[message] = translated;
+ }
+ }
+
+ return dictionary;
+}
diff --git a/packages/ckeditor5/src/messages_integration.spec.ts b/packages/ckeditor5/src/messages_integration.spec.ts
new file mode 100644
index 0000000000..12fce0f814
--- /dev/null
+++ b/packages/ckeditor5/src/messages_integration.spec.ts
@@ -0,0 +1,44 @@
+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");
+ });
+});