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
chore(text): draw reference link titles through editor config
Elian Dorandceb31d5dfe7
diff --git a/.claude/skills/ckeditor5-testing/SKILL.md b/.claude/skills/ckeditor5-testing/SKILL.mdindex 180dea62dc..d46a128380 100644--- a/.claude/skills/ckeditor5-testing/SKILL.md+++ b/.claude/skills/ckeditor5-testing/SKILL.md@@ -212,22 +212,21 @@ button.fire( 'execute' );expect( spy ).toHaveBeenCalledWith( 'insertMermaid' );```-## Stubbing the Trilium glue (`glob` / clipboard / jQuery `$`)+## Stubbing the host and browser globals-Many in-aggregate plugins reference a global `glob` (the Trilium bridge typed in-`src/augmentation.ts`), some hit `navigator.clipboard`, and some converters call jQuery `$(...)`.-Use the globals kit (`test/globals-test-kit.ts`): `installGlobMock({…})` and `mockClipboard({…})`-install the stub **and register their own teardown** (run by the global `afterEach` in-`test/setup.ts`), and `$` is a global passthrough from `setup.ts` — so specs **don't** hand-roll-`globalThis.glob` or delete anything. (Browser mode shares one page, so a leaked global would bleed-into later specs.) See `references/patterns.md` for the recipe.+The plugins take everything they need from Trilium through editor config entries+(`referenceLink`, `contentEmbed`, `linkEmbed`, …), so a spec passes mocks to+`createTestEditor( plugins, { … } )` and swaps one later with `editor.config.set()`. A browser+global a spec must swap gets its restore queued with `registerTestCleanup()` from+`test/globals-test-kit.ts`, run by the global `afterEach` in `test/setup.ts`. (Browser mode shares+one page, so a global left swapped bleeds into later specs.) See `references/patterns.md`.## Reference map| File | Use it for ||------|-----------|| `references/test-utilities.md` | Testing against a real `ClassicEditor` (lifecycle, `licenseKey: 'GPL'`), and the `_setModelData`/`_getModelData`/`_getViewData` helpers from `'ckeditor5'` + the `[]`/`{}` selection syntax. |-| `references/patterns.md` | Idiomatic recipes per concern (schema, conversion round-trips, commands, UI, keystrokes, events, async), all against a real editor; the `glob`/clipboard/jQuery-`$` stubbing recipe (via the globals kit's `installGlobMock`/`mockClipboard`); testing `onEditorError()` listeners without Vitest flagging the dispatched `error` event; measuring real CSS (`?url` vs `?inline` vs `?raw`, transitions, focus); note on the 100% coverage gate for browser-mode packages. |+| `references/patterns.md` | Idiomatic recipes per concern (schema, conversion round-trips, commands, UI, keystrokes, events, async), all against a real editor; the host config entries and `registerTestCleanup()` for browser globals; testing `onEditorError()` listeners without Vitest flagging the dispatched `error` event; measuring real CSS (`?url` vs `?inline` vs `?raw`, transitions, focus); note on the 100% coverage gate for browser-mode packages. || `references/running-and-config.md` | The WebdriverIO `vitest.config.ts` shape, `pnpm --filter` commands, the debug command, `pnpm test:parallel`/`test:sequential` (ckeditor5 + math sequential), coverage thresholds, and troubleshooting a session that never starts (a missing Playwright browser build, the worktree dep-optimizer hang, orphaned headless Chromium). || `references/test-conventions.md` | Trilium test **conventions & gotchas**: real-browser event timing, real-editor teardown, the both-assertion-styles note, unreachable code vs. the 100% gate, and the pointer to `writing-unit-tests`. |diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex f784da8c00..d71ee03a48 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -33,11 +33,11 @@ standalone packages (and legacy specs mid-migration) still hand-roll the scaffol`document.createElement('div')` + `ClassicEditor.create(...)` + an `afterEach` that calls`editor.destroy()` and `editorElement.remove()`.-## Stubbing the Trilium glue (`glob` / `navigator.clipboard` / jQuery `$`)+## Stubbing the host and browser globals-Host services that need no component come through the editor config, so a spec passes them to-`createTestEditor( plugins, { … } )` instead of mocking `glob`: `formatDateTime` (date/time),-`referenceLink: { getTitle, getTitleSync }` (reference links), `linkEmbed` (link previews —+Everything the plugins need from Trilium comes through the editor config, so a spec passes it to+`createTestEditor( plugins, { … } )`: `formatDateTime` (date/time),+`referenceLink: { getTitle, getTitleSync, renderTitle, fixLink }` (reference links), `linkEmbed` (link previews —`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry), and `getNoteId` plus`attachmentUpload: { getHeaders, getLocalUpload, getEmbedBoxSize }` (uploads), and the dialogs abutton hands over to the host: `internalLink: { openDialog }`, `markdownImport: { open }`,@@ -49,34 +49,22 @@ upload without `getNoteId` is rejected), so a spec that does not assert on it caspec sharing one editor across tests can swap an entry with `editor.config.set()`, which theplugins read at call time.-Many in-aggregate plugins still reach for a global `glob` (the Trilium bridge — typed in-`packages/ckeditor5/src/augmentation.ts` with `getComponentByEl`, which finds the host component), some-buttons hit `navigator.clipboard`, and some converters call jQuery `$(...)` (e.g. the `editingDowncast`-converter in `packages/ckeditor5/src/plugins/referencelink.ts`). Use the globals kit-(`test/globals-test-kit.ts`) so each stub **tears itself down** after the test — never hand-roll-`globalThis.glob = …` plus a manual `delete`:+The editor package reads no Trilium global and calls no jQuery. A spec that has to swap a browser+global (`navigator.clipboard`, a `window` method) queues its restore with `registerTestCleanup()`+from `test/globals-test-kit.ts`, which the global `afterEach` in `test/setup.ts` runs:```ts-import { installGlobMock, mockClipboard } from '../../test/globals-test-kit.js';+import { registerTestCleanup } from '../../test/globals-test-kit.js';-beforeEach( async () => {- const loadReferenceLinkTitle = vi.fn( async () => undefined );- installGlobMock( { getComponentByEl: () => ( { loadReferenceLinkTitle } ) } ); // removed after the test- editor = await createTestEditor( [ Essentials, Paragraph, ReferenceLink ] );+const original = navigator.clipboard;+Object.defineProperty( navigator, 'clipboard', { value: clipboard, configurable: true } );+registerTestCleanup( () => {+ Object.defineProperty( navigator, 'clipboard', { value: original, configurable: true } );} );-// no afterEach: setup.ts runs the kit's cleanups (and destroys the editor)```-- `installGlobMock( obj )` casts to the global `glob` type for you and returns `obj` for assertions; its teardown is queued and run by the global `afterEach` in `test/setup.ts`.-- `mockClipboard( obj )` swaps `navigator.clipboard` and restores the original afterwards.-- jQuery `$` is already a global passthrough installed by `test/setup.ts` — specs don't set it.--**Why a kit and not hand-rolled globals:** browser mode runs every spec in **one shared page**, so a-leaked `glob`/`$`/clipboard survives into later specs and causes test-order-dependent flakiness — a-review caught exactly this missing cleanup. The kit makes teardown automatic. (Existing specs still-hand-roll `globalThis.glob = … as unknown as typeof glob` + a manual `delete` in `afterEach`; that's-the legacy pattern being migrated to `installGlobMock` — see-`packages/ckeditor5/src/plugins/internallink.spec.ts`.)+Browser mode runs every spec in **one shared page**, so a global left swapped leaks into later specs+and causes test-order-dependent failures.## Schemadiff --git a/.claude/skills/ckeditor5-testing/references/test-conventions.md b/.claude/skills/ckeditor5-testing/references/test-conventions.mdindex 9411115a18..0b945a7c3f 100644--- a/.claude/skills/ckeditor5-testing/references/test-conventions.md+++ b/.claude/skills/ckeditor5-testing/references/test-conventions.md@@ -44,11 +44,10 @@ standalone packages (and legacy specs mid-migration to the kit) still hand-roll`afterEach` calling `editor.destroy()` and `editorElement.remove()`; forgetting either there leakseditor DOM / body wrappers across tests and causes flakiness.-**Globals: use the kit's installers.** Stub the Trilium `glob` / `navigator.clipboard` via-`installGlobMock()` / `mockClipboard()` from `test/globals-test-kit.ts` — they register their own-teardown (run by `setup.ts`), and `$` is a global passthrough from `setup.ts`. Don't hand-roll-`globalThis.glob` + a manual `delete`; browser mode's shared page leaks a forgotten global into-later specs (see `patterns.md`).+**Host services come through config; globals get a queued restore.** Pass what a plugin needs from+Trilium as an editor config entry. A spec that swaps a browser global queues its restore with+`registerTestCleanup()` from `test/globals-test-kit.ts` (run by `setup.ts`); browser mode's shared+page leaks a global left swapped into later specs (see `patterns.md`).## Assertion styles — both workdiff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsxindex 4771d9d98e..e3d2312ec7 100644--- a/apps/client/src/widgets/EmbeddedNotePane.tsx+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx@@ -403,8 +403,7 @@ function EmbeddedNotePanel({ note, panelClassName, bodyClassName, closeText, maxconst paneRef = useRef<HTMLDivElement>(null);// Applies the note's color class, so the panel does not inherit the color of the host's split.const colorClass = useNoteColorClass(note);- // The text editor resolves its host component from the DOM. Without this, it resolves the widget- // that contains the host view, which does not implement calls such as `loadReferenceLinkTitle`.+ // `appContext.getComponentByEl()` otherwise resolves the widget that contains the host view.useLegacyComponentElement(paneRef);useFollowLinksWithin(paneRef, onFollowLink);const maximized = !!maximize?.maximized;diff --git a/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsx b/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsxindex cc314c02fd..d2691b12a3 100644--- a/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsx+++ b/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsx@@ -22,7 +22,7 @@ import { isIMEComposing } from "../../services/shortcuts";import { escapeQuotes, getErrorMessage } from "../../services/utils";import ActionButton from "../react/ActionButton";import CKEditor, { CKEditorApi } from "../react/CKEditor";-import { useLegacyImperativeHandlers, useLegacyWidget, useTriliumEvent } from "../react/hooks";+import { useLegacyWidget, useTriliumEvent } from "../react/hooks";import { createAutocompleteMentionList, createNoteMentionList } from "../type_widgets/text/mention_list_view";import AttributeDetailWidget, { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_detail";@@ -201,17 +201,6 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxI}});- // Interaction with CKEditor.- useLegacyImperativeHandlers(useMemo(() => ({- loadReferenceLinkTitle: async ($el: JQuery<HTMLElement>, href: string) => {- const { noteId } = link.parseNavigationStateFromUrl(href);- const note = noteId ? await froca.getNote(noteId, true) : null;- const title = note ? note.title : "[missing]";-- $el.text(title);- }- }), []));-// Keyboard shortcutsuseTriliumEvent("addNewLabel", ({ ntxId: eventNtxId }) => {if (eventNtxId !== ntxId) return;@@ -258,6 +247,7 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxItoolbar: { items: [] },placeholder: t("attribute_editor.placeholder"),mention: { feeds: [], hostedFeeds: hostedMentions },+ referenceLink: { renderTitle: renderReferenceTitle },licenseKey: "GPL",language: "en"}}@@ -380,6 +370,13 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxI);}+/** Fills `element` with the title of the note a relation's reference link points to. */+async function renderReferenceTitle(element: HTMLElement, href: string) {+ const { noteId } = link.parseNavigationStateFromUrl(href);+ const note = noteId ? await froca.getNote(noteId, true) : null;+ element.textContent = note ? note.title : "[missing]";+}+/*** Completes the name typed after `marker` as the attributes panel's name box completes it, from the* same names drawn the same way, and inserts the name picked behind the marker.diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex e25458b4fa..4b0931d3b0 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1571,11 +1571,10 @@ export function useLegacyImperativeHandlers(handlers: Record<string, Function>)* bearing a component and reads it off there.** The counterpart of {@link useLegacyImperativeHandlers} — that hook writes methods onto the parent- * component, and this is what lets a caller holding only a DOM node arrive at the same object. The- * text editor is the caller that matters: the calls that need state of the host component, such as- * drawing reference-link titles and rendering included notes, find it with- * `glob.getComponentByEl(editor.editing.view.getDomRoot())`. An editor in a subtree whose parent- * component the DOM cannot name finds whichever widget encloses it, and fails on the first such call.+ * component, and this is what lets a caller holding only a DOM node arrive at the same object, such+ * as `resolveFocusedComponent()`, which collects the shortcut hints of the focused element, or a+ * render note looking up its parent. A subtree whose parent component the DOM cannot name answers+ * with whichever widget encloses it.** Only needed where a subtree provides a `ParentComponent` of its own. A component built as a widget* marks its own element (see `BasicWidget.render`), and a React tree mounted under one answers todiff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 65e7ff3017..2e2d740423 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -13,7 +13,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, useTriliumOption } from "../../react/hooks.js";+import { useTriliumOption } from "../../react/hooks.js";import Icon from "../../react/Icon.js";import LightboxLink from "../../react/LightboxLink.js";import AddProviderModal, { type LlmProviderConfig, type ProviderStep } from "../options/llm/AddProviderModal.js";@@ -115,16 +115,6 @@ export default function ChatInputBar({// Clipboard / drag-drop / file-picker upload management.const attachments = useChatAttachments(chat);- // CKEditor's ReferenceLink plugin calls back into the parent component to- // resolve a note's title from its href.- useLegacyImperativeHandlers({- async loadReferenceLinkTitle(- $el: JQuery<HTMLElement>, href: string | null = null, storedTitle?: string- ) {- await link.loadReferenceLinkTitle($el, href, undefined, storedTitle);- }- });-const baseSubmit = onSubmit ?? chat.handleSubmit;// Clear the editor immediately when a submit fires with non-empty, non-streaming// input — mirrors the rejection check inside chat.handleSubmit so we don't wipe@@ -319,6 +309,11 @@ export default function ChatInputBar({toolbar: { items: [] },placeholder: t("llm_chat.placeholder"),mention: { feeds: [], hostedFeeds: hostedMentions },+ referenceLink: {+ renderTitle: (element, href, storedTitle) => {+ void link.loadReferenceLinkTitle($(element), href, undefined, storedTitle);+ }+ },licenseKey: "GPL"}}// The strings the box shows of its own — the link balloon it raises on Ctrl+K —diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsxindex db4328ec43..74a5614074 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx@@ -4,8 +4,8 @@ import { useRef } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import link from "../../../services/link";import CKEditor, { type CKEditorApi } from "./CKEditor";+import { buildConfig } from "./config";const mocks = vi.hoisted(() => ({options: {} as Record<string, string | boolean>,@@ -14,8 +14,7 @@ const mocks = vi.hoisted(() => ({stopReportingErrors: vi.fn(),reportError: undefined as ((error: Error) => void) | undefined,reportingEditor: undefined as unknown,- note: undefined as { noteId: string; title: string } | undefined,- handlers: {} as Record<string, (...args: unknown[]) => unknown>+ note: undefined as { noteId: string; title: string } | undefined}));vi.mock("@triliumnext/ckeditor5", () => {@@ -47,9 +46,6 @@ vi.mock("@triliumnext/ckeditor5", () => {vi.mock("../../react/hooks", () => ({useKeyboardShortcuts: () => {},- useLegacyImperativeHandlers: (handlers: typeof mocks.handlers) => {- mocks.handlers = handlers;- },useNoteContext: () => ({parentComponent: undefined,ntxId: undefined,@@ -172,10 +168,8 @@ describe("CKEditor", () => {expect(props.editorRef.current).toBeNull();});- it("labels its reference links as links in the note it edits", async () => {+ it("tells the editor config which note it edits, as the note changes", async () => {mocks.note = { noteId: "host1", title: "Host" };- const loadReferenceLinkTitle = vi.spyOn(link, "loadReferenceLinkTitle")- .mockResolvedValue(undefined);const props = {contentLanguage: null,editorRef: createRef<CKTextEditor>(),@@ -187,11 +181,15 @@ describe("CKEditor", () => {render(<CKEditor {...props} />, host);});- const $el = $("<span>");- await mocks.handlers.loadReferenceLinkTitle($el, "#root/host1?block=b1", "Stored");+ await vi.waitFor(() => expect(buildConfig).toHaveBeenCalled());+ const opts = vi.mocked(buildConfig).mock.lastCall?.[0];+ expect(opts?.getNoteId?.()).toBe("host1");- expect(loadReferenceLinkTitle)- .toHaveBeenCalledWith($el, "#root/host1?block=b1", "host1", "Stored");- loadReferenceLinkTitle.mockRestore();+ mocks.note = { noteId: "host2", title: "Other" };+ await act(async () => {+ render(<CKEditor {...props} className="force-rerender" />, host);+ });++ expect(opts?.getNoteId?.()).toBe("host2");});});diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex 3b370fa711..f137fb09d1 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -7,9 +7,8 @@ import { createPortal, HTMLAttributes, RefObject } from "preact";import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";import froca from "../../../services/froca";-import link from "../../../services/link";import { isMobile } from "../../../services/utils";-import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import { useKeyboardShortcuts, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import IconPicker from "../../react/IconPicker";import type { AiNoteLocation } from "./ai_assistant_stream";import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";@@ -267,14 +266,6 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa},}));- useLegacyImperativeHandlers({- async loadReferenceLinkTitle(- $el: JQuery<HTMLElement>, href: string | null = null, storedTitle?: string- ) {- await link.loadReferenceLinkTitle($el, href, note?.noteId, storedTitle);- },- });-async function destroyEditor() {const editor = editorRef.current;editorRef.current = null;@@ -307,7 +298,7 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLagetNoteLocation: () => noteLocationRef.current,getNoteId: () => noteRef.current?.noteId,getComponentId: () => parentComponent?.componentId,- triggerHostCommand: (command) => parentComponent?.triggerCommand(command),+ triggerHostCommand: (command, data) => parentComponent?.triggerCommand(command, data),showIconPicker,referenceSource: {getEditor: () => editorRef.current,diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 13c24650f7..94b8906436 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -248,16 +248,6 @@ export default function EditableText({const opts = getAddLinkOpts(editorApiRef.current, waitForEditor);parentComponent?.triggerCommand("showAddLinkDialog", opts);},- fixReferenceLink(storedTitle: string, fix: (href: string) => void) {- parentComponent?.triggerCommand("showAddLinkDialog", {- text: storedTitle,- hasSelection: false,- fixLink: true,- async addLink(notePath) {- fix(`#${notePath}`);- }- });- },pasteMarkdownIntoTextCommand() {if (!editorApiRef.current) return;parentComponent?.triggerCommand("showPasteMarkdownDialog", {diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxindex ab2c3fd086..407474f447 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -96,7 +96,7 @@ interface ScopedEditorProps {/** The editor, once the note context of the embed holds `note`. */function ScopedEditor({ rootRef, note, block, onBlockChange }: ScopedEditorProps) {const { note: contextNote, noteContext, ntxId, parentComponent } = useNoteContext();- // The plugins of the editor find their host by the element of its component.+ // `appContext.getComponentByEl()` finds the host of the editor by this element.useLegacyComponentElement(rootRef);const badgeSlot = useEmbedBadgeSlot(rootRef);useEditorFindTarget(ntxId);diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex cc24360b49..262c20ed48 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -1,10 +1,11 @@import type { EditorConfig, InlineEmbedSource } from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS, IMAGE_MIMES, LOCALES, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import imageService from "../../../services/image.js";import linkService from "../../../services/link.js";import { ensureMimeTypesForHighlighting } from "../../../services/syntax_highlight.js";+import type { AddLinkOpts } from "../../dialogs/add_link.js";import { buildConfig, type BuildEditorOptions, OPEN_SOURCE_LICENSE_KEY } from "./config.js";// Mutable option values, reset before each test (see `beforeEach`).@@ -498,11 +499,38 @@ describe("CK config - tables", () => {expect(() => host?.loadNote?.("n1", wrapper, undefined, undefined, onBlockChange)).not.toThrow();});- it("titles reference links through the link service", async () => {- expect((await buildConfig(baseOpts())).referenceLink).toStrictEqual({- getTitle: linkService.getReferenceLinkTitle,- getTitleSync: linkService.getReferenceLinkTitleSync- });+ it("titles reference links through the link service, in the note open at the time", async () => {+ const loadTitle = vi.spyOn(linkService, "loadReferenceLinkTitle").mockResolvedValue();+ onTestFinished(() => loadTitle.mockRestore());+ let noteId = "n1";+ const referenceLink = (await buildConfig(baseOpts({ getNoteId: () => noteId }))).referenceLink;+ const element = document.createElement("span");++ referenceLink?.renderTitle?.(element, "#root/n2", "Stored");+ noteId = "n3";+ referenceLink?.renderTitle?.(element, "#root/n2");++ expect(referenceLink?.getTitle).toBe(linkService.getReferenceLinkTitle);+ expect(referenceLink?.getTitleSync).toBe(linkService.getReferenceLinkTitleSync);+ expect(loadTitle.mock.calls.map(([ $el, ...rest ]) => [ $el[0], ...rest ])).toEqual([+ [ element, "#root/n2", "n1", "Stored" ],+ [ element, "#root/n2", "n3", undefined ]+ ]);+ });++ it("asks the host to fix a link to a missing note through the add link dialog", async () => {+ const triggerHostCommand = vi.fn(async () => undefined);+ const fix = vi.fn();+ const referenceLink = (await buildConfig(baseOpts({ triggerHostCommand }))).referenceLink;++ referenceLink?.fixLink?.("Gone", fix);++ expect(triggerHostCommand).toHaveBeenCalledExactlyOnceWith("showAddLinkDialog", expect.objectContaining({+ text: "Gone", hasSelection: false, fixLink: true+ }));+ const [ , dialog ] = triggerHostCommand.mock.calls[0] as unknown as [ string, AddLinkOpts ];+ await dialog.addLink("root/n9", null);+ expect(fix).toHaveBeenCalledExactlyOnceWith("#root/n9");});});diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex e1674bf638..7bd346de3c 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -3,7 +3,7 @@ import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/enimport { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import i18next from "i18next";-import type { CommandNames } from "../../../components/app_context.js";+import type { CommandMappings, CommandNames } from "../../../components/app_context.js";import { buildReferenceConfig, type ReferenceSource } from "../../../services/block_reference.js";import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";import { getUploadBoxSize } from "../../../services/content_renderer.js";@@ -57,8 +57,10 @@ export interface BuildEditorOptions {getNoteId?: () => string | undefined;/** The ID of the component that hosts the editor, which changes the editor makes are sent as. */getComponentId?: () => string | undefined;- /** Triggers `command` on the component that hosts the editor. */- triggerHostCommand?: (command: CommandNames) => Promise<unknown> | undefined | null;+ /** Triggers `command` with `data` on the component that hosts the editor. */+ triggerHostCommand?: <K extends CommandNames>(+ command: K, data?: CommandMappings[K]+ ) => Promise<unknown> | undefined | null;/** Shows the icon picker the editor asks for, as `inlineIcon.showPicker` does. */showIconPicker?: (request: IconPickerRequest) => (() => void) | null;/** The note that the block and tab references the editor copies point to. */@@ -228,7 +230,20 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiformatDateTime: (date, format) => formatDateTime(date, format ?? options.get("customDateTimeFormat")),referenceLink: {getTitle: linkService.getReferenceLinkTitle,- getTitleSync: linkService.getReferenceLinkTitleSync+ getTitleSync: linkService.getReferenceLinkTitleSync,+ renderTitle: (element, href, storedTitle) => {+ void linkService.loadReferenceLinkTitle($(element), href, opts.getNoteId?.(), storedTitle);+ },+ fixLink: (storedTitle, fix) => {+ void opts.triggerHostCommand?.("showAddLinkDialog", {+ text: storedTitle,+ hasSelection: false,+ fixLink: true,+ async addLink(notePath) {+ fix(`#${notePath}`);+ }+ });+ }},linkEmbed: buildLinkEmbedHost(opts.getNoteId),getNoteId: opts.getNoteId,diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 074caf496e..1c55b8251e 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -79,20 +79,5 @@ declare global {*/hasDisplayModes?: boolean;}-- interface EditorComponent {- loadReferenceLinkTitle(- $el: JQuery<HTMLElement>, href: string, storedTitle?: string- ): Promise<void>;- /**- * Lets the user pick the note a reference link to a missing note should point at instead,- * starting from `storedTitle`, and calls `fix()` with the new href.- */- fixReferenceLink?(storedTitle: string, fix: (href: string) => void): void;- }-- var glob: {- getComponentByEl<T>(el: unknown): T;- };}diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex f6947fa3e4..cdec9b9797 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -23,7 +23,6 @@ import bxWindowAlt from "boxicons/svg/regular/bx-window-alt.svg?raw";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-import { installGlobMock } from "../../../test/globals-test-kit.js";import LinkEmbed from "../link_embed/link_embed.js";import ReferenceLink from "../referencelink.js";import ContentEmbed, {@@ -802,12 +801,6 @@ describe("ContentEmbed with attachments", () => {loadEmbeddedNote = vi.fn();loadEmbeddedAttachment = vi.fn();getAttachmentHref = vi.fn(async () => LINK_HREF);- installGlobMock({- getComponentByEl: () => ({- loadReferenceLinkTitle: vi.fn(async () => undefined)- })- });-editor = await createTestEditor([Essentials, Paragraph, Undo, Widget, LinkEditing, ReferenceLink, ContentEmbed], {diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.tsindex 3269dfc358..027a25b02c 100644--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts@@ -12,7 +12,6 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";-import { installGlobMock } from "../../test/globals-test-kit.js";import FindInLinkWidgets from "./find_in_link_widgets.js";import LinkEmbedEditing from "./link_embed/link_embed_editing.js";import ReferenceLink from "./referencelink.js";@@ -21,17 +20,6 @@ describe("FindInLinkWidgets", () => {let editor: ClassicEditor;beforeEach(async () => {- installGlobMock({- getComponentByEl: () => ({- loadReferenceLinkTitle: vi.fn((element: unknown) => {- if (element instanceof HTMLElement) {- element.textContent = "Reference match";- }- return Promise.resolve();- })- })- });-editor = await createTestEditor([Essentials,Paragraph,diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.tsindex bf4845fa8a..6bb100e891 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts@@ -7,7 +7,6 @@ import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";import { beforeAll, beforeEach, describe, expect, it, type Mock, vi } from "vitest";import { createTestEditor, getEditorElement } from "../../../test/editor-kit.js";-import { installGlobMock } from "../../../test/globals-test-kit.js";import ReferenceLink from "../referencelink.js";import InlineIcon from "./inline_icon.js";import InlineIconEditing from "./inline_icon_editing.js";@@ -101,10 +100,6 @@ describe("a reference link pasted from a rendered page", () => {// the clipboard. A reference takes no children, so the icon is dropped rather than split out// beside the link.it("loses the icon the renderer drew inside it, leaving the link alone", async () => {- installGlobMock({- getComponentByEl: () => ({ loadReferenceLinkTitle: () => Promise.resolve() })- });-const editor = await createTestEditor([ Paragraph, Link, ReferenceLink, InlineIcon ], {referenceLink: { getTitle: async () => "Some note", getTitleSync: () => "Some note" }});diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 5812826781..228ee2ea09 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -5,7 +5,6 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";-import { installGlobMock } from "../../test/globals-test-kit.js";import InternalLinkPlugin, {COMMAND_NAME, getLinkAtSelection, replaceLinkAtSelection} from "./internallink.js";@@ -76,9 +75,6 @@ describe("the link at the selection", () => {let getTitle: ReturnType<typeof vi.fn>;beforeEach(async () => {- installGlobMock({- getComponentByEl: () => ({ loadReferenceLinkTitle: async () => undefined })- });getTitle = vi.fn(async () => "Target");editor = await createTestEditor([Essentials, Paragraph, Bold, LinkEditing, InternalLinkPlugin], {referenceLink: { getTitle, getTitleSync: () => "Target" }diff --git a/packages/ckeditor5/src/plugins/mention_customization.spec.ts b/packages/ckeditor5/src/plugins/mention_customization.spec.tsindex cd0642bdfa..ee08013f87 100644--- a/packages/ckeditor5/src/plugins/mention_customization.spec.ts+++ b/packages/ckeditor5/src/plugins/mention_customization.spec.ts@@ -9,7 +9,6 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";-import { installGlobMock } from "../../test/globals-test-kit.js";import TriliumMentionUI from "./mention/trilium_mention_ui.js";import MentionCustomization from "./mention_customization.js";import ReferenceLink from "./referencelink.js";@@ -18,12 +17,6 @@ describe("MentionCustomization", () => {let editor: ClassicEditor;beforeEach(async () => {- installGlobMock({- getComponentByEl: () => ({- loadReferenceLinkTitle: vi.fn(async () => {})- })- });-editor = await createTestEditor([Essentials,Paragraph,diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.tsindex 40da1f0b1c..57d60333a5 100644--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts@@ -2,7 +2,6 @@ import { _getModelData as getModelData, _getViewData as getViewData, _setModelDaimport { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";-import { installGlobMock } from "../../test/globals-test-kit.js";import ReferenceLink, { getAttachmentId, getNoteId } from "./referencelink.js";describe("ReferenceLink", () => {@@ -15,12 +14,12 @@ describe("ReferenceLink", () => {getReferenceLinkTitle = vi.fn(async () => "Some title");getReferenceLinkTitleSync = vi.fn(() => "Some title");loadReferenceLinkTitle = vi.fn(async () => undefined);- installGlobMock({- getComponentByEl: () => ({ loadReferenceLinkTitle })- });-editor = await createTestEditor([Essentials, Paragraph, LinkEditing, ReferenceLink], {- referenceLink: { getTitle: getReferenceLinkTitle, getTitleSync: getReferenceLinkTitleSync }+ referenceLink: {+ getTitle: getReferenceLinkTitle,+ getTitleSync: getReferenceLinkTitleSync,+ renderTitle: loadReferenceLinkTitle+ }});});@@ -178,7 +177,7 @@ describe("ReferenceLink", () => {expect(view).toContain("reference-link");expect(view).toContain("ck-widget");- // Force the UIElement's render callback to run so loadReferenceLinkTitle is invoked.+ // Force the UIElement's render callback to run so `renderTitle` is invoked.const domRoot = editor.editing.view.getDomRoot();const anchor = domRoot?.querySelector("a.reference-link");expect(anchor).not.toBeNull();@@ -187,6 +186,18 @@ describe("ReferenceLink", () => {expect(loadReferenceLinkTitle.mock.calls[0]?.[2]).toBe("Some title");});+ it("shows the title it reads itself without a host to render it", () => {+ editor.config.set("referenceLink", { renderTitle: undefined });+ getReferenceLinkTitleSync.mockReturnValue("Synced title");++ editor.setData('<p><a class="reference-link" href="#root/noteAbc">Stored</a></p>');++ const anchor = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");+ expect(anchor?.textContent).toBe("Synced title");+ expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc", "Stored");+ expect(loadReferenceLinkTitle).not.toHaveBeenCalled();+ });+it("shows a placeholder's file name, then redraws it as a titled link once uploaded", () => {setModelData(editor.model, "<paragraph>[]</paragraph>");const reference = editor.model.change((writer) => {@@ -365,13 +376,10 @@ describe("ReferenceLink", () => {it("asks to fix a reference to a missing note when it is clicked, and not one to a note", () => {const fixReferenceLink = vi.fn();- // The test setup makes `$` a passthrough, so the title element arrives as itself.loadReferenceLinkTitle.mockImplementation(async (el: HTMLElement, href: string) => {el.classList.toggle("reference-link-missing", href === "#root/gone");});- installGlobMock({- getComponentByEl: () => ({ loadReferenceLinkTitle, fixReferenceLink })- });+ editor.config.set("referenceLink", { fixLink: fixReferenceLink });editor.setData('<p><a class="reference-link" href="#root/noteAbc">Fine</a>'+ '<a class="reference-link" href="#root/gone">Gone</a></p>'@@ -403,9 +411,7 @@ describe("ReferenceLink", () => {loadReferenceLinkTitle.mockImplementation(async (el: HTMLElement) => {el.classList.add("reference-link-missing");});- installGlobMock({- getComponentByEl: () => ({ loadReferenceLinkTitle, fixReferenceLink })- });+ editor.config.set("referenceLink", { fixLink: fixReferenceLink });editor.setData('<p><a class="reference-link" href="#root/gone"></a><a href="https://x.org">x</a></p>');diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.tsindex cd775e5fa0..86651de7de 100644--- a/packages/ckeditor5/src/plugins/referencelink.ts+++ b/packages/ckeditor5/src/plugins/referencelink.ts@@ -191,8 +191,8 @@ export class ReferenceLinkEditing extends Plugin {return;}- const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );- component?.fixReferenceLink?.( String( reference.getAttribute( 'storedTitle' ) ?? '' ), href => {+ const storedTitle = String( reference.getAttribute( 'storedTitle' ) ?? '' );+ editor.config.get( 'referenceLink' )?.fixLink?.( storedTitle, href => {editor.execute( 'referenceLink', { href, replace: reference } );editor.editing.view.focus();} );@@ -258,10 +258,12 @@ export class ReferenceLinkEditing extends Plugin {return domElement;}- const editorEl = editor.editing.view.getDomRoot();- const component = glob.getComponentByEl<EditorComponent>(editorEl);-- component.loadReferenceLinkTitle($(domElement), href, storedTitle);+ const renderTitle = editor.config.get( 'referenceLink' )?.renderTitle;+ if ( renderTitle ) {+ renderTitle( domElement, href, storedTitle );+ } else {+ domElement.textContent = getReferenceTitleSync( editor, href, storedTitle );+ }return domElement;});@@ -353,12 +355,22 @@ declare module "ckeditor5" {interface EditorConfig {referenceLink?: {/** Resolves the title of the note or attachment `href` points to, loading it if needed. */- getTitle( href: string ): Promise<string>;+ getTitle?( href: string ): Promise<string>;/*** The title of the note or attachment `href` points to, from what is already loaded.* `storedTitle` is the title the saved content holds, for a note that is not loaded.*/- getTitleSync( href: string, storedTitle?: string ): string;+ getTitleSync?( href: string, storedTitle?: string ): string;+ /**+ * Fills `element` with the label of the link to `href`, which the host can load.+ * Without it, the link shows what `getTitleSync()` reads.+ */+ renderTitle?( element: HTMLElement, href: string, storedTitle?: string ): void;+ /**+ * Lets the user pick the note a reference link to a missing note should point at+ * instead, starting from `storedTitle`, and calls `fix()` with the new href.+ */+ fixLink?( storedTitle: string, fix: ( href: string ) => void ): void;};}}diff --git a/packages/ckeditor5/test/globals-test-kit.ts b/packages/ckeditor5/test/globals-test-kit.tsindex b342c29437..b59187058d 100644--- a/packages/ckeditor5/test/globals-test-kit.ts+++ b/packages/ckeditor5/test/globals-test-kit.ts@@ -1,7 +1,6 @@/**- * Helpers for the Trilium global stubs that several specs install on `globalThis` (the `glob`- * bridge). Each installer registers its own teardown, run after every test by the global- * `afterEach` in `setup.ts`, so specs no longer need to delete/restore these themselves.+ * Per-test teardowns for stubs that specs install on `globalThis`, run after every test by the+ * global `afterEach` in `setup.ts`, so specs need not restore them themselves.** Lives outside `src/`, so it is excluded from both the production build and the 100% coverage* gate (see editor-kit.ts).@@ -21,17 +20,3 @@ export async function runTestCleanups(): Promise<void> {await cleanup();}}--/**- * Install a mock Trilium `glob` on `globalThis` for the current test. Pass only the members the- * spec needs (each typically a `vi.fn()`); the cast to the global `glob` type lives here so specs- * don't repeat it. Returns the same object for convenient assertion access. Removed automatically- * after the test.- */-export function installGlobMock<T extends object>(glob: T): T {- (globalThis as unknown as { glob: T }).glob = glob;- registerTestCleanup(() => {- delete (globalThis as { glob?: unknown }).glob;- });- return glob;-}diff --git a/packages/ckeditor5/test/setup.ts b/packages/ckeditor5/test/setup.tsindex 35d82e4002..5ace8d4ea5 100644--- a/packages/ckeditor5/test/setup.ts+++ b/packages/ckeditor5/test/setup.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach } from "vitest";+import { afterEach } from "vitest";import { destroyTrackedEditors } from "./editor-kit.js";import { runTestCleanups } from "./globals-test-kit.js";@@ -6,13 +6,9 @@ import { runTestCleanups } from "./globals-test-kit.js";/*** Global test setup, registered via `setupFiles` in vitest.config.ts and run before/after every* spec. Owns the boilerplate specs used to repeat:- * - a constant `$` (jQuery) passthrough that several plugins' converters call;* - destroying every editor created through `createTestEditor()`;- * - running per-test cleanups queued by the globals kit (glob / clipboard stubs).+ * - running the per-test cleanups that specs queue with `registerTestCleanup()`.*/-beforeEach(() => {- (globalThis as unknown as { $: (value: unknown) => unknown }).$ = (value) => value;-});afterEach(async () => {await runTestCleanups();diff --git a/packages/ckeditor5/tsconfig.lib.json b/packages/ckeditor5/tsconfig.lib.jsonindex 7b76018da9..0591e55c2a 100644--- a/packages/ckeditor5/tsconfig.lib.json+++ b/packages/ckeditor5/tsconfig.lib.json@@ -10,8 +10,7 @@"forceConsistentCasingInFileNames": true,"lib": ["DOM", "ES2023"],"types": [- "vite/client",- "jquery"+ "vite/client"]},"include": [