Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/block references: add context menu commands for working with block references

Adorian Doran0f483ff37fb0
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.ts
index 2365e77984..7ae7a8d59d 100644
--- a/apps/client/src/menus/note_context_menu.spec.ts
+++ b/apps/client/src/menus/note_context_menu.spec.ts
@@ -20,6 +20,9 @@ vi.mock("../components/app_context.js", () => ({
// The module under test pulls in several DOM/jQuery-heavy collaborators at import
// time; stub them so importing stays cheap and side-effect free.
vi.mock("../components/zoom.js", () => ({ default: {} }));
+vi.mock("../services/block_reference.js", () => ({
+ buildBlockReferenceMenuItems: vi.fn(async () => null)
+}));
vi.mock("../services/clipboard_ext.js", () => ({ copyHtml: vi.fn(), copyTextWithToast: vi.fn() }));
vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));
vi.mock("../services/options.js", () => ({ default: { get: () => "" } }));
@@ -33,6 +36,7 @@ vi.mock("./table_context_menu.js", () => ({
hasTableCellSelection: vi.fn(async () => false)
}));
+import { buildBlockReferenceMenuItems } from "../services/block_reference.js";
import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";
import server from "../services/server.js";
import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";
@@ -310,6 +314,52 @@ describe("buildNoteContextMenuItems", () => {
expect(buildTableContextMenuSections).not.toHaveBeenCalled();
});
+ it("puts the block reference rows in the copy and paste submenus", async () => {
+ const cell = document.createElement("td");
+ vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({
+ main: [],
+ sort: { title: "S" },
+ delete: [],
+ select: { title: "SEL" },
+ pasteRows: [ { title: "PR1" } ]
+ } as TableMenuSections);
+ vi.mocked(buildBlockReferenceMenuItems).mockResolvedValueOnce({
+ copy: { title: "BC" },
+ paste: [ { title: "BP1" }, { title: "BP2" } ]
+ });
+ const host = browserLikeHost({
+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }
+ });
+
+ const items = await build({ isEditable: true, element: cell, selectionText: "" }, host);
+
+ expect(buildBlockReferenceMenuItems).toHaveBeenCalledWith(cell, host.paste);
+ // Built once the table sections have moved the selection into the clicked cell.
+ expect(vi.mocked(buildTableContextMenuSections).mock.invocationCallOrder[0])
+ .toBeLessThan(vi.mocked(buildBlockReferenceMenuItems).mock.invocationCallOrder[0]);
+ expect(titles(submenu(items, "electron_context_menu.copy"))).toEqual([
+ "electron_context_menu.copy",
+ "electron_context_menu.copy-as-markdown",
+ "---",
+ "BC"
+ ]);
+ // Without a selection only the reference can be copied, so the row opens its submenu.
+ expect(findItem(items, "electron_context_menu.copy"))
+ .toMatchObject({ enabled: true, handler: undefined });
+ expect(titles(submenu(items, "electron_context_menu.paste"))).toEqual([
+ "electron_context_menu.paste",
+ "electron_context_menu.paste-as-plain-text",
+ "---",
+ "BP1",
+ "BP2",
+ "---",
+ "PR1"
+ ]);
+
+ await build({ element: cell });
+ expect(buildBlockReferenceMenuItems).toHaveBeenCalledTimes(1);
+ });
+
it("converts the selection through the to-markdown route", async () => {
vi.mocked(server.post).mockResolvedValue({ markdownContent: "# Hi" });
setSelection(document.createElement("span"), "<h1>Hi</h1>");
diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.ts
index 16cc5db51e..5ad00c0963 100644
--- a/apps/client/src/menus/note_context_menu.ts
+++ b/apps/client/src/menus/note_context_menu.ts
@@ -1,6 +1,7 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import appContext, { type CommandNames } from "../components/app_context.js";
+import { buildBlockReferenceMenuItems } from "../services/block_reference.js";
import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";
import { t } from "../services/i18n.js";
import options from "../services/options.js";
@@ -135,6 +136,9 @@ export async function buildNoteContextMenuItems(
// A cell selection supersedes `selectionText`: over one, Electron reports the hidden
// fake-selection label as the selected text, which no row should act on.
const hasCellSelection = tableSections !== null && await hasTableCellSelection(target.element);
+ const blockReferenceItems = target.isEditable
+ ? await buildBlockReferenceMenuItems(target.element, host.paste)
+ : null;
const hasText = !hasCellSelection && target.selectionText.trim().length > 0;
const hasClipboardContent = hasText || hasCellSelection;
@@ -186,6 +190,9 @@ export async function buildNoteContextMenuItems(
handler: copySelectionAsMarkdown
}
];
+ if (blockReferenceItems?.copy) {
+ copyVariants.push({ kind: "separator" }, blockReferenceItems.copy);
+ }
items.push(splitMenuItem({
enabled: host.canCopy && hasClipboardContent,
@@ -220,6 +227,9 @@ export async function buildNoteContextMenuItems(
handler: runAsPlainText
}
];
+ if (blockReferenceItems?.paste.length) {
+ pasteVariants.push({ kind: "separator" }, ...blockReferenceItems.paste);
+ }
if (tableSections?.pasteRows.length) {
pasteVariants.push({ kind: "separator" }, ...tableSections.pasteRows);
}
diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.ts
index 268cf66355..f1dcfd559e 100644
--- a/apps/client/src/services/block_reference.spec.ts
+++ b/apps/client/src/services/block_reference.spec.ts
@@ -1,30 +1,43 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CommandNames } from "../components/app_context.js";
+import type { MenuCommandItem, MenuItem } from "../menus/context_menu.js";
import {
- consumeBlockReference, copyBlockReference, getBlockRangeElements, highlightBlockReference,
+ buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference,
+ getBlockRangeElements, getClipboardBlockReference, highlightBlockReference,
openBlockHandleMenu, revealHighlightedBlocks
} from "./block_reference.js";
import type { ViewScope } from "./link.js";
-const { showError, showMenu, copyHtmlWithToast } = vi.hoisted(() => ({
+const {
+ showError, showMessage, showMenu, copyHtmlWithToast, getTextEditorContaining, getNote
+} = vi.hoisted(() => ({
showError: vi.fn(),
+ showMessage: vi.fn(),
showMenu: vi.fn(),
- copyHtmlWithToast: vi.fn()
+ copyHtmlWithToast: vi.fn(),
+ getTextEditorContaining: vi.fn(),
+ getNote: vi.fn()
}));
vi.mock("./i18n.js", () => ({
t: (key: string, options?: { count?: number }) => options ? `${key}:${options.count}` : key
}));
-vi.mock("./toast.js", () => ({ default: { showError } }));
+vi.mock("./toast.js", () => ({ default: { showError, showMessage } }));
vi.mock("../menus/context_menu.js", () => ({ default: { show: showMenu } }));
+vi.mock("../menus/text_editor_context_menu.js", () => ({ getTextEditorContaining }));
vi.mock("./clipboard_ext.js", () => ({ copyHtmlWithToast }));
+vi.mock("./froca.js", () => ({ default: { getNote } }));
+vi.mock("./content_renderer.js", () => ({ getEmbedBoxSize: () => "medium" }));
const scrollIntoView = vi.fn();
+const getComponentByEl = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
Element.prototype.scrollIntoView = scrollIntoView;
+ glob.getComponentByEl = getComponentByEl;
});
afterEach(() => {
@@ -216,6 +229,168 @@ describe("openBlockHandleMenu", () => {
});
});
+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>"
+ + "<a href=\"#root/parent1/note1?block=s1%3Ae1\">blocks</a></p>";
+
+ expect(getClipboardBlockReference({ html, text: "#root/note2?block=b2" })).toEqual({
+ noteId: "note1",
+ block: "s1:e1",
+ href: "#root/parent1/note1?block=s1:e1"
+ });
+ expect(getClipboardBlockReference({
+ html: "<p>No link</p>",
+ text: " http://localhost:8080/#root/note2?block=b2&ntxId=x \n"
+ })).toEqual({ noteId: "note2", block: "b2", href: "#root/note2?block=b2" });
+ });
+
+ it("finds none in a link to a whole note or with a malformed block parameter", () => {
+ const texts = [
+ "#root/note1", "#root/note1?block=", "#root/note1?block=a:b:c",
+ "#root/note1?block=%E0", "plain text", ""
+ ];
+
+ for (const text of texts) {
+ expect(getClipboardBlockReference({ html: "", text })).toBeNull();
+ }
+ });
+});
+
+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 });
+ 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("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);
+ expect((await buildBlockReferenceMenuItems(element))?.copy).toBeNull();
+
+ getComponentByEl.mockReturnValue({});
+ getTextEditorContaining.mockResolvedValue(buildMenuEditor().editor);
+ expect((await buildBlockReferenceMenuItems(element))?.copy).toBeNull();
+ });
+
+ it("offers no rows outside a text editor with block references", async () => {
+ getTextEditorContaining.mockResolvedValue(null);
+ expect(await buildBlockReferenceMenuItems(element)).toBeNull();
+
+ getTextEditorContaining.mockResolvedValue(buildMenuEditor({ hasPlugin: false }).editor);
+ expect(await buildBlockReferenceMenuItems(element)).toBeNull();
+ });
+
+ it("pastes the reference on the clipboard as a link or an excerpt", async () => {
+ const { editor, pasteTarget } = buildMenuEditor();
+ getTextEditorContaining.mockResolvedValue(editor);
+ getNote.mockResolvedValue({ noteId: "note1" });
+ const clipboard = {
+ enabled: true,
+ read: vi.fn(async () => ({ html: `<a href="${href}">x</a>`, text: "" }))
+ };
+
+ const paste = (await buildBlockReferenceMenuItems(element, clipboard))?.paste ?? [];
+ expect(paste).toMatchObject([
+ { title: "block_reference.paste_as_link", enabled: true },
+ { title: "block_reference.paste_as_excerpt", enabled: true }
+ ]);
+
+ runItem(paste[0]);
+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(1));
+ expect(editor.capturePasteTarget.mock.invocationCallOrder[0])
+ .toBeLessThan(clipboard.read.mock.invocationCallOrder[0]);
+ expect(pasteTarget.paste).toHaveBeenLastCalledWith(
+ `<a class="reference-link" href="${href}">${href}</a>`, href);
+
+ runItem(paste[1]);
+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(2));
+ expect(getNote).toHaveBeenCalledWith("note1", true);
+ expect(pasteTarget.paste).toHaveBeenLastCalledWith(
+ "<figure class=\"include-note\" data-note-id=\"note1\" data-block=\"s1:e1\""
+ + " data-box-size=\"medium\"></figure>",
+ href
+ );
+ });
+
+ it("disables the paste rows for an empty clipboard, and the excerpt where no embed fits",
+ async () => {
+ const clipboard = { enabled: false, read: vi.fn() };
+ getTextEditorContaining.mockResolvedValue(buildMenuEditor().editor);
+ const empty = await buildBlockReferenceMenuItems(element, clipboard);
+
+ clipboard.enabled = true;
+ getTextEditorContaining.mockResolvedValue(buildMenuEditor({ canEmbed: false }).editor);
+ const noEmbed = await buildBlockReferenceMenuItems(element, clipboard);
+
+ expect(getEnabled(empty?.paste)).toEqual([ false, false ]);
+ expect(getEnabled(noEmbed?.paste)).toEqual([ true, false ]);
+ });
+
+ it("reports a clipboard without a reference and a referenced note that is gone", async () => {
+ const { editor, pasteTarget } = buildMenuEditor();
+ getTextEditorContaining.mockResolvedValue(editor);
+ getNote.mockResolvedValue(null);
+ const clipboard = {
+ enabled: true,
+ read: vi.fn(async () => ({ html: "", text: "plain text" }))
+ };
+ const paste = (await buildBlockReferenceMenuItems(element, clipboard))?.paste ?? [];
+
+ runItem(paste[0]);
+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(1));
+ expect(showMessage).toHaveBeenCalledWith(
+ "block_reference.no_reference_on_clipboard", 3000, "bx bx-info-circle");
+
+ clipboard.read.mockResolvedValue({ html: "", text: href });
+ runItem(paste[1]);
+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(2));
+ expect(showError).toHaveBeenCalledWith("block_reference.not_found");
+ expect(pasteTarget.paste).not.toHaveBeenCalled();
+ });
+});
+
+function buildMenuEditor({
+ count = 2, canReference = true, canEmbed = true, hasPlugin = true
+} = {}) {
+ 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 },
+ insertContentEmbed: { isEnabled: canEmbed }
+ };
+ const editor = {
+ plugins: { has: (name: string) => hasPlugin && name === "BlockReference" },
+ commands: { get: (name: string) => commands[name] },
+ editing: { view: { getDomRoot: () => root } },
+ capturePasteTarget: vi.fn(() => pasteTarget)
+ };
+
+ return { editor: editor as typeof editor & CKTextEditor, root, pasteTarget };
+}
+
+function runItem(item: MenuItem<CommandNames> | null | undefined) {
+ (item as MenuCommandItem<CommandNames> | undefined)?.handler?.({} as never, {} as never);
+}
+
+function getEnabled(items: MenuItem<CommandNames>[] | undefined) {
+ return items?.map((item) => (item as MenuCommandItem<CommandNames>).enabled);
+}
+
function buildContainer(html: string) {
const container = document.createElement("div");
container.innerHTML = html;
diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.ts
index eca0e9a209..0baff02feb 100644
--- a/apps/client/src/services/block_reference.ts
+++ b/apps/client/src/services/block_reference.ts
@@ -1,12 +1,18 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
-import { formatBlockRange, resolveBlockRange, resolveBlockReference } from "@triliumnext/commons";
+import {
+ formatBlockRange, parseBlockRange, resolveBlockRange, resolveBlockReference
+} from "@triliumnext/commons";
-import contextMenu from "../menus/context_menu.js";
+import type { CommandNames } from "../components/app_context.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";
import { getBlockExcerpt } from "./block_excerpts.js";
import { copyHtmlWithToast } from "./clipboard_ext.js";
import { expandAncestorDetails } from "./collapsible.js";
+import froca from "./froca.js";
import { t } from "./i18n.js";
-import { calculateHash, type ViewScope } from "./link.js";
+import { calculateHash, parseNavigationStateFromUrl, type ViewScope } from "./link.js";
import toast from "./toast.js";
const FLASH_CLASS = "block-reference-flash";
@@ -14,20 +20,79 @@ const FLASH_CLASS = "block-reference-flash";
const FLASH_DURATION_MS = 1500;
const HIGHLIGHT_CLASS = "block-reference-highlight";
+/** A reference to blocks of a note, read from the clipboard. */
+export interface ClipboardBlockReference {
+ noteId: string;
+ /** The `block` link parameter. */
+ block: string;
+ /** The href of a reference link to the blocks. */
+ href: string;
+}
+
+/** The block reference rows of the text editor's right-click menu. */
+export interface BlockReferenceMenuItems {
+ /** Copies a reference to the selected blocks, in the _Copy_ submenu, or `null`. */
+ copy: MenuItem<CommandNames> | null;
+ /** Pastes the reference on the clipboard, in the _Paste_ submenu. */
+ paste: MenuItem<CommandNames>[];
+}
+
+/** The component of a text editor that copies references to the blocks of its note. */
+interface BlockReferenceHost {
+ copyBlockReference?(): Promise<void>;
+}
+
/** Opens the menu of the block handle at `event`, which copies a reference to `count` blocks. */
export function openBlockHandleMenu(event: MouseEvent, count: number, copyReference: () => void) {
void contextMenu.show({
x: event.pageX,
y: event.pageY,
- items: [ {
- title: t("block_reference.copy", { count }),
- uiIcon: "bx bx-link",
- handler: copyReference
- } ],
+ items: [ getCopyItem(count, copyReference) ],
selectMenuItemHandler: () => {}
});
}
+/**
+ * The block reference rows for a right-click on `element`, or `null` when `element` is not in a
+ * text editor. `clipboard` enables the paste rows.
+ */
+export async function buildBlockReferenceMenuItems(
+ element: Element | null | undefined,
+ clipboard?: ClipboardAccess
+): Promise<BlockReferenceMenuItems | null> {
+ const editor = await getTextEditorContaining(element);
+ if (!editor?.plugins.has("BlockReference")) {
+ return null;
+ }
+
+ return {
+ copy: getCopyMenuItem(editor),
+ paste: clipboard ? getPasteMenuItems(editor, clipboard) : []
+ };
+}
+
+/**
+ * The first link to blocks of a note in the HTML of the clipboard, else its text as such a link,
+ * or `null`.
+ */
+export function getClipboardBlockReference(
+ { html, text }: { html: string; text: string }
+): ClipboardBlockReference | null {
+ const links = html
+ ? new DOMParser().parseFromString(html, "text/html").querySelectorAll("a[href]")
+ : [];
+ const hrefs = Array.from(links, (link) => link.getAttribute("href") ?? "");
+
+ for (const href of [ ...hrefs, text ]) {
+ const reference = parseBlockReferenceHref(href);
+ if (reference) {
+ return reference;
+ }
+ }
+
+ return null;
+}
+
/**
* Gives ids to the selected blocks of `editor`, flashes the blocks and copies a reference link to
* them. `notePath` and `noteTitle` are of the note the editor shows.
@@ -152,6 +217,124 @@ function isInRange(range: Range, node: Node) {
&& range.compareBoundaryPoints(Range.END_TO_END, nodeRange) >= 0;
}
+function getCopyItem(count: number, copyReference: () => void): MenuItem<CommandNames> {
+ return {
+ title: t("block_reference.copy", { count }),
+ uiIcon: "bx bx-link",
+ handler: copyReference
+ };
+}
+
+function 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) {
+ return null;
+ }
+
+ return getCopyItem(command.value, () => void host.copyBlockReference?.());
+}
+
+function getPasteMenuItems(
+ editor: CKTextEditor,
+ clipboard: ClipboardAccess
+): MenuItem<CommandNames>[] {
+ const canEmbed = editor.commands.get("insertContentEmbed")?.isEnabled === true;
+ return [
+ {
+ title: t("block_reference.paste_as_link"),
+ uiIcon: "bx bx-link",
+ enabled: clipboard.enabled,
+ handler: () => void pasteBlockReference(editor, clipboard, getLinkHtml)
+ },
+ {
+ title: t("block_reference.paste_as_excerpt"),
+ uiIcon: "bx bx-window-alt",
+ enabled: clipboard.enabled && canEmbed,
+ handler: () => void pasteBlockReference(editor, clipboard, getExcerptHtml)
+ }
+ ];
+}
+
+/**
+ * Reads the clipboard and pastes the HTML that `toHtml` makes of the block reference on it, at
+ * the selection the menu was opened on. The selection is pinned before the read, which can wait
+ * on a permission prompt. `toHtml` returns `null` for a reference it cannot paste.
+ */
+async function pasteBlockReference(
+ editor: CKTextEditor,
+ clipboard: ClipboardAccess,
+ toHtml: (reference: ClipboardBlockReference) => string | Promise<string | null>
+) {
+ const target = editor.capturePasteTarget();
+ try {
+ const reference = getClipboardBlockReference(await clipboard.read());
+ if (!reference) {
+ toast.showMessage(t("block_reference.no_reference_on_clipboard"), 3000,
+ "bx bx-info-circle");
+ return;
+ }
+
+ const html = await toHtml(reference);
+ if (html) {
+ target.paste(html, reference.href);
+ }
+ } catch (error) {
+ console.warn("Failed to paste a block reference:", error);
+ } finally {
+ target.release();
+ }
+}
+
+function getLinkHtml({ href }: ClipboardBlockReference) {
+ const link = document.createElement("a");
+ link.className = "reference-link";
+ link.setAttribute("href", href);
+ link.textContent = href;
+ return link.outerHTML;
+}
+
+/** The HTML of an embed of the referenced blocks, or `null` when their note is gone. */
+async function getExcerptHtml({ noteId, block }: ClipboardBlockReference) {
+ // Imported on demand: `content_renderer` imports `content_renderer_text`, which imports this
+ // module.
+ const [ note, { getEmbedBoxSize } ] = await Promise.all([
+ froca.getNote(noteId, true),
+ import("./content_renderer.js")
+ ]);
+ if (!note) {
+ toast.showError(t("block_reference.not_found"));
+ return null;
+ }
+
+ const embed = document.createElement("figure");
+ embed.className = "include-note";
+ embed.dataset.noteId = noteId;
+ embed.dataset.block = block;
+ embed.dataset.boxSize = getEmbedBoxSize(note);
+ return embed.outerHTML;
+}
+
+/** The note and the blocks that `href` links to, or `null` for a link to anything else. */
+function parseBlockReferenceHref(href: string): ClipboardBlockReference | null {
+ let state: ReturnType<typeof parseNavigationStateFromUrl>;
+ try {
+ state = parseNavigationStateFromUrl(href);
+ } catch {
+ // A malformed percent escape.
+ return null;
+ }
+
+ const { notePath, noteId } = state;
+ const block = state.viewScope?.block;
+ if (!notePath || !noteId || !block || !parseBlockRange(block)) {
+ return null;
+ }
+
+ return { noteId, block, href: calculateHash({ notePath, viewScope: { block } }) };
+}
+
function flashBlocks(elements: Element[]) {
for (const element of elements) {
element.classList.add(FLASH_CLASS);
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 463a2cf8be..3316c5233c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4599,6 +4599,9 @@
"block_reference": {
"copy_one": "Copy reference to this block",
"copy_other": "Copy reference to these {{count}} blocks",
+ "paste_as_link": "Paste reference as a link",
+ "paste_as_excerpt": "Paste reference as an excerpt",
+ "no_reference_on_clipboard": "The clipboard does not contain a block reference.",
"broken": "Broken reference",
"not_found": "A referenced block could not be found. It might have been deleted.",
"untitled": "Block",
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 8785163e56..7aa036fcd4 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -171,6 +171,16 @@ export default function EditableText({
consumeBlockReference(root, noteContext?.viewScope);
}
+ async function copyReference() {
+ const editor = watchdogRef.current?.editor as CKTextEditor | undefined;
+ if (!editor) return;
+
+ const notePath = noteContext?.notePath ?? `root/${note.noteId}`;
+ await copyBlockReference(editor, notePath, note.title);
+ // Saved now, so that the link resolves in other notes at once.
+ spacedUpdate.updateNowIfNecessary();
+ }
+
useTriliumEvent("scrollToEnd", () => {
const editor = watchdogRef.current?.editor;
if (!editor) return;
@@ -271,16 +281,9 @@ export default function EditableText({
getEmbedBoxSize: getUploadBoxSize,
openContentEmbedMenu,
openBlockHandleMenu(event: MouseEvent, count: number) {
- const editor = watchdogRef.current?.editor as CKTextEditor | undefined;
- if (!editor) return;
-
- const notePath = noteContext?.notePath ?? `root/${note.noteId}`;
- openBlockHandleMenu(event, count, async () => {
- await copyBlockReference(editor, notePath, note.title);
- // Saved now, so that the link resolves in other notes at once.
- spacedUpdate.updateNowIfNecessary();
- });
+ openBlockHandleMenu(event, count, () => void copyReference());
},
+ copyBlockReference: copyReference,
getContentEmbedTools,
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
index dee5bfcfce..9c2b71a7a8 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
@@ -8,7 +8,8 @@
<li>Place the cursor in the block to reference. To reference several consecutive
blocks, select them.</li>
<li>Right-click the block handle, the sequence of dots to the left of the
- block (see <a class="reference-link" href="#root/_help_nRhnJkTT8cPs">Formatting toolbar</a>).</li>
+ block (see <a class="reference-link" href="#root/_help_nRhnJkTT8cPs">Formatting toolbar</a>).
+ Alternatively, right-click the text and open the <em>Copy</em> submenu.</li>
<li>Select <em>Copy reference to this block</em>, or <em>Copy reference to these blocks</em> for
a selection. The referenced blocks flash briefly.</li>
<li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li>
@@ -16,13 +17,24 @@
<p>The link shows the title of the note, followed by the beginning of the
referenced text. A link to blocks of the same note shows only the beginning
of the referenced text.</p>
+<p>The <em>Paste</em> submenu of the context menu offers two more ways to insert
+ a copied reference:</p>
+<ul>
+ <li><em>Paste reference as a link</em> inserts only the link, even when the
+ reference was copied as plain text or along with other content.</li>
+ <li><em>Paste reference as an excerpt</em> inserts an include of the referenced
+ blocks, as described below.</li>
+</ul>
+<p>In a browser, the context menu of the text editor opens only when right-clicking
+ selected text. Elsewhere the browser shows its own menu.</p>
<h2>Following a reference</h2>
<p>Clicking a block reference opens the note, scrolls to the referenced blocks
and flashes them. If a referenced block was deleted, an error message is
shown instead, along with the blocks of the range that still exist.</p>
<h2>Including the referenced blocks</h2>
<p>To show the referenced blocks inside another note, right-click the link
- in a note being edited and select <em>Convert link to note excerpt</em>.
+ in a note being edited and select <em>Convert link to note excerpt</em>,
+ or paste the copied reference with <em>Paste</em> → <em>Paste reference as an excerpt</em>.
The include shows only the referenced blocks, not the rest of the note,
and marks them with an <em>Excerpt</em> badge in its title. To see the whole
note, press the <span class="tn-icon bx bx-link-external"></span> button
@@ -36,7 +48,7 @@
<h2>Limitations</h2>
<ul>
<li>References can be copied only from a note being edited, and not in the
- mobile layout, since the block handle is not shown there.</li>
+ mobile layout.</li>
<li>An include of a range that covers only part of a list or a quote, such
as from its second item to a paragraph after it, cannot be edited in place.</li>
<li>Deleting a block breaks the references to it.</li>
diff --git a/docs/User Guide/User Guide/Note Types/Text/Block references.md b/docs/User Guide/User Guide/Note Types/Text/Block references.md
index c7e5c39202..da1c931fc8 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Block references.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Block references.md
@@ -4,19 +4,26 @@ Block references are [links](Links.md) to a block of a text note, such as a para
## Copying a reference
1. Place the cursor in the block to reference. To reference several consecutive blocks, select them.
-2. Right-click the block handle, the sequence of dots to the left of the block (see <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>).
+2. Right-click the block handle, the sequence of dots to the left of the block (see <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>). Alternatively, right-click the text and open the _Copy_ submenu.
3. Select _Copy reference to this block_, or _Copy reference to these blocks_ for a selection. The referenced blocks flash briefly.
4. Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.
The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.
+The _Paste_ submenu of the context menu offers two more ways to insert a copied reference:
+
+* _Paste reference as a link_ inserts only the link, even when the reference was copied as plain text or along with other content.
+* _Paste reference as an excerpt_ inserts an include of the referenced blocks, as described below.
+
+In a browser, the context menu of the text editor opens only when right-clicking selected text. Elsewhere the browser shows its own menu.
+
## Following a reference
Clicking a block reference opens the note, scrolls to the referenced blocks and flashes them. If a referenced block was deleted, an error message is shown instead, along with the blocks of the range that still exist.
## Including the referenced blocks
-To show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to note excerpt_. The include shows only the referenced blocks, not the rest of the note, and marks them with an _Excerpt_ badge in its title. To see the whole note, press the <span class="tn-icon bx bx-link-external"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.
+To show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to note excerpt_, or paste the copied reference with _Paste_ → _Paste reference as an excerpt_. The include shows only the referenced blocks, not the rest of the note, and marks them with an _Excerpt_ badge in its title. To see the whole note, press the <span class="tn-icon bx bx-link-external"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.
To edit the referenced blocks without leaving the note, turn on _Editable_ in the toolbar of the include, as for any <a class="reference-link" href="Include%20Note.md">Include Note</a>. The changes are saved to the referenced blocks, and the rest of the note stays as it is.
@@ -24,7 +31,7 @@ If a referenced block was deleted, the include shows _Broken reference_.
## Limitations
-* References can be copied only from a note being edited, and not in the mobile layout, since the block handle is not shown there.
+* References can be copied only from a note being edited, and not in the mobile layout.
* An include of a range that covers only part of a list or a quote, such as from its second item to a paragraph after it, cannot be edited in place.
* Deleting a block breaks the references to it.
* Block references are not kept when exporting to Markdown. On a [shared page](../../Advanced%20Usage/Sharing.md), a block reference opens the whole note.
\ No newline at end of file
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts
index 87381aed43..818573276d 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts
@@ -83,6 +83,7 @@ describe("BlockReference", () => {
"<blockQuote><paragraph>o[ne</paragraph></blockQuote>"
+ "<paragraph>two</paragraph><paragraph>thr]ee</paragraph>"
);
+ expect(editor.commands.get("assignBlockReference")?.value).toBe(3);
const reference = editor.execute("assignBlockReference");
const quote = editor.model.document.getRoot()?.getChild(0);
@@ -115,6 +116,7 @@ describe("BlockReference", () => {
"<table><tableRow><tableCell><paragraph>[a</paragraph></tableCell>"
+ "<tableCell><paragraph>b]</paragraph></tableCell></tableRow></table>"
);
+ expect(editor.commands.get("assignBlockReference")?.value).toBe(1);
const reference = editor.execute("assignBlockReference");
@@ -143,7 +145,10 @@ describe("BlockReference", () => {
editor.conversion.elementToElement({ model: "frame", view: "aside" });
setModelData(editor.model, "<frame><paragraph>[]one</paragraph></frame>");
- expect(editor.commands.get("assignBlockReference")?.isEnabled).toBe(false);
+ expect(editor.commands.get("assignBlockReference")).toMatchObject({
+ isEnabled: false,
+ value: 0
+ });
});
});
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.ts
index 0c3be6d126..363b9f045f 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.ts
@@ -1,7 +1,7 @@
import { DomEmitterMixin, Plugin } from "ckeditor5";
import BlockReferenceEditing, {
- type AssignBlockReferenceCommand, getReferenceBlocks
+ type AssignBlockReferenceCommand
} from "./block_reference_editing.js";
/**
@@ -57,13 +57,13 @@ export default class BlockReference extends Plugin {
private openMenu(event: MouseEvent) {
const editor = this.editor;
- const count = getReferenceBlocks(editor.model).length;
- if (!count || !editor.commands.get("assignBlockReference")?.isEnabled) {
+ const command = editor.commands.get("assignBlockReference");
+ if (!command?.isEnabled) {
return;
}
const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
- component?.openBlockHandleMenu?.(event, count);
+ component?.openBlockHandleMenu?.(event, command.value);
}
}
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
index 0e99d51e10..6f445f9b7c 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
@@ -88,8 +88,12 @@ export default class BlockReferenceEditing extends Plugin {
/** Gives ids to the first and the last block of the selection, and returns the reference. */
export class AssignBlockReferenceCommand extends Command {
+ /** The number of blocks that a reference made from the selection points at. */
+ declare value: number;
+
override refresh() {
- this.isEnabled = getReferenceBlocks(this.editor.model).length > 0;
+ this.value = getReferenceBlocks(this.editor.model).length;
+ this.isEnabled = this.value > 0;
}
override execute(): BlockReferenceTarget {