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): retire config.translate for a shortcut renderer
Elian Doranfba071e3a177
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex e05e98456f..38ed65c3e0 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,6 +1,6 @@import { buildExtraCommands, type EditorConfig, getCkLocale, SnippetDefinition } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";-import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";+import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import i18next from "i18next";import { copyTextWithToast } from "../../../services/clipboard_ext.js";@@ -11,6 +11,7 @@ import { default as mimeTypesService, getHighlightJsNameForMime } from "../../..import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";import options from "../../../services/options.js";import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";+import { isMac } from "../../../services/utils.js";import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import { buildToolbarConfig } from "./toolbar.js";@@ -194,8 +195,12 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi(config as Record<string, unknown>).taskStates = await getTaskStateDefinitions();(config as Record<string, unknown>).editTaskStates = openCustomTaskStateConfig;- // The app's i18n translate function, so plugins can resolve Trilium translation keys.- (config as Record<string, unknown>).translate = (key: string, params?: Record<string, unknown>) => t(key, params);+ // Renders a keystroke a plugin mentions in a hint. The editor's own strings translate through+ // its dictionary (see `messages.ts` in the ckeditor5 package), but the key names inside a+ // shortcut come from `keyboard_shortcut_keys`, which the command palette and the help dialog+ // read too — so the app renders them and hands the markup over.+ (config as Record<string, unknown>).renderShortcut = (shortcut: string) =>+ joinShortcut(formatShortcut(shortcut, t, isMac()).map((token) => `<kbd>${token}</kbd>`), isMac());// Global on/off switch for content-area hints (bottom-corner popups on task// checkboxes, collapsible summaries, drag handles). Plugins consult this viadiff --git a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.tsindex 1b229b1068..b4c7c16bfc 100644--- a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts+++ b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts@@ -1,18 +1,10 @@-import { Plugin, Enter, Delete, enableViewPlaceholder, env, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent, type ViewDocumentArrowKeyEvent } from "ckeditor5";-import { formatShortcut, joinShortcut } from "@triliumnext/commons";+import { Plugin, Enter, Delete, enableViewPlaceholder, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent, type ViewDocumentArrowKeyEvent } from "ckeditor5";import { ContentHintManager, type HintHandle } from "../../content_hint_manager.js";+import { renderShortcut } from "../../shortcut.js";import BlockDragHandle from "./block_drag_handle.js";import CollapsibleCommand from "./collapsible_command.js";import { OPEN_ATTRIBUTE, TRANSIENT_OPEN_ATTRIBUTE } from "./constants.js";-/**- * 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 collapsible says- * in its own voice goes through `editor.t()` instead.- */-type TranslateFn = (key: string) => string;-/*** The keyboard shortcut for toggling a collapsible's `open` state. Shared as* a single source of truth between the `Ctrl+Enter` DOM keydown handler in@@ -300,12 +292,6 @@ export default class CollapsibleEditing extends Plugin {});}- /** See {@link TranslateFn}: shortcut key names only. */- private translate(): TranslateFn {- return (this.editor.config.get("translate") as TranslateFn | undefined)- ?? ((key: string) => key);- }-/*** Editing-view summary: a normal <summary> with a non-editable arrow UIElement* prepended. Clicking the arrow toggles the native <details>; the data view@@ -1008,10 +994,13 @@ export default class CollapsibleEditing extends Plugin {*/private registerSummaryHints() {const editor = this.editor;- // Two catalogs meet here: the sentence is ours, the key names inside the shortcut belong to- // the app-wide `keyboard_shortcuts.keys.*` set. The rendered shortcut is `<kbd>` markup, and- // nothing escapes it on the way in — the hint's tooltip sets `sanitize: false`.- const title = editor.t("Click on the arrow or press %0 to collapse/expand.", renderToggleShortcut(this.translate()));+ // The host renders the shortcut: its key names come from the app-wide catalog, not ours.+ // The result is `<kbd>` markup and nothing escapes it on the way in — the hint's tooltip+ // sets `sanitize: false`.+ const title = editor.t(+ "Click on the arrow or press %0 to collapse/expand.",+ renderShortcut(editor, TOGGLE_SHORTCUT)+ );const manager = new ContentHintManager({tooltipOptions: {sanitize: false,@@ -1404,15 +1393,3 @@ export default class CollapsibleEditing extends Plugin {return true;}}--/**- * Render the toggle shortcut as `<kbd>Ctrl</kbd>+<kbd>Enter</kbd>` (or- * `<kbd>⌃</kbd><kbd>↩</kbd>` on macOS). Uses the shared `formatShortcut` /- * `joinShortcut` from `@triliumnext/commons` so key labels flow through the- * same i18n and Mac-glyph rules as the rest of the app.- */-function renderToggleShortcut(translate: TranslateFn): string {- const kbdTokens = formatShortcut(TOGGLE_SHORTCUT, translate, env.isMac)- .map((token: string) => `<kbd>${token}</kbd>`);- return joinShortcut(kbdTokens, env.isMac);-}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 b94156f9f5..6ab2ad8e01 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@@ -1,8 +1,9 @@-import { DEFAULT_TASK_STATES, DONE_STATE_NAME, formatShortcut, isAnchorState, joinShortcut, NONE_STATE_NAME, type TaskStateDef } from "@triliumnext/commons";-import { Command, env, ListEditing, Plugin, TodoList, type Editor, type ModelElement, type ViewElement } from "ckeditor5";+import { DEFAULT_TASK_STATES, DONE_STATE_NAME, isAnchorState, NONE_STATE_NAME, type TaskStateDef } from "@triliumnext/commons";+import { Command, ListEditing, Plugin, TodoList, type Editor, type ModelElement, type ViewElement } from "ckeditor5";import { onTodoRowSplit } from "../todo_list_uncheck_on_enter.js";import { ContentHintManager, type HintHandle } from "../../content_hint_manager.js";+import { renderShortcut } from "../../shortcut.js";/*** Dwell delay before a hover or a stationary caret pops the checkbox tooltip.@@ -73,15 +74,10 @@ export default class TodoListMultistateEditing extends Plugin {/** State-name → definition, keyed for `buildTooltipTitle` calls. */private _stateByName!: Map<string, TaskStateDef>;- /** Key resolver for the shortcut key names only — see {@link TranslateFn}. Identity fallback. */- private _translate!: TranslateFn;-init() {const editor = this.editor;const states = getConfiguredTaskStates(editor);this._stateByName = new Map(states.map((state) => [state.name, state]));- this._translate = (editor.config.get("translate") as TranslateFn | undefined)- ?? ((key: string) => key);const stateByName = this._stateByName;// Global user preference: skip all content-hint wiring when off. The// rest of `init()` (schema, keystroke, downcast/upcast, post-fixer)@@ -441,7 +437,7 @@ export default class TodoListMultistateEditing extends Plugin {readTaskState(input),this._stateByName,this.editor.t,- renderCycleShortcut(this._translate)+ renderShortcut(this.editor, STATE_CYCLE_SHORTCUT));}@@ -479,14 +475,6 @@ export default class TodoListMultistateEditing extends Plugin {}-/**- * 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* states (`none`/`done`) never carry a `data-trilium-task-state`, so this@@ -518,8 +506,7 @@ function readTaskState(input: HTMLInputElement): string | null {** @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+ * {@link renderShortcut} — the host renders it, so it arrives as content. Nothing* escapes it here, and the tooltip opts out of Bootstrap's sanitizer.*/export function buildTooltipTitle(@@ -555,18 +542,6 @@ export function buildTooltipTitle(*/const STATE_CYCLE_SHORTCUT = "Ctrl+Shift+Enter";-/**- * Render the state-cycle shortcut as `<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd>`- * (or `<kbd>⌃</kbd><kbd>⇧</kbd><kbd>↩</kbd>` on macOS). Uses the shared- * `formatShortcut`/`joinShortcut` from `@triliumnext/commons` so key labels- * flow through the same i18n and Mac-glyph rules as the rest of the app.- */-function renderCycleShortcut(translate: TranslateFn): string {- const kbdTokens = formatShortcut(STATE_CYCLE_SHORTCUT, translate, env.isMac)- .map((token) => `<kbd>${token}</kbd>`);- return joinShortcut(kbdTokens, env.isMac);-}-/*** "<mini-checkbox> <strong>Name</strong>" — the icon and name flow inline* after the "Task state:" label. Built via the DOM API so the state namediff --git a/packages/ckeditor5/src/shortcut.spec.ts b/packages/ckeditor5/src/shortcut.spec.tsnew file mode 100644index 0000000000..f4809e86ab--- /dev/null+++ b/packages/ckeditor5/src/shortcut.spec.ts@@ -0,0 +1,24 @@+import { Essentials, Paragraph } from "ckeditor5";+import { describe, expect, it } from "vitest";++import { createTestEditor } from "../test/editor-kit.js";+import { renderShortcut } from "./shortcut.js";++describe("renderShortcut", () => {+ it("hands the keystroke to the host renderer", async () => {+ // `renderShortcut` is not declared on the editor config type; the host sets it via a cast.+ const editor = await createTestEditor([Essentials, Paragraph], {+ renderShortcut: (shortcut: string) => `<kbd>${shortcut}</kbd>`+ } as unknown as Parameters<typeof createTestEditor>[1]);++ expect(renderShortcut(editor, "Ctrl+Enter")).toBe("<kbd>Ctrl+Enter</kbd>");+ });++ // A standalone editor or a test has no host to render key names, and a hint that mentions a+ // shortcut still has to name one.+ it("falls back to the stored form when no host renderer is configured", async () => {+ const editor = await createTestEditor([Essentials, Paragraph]);++ expect(renderShortcut(editor, "Ctrl+Shift+Enter")).toBe("Ctrl+Shift+Enter");+ });+});diff --git a/packages/ckeditor5/src/shortcut.ts b/packages/ckeditor5/src/shortcut.tsnew file mode 100644index 0000000000..a16aa6e5d6--- /dev/null+++ b/packages/ckeditor5/src/shortcut.ts@@ -0,0 +1,22 @@+import type { Editor } from "ckeditor5";++/**+ * Render a keystroke for display inside a message, as `<kbd>Ctrl</kbd>+<kbd>Enter</kbd>` (or+ * `<kbd>⌃</kbd><kbd>↩</kbd>` on macOS).+ *+ * The host does the rendering, through the `renderShortcut` editor config entry. Key names are+ * translated — "Ctrl" is "Strg" in German — but they live in the app-wide `keyboard_shortcut_keys`+ * catalog that the command palette and the help dialog also read, not among the messages this+ * package owns. Resolving them here would mean either duplicating fifteen strings translators have+ * already done, or overriding CKEditor's own "Insert".+ *+ * Falls back to the stored form (`"Ctrl+Enter"`) when no host is attached — a standalone editor, or+ * a test — so a shortcut always reads as a shortcut rather than disappearing.+ *+ * The result is markup: a caller interpolating it into a message must not escape it, and the+ * tooltip showing that message must not sanitize it.+ */+export function renderShortcut(editor: Editor, shortcut: string): string {+ const render = editor.config.get("renderShortcut") as ((shortcut: string) => string) | undefined;+ return render?.(shortcut) ?? shortcut;+}