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(ckeditor5): make the anchor rename work again, in every locale
Elian Doranb5fd1686f810
diff --git a/apps/client/src/services/i18n.spec.ts b/apps/client/src/services/i18n.spec.tsindex 51529e7e21..ca3896782e 100644--- a/apps/client/src/services/i18n.spec.ts+++ b/apps/client/src/services/i18n.spec.ts@@ -1,4 +1,4 @@-import { MESSAGE_KEY_PREFIX, slugify } from "@triliumnext/ckeditor5";+import { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "@triliumnext/ckeditor5";import { dayjs, findDuplicateJsonKeys, findPluralKeyConflicts, LOCALES } from "@triliumnext/commons";import { readdirSync, readFileSync } from "fs";import { join } from "path";@@ -103,6 +103,12 @@ describe("i18n", () => {}}+ // Renames of CKEditor's own strings are declared rather than called, and the wording we+ // substitute needs an English entry like any other message.+ for (const replacement of Object.values(MESSAGE_OVERRIDES)) {+ messages.add(replacement);+ }+return [ ...messages ];}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 842a9d1b4f..d673ca7a0c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3573,6 +3573,12 @@"align-text-to-the-left": "Align text to the left","align-text-to-the-right": "Align text to the right","anchor": "Anchor",+ "anchor-name": "Anchor name",+ "anchor-name-already-exists": "Anchor name already exists.",+ "anchor-name-cannot-contain-space-characters": "Anchor name cannot contain space characters.",+ "anchor-name-must-not-be-empty": "Anchor name must not be empty.",+ "anchor-toolbar": "Anchor toolbar",+ "anchors": "Anchors","box-size": "Box size","bulleted-list": "Bulleted list","card": "Card",@@ -3596,9 +3602,11 @@"display-the-content-of-another-note-in-this-note": "Display the content of another note in this note","download-image": "Download image","drag-to-reposition-the-collapsible-block": "Drag to reposition the collapsible block",+ "edit-anchor": "Edit anchor","edit-task-states": "Edit task states","edit-title": "Edit title","embed": "Embed",+ "enter-the-anchor-name-without-spaces": "Enter the anchor name without spaces.","equation-preview": "Equation preview","error-rendering-equation": "Error rendering equation","expandable": "Expandable",@@ -3629,7 +3637,7 @@"insert-mermaid-source-code": "Insert Mermaid source code","insert-paragraph-after-code-block": "Insert paragraph after code block","insert-paragraph-before-code-block": "Insert paragraph before code block",- "insert-template": "Insert template",+ "insert-text-snippet": "Insert text snippet","insert-the-current-date-and-time": "Insert the current date and time","inserts-a-new-admonition": "Inserts a new admonition","internal-trilium-link": "Internal Trilium link",@@ -3660,7 +3668,7 @@"quote-a-passage-from-another-source": "Quote a passage from another source.","read-more-about-mermaid-diagram-syntax": "Read more about Mermaid diagram syntax","right-click-or-press-0-to-change-state": "Right-click or press %0 to change state.",- "search-template": "Search template",+ "search-text-snippet": "Search text snippet","select-collapsible-block": "Select collapsible block","source-view": "Source view","split-view": "Split view",diff --git a/apps/client/src/translations/ro/translation.json b/apps/client/src/translations/ro/translation.jsonindex 8633d85dd8..1b53c53ef3 100644--- a/apps/client/src/translations/ro/translation.json+++ b/apps/client/src/translations/ro/translation.json@@ -2691,13 +2691,24 @@"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",+ "anchor": "Ancoră",+ "anchor-name": "Numele ancorei",+ "anchor-name-already-exists": "Numele ancorei există deja.",+ "anchor-name-cannot-contain-space-characters": "Numele ancorei nu poate conține spații.",+ "anchor-name-must-not-be-empty": "Numele ancorei nu trebuie să fie gol.",+ "anchor-toolbar": "Bară de instrumente pentru ancoră",+ "anchors": "Ancore","caution": "Atenție","copy-formatting": "Copiază formatarea",+ "edit-anchor": "Editează ancora",+ "enter-the-anchor-name-without-spaces": "Introduceți numele ancorei fără spații.","important": "Important","include-note": "Include notița",+ "insert-text-snippet": "Inserează fragment de text","keyboard-shortcut": "Scurtătură de la tastatură","link-preview": "Previzualizare link","note": "Notă",+ "search-text-snippet": "Caută fragment de text","tip": "Sfat","warning": "Avertisment"},diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 54263b6f17..9c346e7aec 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -129,11 +129,12 @@ 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();- // 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);+ // The merge seed, CKEditor's GPL core translations, and the Trilium dictionary. The+ // premium bundle used to contribute another entry, but no premium plugin is loaded+ // any more. i18next is not initialized here, so the dictionary holds only the+ // renames of CKEditor's own strings — those apply with or without a catalog — and+ // every other editor string falls back to its English message id.+ expect(config.translations, locale.id).toHaveLength(3);}}}, 20_000);diff --git a/packages/ckeditor5/src/i18n.spec.ts b/packages/ckeditor5/src/i18n.spec.tsindex c0fcd290f2..cd3d685419 100644--- a/packages/ckeditor5/src/i18n.spec.ts+++ b/packages/ckeditor5/src/i18n.spec.ts@@ -82,7 +82,8 @@ describe("getCkLocale", () => {// 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" } } });+ const dictionary = (translations[2] as Record<string, { dictionary: Record<string, string> }>).de.dictionary;+ expect(dictionary.Admonition).toBe("Ermahnung");});// CKEditor merges the `translations` array in place via `reduce(merge)`, so a missing seed@@ -98,19 +99,27 @@ describe("getCkLocale", () => {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.+ // A locale with no CKEditor translation still needs the dictionary, since it also carries the+ // renames 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", admonitionOnly("Rabhadh"));expect(language).toBeUndefined();- expect(translations).toEqual([ {}, { en: { dictionary: { Admonition: "Rabhadh" } } } ]);+ if (!Array.isArray(translations)) throw new Error("expected an array of translations");+ expect(translations).toHaveLength(2);+ expect((translations[1] as Record<string, { dictionary: Record<string, string> }>).en.dictionary.Admonition)+ .toBe("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", { englishMessages: ENGLISH_MESSAGES, translate: (key) => key })).toEqual({});+ // Even with nothing to translate, the dictionary still carries the renames of CKEditor's own+ // strings — dropping it would put "Bookmark" back in front of the user.+ it("supplies the renames when the translator resolves nothing", async () => {+ const { translations } = await getCkLocale("ga", { englishMessages: ENGLISH_MESSAGES, translate: (key) => key });++ if (!Array.isArray(translations)) throw new Error("expected an array of translations");+ const dictionary = (translations[1] as Record<string, { dictionary: Record<string, string> }>).en.dictionary;+ expect(dictionary.Bookmark).toBe("Anchor");+ expect(dictionary).not.toHaveProperty("Admonition");});// End-to-end over a real editor: `AdmonitionUI` localizes with plain `editor.t("Admonition")`,diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 929077178f..437cbd4974 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -7,7 +7,6 @@ import "./theme/code_block_toolbar.css";import "./theme/link_embed_form.css";import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";-import "./translation_overrides.js";export { default as EditorWatchdog } from "./custom_watchdog";export { CHAT_INPUT_PLUGINS } from "./plugins.js";export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";@@ -17,7 +16,7 @@ export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";export { default as buildExtraCommands } from "./extra_slash_commands.js";export { default as getCkLocale } from "./i18n.js";-export { MESSAGE_KEY_PREFIX, slugify } from "./messages.js";+export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";export * from "./utils.js";// Import with sideffects to ensure that type augmentations are present.diff --git a/packages/ckeditor5/src/messages.spec.ts b/packages/ckeditor5/src/messages.spec.tsindex a0b6f0cc4b..169ad545ed 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, slugify, translateMessage } from "./messages.js";+import { buildMessageDictionary, MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify, translateMessage } from "./messages.js";describe("slugify", () => {// The punctuation cases matter: `.` separates key paths in i18next, and `"`/`%0` would be@@ -22,19 +22,42 @@ describe("buildMessageDictionary", () => {it("maps each English message to its translation", () => {const dictionary = buildMessageDictionary(ENGLISH, (key) => `translated:${key}`);- expect(dictionary).toEqual({- Admonition: `translated:${MESSAGE_KEY_PREFIX}admonition`,- Warning: `translated:${MESSAGE_KEY_PREFIX}warning`- });+ expect(dictionary.Admonition).toBe(`translated:${MESSAGE_KEY_PREFIX}admonition`);+ expect(dictionary.Warning).toBe(`translated:${MESSAGE_KEY_PREFIX}warning`);+ });++ // Trilium calls CKEditor's bookmarks "anchors". The dictionary has to be keyed by the upstream+ // message id for CKEditor to find it, while the text comes from our entry for the replacement —+ // which is what makes the rename translatable rather than English-only.+ it("renames CKEditor's own strings, in the locale's own words", () => {+ const dictionary = buildMessageDictionary(+ { anchor: "Anchor" },+ (key) => (key === `${MESSAGE_KEY_PREFIX}anchor` ? "Ancoră" : key)+ );++ expect(dictionary.Bookmark).toBe("Ancoră");+ });++ // A rename is not a translation: the English replacement is itself the point, so it has to+ // stand in even where the locale has nothing — otherwise the editor says "Bookmark" again.+ it("applies a rename even when nothing resolves", () => {+ const dictionary = buildMessageDictionary({}, (key) => key);++ expect(dictionary.Bookmark).toBe("Anchor");+ expect(dictionary["Edit bookmark"]).toBe("Edit anchor");});// 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.+ // render `text-editor.ck.admonition` at the user; leaving the message out lets CKEditor fall+ // back to the message id, which is the English text. Only the renames remain.it("omits messages whose key the translator does not resolve", () => {- expect(buildMessageDictionary(ENGLISH, (key) => key)).toEqual({});- expect(buildMessageDictionary(ENGLISH, () => "")).toEqual({});- expect(buildMessageDictionary({}, (key) => `translated:${key}`)).toEqual({});+ for (const translate of [ (key: string) => key, () => "" ]) {+ const dictionary = buildMessageDictionary(ENGLISH, translate);++ expect(dictionary).not.toHaveProperty("Admonition");+ expect(dictionary).not.toHaveProperty("Warning");+ expect(Object.keys(dictionary)).toEqual(Object.keys(MESSAGE_OVERRIDES));+ }});});diff --git a/packages/ckeditor5/src/messages.ts b/packages/ckeditor5/src/messages.tsindex 9db49da7c5..07ebec359c 100644--- a/packages/ckeditor5/src/messages.ts+++ b/packages/ckeditor5/src/messages.ts@@ -38,6 +38,31 @@ export function slugify(message: string): string {.replace(/^-+|-+$/g, "");}+/**+ * CKEditor's own strings that Trilium renames, mapping the upstream message id to the English+ * wording we show instead. Trilium calls CKEditor's bookmarks "anchors", so every string the+ * upstream `Bookmark` plugin renders is relabelled here.+ *+ * This is the one case where a message id and its English text differ, which is why the pairs are+ * declared rather than discovered: the dictionary has to be keyed by the *upstream* id for CKEditor+ * to find it, while the text shown comes from our catalog entry for the replacement. Both halves of+ * a pair therefore live here, and the replacement needs its own English entry like any other+ * message — which is what makes the rename translatable per locale instead of English-only.+ *+ * A plugin Trilium owns never belongs here: rename its message id at the call site instead.+ */+export const MESSAGE_OVERRIDES: Record<string, string> = {+ "Bookmark": "Anchor",+ "Bookmarks": "Anchors",+ "Bookmark name": "Anchor name",+ "Bookmark must not be empty.": "Anchor name must not be empty.",+ "Bookmark name already exists.": "Anchor name already exists.",+ "Bookmark name cannot contain space characters.": "Anchor name cannot contain space characters.",+ "Edit bookmark": "Edit anchor",+ "Enter the bookmark name without spaces.": "Enter the anchor name without spaces.",+ "Bookmark toolbar": "Anchor toolbar"+};+/*** Build the CKEditor dictionary from the host's English catalog and translator.*@@ -62,6 +87,13 @@ export function buildMessageDictionary(}}+ // Renames are applied last, so an upstream id resolves to our wording rather than CKEditor's.+ // Unlike a translation, a rename applies even when the locale has no entry: the English+ // replacement is itself the point, so it stands in until a translator supplies the rest.+ for (const [ upstreamMessage, replacement ] of Object.entries(MESSAGE_OVERRIDES)) {+ dictionary[upstreamMessage] = dictionary[replacement] ?? replacement;+ }+return dictionary;}diff --git a/packages/ckeditor5/src/plugins/snippets/snippets.spec.ts b/packages/ckeditor5/src/plugins/snippets/snippets.spec.tsindex 260b91a1c7..5441774661 100644--- a/packages/ckeditor5/src/plugins/snippets/snippets.spec.ts+++ b/packages/ckeditor5/src/plugins/snippets/snippets.spec.ts@@ -14,7 +14,6 @@ import {} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";-import "../../translation_overrides.js";import { createTestEditor } from "../../../test/editor-kit.js";import TriliumSnippets from "./snippets.js";import type { SnippetDefinition } from "./snippetsconfig.js";@@ -123,7 +122,9 @@ describe("SnippetsUI — insertTemplate dropdown", () => {});it("labels the toggle and binds it to the command", () => {- expect(dropdown.buttonView.label).toBe("Insert text snippet"); // relabelled by translation_overrides+ // The message id itself, no dictionary configured: the plugin says "text snippet" rather+ // than the "template" wording of the premium plugin it replaces.+ expect(dropdown.buttonView.label).toBe("Insert text snippet");expect(dropdown.buttonView.icon).toContain("<svg");const command = editor.commands.get("insertTemplate");diff --git a/packages/ckeditor5/src/plugins/snippets/snippetsui.ts b/packages/ckeditor5/src/plugins/snippets/snippetsui.tsindex 83097877b1..438f7dc770 100644--- a/packages/ckeditor5/src/plugins/snippets/snippetsui.ts+++ b/packages/ckeditor5/src/plugins/snippets/snippetsui.ts@@ -10,9 +10,9 @@ import "./theme/snippets.css";* `menuBar:insertTemplate` menu entry. Both render from {@link SnippetsEditing}'s live definition* collection, so snippet changes appear without recreating the editor.*- * The user-facing strings deliberately reuse the same English source keys as the premium plugin this- * replaces (`"Insert template"`, `"Search template"`, …) so the existing `translation_overrides.ts`- * relabelling ("Insert text snippet" / "Search text snippet") keeps applying.+ * The user-facing strings say "text snippet" rather than the "template" wording of the premium+ * plugin this replaces. They used to reuse premium's English ids verbatim and be relabelled by a+ * global override; with the message ids being Trilium's own now, they simply say what they mean.*/export default class SnippetsUI extends Plugin {@@ -45,7 +45,7 @@ export default class SnippetsUI extends Plugin {const searchView = new SearchTextView(locale, {filteredView: listView,queryView: {- label: t("Search template")+ label: t("Search text snippet")},class: "ck-template-form",infoView: {@@ -70,7 +70,7 @@ export default class SnippetsUI extends Plugin {dropdownView.bind("isEnabled").to(command);dropdownView.panelView.children.add(searchView);dropdownView.buttonView.set({- label: t("Insert template"),+ label: t("Insert text snippet"),icon: templateIcon,tooltip: true});diff --git a/packages/ckeditor5/src/translation_overrides.spec.ts b/packages/ckeditor5/src/translation_overrides.spec.tsdeleted file mode 100644index da8f1e8e2d..0000000000--- a/packages/ckeditor5/src/translation_overrides.spec.ts+++ /dev/null@@ -1,49 +0,0 @@-import { Bookmark, ClassicEditor, Essentials, Paragraph } from "ckeditor5";-import { beforeEach, describe, expect, it } from "vitest";--import { createTestEditor } from "../test/editor-kit.js";-// Side effect: assigns window.CKEDITOR_TRANSLATIONS, the global CKEditor reads to relabel its-// built-in strings. Imported before any editor is created so the override is in place.-import "./translation_overrides.js";--describe("translation overrides", () => {- let editor: ClassicEditor;-- beforeEach(async () => {- editor = await createTestEditor([Essentials, Paragraph, Bookmark], {- toolbar: { items: ["bookmark"] }- });- });-- it("are picked up by the editor UI (Bookmark relabelled to Anchor)", () => {- const labels = toolbarLabels(editor);- expect(labels).toContain("Anchor");- expect(labels).not.toContain("Bookmark");- });-- it("register the text-snippet relabels for the snippets feature", () => {- // The GPL `TriliumSnippets` plugin reuses the same English source strings the premium- // Template feature used ("Insert template" / "Search template"), so these overrides relabel- // its dropdown to "…text snippet". Assert the override dictionary carries them.- const dictionary = window.CKEDITOR_TRANSLATIONS?.en?.dictionary ?? {};- expect(dictionary["Insert template"]).toBe("Insert text snippet");- expect(dictionary["Search template"]).toBe("Search text snippet");- });-});--function toolbarLabels(editor: ClassicEditor): string[] {- const labels: string[] = [];- for (const item of editor.ui.view.toolbar?.items ?? []) {- // Toolbar items are buttons (label directly) or dropdowns (label on the inner buttonView).- const view = item as unknown as { label?: unknown; buttonView?: { label?: unknown } };- const label = typeof view.label === "string"- ? view.label- : typeof view.buttonView?.label === "string"- ? view.buttonView.label- : null;- if (label) {- labels.push(label);- }- }- return labels;-}diff --git a/packages/ckeditor5/src/translation_overrides.ts b/packages/ckeditor5/src/translation_overrides.tsdeleted file mode 100644index 008f2f0f4a..0000000000--- a/packages/ckeditor5/src/translation_overrides.ts+++ /dev/null@@ -1,17 +0,0 @@-window.CKEDITOR_TRANSLATIONS = {- en: {- dictionary: {- "Insert template": "Insert text snippet",- "Search template": "Search text snippet",- "Bookmark": "Anchor",- "Bookmarks": "Anchors",- "Bookmark name": "Anchor name",- "Bookmark must not be empty.": "Anchor name must not be empty.",- "Bookmark name already exists.": "Anchor name already exists.",- "Bookmark name cannot contain space characters.": "Anchor name cannot contain space characters.",- "Edit bookmark": "Edit anchor",- "Enter the bookmark name without spaces.": "Enter the anchor name without spaces.",- "Bookmark toolbar": "Anchor toolbar"- }- }-};