Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor5): let the small fields speak the language the rest of Trilium does

Elian Doran025c30a912b1
diff --git a/apps/client/src/widgets/react/CKEditor.tsx b/apps/client/src/widgets/react/CKEditor.tsx
index 1e97a2c8b1..c525efaed8 100644
--- a/apps/client/src/widgets/react/CKEditor.tsx
+++ b/apps/client/src/widgets/react/CKEditor.tsx
@@ -1,4 +1,5 @@
import type { CKTextEditor, AttributeEditor, EditorConfig, ModelPosition } from "@triliumnext/ckeditor5";
+import type { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { useEffect, useImperativeHandle, useRef } from "preact/compat";
import { MutableRef } from "preact/hooks";
@@ -30,6 +31,17 @@ interface CKEditorOpts {
className: string;
tabIndex?: number;
config: EditorConfig;
+ /**
+ * The language the editor's own strings — a toolbar's tooltips, the link balloon — are to be
+ * shown in, whose dictionary is fetched and laid within reach before the editor is raised (see
+ * `registerCkTranslations`). Settled here rather than in the configuration a caller hands over
+ * because the editor is already built from within an effect, where waiting costs a field
+ * nothing; a caller that waited would be holding back its own mounting instead.
+ *
+ * Left out, the editor speaks whatever its configuration says, which is the English it was
+ * written in.
+ */
+ uiLanguage?: DISPLAYABLE_LOCALE_IDS;
editor: typeof AttributeEditor;
disableNewlines?: boolean;
disableSpellcheck?: boolean;
@@ -40,7 +52,7 @@ interface CKEditorOpts {
onInitialized?: (editorInstance: CKTextEditor) => void;
}
-export default function CKEditor({ apiRef, currentValue, editor, config, disableNewlines, disableSpellcheck, onChange, onClick, onInitialized, ...restProps }: CKEditorOpts) {
+export default function CKEditor({ apiRef, currentValue, editor, config, uiLanguage, disableNewlines, disableSpellcheck, onChange, onClick, onInitialized, ...restProps }: CKEditorOpts) {
const editorContainerRef = useRef<HTMLDivElement>(null);
const textEditorRef = useRef<CKTextEditor>(null);
/** The value as it stands now, for the building of the editor to end on rather than begin with. */
@@ -107,10 +119,19 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable
}, [ editorContainerRef ]);
useEffect(() => {
- if (!editorContainerRef.current) return;
+ const container = editorContainerRef.current;
+ if (!container) return;
let unmounted = false;
- editor.create(editorContainerRef.current, config).then((textEditor) => {
+ // Raised at once where no language was asked for, which is how every field that asks for
+ // none has always been built. Where one was, the dictionary it is to speak from is laid
+ // within reach first: an editor reads from what was there when it was raised, so a catalog
+ // arriving after it would be a catalog it never looks in.
+ const created = uiLanguage
+ ? layTranslationsWithinReach(uiLanguage).then((language) => editor.create(container, { ...config, ...language }))
+ : editor.create(container, config);
+
+ created.then((textEditor) => {
// Gone before it was ready: build no further, and take with it what it has put on the
// page, or the next editor would find it there and take it for its own content.
if (unmounted) {
@@ -184,6 +205,21 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable
)
}
+/**
+ * Lays the locale's CKEditor dictionary within reach of the editor about to be raised, and says
+ * which language it is then to speak.
+ *
+ * Fetched rather than named outright at the head of this module: everything else this module takes
+ * from the editor package is a type, and a value taken from it here would put the whole of CKEditor
+ * into every module that so much as mounts a field — the script API among them, which carries none
+ * of it today. Nothing is really fetched: whoever asks for a language handed over an editor class
+ * to build from, so the package is already in hand.
+ */
+async function layTranslationsWithinReach(uiLanguage: DISPLAYABLE_LOCALE_IDS) {
+ const { registerCkTranslations } = await import("@triliumnext/ckeditor5");
+ return registerCkTranslations(uiLanguage);
+}
+
/**
* Groups the (already `> `-stripped) lines of a markdown quote into paragraphs: a blank line starts a
* new paragraph, and consecutive non-blank lines belong to the same one. Returns one entry per
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index d1b9fdc073..39face94de 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -1,6 +1,7 @@
import "./ChatInputBar.css";
import { AttributeEditor as CKEditorAttributeEditor, CHAT_INPUT_PLUGINS, type CKTextEditor, type MentionFeed } from "@triliumnext/ckeditor5";
+import type { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { Fragment } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
@@ -13,7 +14,7 @@ import Button from "../../react/Button.js";
import CKEditor, { type CKEditorApi } from "../../react/CKEditor.js";
import Dropdown from "../../react/Dropdown.js";
import { FormListHeader, FormListItem } from "../../react/FormList.js";
-import { useLegacyImperativeHandlers } from "../../react/hooks.js";
+import { useLegacyImperativeHandlers, useTriliumOption } from "../../react/hooks.js";
import MaskedIcon from "../../react/MaskedIcon.js";
import AddProviderModal, { type LlmProviderConfig, type ProviderStep } from "../options/llm/AddProviderModal.js";
import { providerIconUrl } from "../options/llm/provider_icons.js";
@@ -98,6 +99,7 @@ export default function ChatInputBar({
const [openToken, setOpenToken] = useState(0);
const editorApiRef = useRef<CKEditorApi>();
const editorInstanceRef = useRef<CKTextEditor>();
+ const [ uiLanguage ] = useTriliumOption("locale");
// Always-fresh submit handler for the editor's enter listener.
const submitRef = useRef<(e: Event) => void>(() => {});
@@ -304,9 +306,12 @@ export default function ChatInputBar({
toolbar: { items: [] },
placeholder: t("llm_chat.placeholder"),
mention: { feeds: mentionFeeds },
- licenseKey: "GPL",
- language: "en"
+ licenseKey: "GPL"
}}
+ // The strings the box shows of its own — the link balloon it raises on Ctrl+K —
+ // in the language the rest of Trilium is read in; the dictionary is fetched for
+ // it before the editor is raised.
+ uiLanguage={uiLanguage as DISPLAYABLE_LOCALE_IDS}
onChange={(html) => {
chat.setInput(editorHtmlToMarkdown(html ?? ""));
}}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodeMemo.tsx b/apps/client/src/widgets/type_widgets/mind_map/NodeMemo.tsx
index 6aeaa96a0a..c65181168b 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodeMemo.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodeMemo.tsx
@@ -1,12 +1,14 @@
import "./NodeMemo.css";
import { AttributeEditor, type CKTextEditor, type EditorConfig, MEMO_PLUGINS } from "@triliumnext/ckeditor5";
+import type { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import type { NodeObj } from "mind-elixir";
import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { t } from "../../../services/i18n";
import { escapeHtml } from "../../../services/utils";
import CKEditor, { type CKEditorApi } from "../../react/CKEditor";
+import { useTriliumOption } from "../../react/hooks";
/**
* The memo a node carries: text kept about it, which the map itself never shows.
@@ -28,6 +30,7 @@ export default function NodeMemo({ selectionKey, memo, readOnly, onCommit }: {
}) {
const apiRef = useRef<CKEditorApi>();
const editorRef = useRef<CKTextEditor>(null);
+ const [ uiLanguage ] = useTriliumOption("locale");
const html = toMemoHtml(memo);
// Both are stamped with the selection they belong to: what the field was handed, and what it
// holds now. The editor reports a change for a memo handed to it as readily as for one typed,
@@ -81,6 +84,7 @@ export default function NodeMemo({ selectionKey, memo, readOnly, onCommit }: {
className="mind-map-node-memo"
editor={AttributeEditor}
config={buildMemoEditorConfig()}
+ uiLanguage={uiLanguage as DISPLAYABLE_LOCALE_IDS}
currentValue={html}
onChange={(html) => (typed.current = { key: currentKey.current, html: html ?? "" })}
onInitialized={(editor) => {
@@ -104,18 +108,16 @@ export default function NodeMemo({ selectionKey, memo, readOnly, onCommit }: {
* and the catalogue is not yet loaded when this module is. Nothing is spent on rebuilding it — an
* editor is raised from the configuration it is handed as it mounts, and never reconfigured.
*
- * English, as the two other fields built on an {@link AttributeEditor} are (the ribbon's attributes,
- * the chat box): the strings on show are CKEditor's own, and the dictionary they resolve through is
- * fetched, which an editor raised as its field mounts cannot wait for. That leaves the toolbar's
- * tooltips in English wherever the rest of Trilium is not, for all three of them together to answer.
+ * The language is not among what is settled here: the strings on show are CKEditor's own, and their
+ * dictionary has to be fetched, which is done for the field by the wrapper that raises the editor
+ * (see the `uiLanguage` it is handed).
*/
function buildMemoEditorConfig(): EditorConfig {
return {
extraPlugins: MEMO_PLUGINS,
toolbar: { items: MEMO_TOOLBAR_ITEMS },
placeholder: t("mind-map.memo-placeholder"),
- licenseKey: "GPL",
- language: "en"
+ licenseKey: "GPL"
};
}
diff --git a/packages/ckeditor5/src/i18n.spec.ts b/packages/ckeditor5/src/i18n.spec.ts
index cd3d685419..51d5d611be 100644
--- a/packages/ckeditor5/src/i18n.spec.ts
+++ b/packages/ckeditor5/src/i18n.spec.ts
@@ -1,9 +1,9 @@
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
-import { Essentials, Paragraph, SplitButtonView } from "ckeditor5";
+import { Bold, ButtonView, Essentials, Paragraph, SplitButtonView } from "ckeditor5";
import { describe, expect, it } from "vitest";
import { createTestEditor } from "../test/editor-kit.js";
-import getCkLocale from "./i18n.js";
+import getCkLocale, { registerCkTranslations } from "./i18n.js";
import { MESSAGE_KEY_PREFIX } from "./messages.js";
import Admonition from "./plugins/admonition/admonition.js";
import AdmonitionUI from "./plugins/admonition/admonition_ui.js";
@@ -197,3 +197,50 @@ describe("getCkLocale", () => {
expect(typeof translations[1]).toBe("object");
});
});
+
+describe("registerCkTranslations", () => {
+ /** What an editor carrying no dictionary of its own reads from (see the function's own note). */
+ function globalDictionary(languageCode: string) {
+ return window.CKEDITOR_TRANSLATIONS?.[languageCode]?.dictionary;
+ }
+
+ it("lays a locale's dictionary where an editor built without one will read it", async () => {
+ expect(await registerCkTranslations("de")).toEqual({ language: "de" });
+
+ // The strings the small fields show are CKEditor's own, and this is them arriving.
+ expect(globalDictionary("de")?.["Bold"]).toBe("Fett");
+ expect(globalDictionary("de")?.["Insert code block"]).toBe("Code-Block einfügen");
+ });
+
+ it("files a dictionary under the name the editor will ask for, not the one it arrived under", async () => {
+ // Both spellings part ways: what we ask CKEditor to speak is `zh`, while the catalog is
+ // `zh-cn.js` and carries `zh-cn`. Filed as it arrived, it would be a dictionary unread.
+ expect(await registerCkTranslations("cn")).toEqual({ language: "zh" });
+ expect(globalDictionary("zh")?.["Bold"]).toBeTruthy();
+ });
+
+ it("says nothing of a locale CKEditor has no catalog for, which is the English it was written in", async () => {
+ for (const locale of [ "en", "en_rtl", "ga" ] as DISPLAYABLE_LOCALE_IDS[]) {
+ expect(await registerCkTranslations(locale)).toEqual({});
+ }
+ });
+
+ it("is read by an editor that carries no dictionary of its own, which is the whole point", async () => {
+ // What the small fields are: raised from a configuration settled as they mount, with no
+ // `translations` in it. CKEditor falls back to the global registry for exactly those, so a
+ // button built afterwards wears the language without the field ever having carried it.
+ const { language } = await registerCkTranslations("de");
+ const editor = await createTestEditor([ Essentials, Paragraph, Bold ], { language });
+
+ const boldButton = editor.ui.componentFactory.create("bold");
+ if (!(boldButton instanceof ButtonView)) throw new Error("expected the bold component to be a button");
+ expect(boldButton.label).toBe("Fett");
+ });
+
+ it("fetches a locale once, however many fields ask for it", async () => {
+ // Every field on the page asks as it is built, and a catalog is a chunk to go and get.
+ expect(registerCkTranslations("fr")).toBe(registerCkTranslations("fr"));
+ await registerCkTranslations("fr");
+ expect(globalDictionary("fr")?.["Bold"]).toBeTruthy();
+ });
+});
diff --git a/packages/ckeditor5/src/i18n.ts b/packages/ckeditor5/src/i18n.ts
index 66f45b8644..b70cf9ee73 100644
--- a/packages/ckeditor5/src/i18n.ts
+++ b/packages/ckeditor5/src/i18n.ts
@@ -1,5 +1,5 @@
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
-import { EditorConfig, Translations } from "ckeditor5";
+import { add, EditorConfig, Translations } from "ckeditor5";
import { buildMessageDictionary } from "./messages.js";
@@ -135,3 +135,51 @@ export default async function getCkLocale(
...(translations.length > 0 ? { translations: [ {}, ...translations ] } : {})
};
}
+
+/**
+ * Puts the locale's CKEditor dictionary where an editor carrying none of its own will find it, and
+ * hands back the language such an editor is then to be told to speak.
+ *
+ * The small fields — a mind map node's memo, the chat box — are raised from a configuration settled
+ * as they mount, which cannot wait on a dictionary that has to be fetched. CKEditor resolves a
+ * message against `window.CKEDITOR_TRANSLATIONS` whenever an editor was given no `translations` of
+ * its own, so the catalog is laid there once, ahead of them, and each of those fields speaks the
+ * language without having to carry it.
+ *
+ * A locale is fetched once however many fields ask for it: what the first asked for is what the
+ * rest are handed. The full text editor is untouched by any of this — it hands its own
+ * `translations` over (see {@link getCkLocale}), and what an editor carries is what it reads from.
+ */
+export function registerCkTranslations(locale: DISPLAYABLE_LOCALE_IDS) {
+ let registration = registeredTranslations.get(locale);
+
+ if (!registration) {
+ registration = putTranslationsWithinReach(locale);
+ registeredTranslations.set(locale, registration);
+ }
+
+ return registration;
+}
+
+/** The locales already laid within reach, by the one that was asked for. */
+const registeredTranslations = new Map<DISPLAYABLE_LOCALE_IDS, Promise<Pick<EditorConfig, "language">>>();
+
+async function putTranslationsWithinReach(locale: DISPLAYABLE_LOCALE_IDS): Promise<Pick<EditorConfig, "language">> {
+ const mapping = LOCALE_MAPPINGS[locale];
+
+ // `en`, the `en_rtl` pseudo-locale and `ga` have no CKEditor translation to load, and no
+ // language to name either: an editor told none of its own speaks the English it was written in.
+ if (!mapping) return {};
+
+ // Filed under the code the editor will be answering to rather than the one the catalog arrives
+ // under: a locale is not always spelled the same on both sides (`zh-cn.js` carries what we ask
+ // for as `zh`), and a dictionary filed under a name nothing asks for is a dictionary unread.
+ const catalog = (await mapping.coreTranslation()).default;
+ const [ arrived ] = Object.values(catalog);
+ // A catalog may answer which plural form to take with a boolean where two forms are all there
+ // are, which is the same answer CKEditor reads through `Number()` when it takes one itself.
+ const pluralForm = arrived.getPluralForm;
+ add(mapping.languageCode, arrived.dictionary, pluralForm ? (count) => Number(pluralForm(count)) : undefined);
+
+ return { language: mapping.languageCode };
+}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index fd8d88629a..be5082d929 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -14,7 +14,7 @@ export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/menti
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
-export { default as getCkLocale } from "./i18n.js";
+export { default as getCkLocale, registerCkTranslations } from "./i18n.js";
export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";
export * from "./utils.js";