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): title the admonition types through a switch of t() calls
Elian Doran508dfc3d6b69
diff --git a/apps/client/src/services/i18n.spec.ts b/apps/client/src/services/i18n.spec.tsindex ca7a4d628a..51529e7e21 100644--- a/apps/client/src/services/i18n.spec.ts+++ b/apps/client/src/services/i18n.spec.ts@@ -1,5 +1,4 @@import { MESSAGE_KEY_PREFIX, slugify } from "@triliumnext/ckeditor5";-import { ADMONITION_TYPES } from "@triliumnext/ckeditor5/src/plugins/admonition/admonition_ui.js";import { dayjs, findDuplicateJsonKeys, findPluralKeyConflicts, LOCALES } from "@triliumnext/commons";import { readdirSync, readFileSync } from "fs";import { join } from "path";@@ -104,12 +103,6 @@ describe("i18n", () => {}}- // The admonition type titles are passed as a variable rather than a literal, so they- // are invisible to the scan and are read from their own declaration.- for (const definition of Object.values(ADMONITION_TYPES)) {- messages.add(definition.title);- }-return [ ...messages ];}diff --git a/packages/ckeditor5/src/extra_slash_commands.spec.ts b/packages/ckeditor5/src/extra_slash_commands.spec.tsindex 6be4cf5e10..a981183b0d 100644--- a/packages/ckeditor5/src/extra_slash_commands.spec.ts+++ b/packages/ckeditor5/src/extra_slash_commands.spec.ts@@ -249,36 +249,37 @@ describe("buildExtraCommands", () => {});describe("admonition commands", () => {- it("includes one command per ADMONITION_TYPE with execute function", async () => {- const { ADMONITION_TYPES } = await import("./plugins/admonition/admonition_ui.js");+ // `t` echoes the key back here, so every title falls back to its English message id.+ const ENGLISH_TITLES = { note: "Note", tip: "Tip", important: "Important", caution: "Caution", warning: "Warning" };++ it("includes one command per admonition type with execute function", async () => {+ const { ADMONITION_TYPE_NAMES } = await import("./plugins/admonition/admonition_command.js");const commands = buildExtraCommands(t);- for (const keyword of Object.keys(ADMONITION_TYPES)) {+ for (const keyword of ADMONITION_TYPE_NAMES) {const cmd = commands.find((c) => c.id === keyword);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?.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);+ expect(cmd?.title).toBe(ENGLISH_TITLES[keyword]);}});// 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");+ it("translates the titles through the host translator", () => {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);+ expect(commands.find((c) => c.id === "note")?.title).toBe(ENGLISH_TITLES.note);});it("admonition execute calls editor.execute('admonition') with the keyword", async () => {- const { ADMONITION_TYPES } = await import("./plugins/admonition/admonition_ui.js");+ const { ADMONITION_TYPE_NAMES } = await import("./plugins/admonition/admonition_command.js");const commands = buildExtraCommands(t);- for (const keyword of Object.keys(ADMONITION_TYPES)) {+ for (const keyword of ADMONITION_TYPE_NAMES) {const cmd = commands.find((c) => c.id === keyword);const { editor, executeSpy } = makeFakeEditor();cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.tsindex 9c073860a0..4542329f17 100644--- a/packages/ckeditor5/src/extra_slash_commands.ts+++ b/packages/ckeditor5/src/extra_slash_commands.ts@@ -10,8 +10,8 @@ import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from './plugins/insert_date_import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from './plugins/internallink.js';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 { getAdmonitionTitle } from "./plugins/admonition/admonition_ui.js";+import { ADMONITION_TYPE_NAMES, 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';@@ -215,15 +215,17 @@ function buildAdmonitionExtraCommands(t: SlashTranslateFn): SlashCommandDefinitiwarning: bxError,};- for (const [ keyword, definition ] of Object.entries(ADMONITION_TYPES)) {+ // 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: keyword,- // 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),+ id: type,+ title: getAdmonitionTitle(translate, type),description: t("slash_commands.admonition_description"),- icon: admonitionIcons[keyword as AdmonitionType],- execute: (editor: Editor) => editor.execute("admonition", { forceValue: keyword as AdmonitionType }),+ icon: admonitionIcons[type],+ execute: (editor: Editor) => editor.execute("admonition", { forceValue: type }),aliases: [ "box" ]});}diff --git a/packages/ckeditor5/src/plugins/admonition/README.md b/packages/ckeditor5/src/plugins/admonition/README.mdindex de155f9186..0bdc0ce97d 100644--- a/packages/ckeditor5/src/plugins/admonition/README.md+++ b/packages/ckeditor5/src/plugins/admonition/README.md@@ -51,8 +51,8 @@ Two things were straightened out during the move:- The package exported **two different** `ADMONITION_TYPES` — a tuple of names from the commandmodule and a `Record<type, {title}>` from the UI module — and the barrel re-exported the UI one,- shadowing the other. The tuple is now `ADMONITION_TYPE_NAMES`; `ADMONITION_TYPES` remains the- record consumers already used.+ shadowing the other. The tuple is now `ADMONITION_TYPE_NAMES` and is the only list of types; the+ record is gone, its titles now coming from `getAdmonitionTitle()`, which translates them.- `theme/blockquote.css` did not belong to this feature at all — it is CKEditor's baseline`blockquote` styling, inherited from the fork. It moved to `src/theme/blockquote.css` and isimported from `src/index.ts` with the other global stylesheets.diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_command.ts b/packages/ckeditor5/src/plugins/admonition/admonition_command.tsindex 69b95f6368..d41936bc71 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_command.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_command.ts@@ -17,8 +17,9 @@ import type { ModelElement, ModelPosition, ModelRange, ModelSchema, ModelWriter/*** The admonition type names, in the order they are offered in the UI.*- * The user-facing titles live in `ADMONITION_TYPES` in `admonition_ui.ts`; this is the bare list- * of names, used where only the names matter (autoformat, upcast).+ * The user-facing titles come from `getAdmonitionTitle()` in `admonition_ui.ts`; this is the bare+ * list of names, used wherever a title is not needed (autoformat, upcast) and to drive the order of+ * the type lists that do show titles.*/export const ADMONITION_TYPE_NAMES = ["note", "tip", "important", "caution", "warning"] as const;export const ADMONITION_TYPE_ATTRIBUTE = "admonitionType";diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.spec.ts b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.spec.tsindex 4dde61ac00..a3b1d7b4e5 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.spec.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.spec.ts@@ -1,6 +1,6 @@import { ClassicEditor, Essentials, Paragraph, _setModelData as setModelData } from "ckeditor5";import Admonition from "./admonition.js";-import { ADMONITION_TYPES } from "./admonition_ui.js";+import { ADMONITION_TYPE_NAMES } from "./admonition_command.js";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";@@ -127,12 +127,14 @@ describe("AdmonitionTypeDropdown", () => {const dropdown = editor.ui.componentFactory.create("admonitionTypeDropdown") as unknown as DropdownView;const command = editor.commands.get("admonition") as { value: string };expect(command.value).toBe("note");- expect(dropdown.buttonView.label).toBe(ADMONITION_TYPES["note"].title);+ // No dictionary is configured here, so `t()` renders the message id, which is the English+ // title.+ expect(dropdown.buttonView.label).toBe("Note");});it("button label falls back to the raw value for unknown admonition types", () => {- // Sets an admonitionType value not in ADMONITION_TYPES so typeDef is undefined- // and the `?? value` fallback path is exercised.+ // Sets an admonitionType value that has no title, so the untranslated-fallback path of+ // `getAdmonitionTitle()` is exercised.editor.setData('<aside class="admonition note"><p>Hello</p></aside>');editor.model.change((writer) => {const root = editor.model.document.getRoot();@@ -152,39 +154,31 @@ describe("AdmonitionTypeDropdown", () => {});const dropdown = editor.ui.componentFactory.create("admonitionTypeDropdown") as unknown as DropdownView;- // typeDef is undefined for "custom-unknown", so label falls back to the raw value.+ // "custom-unknown" has no title, so the label falls back to the raw value.expect(dropdown.buttonView.label).toBe("custom-unknown");});- it("dropdown panel contains one list item per admonition type", () => {+ it("dropdown panel contains one titled list item per admonition type", () => {const dropdown = editor.ui.componentFactory.create("admonitionTypeDropdown") as unknown as DropdownView;const listView = openDropdown(dropdown);- const typeCount = Object.keys(ADMONITION_TYPES).length;- expect(listView.items.length).toBe(typeCount);- });- it("each list item has the correct commandParam matching an admonition type", () => {- const dropdown = editor.ui.componentFactory.create("admonitionTypeDropdown") as unknown as DropdownView;- const listView = openDropdown(dropdown);- const types = Object.keys(ADMONITION_TYPES);+ expect(listView.items.length).toBe(ADMONITION_TYPE_NAMES.length);+ const items = [];for (let i = 0; i < listView.items.length; i++) {const button = listView.items.get(i).children.get(0);- expect(types).toContain(button.commandParam);+ items.push({ type: button.commandParam, label: button.label });}- });-- it("each list item label matches the type title", () => {- const dropdown = editor.ui.componentFactory.create("admonitionTypeDropdown") as unknown as DropdownView;- const listView = openDropdown(dropdown);- for (let i = 0; i < listView.items.length; i++) {- const button = listView.items.get(i).children.get(0);- const type = button.commandParam as keyof typeof ADMONITION_TYPES | undefined;- if (type) {- expect(button.label).toBe(ADMONITION_TYPES[type].title);- }- }+ // No dictionary is configured here, so `t()` renders the message id, which is the English+ // title.+ expect(items).toEqual([+ { type: "note", label: "Note" },+ { type: "tip", label: "Tip" },+ { type: "important", label: "Important" },+ { type: "caution", label: "Caution" },+ { type: "warning", label: "Warning" }+ ]);});it("each list item has the correct CSS classes", () => {diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.tsindex 56d886dff8..6d1b5bc14e 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_type_dropdown.ts@@ -1,8 +1,8 @@import { Plugin, type ListDropdownButtonDefinition, Collection, ViewModel, createDropdown, addListToDropdown, DropdownButtonView } from "ckeditor5";import Admonition from "./admonition.js";import type AdmonitionCommand from "./admonition_command.js";-import type { AdmonitionType } from "./admonition_command.js";-import { ADMONITION_TYPES } from "./admonition_ui.js";+import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "./admonition_command.js";+import { getAdmonitionTitle } from "./admonition_ui.js";/*** Toolbar item which displays the list of admonition types in a dropdown.@@ -29,10 +29,7 @@ export default class AdmonitionTypeDropdown extends Plugin {dropdownView.bind("isEnabled").to(command, "value", value => !!value);dropdownView.buttonView.bind("label").to(command, "value", (value) => {if (!value) return "";- const typeDef = ADMONITION_TYPES[value as AdmonitionType];- // 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;+ return getAdmonitionTitle(editor.t, value as AdmonitionType);});dropdownView.on("execute", evt => {const source = evt.source as any;@@ -51,12 +48,12 @@ export default class AdmonitionTypeDropdown extends Plugin {const command = editor.commands.get("admonition") as AdmonitionCommand;const itemDefinitions = new Collection<ListDropdownButtonDefinition>();- for (const [type, typeDef] of Object.entries(ADMONITION_TYPES)) {+ for (const type of ADMONITION_TYPE_NAMES) {const definition: ListDropdownButtonDefinition = {type: "button",model: new ViewModel({commandParam: type,- label: editor.t(typeDef.title),+ label: getAdmonitionTitle(editor.t, type),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 514428af72..65a70cc171 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_ui.spec.ts@@ -4,7 +4,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import Admonition from "./admonition.js";import type AdmonitionCommand from "./admonition_command.js";-import AdmonitionUI, { ADMONITION_TYPES } from "./admonition_ui.js";+import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "./admonition_command.js";+import AdmonitionUI, { getAdmonitionTitle } from "./admonition_ui.js";// ---- Typed interfaces for the dropdown internals ----@@ -103,21 +104,24 @@ describe("AdmonitionUI", () => {it("offers every admonition type in the dropdown", () => {const dropdown = createButton(editor);const listView = openDropdown(dropdown);- const types = Object.keys(ADMONITION_TYPES);- expect(listView.items.length).toBe(types.length);+ expect(listView.items.length).toBe(ADMONITION_TYPE_NAMES.length);+ const items = [];for (let i = 0; i < listView.items.length; i++) {const button = listView.items.get(i).children.get(0);- const type = button.commandParam as keyof typeof ADMONITION_TYPES | undefined;-- 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);- }+ items.push({ type: button.commandParam, label: button.label });}++ // No dictionary is configured here, so `t()` renders the message id, which is the+ // English title.+ expect(items).toEqual([+ { type: "note", label: "Note" },+ { type: "tip", label: "Tip" },+ { type: "important", label: "Important" },+ { type: "caution", label: "Caution" },+ { type: "warning", label: "Warning" }+ ]);});@@ -150,6 +154,21 @@ describe("AdmonitionUI", () => {});});+ describe("getAdmonitionTitle", () => {+ it("passes every type title through the translation function", () => {+ const translated = ADMONITION_TYPE_NAMES.map((type) => getAdmonitionTitle((message) => `xx:${message}`, type));++ expect(translated).toEqual([ "xx:Note", "xx:Tip", "xx:Important", "xx:Caution", "xx:Warning" ]);+ });++ it("returns an unrecognized type as-is, without translating it", () => {+ const translate = vi.fn();++ expect(getAdmonitionTitle(translate, "custom-unknown" as AdmonitionType)).toBe("custom-unknown");+ expect(translate).not.toHaveBeenCalled();+ });+ });+describe("without the editing plugin", () => {it("still builds a button, with no command bindings and an empty dropdown", async () => {const editor = await createTestEditor([Essentials, Paragraph, AdmonitionUI]);diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts b/packages/ckeditor5/src/plugins/admonition/admonition_ui.tsindex 4a563749e5..2553941085 100644--- a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts+++ b/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts@@ -11,33 +11,7 @@import { addListToDropdown, Collection, createDropdown, ListDropdownItemDefinition, Plugin, SplitButtonView, ViewModel } from "ckeditor5";import admonitionIcon from "../../icons/admonition.svg?raw";-import { AdmonitionType } from "./admonition_command.js";--interface AdmonitionDefinition {- title: string;-}--/**- * The user-facing definition of each admonition type. Keyed by the type names in- * `ADMONITION_TYPE_NAMES` (see `admonition_command.ts`).- */-export const ADMONITION_TYPES: Record<AdmonitionType, AdmonitionDefinition> = {- note: {- title: "Note"- },- tip: {- title: "Tip"- },- important: {- title: "Important"- },- caution: {- title: "Caution"- },- warning: {- title: "Warning"- }-};+import { ADMONITION_TYPE_NAMES, AdmonitionType } from "./admonition_command.js";/*** The admonition UI plugin.@@ -109,16 +83,12 @@ 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)) {+ for (const type of ADMONITION_TYPE_NAMES) {const definition: ListDropdownItemDefinition = {type: "button",model: new ViewModel({commandParam: type,- label: t(admonition.title),+ label: getAdmonitionTitle(this.editor.t, type),class: `ck-tn-admonition-option ck-tn-admonition-${type}`,role: "menuitemradio",withText: true@@ -133,3 +103,32 @@ export default class AdmonitionUI extends Plugin {}}++/**+ * The user-facing title of an admonition type, as shown by the toolbar dropdown, the type dropdown+ * and the slash commands.+ *+ * A switch rather than a table of titles, so that each title is written as a literal argument of a+ * `t()` call: that is how the messages this package owns are discovered (see `messages.ts`) and a+ * title tucked away in a table would be invisible to translators.+ *+ * @param t the editor's translation function (`editor.t`), or the host translator where no editor+ * exists yet — see `translateMessage()`.+ * @param type the admonition type; an unrecognized one has no title and is returned as-is.+ */+export function getAdmonitionTitle(t: (message: string) => string, type: AdmonitionType): string {+ switch (type) {+ case "note":+ return t("Note");+ case "tip":+ return t("Tip");+ case "important":+ return t("Important");+ case "caution":+ return t("Caution");+ case "warning":+ return t("Warning");+ default:+ return type;+ }+}