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): move the slash commands off the translation-key bridge
Elian Doranba1ecf12149e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c339a39fb3..f95a0b1eb2 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -370,25 +370,6 @@"table_column": "Column {{number}}"}},- "slash_commands": {- "bulleted_list_description": "Create a bulleted list",- "numbered_list_description": "Create a numbered list",- "todo_list_description": "Create a to-do list",- "align_left_description": "Align text to the left",- "align_center_description": "Align text to the center",- "align_right_description": "Align text to the right",- "justify_description": "Justify text alignment",- "admonition_description": "Inserts a new admonition",- "collapsible_description": "Insert a toggleable section that hides/shows content on click.",- "footnote_description": "Create a new footnote and reference it here",- "datetime_description": "Insert the current date and time",- "internal_link_description": "Insert a link to another Trilium note",- "math_description": "Insert a math equation",- "include_note_description": "Display the content of another note in this note",- "page_break_description": "Insert a page break (for printing)",- "markdown_import_description": "Import a markdown file into this note",- "anchor_description": "Insert an anchor for internal linking"- },"move_to": {"dialog_title": "Move notes to ...","notes_to_move": "Notes to move",@@ -3364,8 +3345,6 @@"mermaid": {"placeholder": "Type the content of your Mermaid diagram or use one of the sample diagrams below.","sample_diagrams": "Sample diagrams:",- "slash_command_blank_description": "Insert an empty Mermaid diagram",- "slash_command_description": "Insert a \"{{name}}\" Mermaid diagram template","sample_flowchart": "Flowchart","sample_class": "Class","sample_sequence": "Sequence",@@ -3606,37 +3585,65 @@"checkbox-tooltip-state-unknown-suffix": "(missing definition)","ck": {"admonition": "Admonition",+ "align-text-to-the-center": "Align text to the center",+ "align-text-to-the-left": "Align text to the left",+ "align-text-to-the-right": "Align text to the right",+ "anchor": "Anchor",+ "bulleted-list": "Bulleted list","caution": "Caution",+ "collapsible-block": "Collapsible block","copy-formatting": "Copy formatting",+ "create-a-bulleted-list": "Create a bulleted list",+ "create-a-new-footnote-and-reference-it-here": "Create a new footnote and reference it here",+ "create-a-numbered-list": "Create a numbered list",+ "create-a-to-do-list": "Create a to-do list","cut-paste-selection-to-sub-note": "Cut & paste selection to sub-note","date-time": "Date time","decrease-the-indentation-of-the-current-block": "Decrease the indentation of the current block.","display-mode": "Display mode",+ "display-the-content-of-another-note-in-this-note": "Display the content of another note in this note","equation-preview": "Equation preview","error-rendering-equation": "Error rendering equation","footnote": "Footnote","footnote-widget": "footnote widget",+ "import-a-markdown-file-into-this-note": "Import a markdown file into this note","important": "Important","include-note": "Include note","increase-the-indentation-of-the-current-block": "Increase the indentation of the current block.","indent": "Indent",+ "insert-a-0-mermaid-diagram-template": "Insert a \"%0\" Mermaid diagram template","insert-a-block-of-preformatted-code": "Insert a block of preformatted code.","insert-a-horizontal-rule": "Insert a horizontal rule.",+ "insert-a-link-to-another-trilium-note": "Insert a link to another Trilium note",+ "insert-a-math-equation": "Insert a math equation",+ "insert-a-page-break-for-printing": "Insert a page break (for printing)","insert-a-table": "Insert a table.",+ "insert-a-toggleable-section-that-hides-shows-content-on-click": "Insert a toggleable section that hides/shows content on click.",+ "insert-an-anchor-for-internal-linking": "Insert an anchor for internal linking",+ "insert-an-empty-mermaid-diagram": "Insert an empty Mermaid diagram",+ "insert-date-time": "Insert date/time","insert-footnote-0": "Insert footnote %0","insert-math": "Insert math","insert-mermaid-diagram": "Insert Mermaid diagram","insert-mermaid-source-code": "Insert Mermaid source code",+ "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",+ "justify-text-alignment": "Justify text alignment","keyboard-shortcut": "Keyboard shortcut","latex": "LaTeX","link-preview": "Link preview",+ "markdown-import": "Markdown import","markdown-import-from-clipboard": "Markdown import from clipboard","math-editor-unavailable": "Math editor unavailable",+ "math-equation": "Math equation",+ "mermaid-diagram": "Mermaid diagram",+ "mermaid-diagram-0": "Mermaid diagram: %0","mermaid-toolbar": "Mermaid toolbar","mermaid-widget": "Mermaid widget","new-footnote": "New footnote","note": "Note",+ "numbered-list": "Numbered list","outdent": "Outdent","preview": "Preview","quote-a-passage-from-another-source": "Quote a passage from another source.",@@ -3644,6 +3651,7 @@"source-view": "Source view","split-view": "Split view","tip": "Tip",+ "to-do-list": "To-do list","turn-the-current-block-into-a-heading": "Turn the current block into a heading.","turn-the-current-block-into-a-paragraph": "Turn the current block into a paragraph.","warning": "Warning"diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 79f0710604..e05e98456f 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -176,7 +176,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi// (Title Case titles, normalized to sentence case).removeCommands: ["insertMermaidCommand", "bulletedList", "numberedList", "todoList"],dropdownLimit: Number.MAX_SAFE_INTEGER,- extraCommands: buildExtraCommands((key, params) => t(key, params), SAMPLE_DIAGRAMS)+ extraCommands: buildExtraCommands((key) => t(key), SAMPLE_DIAGRAMS)},snippets: {definitions: opts.templatesdiff --git a/packages/ckeditor5/src/extra_slash_commands.spec.ts b/packages/ckeditor5/src/extra_slash_commands.spec.tsindex a981183b0d..ec41e75056 100644--- a/packages/ckeditor5/src/extra_slash_commands.spec.ts+++ b/packages/ckeditor5/src/extra_slash_commands.spec.ts@@ -19,12 +19,9 @@ function makeFakeEditor() {}describe("buildExtraCommands", () => {- const t = (key: string, params?: Record<string, unknown>) => {- if (params) {- return `${key}(${JSON.stringify(params)})`;- }- return key;- };+ // The host translator, which i18next-style echoes back a key it has no entry for. Every message+ // therefore falls back to its English id, which is what these assertions pin.+ const t = (key: string) => key;it("returns an array", () => {const commands = buildExtraCommands(t);@@ -38,7 +35,7 @@ describe("buildExtraCommands", () => {expect(cmd).toBeDefined();expect(cmd?.title).toBe("Collapsible block");expect(cmd?.commandName).toBe("collapsible");- expect(cmd?.description).toBe("slash_commands.collapsible_description");+ expect(cmd?.description).toBe("Insert a toggleable section that hides/shows content on click.");expect(Array.isArray(cmd?.aliases)).toBe(true);expect(cmd?.icon).toBeTruthy();});@@ -260,7 +257,7 @@ describe("buildExtraCommands", () => {expect(cmd, `admonition command for ${keyword}`).toBeDefined();expect(typeof cmd?.execute).toBe("function");expect(cmd?.icon).toBeTruthy();- expect(cmd?.description).toBe("slash_commands.admonition_description");+ expect(cmd?.description).toBe("Inserts a new admonition");expect(cmd?.aliases).toContain("box");expect(cmd?.title).toBe(ENGLISH_TITLES[keyword]);}@@ -296,7 +293,7 @@ describe("buildExtraCommands", () => {expect(cmd?.title).toBe("Mermaid diagram");expect(cmd?.commandName).toBeTruthy();expect(cmd?.icon).toBeTruthy();- expect(cmd?.description).toBe("mermaid.slash_command_blank_description");+ expect(cmd?.description).toBe("Insert an empty Mermaid diagram");});it("includes no sample commands when mermaidSamples is empty", () => {@@ -315,7 +312,7 @@ describe("buildExtraCommands", () => {const cmd0 = commands.find((c) => c.id === "mermaid-sample-0");expect(cmd0).toBeDefined();expect(cmd0?.title).toBe("Mermaid diagram: Flowchart");- expect(cmd0?.description).toBe("mermaid.slash_command_description({\"name\":\"Flowchart\"})");+ expect(cmd0?.description).toBe("Insert a \"Flowchart\" Mermaid diagram template");expect(cmd0?.aliases).toContain("Flowchart");expect(cmd0?.icon).toBeTruthy();@@ -338,32 +335,33 @@ describe("buildExtraCommands", () => {expect(executeSpy).toHaveBeenCalledWith(INSERT_MERMAID_COMMAND, { source: "flowchart LR\n A --> B" });});- it("translate function is called with sample name for sample commands", () => {- const tSpy = vi.fn((key: string, params?: Record<string, unknown>) => {- if (params) {- return `${key}(${JSON.stringify(params)})`;- }- return key;- });+ // The sample name is interpolated into the translation, not concatenated onto it, so a+ // locale that has an entry decides where the name goes.+ it("substitutes the sample name into the localized title and description", () => {const samples = [{ name: "MyDiagram", content: "graph TD\n A" }];- buildExtraCommands(tSpy, samples);- expect(tSpy).toHaveBeenCalledWith("mermaid.slash_command_description", { name: "MyDiagram" });+ const translations: Record<string, string> = {+ "text-editor.ck.mermaid-diagram-0": "Diagramă %0",+ "text-editor.ck.insert-a-0-mermaid-diagram-template": "Șablon Mermaid „%0”"+ };+ const commands = buildExtraCommands((key) => translations[key] ?? key, samples);+ const cmd = commands.find((c) => c.id === "mermaid-sample-0");++ expect(cmd?.title).toBe("Diagramă MyDiagram");+ expect(cmd?.description).toBe("Șablon Mermaid „MyDiagram”");});});- it("passes the translation key to t() for every command description", () => {+ // Every string these definitions show is looked up, and each lookup lands under the prefix the+ // English catalog is keyed by — a definition that hardcoded its text would ask for nothing.+ it("resolves every title and description to a text-editor.ck key", () => {const keys: string[] = [];- const tRecording = (key: string, params?: Record<string, unknown>) => {++ buildExtraCommands((key) => {keys.push(key);return key;- };+ }, [ { name: "Flowchart", content: "graph TD\n A" } ]);- buildExtraCommands(tRecording);expect(keys.length).toBeGreaterThan(0);- // All translation keys should be non-empty strings.- for (const key of keys) {- expect(typeof key).toBe("string");- expect(key.length).toBeGreaterThan(0);- }+ expect(keys.filter((key) => !key.startsWith("text-editor.ck."))).toEqual([]);});});diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.tsindex 4542329f17..6a17816dbc 100644--- a/packages/ckeditor5/src/extra_slash_commands.ts+++ b/packages/ckeditor5/src/extra_slash_commands.ts@@ -28,16 +28,28 @@ import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";import type { SlashCommandDefinition } from './plugins/mention/slash_commands.js';/**- * Translation function supplied by the client (which owns i18n). Resolves the- * `slash_commands.*` (and `mermaid.*`) keys used for the command descriptions.- * Command titles are intentionally kept hardcoded in English.+ * Resolves a full i18next key to the localized string. Supplied by the client, which owns i18n.+ *+ * The definitions below do not name keys themselves: they pass English message ids to a+ * {@link MessageTranslateFn}, which derives the key. This is the host translator that lookup ends+ * at.*/-export type SlashTranslateFn = (key: string, params?: Record<string, unknown>) => string;+export type SlashTranslateFn = (key: string) => string;++/**+ * Translates one English message id, substituting `%0`, `%1`, … with `values`.+ *+ * The same contract as the `editor.t()` a plugin would call, which these definitions cannot: they+ * are built before any editor exists.+ */+type MessageTranslateFn = (message: string, ...values: string[]) => string;export default function buildExtraCommands(- t: SlashTranslateFn,+ translate: SlashTranslateFn,mermaidSamples: MermaidSample[] = []): SlashCommandDefinition[] {+ const t: MessageTranslateFn = (message, ...values) => translateMessage(translate, message, values);+return [...buildListExtraCommands(t),...buildAlignmentExtraCommands(t),@@ -45,67 +57,67 @@ export default function buildExtraCommands(...buildMermaidCommands(t, mermaidSamples),{id: "collapsible",- title: "Collapsible block",- description: t("slash_commands.collapsible_description"),+ title: t("Collapsible block"),+ description: t("Insert a toggleable section that hides/shows content on click."),aliases: [ "details", "fold", "toggle" ],icon: collapsibleIcon,commandName: "collapsible"},{id: 'footnote',- title: 'Footnote',- description: t("slash_commands.footnote_description"),+ title: t("Footnote"),+ description: t("Create a new footnote and reference it here"),icon: insertFootnoteIcon,commandName: "InsertFootnote"},{id: "datetime",- title: "Insert date/time",- description: t("slash_commands.datetime_description"),+ title: t("Insert date/time"),+ description: t("Insert the current date and time"),icon: dateTimeIcon,commandName: INSERT_DATE_TIME_COMMAND},{id: "internal-link",- title: "Internal Trilium link",- description: t("slash_commands.internal_link_description"),+ title: t("Internal Trilium link"),+ description: t("Insert a link to another Trilium note"),aliases: [ "internal link", "trilium link", "reference link" ],icon: internalLinkIcon,commandName: INTERNAL_LINK_COMMAND},{id: "math",- title: "Math equation",- description: t("slash_commands.math_description"),+ title: t("Math equation"),+ description: t("Insert a math equation"),aliases: [ "latex", "equation" ],icon: mathIcon,execute: (editor: Editor) => editor.plugins.get(MathUI)._showUI()},{id: "include-note",- title: "Include note",- description: t("slash_commands.include_note_description"),+ title: t("Include note"),+ description: t("Display the content of another note in this note"),icon: noteIcon,commandName: INCLUDE_NOTE_COMMAND},{id: "page-break",- title: "Page break",- description: t("slash_commands.page_break_description"),+ title: t("Page break"),+ description: t("Insert a page break (for printing)"),icon: IconPageBreak,commandName: "pageBreak"},{id: "markdown-import",- title: "Markdown import",- description: t("slash_commands.markdown_import_description"),+ title: t("Markdown import"),+ description: t("Import a markdown file into this note"),icon: importMarkdownIcon,commandName: MARKDOWN_IMPORT_COMMAND},{id: "anchor",- title: "Anchor",- description: t("slash_commands.anchor_description"),+ title: t("Anchor"),+ description: t("Insert an anchor for internal linking"),aliases: [ "bookmark" ],icon: bxBookmark,execute: (editor: Editor) => {@@ -121,39 +133,39 @@ export default function buildExtraCommands(// Replaces CKEditor's built-in `bulletedList`/`numberedList`/`todoList` slash// commands (removed via `removeCommands`), whose titles are Title Case, with// sentence-case equivalents that run the same commands.-function buildListExtraCommands(t: SlashTranslateFn): SlashCommandDefinition[] {+function buildListExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {return [{id: "bulletedList",- title: "Bulleted list",- description: t("slash_commands.bulleted_list_description"),+ title: t("Bulleted list"),+ description: t("Create a bulleted list"),icon: IconBulletedList,commandName: "bulletedList"},{id: "numberedList",- title: "Numbered list",- description: t("slash_commands.numbered_list_description"),+ title: t("Numbered list"),+ description: t("Create a numbered list"),icon: IconNumberedList,commandName: "numberedList"},{id: "todoList",- title: "To-do list",- description: t("slash_commands.todo_list_description"),+ title: t("To-do list"),+ description: t("Create a to-do list"),icon: IconTodoList,commandName: "todoList"}];}-function buildMermaidCommands(t: SlashTranslateFn, samples: MermaidSample[]): SlashCommandDefinition[] {+function buildMermaidCommands(t: MessageTranslateFn, samples: MermaidSample[]): SlashCommandDefinition[] {// The blank diagram. Replaces CKEditor's built-in `insertMermaidCommand`// slash command (removed via `removeCommands`), which uses a generic icon.const blank: SlashCommandDefinition = {id: "mermaid",- title: "Mermaid diagram",- description: t("mermaid.slash_command_blank_description"),+ title: t("Mermaid diagram"),+ description: t("Insert an empty Mermaid diagram"),aliases: [ "mermaid", "diagram", "flowchart" ],icon: bxNetworkChart,commandName: INSERT_MERMAID_COMMAND@@ -161,8 +173,10 @@ function buildMermaidCommands(t: SlashTranslateFn, samples: MermaidSample[]): Slconst templates = samples.map((sample, index) => ({id: `mermaid-sample-${index}`,- title: `Mermaid diagram: ${sample.name}`,- description: t("mermaid.slash_command_description", { name: sample.name }),+ // The sample name is a placeholder rather than an appended string, so a locale can put the+ // name where its grammar wants it. It arrives already localized, from `mermaid.samples`.+ title: t("Mermaid diagram: %0", sample.name),+ description: t("Insert a \"%0\" Mermaid diagram template", sample.name),aliases: [ "mermaid", "diagram", sample.name ],icon: bxNetworkChart,// Inserts a mermaid block pre-filled with the sample source (see insertMermaidCommand).@@ -172,40 +186,40 @@ function buildMermaidCommands(t: SlashTranslateFn, samples: MermaidSample[]): Slreturn [ blank, ...templates ];}-function buildAlignmentExtraCommands(t: SlashTranslateFn): SlashCommandDefinition[] {+function buildAlignmentExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {return [{id: "align-left",- title: "Align left",- description: t("slash_commands.align_left_description"),+ title: t("Align left"),+ description: t("Align text to the left"),icon: IconAlignLeft,execute: (editor: Editor) => editor.execute("alignment", { value: "left" }),},{id: "align-center",- title: "Align center",- description: t("slash_commands.align_center_description"),+ title: t("Align center"),+ description: t("Align text to the center"),icon: IconAlignCenter,execute: (editor: Editor) => editor.execute("alignment", { value: "center" }),},{id: "align-right",- title: "Align right",- description: t("slash_commands.align_right_description"),+ title: t("Align right"),+ description: t("Align text to the right"),icon: IconAlignRight,execute: (editor: Editor) => editor.execute("alignment", { value: "right" }),},{id: "align-justify",- title: "Justify",- description: t("slash_commands.justify_description"),+ title: t("Justify"),+ description: t("Justify text alignment"),icon: IconAlignJustify,execute: (editor: Editor) => editor.execute("alignment", { value: "justify" }),}];}-function buildAdmonitionExtraCommands(t: SlashTranslateFn): SlashCommandDefinition[] {+function buildAdmonitionExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {const commands: SlashCommandDefinition[] = [];const admonitionIcons: Record<AdmonitionType, string> = {note: bxInfoCircle,@@ -215,15 +229,11 @@ function buildAdmonitionExtraCommands(t: SlashTranslateFn): SlashCommandDefinitiwarning: bxError,};- // Built before any editor exists, so the titles go through the host translator directly rather- // than `editor.t()` — same message ids, same fallback to English.- const translate = (message: string) => translateMessage(t, message);-for (const type of ADMONITION_TYPE_NAMES) {commands.push({id: type,- title: getAdmonitionTitle(translate, type),- description: t("slash_commands.admonition_description"),+ title: getAdmonitionTitle(t, type),+ description: t("Inserts a new admonition"),icon: admonitionIcons[type],execute: (editor: Editor) => editor.execute("admonition", { forceValue: type }),aliases: [ "box" ]diff --git a/packages/ckeditor5/src/messages.spec.ts b/packages/ckeditor5/src/messages.spec.tsindex f83555c729..a0b6f0cc4b 100644--- a/packages/ckeditor5/src/messages.spec.ts+++ b/packages/ckeditor5/src/messages.spec.ts@@ -50,4 +50,19 @@ describe("translateMessage", () => {expect(translateMessage((key) => key, "Warning")).toBe("Warning");expect(translateMessage(() => "", "Warning")).toBe("Warning");});++ // `%0`-style placeholders are what CKEditor's own translation function substitutes, so a message+ // reads the same either way — including when it falls back to English.+ it("substitutes %0-style placeholders, in the translation and in the fallback alike", () => {+ expect(translateMessage(() => "Șablon „%0” (%1)", "Template \"%0\" (%1)", [ "Flowchart", "2" ]))+ .toBe("Șablon „Flowchart” (2)");+ expect(translateMessage((key) => key, "Insert %0", [ "Flowchart" ])).toBe("Insert Flowchart");+ });++ // A placeholder with no value is left alone rather than blanked, so a mismatched translation+ // shows the gap instead of silently dropping text.+ it("leaves a placeholder with no corresponding value untouched", () => {+ expect(translateMessage((key) => key, "Insert %0 into %1", [ "Flowchart" ]))+ .toBe("Insert Flowchart into %1");+ });});diff --git a/packages/ckeditor5/src/messages.ts b/packages/ckeditor5/src/messages.tsindex 770fa8344c..9db49da7c5 100644--- a/packages/ckeditor5/src/messages.ts+++ b/packages/ckeditor5/src/messages.ts@@ -72,9 +72,26 @@ export function buildMessageDictionary(** Falls back to the message id, which is the English text, so a missing entry renders English* rather than a raw key.+ *+ * @param values substituted for the `%0`, `%1`, … placeholders, as {@link interpolate} describes.*/-export function translateMessage(translate: (key: string) => string, message: string): string {+export function translateMessage(+ translate: (key: string) => string,+ message: string,+ values: readonly string[] = []+): string {const key = MESSAGE_KEY_PREFIX + slugify(message);const translated = translate(key);- return translated && translated !== key ? translated : message;+ return interpolate(translated && translated !== key ? translated : message, values);+}++/**+ * Substitute `%0`, `%1`, … in a translated message, which is how CKEditor's own translation function+ * interpolates. A message therefore reads the same whether it was translated by the editor or by+ * {@link translateMessage}, and translators see one placeholder convention.+ *+ * A placeholder with no corresponding value is left as written, rather than blanked.+ */+function interpolate(message: string, values: readonly string[]): string {+ return message.replace(/%(\d+)/g, (placeholder, index) => values[Number(index)] ?? placeholder);}