Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/include notes: add a context menu item for note links to be converted to an include note

Adorian Doran342c4bbfb357
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index 21547b1dc3..af9d1b5a7d 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
hasActiveContext: true,
noteContexts: [] as { ntxId: string; isReadOnly: () => Promise<boolean> }[],
getAttachmentOfNote: vi.fn(),
+ getNote: vi.fn(),
getAttachmentActionGroups: vi.fn(),
getTextEditorContaining: vi.fn(),
getEmbedBoxSize: vi.fn()
@@ -31,7 +32,7 @@ vi.mock("../services/content_renderer", () => ({ getEmbedBoxSize: mocks.getEmbed
vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));
vi.mock("../services/froca", () => ({
- default: { getAttachmentOfNote: mocks.getAttachmentOfNote }
+ default: { getAttachmentOfNote: mocks.getAttachmentOfNote, getNote: mocks.getNote }
}));
vi.mock("../services/attachment_actions", () => ({
@@ -326,7 +327,7 @@ describe("openContextMenu", () => {
]);
items.at(-1).handler();
expect(mocks.getEmbedBoxSize).toHaveBeenCalledWith(attachment);
- expect(execute).toHaveBeenCalledWith("embedAttachmentLink", {
+ expect(execute).toHaveBeenCalledWith("convertLinkToEmbed", {
domElement: link,
boxSize: "small"
});
@@ -338,6 +339,41 @@ describe("openContextMenu", () => {
expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);
});
+ it("ends with converting a note link to an embed, but not one inside an embed", async () => {
+ const execute = vi.fn();
+ const note = { noteId: "n1" };
+ mocks.getNote.mockResolvedValue(note);
+ mocks.getEmbedBoxSize.mockReturnValue("full");
+ mocks.getTextEditorContaining.mockResolvedValue({
+ commands: { get: () => ({ isEnabled: true }) },
+ execute
+ });
+ const editable = document.createElement("div");
+ editable.className = "ck-editor__editable";
+ editable.setAttribute("contenteditable", "true");
+ editable.innerHTML = `<p><a class="reference-link" href="#root/n1">Note</a></p>`
+ + `<figure class="include-note"><div class="include-note-content">`
+ + `<a class="reference-link" href="#root/n1">Note</a></div></figure>`;
+ const [ link, embeddedLink ] = editable.querySelectorAll("a");
+
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(link));
+ const { items } = mocks.show.mock.calls[0][0];
+ expect(items.slice(4)).toMatchObject([
+ { kind: "separator" },
+ { title: "link_context_menu.convert_link_to_included_note", uiIcon: "bx bx-window-alt" }
+ ]);
+ items.at(-1).handler();
+ expect(mocks.getNote).toHaveBeenCalledWith("n1");
+ expect(mocks.getEmbedBoxSize).toHaveBeenCalledWith(note);
+ expect(execute).toHaveBeenCalledWith("convertLinkToEmbed", {
+ domElement: link,
+ boxSize: "full"
+ });
+
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(embeddedLink));
+ expect(mocks.show.mock.calls[1][0].items).toHaveLength(4);
+ });
+
describe("opened on an embed in a note being edited", () => {
const CHECK = "bx bx-check";
const execute = vi.fn();
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 6362415f5f..453e2f2353 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -4,6 +4,7 @@ import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";
import appContext, { type CommandNames } from "../components/app_context.js";
import type FAttachment from "../entities/fattachment.js";
+import type FNote from "../entities/fnote.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
@@ -42,7 +43,7 @@ async function openContextMenu(
const embed = editor && getMenuEmbed(e, editor);
const ownItems = viewScope.viewMode === "attachments" && viewScope.attachmentId
? await getAttachmentItems(noteId, viewScope.attachmentId, e, editor, embed)
- : getEmbeddedNoteItems(embed);
+ : await getNoteItems(noteId, e, editor, embed);
// A later right-click opened its own menu while this one waited for the editor or the
// attachment.
if (request !== lastMenuRequest) {
@@ -184,7 +185,9 @@ async function getAttachmentItems(
.filter((group) => group.length > 0)
.flatMap((group): MenuItem<CommandNames>[] => [ { kind: "separator" }, ...group ]);
- const embedItem = await getConvertToEmbedItem(e, editor, attachment);
+ const embedItem = await getConvertToEmbedItem(
+ e, editor, t("link_context_menu.convert_link_to_embed"), async () => attachment
+ );
const conversionItems = [ embedItem, embed && getConvertToLinkItem(embed) ]
.filter((item) => !!item);
return [ ...actionItems, ...conversionItems ];
@@ -192,11 +195,20 @@ async function getAttachmentItems(
/**
* The commands of an embedded note that the menu is opened on, in a group of their own, and
- * converting it in another.
+ * converting it in another. A menu opened on a link to the note offers converting the link.
*/
-function getEmbeddedNoteItems(embed: MenuEmbed | null): MenuItem<CommandNames>[] {
+async function getNoteItems(
+ noteId: string,
+ e: LinkMenuOrigin,
+ editor: CKTextEditor | null,
+ embed: MenuEmbed | null
+): Promise<MenuItem<CommandNames>[]> {
if (!embed) {
- return [];
+ const embedItem = await getConvertToEmbedItem(
+ e, editor, t("link_context_menu.convert_link_to_included_note"),
+ () => froca.getNote(noteId)
+ );
+ return embedItem ? [ { kind: "separator" }, embedItem ] : [];
}
const linkItem = getConvertToLinkItem(embed);
@@ -270,25 +282,38 @@ function runEmbedCommand(
}
}
-/** "Convert link to an embed", for an attachment link in a text note open for editing. */
+/**
+ * The item titled `title` that converts a link to a note or an attachment into an embed, in a
+ * text note open for editing. A link in the content of an embed is not part of the note, and
+ * offers none.
+ */
async function getConvertToEmbedItem(
e: LinkMenuOrigin,
editor: CKTextEditor | null,
- attachment: FAttachment
+ title: string,
+ getLinkedEntity: () => Promise<FNote | FAttachment | null>
): Promise<MenuItem<CommandNames> | null> {
const link = getTarget(e)?.closest<HTMLElement>("a.reference-link");
- if (!link || !editor?.commands.get("embedAttachmentLink")?.isEnabled) {
+ if (!link || link.closest(".include-note")
+ || !editor?.commands.get("convertLinkToEmbed")?.isEnabled) {
return null;
}
// Imported on demand: `content_renderer` imports `link`, which imports this module.
- const { getEmbedBoxSize } = await import("../services/content_renderer.js");
+ const [ entity, { getEmbedBoxSize } ] = await Promise.all([
+ getLinkedEntity(),
+ import("../services/content_renderer.js")
+ ]);
+ if (!entity) {
+ return null;
+ }
+
return {
- title: t("link_context_menu.convert_link_to_embed"),
+ title,
uiIcon: "bx bx-window-alt",
- handler: () => editor.execute("embedAttachmentLink", {
+ handler: () => editor.execute("convertLinkToEmbed", {
domElement: link,
- boxSize: getEmbedBoxSize(attachment)
+ boxSize: getEmbedBoxSize(entity)
})
};
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fd8ebce1fe..61d35d03f6 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3060,6 +3060,7 @@
"open_note_in_new_window": "Open note in a new window",
"open_note_in_popup": "Quick edit",
"convert_link_to_embed": "Convert link to an embed",
+ "convert_link_to_included_note": "Convert link to an included note",
"convert_embed_to_link": "Convert to link",
"include_size": "Size",
"show_title": "Show title",
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
index 2bddf612ad..1d580e4104 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
@@ -7,6 +7,10 @@
look for the&nbsp;<span class="tn-icon cke cke-trilium-note"></span> button.
There is also a keyboard shortcut defined for it but it is not allocated
by default.</p>
+<p>To include a note that is already linked, right-click a reference link
+ to it in a text note being edited and select <em>Convert link to an included note</em>,
+ at the end of the menu. The include gets the box size that suits the note,
+ as one added from the button does.</p>
<p>An <a href="#root/_help_0vhv7lsOLy82">attachment</a> can be included the
same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p>
<h2>Box sizes</h2>
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 63000afe6b..ab63f485e5 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -7,6 +7,8 @@ This can be useful for e.g. including a dynamically generated chart (from script
In the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, look for the <span class="tn-icon cke cke-trilium-note"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.
+To include a note that is already linked, right-click a reference link to it in a text note being edited and select _Convert link to an included note_, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.
+
An [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) can be included the same way, from the context menu of a link to it (see _Embedding an attachment_ there).
## Box sizes
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
index 02d15572ac..975ce12605 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -25,8 +25,8 @@ import ContentEmbed, {
BOX_SIZE_COMMAND_NAME,
BOX_SIZES,
COMMAND_NAME,
- EMBED_ATTACHMENT_LINK_COMMAND,
CONVERT_EMBED_TO_LINK_COMMAND,
+ CONVERT_LINK_TO_EMBED_COMMAND,
CONTENT_EMBED_MENU,
TOGGLE_CAPTION_COMMAND_NAME,
TOGGLE_TITLE_COMMAND_NAME
@@ -719,7 +719,7 @@ describe("ContentEmbed with attachments", () => {
editor.setData(`<p>Before <a class="reference-link" href="${LINK_HREF}">x</a> after</p>`);
const link = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");
- editor.execute(EMBED_ATTACHMENT_LINK_COMMAND, { domElement: link, boxSize: "expandable" });
+ editor.execute(CONVERT_LINK_TO_EMBED_COMMAND, { domElement: link, boxSize: "expandable" });
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
"<paragraph>Before </paragraph>" +
@@ -733,23 +733,31 @@ describe("ContentEmbed with attachments", () => {
);
const relinked = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");
- editor.execute(EMBED_ATTACHMENT_LINK_COMMAND, { domElement: relinked });
+ editor.execute(CONVERT_LINK_TO_EMBED_COMMAND, { domElement: relinked });
expect(findContentEmbed(editor)?.getAttribute("boxSize")).toBe("medium");
});
- it("leaves a link to a note, and anything other than a link, alone", () => {
- editor.setData(`<p>Before <a class="reference-link" href="#root/noteAbc">x</a></p>`);
+ it("turns a link to a note into an embed of the note, and leaves anything else alone", () => {
+ editor.setData(
+ `<p>Before <a class="reference-link" href="#root/parentAbc/noteAbc">x</a> after</p>`
+ );
const before = getModelData(editor.model, { withoutSelection: true });
const domRoot = editor.editing.view.getDomRoot();
- const link = domRoot?.querySelector("a.reference-link");
const paragraph = domRoot?.querySelector("p");
const detached = document.createElement("a");
- for (const domElement of [ link, paragraph, detached ]) {
- editor.execute(EMBED_ATTACHMENT_LINK_COMMAND, { domElement });
+ for (const domElement of [ paragraph, detached ]) {
+ editor.execute(CONVERT_LINK_TO_EMBED_COMMAND, { domElement });
}
-
expect(getModelData(editor.model, { withoutSelection: true })).toBe(before);
+
+ const link = domRoot?.querySelector("a.reference-link");
+ editor.execute(CONVERT_LINK_TO_EMBED_COMMAND, { domElement: link, boxSize: "full" });
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<paragraph>Before </paragraph>" +
+ "<contentEmbed boxSize=\"full\" noteId=\"noteAbc\"></contentEmbed>" +
+ "<paragraph> after</paragraph>"
+ );
});
it("loads an embed that names nothing, as one saved mid-upload, as an empty box", () => {
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index 2f2170e516..cf59de9b5b 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -23,11 +23,11 @@ import {
} from 'ckeditor5';
import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';
import noteIcon from '../../icons/note.svg?raw';
-import { getAttachmentId } from '../referencelink.js';
+import { getAttachmentId, getNoteId } from '../referencelink.js';
export const COMMAND_NAME = 'insertContentEmbed';
export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';
-export const EMBED_ATTACHMENT_LINK_COMMAND = 'embedAttachmentLink';
+export const CONVERT_LINK_TO_EMBED_COMMAND = 'convertLinkToEmbed';
export const CONVERT_EMBED_TO_LINK_COMMAND = 'convertEmbedToLink';
export const TOGGLE_CAPTION_COMMAND_NAME = 'toggleContentEmbedCaption';
export const TOGGLE_TITLE_COMMAND_NAME = 'toggleContentEmbedTitle';
@@ -284,7 +284,7 @@ class ContentEmbedEditing extends Plugin {
const commands = editor.commands;
commands.add( COMMAND_NAME, new InsertContentEmbedCommand( editor ) );
commands.add( BOX_SIZE_COMMAND_NAME, new ContentEmbedBoxSizeCommand( editor ) );
- commands.add( EMBED_ATTACHMENT_LINK_COMMAND, new EmbedAttachmentLinkCommand( editor ) );
+ commands.add( CONVERT_LINK_TO_EMBED_COMMAND, new ConvertLinkToEmbedCommand( editor ) );
commands.add( CONVERT_EMBED_TO_LINK_COMMAND, new ConvertEmbedToLinkCommand( editor ) );
commands.add( TOGGLE_CAPTION_COMMAND_NAME, new ToggleContentEmbedCaptionCommand( editor ) );
commands.add( TOGGLE_TITLE_COMMAND_NAME, new ToggleContentEmbedTitleCommand( editor ) );
@@ -680,8 +680,8 @@ export class ToggleContentEmbedTitleCommand extends Command {
}
}
-/** Replaces an attachment link with an embed of the attachment, in the same place. */
-class EmbedAttachmentLinkCommand extends Command {
+/** Replaces a reference link with an embed of the note or attachment it points to, in its place. */
+class ConvertLinkToEmbedCommand extends Command {
/**
* @param options.domElement the link, as the editing view renders it.
* @param options.boxSize the size of the embed, `medium` when not given.
@@ -692,16 +692,18 @@ class EmbedAttachmentLinkCommand extends Command {
const reference = viewElement?.is( 'element' )
? editor.editing.mapper.toModelElement( viewElement )
: undefined;
- const attachmentId = reference?.is( 'element', 'reference' )
- ? getAttachmentId( reference.getAttribute( 'href' ) )
+ const href = reference?.is( 'element', 'reference' )
+ ? reference.getAttribute( 'href' )
: null;
- if ( !reference || !attachmentId ) {
+ const attachmentId = getAttachmentId( href );
+ const noteId = getNoteId( href );
+ if ( !reference || !noteId ) {
return;
}
editor.model.change( writer => {
const embed = writer.createElement( 'contentEmbed', {
- attachmentId,
+ ...( attachmentId ? { attachmentId } : { noteId } ),
boxSize: boxSize ?? 'medium'
} );
const range = writer.createRangeOn( reference );
diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.ts
index 573f61b9a4..fdafe1d311 100644
--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts
@@ -3,7 +3,7 @@ import { 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 } from "./referencelink.js";
+import ReferenceLink, { getAttachmentId, getNoteId } from "./referencelink.js";
describe("ReferenceLink", () => {
let editor: ClassicEditor;
@@ -263,6 +263,14 @@ describe("ReferenceLink", () => {
expect(getAttachmentId(undefined)).toBeNull();
});
+ it("reads the note a link points to, or the attachment's owner, from its note path", () => {
+ expect(getNoteId("#root/parentAbc/noteAbc")).toBe("noteAbc");
+ expect(getNoteId("#root/owner?viewMode=attachments&attachmentId=att1")).toBe("owner");
+ expect(getNoteId("#root")).toBe("root");
+ expect(getNoteId("")).toBeNull();
+ expect(getNoteId(undefined)).toBeNull();
+ });
+
it("dataDowncasts a reference back to an anchor, resolving the title synchronously", () => {
editor.setData('<p><a class="reference-link" href="#root/noteAbc">old</a></p>');
diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.ts
index df75b0d9b7..0d1f4d844a 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -239,6 +239,15 @@ export function getAttachmentId( href: unknown ) {
return query ? new URLSearchParams( query ).get( 'attachmentId' ) : null;
}
+/**
+ * The note a reference link points to, the last segment of its note path. For a link to an
+ * attachment, the note that owns it.
+ */
+export function getNoteId( href: unknown ) {
+ const notePath = typeof href === 'string' ? href.split( '?' )[ 0 ].replace( /^#/, '' ) : '';
+ return notePath.split( '/' ).at( -1 ) || null;
+}
+
declare module "ckeditor5" {
interface PluginsMap {
[ReferenceLinkEditing.pluginName]: ReferenceLinkEditing;