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 todo multistate strings off the translation-key bridge
Elian Dorana5599e6d3e48
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 8307f26ff0..bd091fc8e5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3577,9 +3577,6 @@"export-csv-failed": "Failed to export the spreadsheet to CSV."},"text-editor": {- "checkbox-tooltip": "Right-click or press {{- shortcut}} to change state.",- "checkbox-tooltip-state-label": "Task state:",- "checkbox-tooltip-state-unknown-suffix": "(missing definition)","ck": {"0-templates-found": "%0 templates found","admonition": "Admonition",@@ -3605,6 +3602,7 @@"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-task-states": "Edit task states","equation-preview": "Equation preview","error-rendering-equation": "Error rendering equation","footnote": "Footnote",@@ -3645,6 +3643,7 @@"mermaid-diagram-0": "Mermaid diagram: %0","mermaid-toolbar": "Mermaid toolbar","mermaid-widget": "Mermaid widget",+ "missing-definition": "(missing definition)","new-footnote": "New footnote","no-templates-available": "No templates available.","no-templates-were-found-matching-0": "No templates were found matching \"%0\".",@@ -3654,11 +3653,13 @@"preview": "Preview","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","select-collapsible-block": "Select collapsible block","source-view": "Source view","split-view": "Split view","summary": "Summary",+ "task-state": "Task state:","template": "Template","tip": "Tip","to-do-list": "To-do list",@@ -3666,10 +3667,9 @@"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.","type-the-content-here": "Type the content here...",+ "undefined-custom-task-state": "Undefined custom task state","warning": "Warning"},- "edit-states-tooltip": "Edit task states",- "unknown-task-state": "Undefined custom task state","task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.","task-state-dropped-message_other": "{{count}} custom task state definitions are invalid and were ignored.",diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.tsindex 59b4c89745..292e1e5e66 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts@@ -391,13 +391,12 @@ describe("TodoListMultistateEditing", () => {expect(command?.value).toBe("doing");});- it("downcasts a default custom state; the identity translate fallback doesn't crash the tooltip pipeline", () => {+ it("downcasts a default custom state without a host translator configured", () => {editor.execute("setTaskState", { state: "doing" });expect(editor.getData()).toContain('data-trilium-task-state="doing"');- // No `translate` config → the identity `(key) => key` fallback feeds- // the raw i18n keys straight into `buildTooltipTitle`. It must not- // crash the render loop even though the assembled HTML then reads- // like `"…{{shortcut}}…"` because the fallback echoes keys back.+ // No dictionary and no host bridge: the tooltip messages fall back to their English+ // ids and the shortcut key names to the identity `(key) => key`. Neither may crash the+ // render loop.const domRoot = editor.editing.view.getDomRoot();const input = domRoot?.querySelector<HTMLInputElement>('.todo-list__label input[type="checkbox"]');expect(input).not.toBeNull();@@ -405,14 +404,14 @@ describe("TodoListMultistateEditing", () => {});describe("helper functions and tooltip lifecycle", () => {- let translate: ReturnType<typeof vi.fn>;+ let t: ReturnType<typeof vi.spyOn>;beforeEach(async () => {- translate = vi.fn((key: string) => `T:${key}`);- editor = await createEditor({- taskStates: CUSTOM_STATES,- translate- });+ editor = await createEditor({ taskStates: CUSTOM_STATES });+ // `editor.t` is an own property assigned in the editor's constructor, and+ // `_computeContent` reads it fresh on each rebuild, so spying here intercepts every+ // tooltip message. Installed before the fixture, which is what triggers the first render.+ t = vi.spyOn(editor, "t");setModelData(editor.model, TODO_FIXTURE);});@@ -423,14 +422,10 @@ describe("TodoListMultistateEditing", () => {expect(active).not.toContain("secret");});- it("consults the configured translate provider for the tooltip content on each rendered checkbox", () => {- // Render creates hover handles eagerly per checkbox; each handle's- // initial content is assembled via `buildTooltipTitle` which calls- // `translate("text-editor.checkbox-tooltip", { shortcut: … })`.- // We don't need the popup on screen to verify that.- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip", expect.objectContaining({- shortcut: expect.any(String)- }));+ it("builds the tooltip content on each rendered checkbox", () => {+ // Render creates hover handles eagerly per checkbox; each handle's initial content is+ // assembled via `buildTooltipTitle`. We don't need the popup on screen to verify that.+ expect(t).toHaveBeenCalledWith("Right-click or press %0 to change state.", expect.any(String));});it("disposes the hover handle of a checkbox that becomes disconnected and re-attaches to the fresh input", () => {@@ -459,59 +454,56 @@ describe("TodoListMultistateEditing", () => {// this test exists to verify.});- it("consults the state-label translation key when a configured state is set", () => {- translate.mockClear();+ it("includes the state label when a configured state is set", () => {+ t.mockClear();editor.execute("setTaskState", { state: "doing" });- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");+ expect(t).toHaveBeenCalledWith("Task state:");});- it("consults the unknown-state suffix translation when the state has no definition", () => {- translate.mockClear();+ it("uses the unknown-state suffix when the state has no definition", () => {+ t.mockClear();editor.model.change((writer) => {writer.setAttribute(TASK_STATE_ATTRIBUTE, "ghost", getBlock(editor, 0));});- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-unknown-suffix");+ expect(t).toHaveBeenCalledWith("Task state:");+ expect(t).toHaveBeenCalledWith("(missing definition)");});it("omits the state prefix entirely for anchor states (unchecked / checked)", () => {// Starting fixture has no taskState → anchor. Re-render explicitly and assert// neither state-prefix key was consulted.- translate.mockClear();+ t.mockClear();editor.editing.view.forceRender();- expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");- expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-unknown-suffix");+ expect(t).not.toHaveBeenCalledWith("Task state:");+ expect(t).not.toHaveBeenCalledWith("(missing definition)");});it("rebuilds hover-handle content when the state changes on a rendered checkbox", () => {- translate.mockClear();+ t.mockClear();// A state change on the todo item triggers a reconvert of the list// item block (any scope-`item` attribute mutation does), which// gives us a new `<input>` and a new hover handle. Either way the- // plugin must consult `translate` for the fresh content — including- // the state-prefix keys — so a subsequent hover shows the right- // tooltip.+ // plugin must rebuild the fresh content — including the state+ // prefix — so a subsequent hover shows the right tooltip.editor.execute("setTaskState", { state: "doing" });- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip", expect.objectContaining({- shortcut: expect.any(String)- }));- expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");+ expect(t).toHaveBeenCalledWith("Right-click or press %0 to change state.", expect.any(String));+ expect(t).toHaveBeenCalledWith("Task state:");});it("does not touch handle content when a render fires without any state change", () => {const input = editor.editing.view.getDomRoot()?.querySelector<HTMLInputElement>('.todo-list__label input[type="checkbox"]');expect(input).not.toBeNull();- translate.mockClear();+ t.mockClear();// Render fires but the tracked state on every input matches the DOM,// so the plugin does no work.editor.editing.view.forceRender();// No content-rebuild keys were consulted.- expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip", expect.anything());- expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");+ expect(t).not.toHaveBeenCalledWith("Right-click or press %0 to change state.", expect.anything());+ expect(t).not.toHaveBeenCalledWith("Task state:");});});@@ -823,21 +815,14 @@ describe("TodoListMultistateEditing", () => {// returned string directly rather than introspecting Bootstrap Tooltip// instances — no `_config` peeking, no editor scaffolding needed.describe("buildTooltipTitle", () => {- const translate = (key: string, params: Record<string, unknown> = {}) => {- if (key === "text-editor.checkbox-tooltip") {- return `Right-click or press ${params.shortcut} to change state.`;- }- if (key === "text-editor.checkbox-tooltip-state-label") {- return "Task state:";- }- if (key === "text-editor.checkbox-tooltip-state-unknown-suffix") {- return "(missing definition)";- }- return key;- };+ // Stands in for `editor.t`: no dictionary, so each message id renders as its own English+ // text, with `%0` substituted the way CKEditor would.+ const t = (message: string, ...values: string[]) =>+ message.replace(/%(\d+)/g, (placeholder, index) => values[Number(index)] ?? placeholder);+ const SHORTCUT = "<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd>";it("returns just the body for an anchor state (null)", () => {- const title = buildTooltipTitle(document, null, new Map(), translate);+ const title = buildTooltipTitle(document, null, new Map(), t, SHORTCUT);expect(title).toContain("Right-click or press");expect(title).toContain("to change state.");expect(title).not.toContain("Task state:");@@ -845,7 +830,7 @@ describe("TodoListMultistateEditing", () => {it("prepends the state prefix with a bold state title for a configured state", () => {const stateByName = new Map(CUSTOM_STATES.map((state) => [state.name, state]));- const title = buildTooltipTitle(document, "doing", stateByName, translate);+ const title = buildTooltipTitle(document, "doing", stateByName, t, SHORTCUT);expect(title).toContain("Task state:");expect(title).toContain("<strong>Doing</strong>"); // state.title takes precedence over nameexpect(title).toContain('data-trilium-task-state="doing"');@@ -856,12 +841,12 @@ describe("TodoListMultistateEditing", () => {const stateByName = new Map<string, TaskStateDef>([["bare", { id: "_bare", name: "bare", title: "", markdownSymbol: "b", isCompleted: false, icon: "bx bx-x" }]]);- const title = buildTooltipTitle(document, "bare", stateByName, translate);+ const title = buildTooltipTitle(document, "bare", stateByName, t, SHORTCUT);expect(title).toContain("<strong>bare</strong>");});it("uses the unknown-state suffix for a state with no definition, without bold or icon", () => {- const title = buildTooltipTitle(document, "ghost", new Map(), translate);+ const title = buildTooltipTitle(document, "ghost", new Map(), t, SHORTCUT);expect(title).toContain("Task state:");expect(title).toContain("ghost (missing definition)");expect(title).not.toContain("<strong>");@@ -869,7 +854,7 @@ describe("TodoListMultistateEditing", () => {});it("text-escapes the raw state name in the unknown-state suffix (no HTML injection)", () => {- const title = buildTooltipTitle(document, "<script>alert(1)</script>", new Map(), translate);+ const title = buildTooltipTitle(document, "<script>alert(1)</script>", new Map(), t, SHORTCUT);expect(title).not.toContain("<script>");expect(title).toContain("<script>");});diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.tsindex 651d814877..b94156f9f5 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts@@ -73,7 +73,7 @@ export default class TodoListMultistateEditing extends Plugin {/** State-name → definition, keyed for `buildTooltipTitle` calls. */private _stateByName!: Map<string, TaskStateDef>;- /** Translate function resolved once from editor config; identity fallback. */+ /** Key resolver for the shortcut key names only — see {@link TranslateFn}. Identity fallback. */private _translate!: TranslateFn;init() {@@ -440,7 +440,8 @@ export default class TodoListMultistateEditing extends Plugin {input.ownerDocument,readTaskState(input),this._stateByName,- this._translate+ this.editor.t,+ renderCycleShortcut(this._translate));}@@ -478,7 +479,13 @@ export default class TodoListMultistateEditing extends Plugin {}-export type TranslateFn = (key: string, params?: Record<string, unknown>) => string;+/**+ * Resolves an i18next key. Still needed for the shortcut key names, which live in the app-wide+ * `keyboard_shortcuts.keys.*` catalog that {@link formatShortcut} reads and the command palette and+ * help dialog share — those are not this package's messages to own. Everything the plugin says in+ * its own voice goes through `editor.t()` instead.+ */+export type TranslateFn = (key: string) => string;/*** The task state applied to the todo item that owns the given checkbox. Anchor@@ -508,16 +515,21 @@ function readTaskState(input: HTMLInputElement): string | null {** Exported so specs can verify the assembled HTML directly, without having to* introspect Bootstrap Tooltip's private `_config` field.+ *+ * @param t the editor's translation function, for the strings this package owns.+ * @param shortcut the cycle shortcut, already rendered as `<kbd>` markup by+ * {@link renderCycleShortcut} — its key names come from the app-wide catalog rather+ * than from ours, so it is resolved by the caller and passed in as content. Nothing+ * escapes it here, and the tooltip opts out of Bootstrap's sanitizer.*/export function buildTooltipTitle(doc: Document,state: string | null,stateByName: Map<string, TaskStateDef>,- translate: TranslateFn+ t: (message: string, ...values: string[]) => string,+ shortcut: string): string {- const body = translate("text-editor.checkbox-tooltip", {- shortcut: renderCycleShortcut(translate)- });+ const body = t("Right-click or press %0 to change state.", shortcut);if (!state) {return body;}@@ -527,9 +539,9 @@ export function buildTooltipTitle(: buildUnknownStateSuffixHtml(doc,state,- translate("text-editor.checkbox-tooltip-state-unknown-suffix")+ t("(missing definition)"));- const label = translate("text-editor.checkbox-tooltip-state-label");+ const label = t("Task state:");// The status line is a block-level <div> so it forces a line break before// the body and the CSS `margin-bottom: 8px` cleanly separates the two.return `<div class="tn-task-tooltip-state">${label} ${suffix}</div>${body}`;diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.spec.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.spec.tsindex 95bf512c5a..1b94389c11 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.spec.ts@@ -205,17 +205,17 @@ describe("TodoListMultistateToolbar", () => {expect(balloon.visibleView).toBeNull();});- it("uses the configured translate function for labels", async () => {- const translate = vi.fn((key: string) => `T:${key}`);- await createEditor({ translate });+ it("labels the edit button from the editor dictionary", async () => {+ // Keyed by `en`, the language the editor resolves messages under when none is configured.+ await createEditor({ translations: [ {}, { en: { dictionary: { "Edit task states": "Editează stările" } } } ] });rightClick(getCheckbox(0));- // The edit button tooltip is routed through translate().- expect(translate).toHaveBeenCalledWith("text-editor.edit-states-tooltip");++ const editButton = getBalloon().view.element?.querySelector(".ck-task-state-edit");+ expect(editButton?.getAttribute("data-cke-tooltip-text")).toBe("Editează stările");});it("appends an unknown-state label for an unconfigured task state", async () => {- const translate = vi.fn((key: string) => key === "text-editor.unknown-task-state" ? "Unknown state" : key);- await createEditor({ translate });+ await createEditor();// Give the first todo item a state not present in the configured set.editor.model.change((writer) => {writer.setAttribute("taskState", "mystery", getBlock(0));@@ -225,6 +225,8 @@ describe("TodoListMultistateToolbar", () => {const unknown = balloon.view.element?.querySelector(".tn-task-state-unknown");expect(unknown).not.toBeNull();+ // No dictionary is configured, so the prefix renders its English message id.+ expect(unknown?.textContent).toBe("Undefined custom task state: mystery");const name = balloon.view.element?.querySelector(".tn-task-state-unknown-name");expect(name?.textContent).toBe("mystery");});diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.tsindex 9e68e4c7d2..1bb3485671 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts@@ -85,17 +85,12 @@ export default class TodoListMultistateToolbar extends Plugin {return toolbar;}- private _translate(key: string): string {- const translate = this.editor.config.get("translate") as ((key: string) => string) | undefined;- return translate ? translate(key) : key;- }-private _createEditButton(): ButtonView {const editor = this.editor;const button = new ButtonView(editor.locale);button.set({- label: this._translate("text-editor.edit-states-tooltip"),+ label: editor.t("Edit task states"),withText: false,tooltip: true,class: "ck-task-state-edit bx bx-pencil"@@ -206,7 +201,7 @@ export default class TodoListMultistateToolbar extends Plugin {class: "ck tn-task-state-unknown"},children: [- { text: `${this._translate("text-editor.unknown-task-state")}: ` },+ { text: `${this.editor.t("Undefined custom task state")}: ` },{tag: "span",attributes: {