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): copy block and tab references through editor config
Elian Doran2bef475f6e48
diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex eb377075f5..732cb3b15d 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -41,10 +41,11 @@ Host services that need no component come through the editor config, so a spec p`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 }`,-`contentEmbed: { pickNote }`, `cutToNote: { cut, saveNow }` and `inlineIcon: { showPicker }`. Each falls back to a placeholder or a-no-op when left out (an upload without `getNoteId` is rejected), so a spec that does not assert on-it can omit it. A spec sharing one editor across tests can swap an entry with-`editor.config.set()`, which the plugins read at call time.+`contentEmbed: { pickNote }`, `cutToNote: { cut, saveNow }`, `inlineIcon: { showPicker }`,+`blockReference: { openHandleMenu, copyReference }` and `tabs: { copyReference }`. Each falls+back to a placeholder or a no-op when left out (an upload without `getNoteId` is rejected), so+a spec that does not assert on it can omit it. A spec sharing one editor across tests can swap+an entry with `editor.config.set()`, which the plugins 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), somediff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex 6944de887b..cbd0cf151c 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -1,19 +1,21 @@-import type { CKTextEditor } from "@triliumnext/ckeditor5";+import type { CKTextEditor, EditorConfig } from "@triliumnext/ckeditor5";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { CommandNames } from "../components/app_context.js";+import type FNote from "../entities/fnote.js";import type { MenuCommandItem, MenuItem } from "../menus/context_menu.js";import {- buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference, copyBlockShareLink,- copyTabReference, getClipboardBlockReference, highlightBlockReference, openBlockHandleMenu,- revealHighlightedBlocks+ buildBlockReferenceMenuItems, buildReferenceConfig, consumeBlockReference, copyBlockReference,+ copyBlockShareLink, copyTabReference, getClipboardBlockReference, highlightBlockReference,+ openBlockHandleMenu, revealHighlightedBlocks} from "./block_reference.js";import type { ViewScope } from "./link.js";const {showError, showMessage, showMenu, copyHtmlWithToast, copyTextWithToast, getTextEditorContaining,- getNote+ getNote, getNoteShareLink} = vi.hoisted(() => ({+ getNoteShareLink: vi.fn(),showError: vi.fn(),showMessage: vi.fn(),showMenu: vi.fn(),@@ -35,14 +37,14 @@ vi.mock("./content_renderer.js", () => ({getEmbedBoxSize: () => "medium"}));+vi.mock("./share_link.js", () => ({ getNoteShareLink }));+const scrollBy = vi.fn();-const getComponentByEl = vi.fn();beforeEach(() => {vi.clearAllMocks();vi.useFakeTimers();Element.prototype.scrollBy = scrollBy;- glob.getComponentByEl = getComponentByEl;});afterEach(() => {@@ -270,6 +272,86 @@ describe("openBlockHandleMenu", () => {});});+describe("buildReferenceConfig", () => {+ const note = { noteId: "n1", title: "Note" } as FNote;+ const tabHtml = "<div class=\"trilium-tabs\"><section class=\"trilium-tab\" "+ + "data-trilium-block-id=\"t1\"><p class=\"trilium-tab-title\">Linux</p></section></div>"+ + "<p data-trilium-block-id=\"s1\">Start</p>";++ function buildSource(notePath?: string) {+ const root = buildContainer(tabHtml);+ const editor = buildEditor(root, { startId: "s1", endId: "s1", count: 1 });+ vi.mocked(editor.execute).mockImplementation(((name: string) => name === "assignTabReference"+ ? { startId: "t1", endId: "t1", count: 1 }+ : { startId: "s1", endId: "s1", count: 1 }) as never);+ const save = vi.fn();+ const config = buildReferenceConfig({+ getEditor: () => editor,+ getNote: () => note,+ getNotePath: () => notePath,+ save+ });+ return { config, editor, save };+ }++ it("copies references to the blocks and the tab of the note, then saves it", async () => {+ const { config, save } = buildSource("root/p1/n1");++ config.blockReference?.copyReference?.();+ await vi.waitFor(() => expect(save).toHaveBeenCalledTimes(1));+ config.tabs?.copyReference?.();+ await vi.waitFor(() => expect(save).toHaveBeenCalledTimes(2));++ expect(copyHtmlWithToast).toHaveBeenNthCalledWith(1,+ "<a class=\"reference-link\" href=\"#root/p1/n1?block=s1\">Note - Start</a>",+ "#root/p1/n1?block=s1");+ expect(copyHtmlWithToast).toHaveBeenNthCalledWith(2,+ "<a class=\"reference-link\" href=\"#root/p1/n1?block=t1\">Note - Linux</a>",+ "#root/p1/n1?block=t1");+ expect(copyHtmlWithToast.mock.invocationCallOrder[0])+ .toBeLessThan(save.mock.invocationCallOrder[0]);+ });++ it("opens the block handle menu, which copies a reference or the public link", async () => {+ const { config, save } = buildSource();+ const event = new MouseEvent("contextmenu");+ getNoteShareLink.mockReturnValue("https://notes.example.com/share/page");++ config.blockReference?.openHandleMenu?.(event, 1);+ const items = showMenu.mock.calls[0][0].items as MenuItem<CommandNames>[];+ runItem(items[0]);+ await vi.waitFor(() => expect(save).toHaveBeenCalledTimes(1));+ runItem(items[1]);+ await vi.waitFor(() => expect(save).toHaveBeenCalledTimes(2));++ expect(getNoteShareLink).toHaveBeenCalledWith(note);+ expect(copyHtmlWithToast).toHaveBeenCalledWith(expect.anything(), "#root/n1?block=s1");+ expect(copyTextWithToast).toHaveBeenCalledWith(+ "https://notes.example.com/share/page?block=s1");++ getNoteShareLink.mockReturnValue(null);+ config.blockReference?.openHandleMenu?.(event, 1);+ expect(showMenu.mock.calls[1][0].items).toHaveLength(1);+ });++ it("copies nothing before the editor or the note is there", async () => {+ const save = vi.fn();+ const config = buildReferenceConfig({+ getEditor: () => null,+ getNote: () => note,+ getNotePath: () => undefined,+ save+ });++ config.blockReference?.copyReference?.();+ config.tabs?.copyReference?.();+ await vi.runAllTimersAsync();++ expect(copyHtmlWithToast).not.toHaveBeenCalled();+ expect(save).not.toHaveBeenCalled();+ });+});+describe("getClipboardBlockReference", () => {it("reads the first link to blocks in the HTML, else the text, as a reference link", () => {const html = "<p><a href=\"https://example.com\">web</a><a href=\"#root/note0\">note</a>"@@ -302,47 +384,48 @@ describe("buildBlockReferenceMenuItems", () => {const element = document.createElement("p");const href = "#root/parent1/note1?block=s1:e1";- it("copies a reference to the selected blocks through the host of the editor", async () => {- const copyReference = vi.fn(async () => {});- const { editor, root } = buildMenuEditor({ count: 3 });+ it("copies a reference to the selected blocks through the editor config", async () => {+ const copyReference = vi.fn();+ const { editor } = buildMenuEditor({+ count: 3, hosts: { blockReference: { copyReference } }+ });getTextEditorContaining.mockResolvedValue(editor);- getComponentByEl.mockReturnValue({ copyBlockReference: copyReference });const items = await buildBlockReferenceMenuItems(element);runItem(items?.copy);expect(getTextEditorContaining).toHaveBeenCalledWith(element);- expect(getComponentByEl).toHaveBeenCalledWith(root);expect(items?.copy).toMatchObject({ title: "block_reference.copy:3" });expect(copyReference).toHaveBeenCalledTimes(1);expect(items?.paste).toEqual([]);});- it("copies a link to the tab holding the selection through the host of the editor", async () => {- const copyTabReference = vi.fn();- const { editor } = buildMenuEditor();+ it("copies a link to the tab holding the selection through the editor config", async () => {+ const copyReference = vi.fn();+ const { editor } = buildMenuEditor({ hosts: { tabs: { copyReference } } });getTextEditorContaining.mockResolvedValue(editor);- getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn(), copyTabReference });const items = await buildBlockReferenceMenuItems(element);runItem(items?.copyTab);expect(items?.copyTab).toMatchObject({ title: "block_reference.copy_tab" });- expect(copyTabReference).toHaveBeenCalledTimes(1);+ expect(copyReference).toHaveBeenCalledTimes(1);- getTextEditorContaining.mockResolvedValue(buildMenuEditor({ isInTab: false }).editor);+ getTextEditorContaining.mockResolvedValue(buildMenuEditor({+ isInTab: false, hosts: { tabs: { copyReference } }+ }).editor);expect((await buildBlockReferenceMenuItems(element))?.copyTab).toBeNull();- getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn() });- getTextEditorContaining.mockResolvedValue(editor);+ getTextEditorContaining.mockResolvedValue(buildMenuEditor().editor);expect((await buildBlockReferenceMenuItems(element))?.copyTab).toBeNull();});it("offers no copy row where no reference can be made or the host cannot copy", async () => {- getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn() });- getTextEditorContaining.mockResolvedValue(buildMenuEditor({ canReference: false }).editor);+ const hosts = { blockReference: { copyReference: vi.fn() } };+ getTextEditorContaining.mockResolvedValue(buildMenuEditor({+ canReference: false, hosts+ }).editor);expect((await buildBlockReferenceMenuItems(element))?.copy).toBeNull();- getComponentByEl.mockReturnValue({});getTextEditorContaining.mockResolvedValue(buildMenuEditor().editor);expect((await buildBlockReferenceMenuItems(element))?.copy).toBeNull();});@@ -431,9 +514,9 @@ describe("buildBlockReferenceMenuItems", () => {});function buildMenuEditor({- count = 2, canReference = true, canEmbed = true, hasPlugin = true, isInTab = true+ count = 2, canReference = true, canEmbed = true, hasPlugin = true, isInTab = true,+ hosts = {} as Pick<EditorConfig, "blockReference" | "tabs">} = {}) {- const root = document.createElement("div");const pasteTarget = { paste: vi.fn(), release: vi.fn() };const commands: Record<string, { isEnabled: boolean; value?: number }> = {assignBlockReference: { isEnabled: canReference, value: count },@@ -443,11 +526,11 @@ function buildMenuEditor({const editor = {plugins: { has: (name: string) => hasPlugin && name === "BlockReference" },commands: { get: (name: string) => commands[name] },- editing: { view: { getDomRoot: () => root } },+ config: { get: (name: "blockReference" | "tabs") => hosts[name] },capturePasteTarget: vi.fn(() => pasteTarget)};- return { editor: editor as typeof editor & CKTextEditor, root, pasteTarget };+ return { editor: editor as typeof editor & CKTextEditor, pasteTarget };}function runItem(item: MenuItem<CommandNames> | null | undefined) {diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.tsindex d7f2643491..9dcb4a8377 100644--- a/apps/client/src/services/block_reference.ts+++ b/apps/client/src/services/block_reference.ts@@ -1,4 +1,4 @@-import type { CKTextEditor } from "@triliumnext/ckeditor5";+import type { CKTextEditor, EditorConfig } from "@triliumnext/ckeditor5";import {flashBlocks, getBlockBoxes, getBlockRangeElements, showBlockReference} from "@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js";@@ -8,6 +8,7 @@ import {} from "@triliumnext/commons";import type { CommandNames } from "../components/app_context.js";+import type FNote from "../entities/fnote.js";import contextMenu, { type MenuItem } from "../menus/context_menu.js";import type { ClipboardAccess } from "../menus/table_context_menu.js";import { getTextEditorContaining } from "../menus/text_editor_context_menu.js";@@ -17,6 +18,7 @@ import { revealElement } from "./collapsible.js";import froca from "./froca.js";import { t } from "./i18n.js";import { calculateHash, parseNavigationStateFromUrl, type ViewScope } from "./link.js";+import { getNoteShareLink } from "./share_link.js";import toast from "./toast.js";const HIGHLIGHT_CLASS = "block-reference-highlight";@@ -48,10 +50,51 @@ export interface BlockHandleMenuActions {copyShareLink?: () => void;}-/** The component of a text editor that copies references to the blocks of its note. */-interface BlockReferenceHost {- copyBlockReference?(): Promise<void>;- copyTabReference?(): void;+/** The note a text editor is open on, which the references it copies point to. */+export interface ReferenceSource {+ getEditor(): CKTextEditor | null | undefined;+ getNote(): FNote | null | undefined;+ /** The path the note is open at, if known. */+ getNotePath(): string | null | undefined;+ /** Saves the note now, so that a copied link resolves at once. */+ save(): unknown;+}++type CopyReference = (editor: CKTextEditor, notePath: string, noteTitle: string) => unknown;++/** The `blockReference` and `tabs` editor config, which copy references into `source`. */+export function buildReferenceConfig(+ source: ReferenceSource+): Pick<EditorConfig, "blockReference" | "tabs"> {+ async function copy(copyTo: CopyReference) {+ const editor = source.getEditor();+ const note = source.getNote();+ if (!editor || !note) {+ return;+ }++ await copyTo(editor, source.getNotePath() ?? `root/${note.noteId}`, note.title);+ await source.save();+ }++ return {+ blockReference: {+ openHandleMenu(event, count) {+ const note = source.getNote();+ const shareLink = note && getNoteShareLink(note);+ openBlockHandleMenu(event, count, {+ copyReference: () => void copy(copyBlockReference),+ copyShareLink: shareLink+ ? () => void copy((editor) => copyBlockShareLink(editor, shareLink))+ : undefined+ });+ },+ copyReference: () => void copy(copyBlockReference)+ },+ tabs: {+ copyReference: () => void copy(copyTabReference)+ }+ };}/** Opens the menu of the block handle at `event`, for `count` selected blocks. */@@ -261,27 +304,25 @@ function getCopyItem(count: number, copyReference: () => void): MenuItem<Commandfunction getCopyMenuItem(editor: CKTextEditor) {const command = editor.commands.get("assignBlockReference");- const root = editor.editing.view.getDomRoot();- const host: BlockReferenceHost | undefined = root && glob.getComponentByEl(root);- if (!command?.isEnabled || !host?.copyBlockReference) {+ const copyReference = editor.config.get("blockReference")?.copyReference;+ if (!command?.isEnabled || !copyReference) {return null;}- return getCopyItem(command.value, () => void host.copyBlockReference?.());+ return getCopyItem(command.value, () => copyReference());}function getCopyTabMenuItem(editor: CKTextEditor): MenuItem<CommandNames> | null {const command = editor.commands.get("assignTabReference");- const root = editor.editing.view.getDomRoot();- const host: BlockReferenceHost | undefined = root && glob.getComponentByEl(root);- if (!command?.isEnabled || !host?.copyTabReference) {+ const copyReference = editor.config.get("tabs")?.copyReference;+ if (!command?.isEnabled || !copyReference) {return null;}return {title: t("block_reference.copy_tab"),uiIcon: "bx bx-link",- handler: () => host.copyTabReference?.()+ handler: () => copyReference()};}diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex 261c948de2..339bc9b7a2 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -134,8 +134,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa// note would name whichever one happened to be open when the editor was built.const noteLocationRef = useRef<AiNoteLocation | null>(null);noteLocationRef.current = note ? { title: note.title, notePath } : null;- const noteIdRef = useRef<string | undefined>(undefined);- noteIdRef.current = note?.noteId;+ const noteRef = useRef(note);+ noteRef.current = note;/** The open icon picker request and its balloon container, or `null` when none is open. */const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerRequest | null>(null);@@ -301,10 +301,16 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLacontentLanguage: contentLanguage ?? null,templates: templatesRef.current,getNoteLocation: () => noteLocationRef.current,- getNoteId: () => noteIdRef.current,+ getNoteId: () => noteRef.current?.noteId,getComponentId: () => parentComponent?.componentId,triggerHostCommand: (command) => parentComponent?.triggerCommand(command),- showIconPicker+ showIconPicker,+ referenceSource: {+ getEditor: () => editorRef.current,+ getNote: () => noteRef.current,+ getNotePath: () => noteLocationRef.current?.notePath,+ save: () => parentComponent?.triggerCommand("saveNoteDetailNow")+ }});if (isStale) {diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 43f4994ce6..2fb7b53e68 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -14,10 +14,7 @@ import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commonimport { useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";-import {- consumeBlockReference, copyBlockReference, copyBlockShareLink, copyTabReference,- openBlockHandleMenu-} from "../../../services/block_reference";+import { consumeBlockReference } from "../../../services/block_reference";import { consumeBookmark } from "../../../services/bookmark_jump";import dialog from "../../../services/dialog";import froca from "../../../services/froca";@@ -26,7 +23,6 @@ import link, { parseNavigationStateFromUrl, type ViewScope } from "../../../servimport type LoadResults from "../../../services/load_results";import note_create from "../../../services/note_create";import { consumeSearchTerms } from "../../../services/search_jump";-import { getNoteShareLink } from "../../../services/share_link";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";import type { AddLinkOpts } from "../../dialogs/add_link";@@ -190,19 +186,6 @@ export default function EditableText({consumeBlockReference(root, noteContext?.viewScope);}- async function copyReference(- copy: (editor: CKTextEditor, notePath: string, noteTitle: string) => void | Promise<void>- = copyBlockReference- ) {- const editor = editorRef.current;- if (!editor) return;-- const notePath = noteContext?.notePath ?? `root/${note.noteId}`;- await copy(editor, notePath, note.title);- // Saved now, so that the link resolves at once.- spacedUpdate.updateNowIfNecessary();- }-useTriliumEvent("scrollToEnd", () => {const editor = editorRef.current;if (!editor) return;@@ -304,17 +287,6 @@ export default function EditableText({},getAttachmentHref,openContentEmbedMenu,- openBlockHandleMenu(event: MouseEvent, count: number) {- const shareLink = getNoteShareLink(note);- openBlockHandleMenu(event, count, {- copyReference: () => void copyReference(),- copyShareLink: shareLink- ? () => void copyReference((editor) => copyBlockShareLink(editor, shareLink))- : undefined- });- },- copyBlockReference: () => copyReference(),- copyTabReference: () => void copyReference(copyTabReference),getContentEmbedTools,enterContentEmbed,// Keyboard shortcut@@ -372,7 +344,7 @@ export default function EditableText({});},async saveNoteDetailNowCommand() {- // used by cutToNote in CKEditor build+ // Used by `cutToNote` and by the block and tab references the editor copies.spacedUpdate.updateNowIfNecessary();}});diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex ee020f484e..d33c2bef88 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -417,6 +417,22 @@ describe("CK config - tables", () => {expect((await buildConfig(baseOpts())).inlineIcon?.showPicker(request)).toBeNull();});+ it("copies block and tab references from the reference source, and none without one", async () => {+ const getEditor = vi.fn(() => null);+ const referenceSource = {+ getEditor, getNote: () => null, getNotePath: () => undefined, save: vi.fn()+ };+ const config = await buildConfig(baseOpts({ referenceSource }));++ config.blockReference?.copyReference?.();+ config.tabs?.copyReference?.();++ expect(getEditor).toHaveBeenCalledTimes(2);+ const bare = await buildConfig(baseOpts());+ expect(bare.blockReference).toBeUndefined();+ expect(bare.tabs).toBeUndefined();+ });+it("titles reference links through the link service", async () => {expect((await buildConfig(baseOpts())).referenceLink).toStrictEqual({getTitle: linkService.getReferenceLinkTitle,diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex a7edd830c8..eae9789a7a 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -4,6 +4,7 @@ import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOADimport i18next from "i18next";import type { 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";import { prompt } from "../../../services/dialog.js";@@ -59,6 +60,8 @@ export interface BuildEditorOptions {triggerHostCommand?: (command: CommandNames) => 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. */+ referenceSource?: ReferenceSource;}export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {@@ -222,6 +225,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiinternalLink: { openDialog: bindHostCommand(opts, "addLinkToText") },markdownImport: { open: bindHostCommand(opts, "pasteMarkdownIntoText") },inlineIcon: { showPicker: (request) => opts.showIconPicker?.(request) ?? null },+ ...(opts.referenceSource && buildReferenceConfig(opts.referenceSource)),cutToNote: {cut: bindHostCommand(opts, "cutIntoNote"),saveNow: bindHostCommand(opts, "saveNoteDetailNow")diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 82dde980ae..e98ce865ea 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -124,16 +124,6 @@ declare global {* leave it out.*/openContentEmbedMenu?(embed: HTMLElement, anchor: HTMLElement): void;- /**- * Opens the menu of the block handle at `event`, for `count` selected blocks. Hosts- * without block references leave it out.- */- openBlockHandleMenu?(event: MouseEvent, count: number): void;- /**- * Copies a link to the tab that holds the selection. Hosts without block references leave- * it out.- */- copyTabReference?(): void;/*** The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. Hosts* without embeds leave it out.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 8e5a764ba1..c2d12c609a 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -39,6 +39,7 @@ export type { default as MobileToolbarItems } from "./plugins/mobile_toolbar_iteexport type { LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";export type { AttachmentUploadHost } from "./plugins/uploadimage.js";export type { IconPickerRequest } from "./plugins/inline_icon/inline_icon_ui.js";+export type { BlockReferenceHost } from "./plugins/block_reference/block_reference.js";export type { ColorMenuHost, ColorMenuRequest, ColorMenuTarget } from "./plugins/color_menu.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.tsindex 1f1a7053ae..d5d9a00e77 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts@@ -6,7 +6,6 @@ import {import { describe, expect, it, vi } from "vitest";import { createTestEditor, createTestEditorOf } from "../../../test/editor-kit.js";-import { installGlobMock } from "../../../test/globals-test-kit.js";import BlockDragHandle from "../block_drag_handle.js";import Multicolumn from "../multicolumn/multicolumn.js";import BlockReference from "./block_reference.js";@@ -305,9 +304,10 @@ describe("BlockReference", () => {describe("block handle menu", () => {it("asks the host to open the menu for the selected blocks", async () => {- const openBlockHandleMenu = vi.fn();- installGlobMock({ getComponentByEl: () => ({ openBlockHandleMenu }) });- const editor = await createTestEditor([ ...PLUGINS, BlockDragHandle ]);+ const openHandleMenu = vi.fn();+ const editor = await createTestEditor([ ...PLUGINS, BlockDragHandle ], {+ blockReference: { openHandleMenu }+ });setModelData(editor.model, "<paragraph>[one</paragraph><paragraph>two]</paragraph>");const handle = getHandle(editor.plugins.get(BlockDragHandle).buttonView?.element);@@ -321,25 +321,36 @@ describe("BlockReference", () => {expect(rightDown.defaultPrevented).toBe(true);expect(leftDown.defaultPrevented).toBe(false);expect(contextMenu.defaultPrevented).toBe(true);- expect(openBlockHandleMenu).toHaveBeenCalledWith(contextMenu, 2);+ expect(openHandleMenu).toHaveBeenCalledWith(contextMenu, 2);editor.enableReadOnlyMode("spec");handle.dispatchEvent(new MouseEvent("contextmenu", { cancelable: true }));- expect(openBlockHandleMenu).toHaveBeenCalledTimes(1);+ expect(openHandleMenu).toHaveBeenCalledTimes(1);});it("uses the button of the block toolbar in the floating toolbar editor", async () => {- const openBlockHandleMenu = vi.fn();- installGlobMock({ getComponentByEl: () => ({ openBlockHandleMenu }) });+ const openHandleMenu = vi.fn();const editor = await createTestEditorOf(BalloonEditor, [ ...PLUGINS, BlockToolbar ], {- blockToolbar: [ "heading" ]+ blockToolbar: [ "heading" ],+ blockReference: { openHandleMenu }});setModelData(editor.model, "<paragraph>[]one</paragraph>");getHandle(editor.plugins.get(BlockToolbar).buttonView.element).dispatchEvent(new MouseEvent("contextmenu", { cancelable: true }));- expect(openBlockHandleMenu).toHaveBeenCalledWith(expect.any(MouseEvent), 1);+ expect(openHandleMenu).toHaveBeenCalledWith(expect.any(MouseEvent), 1);+ });++ it("keeps the browser menu away without a host for the menu", async () => {+ const editor = await createTestEditor([ ...PLUGINS, BlockDragHandle ]);+ setModelData(editor.model, "<paragraph>[one]</paragraph>");+ const handle = getHandle(editor.plugins.get(BlockDragHandle).buttonView?.element);++ const contextMenu = new MouseEvent("contextmenu", { cancelable: true });+ handle.dispatchEvent(contextMenu);++ expect(contextMenu.defaultPrevented).toBe(true);});it("does nothing in an editor without a block handle", async () => {diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.tsindex 363b9f045f..967ea45707 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.ts@@ -6,7 +6,8 @@ import BlockReferenceEditing, {/*** References to blocks of a text note. A right click on the block handle calls- * `openBlockHandleMenu()` of the host, whose menu copies a reference to the selected blocks.+ * `blockReference.openHandleMenu()` of the host, whose menu copies a reference to the selected+ * blocks.*/export default class BlockReference extends Plugin {@@ -62,12 +63,23 @@ export default class BlockReference extends Plugin {return;}- const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());- component?.openBlockHandleMenu?.(event, command.value);+ editor.config.get("blockReference")?.openHandleMenu?.(event, command.value);}}+/** What the host of the editor does with references to blocks. */+export interface BlockReferenceHost {+ /** Opens the menu of the block handle at `event`, for `count` selected blocks. */+ openHandleMenu(event: MouseEvent, count: number): void;+ /** Copies a reference to the selected blocks. */+ copyReference(): void;+}+declare module "ckeditor5" {+ interface EditorConfig {+ blockReference?: Partial<BlockReferenceHost>;+ }+interface PluginsMap {[BlockReference.pluginName]: BlockReference;[BlockReferenceEditing.pluginName]: BlockReferenceEditing;diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.tsindex 21a70175d3..615d5ebcdb 100644--- a/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts@@ -14,7 +14,6 @@ import {} from "ckeditor5";import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";-import { installGlobMock } from "../../../test/globals-test-kit.js";import tabsBottomIcon from "../../icons/tabs-bottom.svg?raw";import tabsIcon from "../../icons/tabs.svg?raw";import Tabs from "./tabs.js";@@ -51,8 +50,7 @@ describe("TabsUI", () => {});it("copies a link to the tab holding the selection through the host", () => {- const copyTabReference = vi.fn();- installGlobMock({ getComponentByEl: () => ({ copyTabReference }) });+ const copyReference = vi.fn();editor.setData("<p>x</p>");const button = editor.ui.componentFactory.create("copyTabLink") as ButtonView;expect(button.isEnabled).toBe(false);@@ -61,8 +59,10 @@ describe("TabsUI", () => {expect(button.isEnabled).toBe(true);expect(button.label && button.icon && button.tooltip).toBeTruthy();button.fire("execute");+ editor.config.set("tabs", { copyReference });+ button.fire("execute");- expect(copyTabReference).toHaveBeenCalledTimes(1);+ expect(copyReference).toHaveBeenCalledTimes(1);});it("aligns the tabs from a dropdown at the end of the toolbar", () => {diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts b/packages/ckeditor5/src/plugins/tabs/tabs_ui.tsindex ba03033ef3..97f4d3e2a2 100644--- a/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts+++ b/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts@@ -4,7 +4,6 @@ import {Collection,type Command,createDropdown,- type Editor,IconLink,IconNextArrow,IconPlus,@@ -74,7 +73,7 @@ export default class TabsUI extends Plugin {const command = editor.commands.get("assignTabReference") as Command;button.bind("isEnabled").to(command, "isEnabled");- this.listenTo(button, "execute", () => getHost(editor).copyTabReference?.());+ this.listenTo(button, "execute", () => editor.config.get("tabs")?.copyReference?.());return button;});}@@ -141,7 +140,12 @@ function getAlignmentIcon(alignment: TabAlignment): string {return alignment === "bottom" ? tabsBottomIcon : tabsIcon;}-/** Returns the host component of `editor`, which copies links. */-function getHost(editor: Editor) {- return glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());+declare module "ckeditor5" {+ interface EditorConfig {+ /** What the host of the editor does with tabs blocks. */+ tabs?: {+ /** Copies a link to the tab that holds the selection. */+ copyReference?(): void;+ };+ }}