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
client/text editor: allow attachment links to be converted to an embedded view
Adorian Doran0d2e0f6478c0
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex 2a96555501..a6391377bb 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -15,9 +15,16 @@ const mocks = vi.hoisted(() => ({/** False when no tab is open at all, which leaves both the hoisting and the split unresolvable. */hasActiveContext: true,getAttachment: vi.fn(),- getAttachmentActionGroups: vi.fn()+ getAttachmentActionGroups: vi.fn(),+ getTextEditorContaining: vi.fn()}));+vi.mock("./text_editor_context_menu", () => ({+ getTextEditorContaining: mocks.getTextEditorContaining+}));++vi.mock("../services/options", () => ({ default: { get: () => "expandable" } }));+vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));vi.mock("../services/froca", () => ({ default: { getAttachment: mocks.getAttachment } }));@@ -245,6 +252,44 @@ describe("openContextMenu", () => {expect(download).toHaveBeenCalledOnce();});+ it("ends with converting an attachment link to an embed, only in a note being edited", async () => {+ const execute = vi.fn();+ mocks.getAttachment.mockResolvedValue({ attachmentId: "att-1" });+ mocks.getAttachmentActionGroups.mockReturnValue([+ [ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]+ ]);+ mocks.getTextEditorContaining.mockResolvedValue({+ commands: { get: () => ({ isEnabled: true }) },+ execute+ });+ const editable = document.createElement("div");+ editable.className = "ck-editor__editable";+ editable.setAttribute("contenteditable", "true");+ editable.innerHTML = `<a class="reference-link" href="#"><span>report.pdf</span></a>`;+ const link = editable.querySelector("a");++ const title = link?.querySelector("span") ?? undefined;+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(title), VIEW_SCOPE);++ const { items } = mocks.show.mock.calls[0][0];+ expect(items.slice(4)).toMatchObject([+ { kind: "separator" },+ { title: "Download" },+ { title: "link_context_menu.convert_link_to_embed" }+ ]);+ items.at(-1).handler();+ expect(execute).toHaveBeenCalledWith("embedAttachmentLink", {+ domElement: link,+ boxSize: "expandable"+ });++ editable.removeAttribute("contenteditable");+ const event = contextMenuEvent(link ?? undefined);+ await linkContextMenu.openContextMenu("root/n1", event, VIEW_SCOPE);+ expect(mocks.show.mock.calls[1][0].items).toHaveLength(6);+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);+ });+it("adds nothing for a link to a note, or to an attachment that no longer exists", async () => {await linkContextMenu.openContextMenu("root/n1", contextMenuEvent());expect(mocks.getAttachment).not.toHaveBeenCalled();diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex 3afd0a225d..65b4818adb 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -4,9 +4,11 @@ import appContext, { type CommandNames } from "../components/app_context.js";import froca from "../services/froca.js";import { t } from "../services/i18n.js";import type { ViewScope } from "../services/link.js";+import options from "../services/options.js";import utils, { isMobile } from "../services/utils.js";import { getClosestNtxId } from "../widgets/widget_utils.js";import contextMenu, { type ContextMenuEvent, type MenuItem } from "./context_menu.js";+import { getTextEditorContaining } from "./text_editor_context_menu.js";async function openContextMenu(notePath: string,@@ -14,7 +16,7 @@ async function openContextMenu(viewScope: ViewScope = {},hoistedNoteId: string | null = null) {- const attachmentItems = await getAttachmentItems(viewScope);+ const attachmentItems = await getAttachmentItems(viewScope, e);contextMenu.show({x: e.pageX,@@ -89,22 +91,25 @@ function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEv/** The actions on the attachment a link points to, each group after a separator. */async function getAttachmentItems(- { viewMode, attachmentId }: ViewScope+ { viewMode, attachmentId }: ViewScope,+ e: ContextMenuEvent): Promise<MenuItem<CommandNames>[]> {if (viewMode !== "attachments" || !attachmentId) {return [];}// Imported on demand: `attachment_actions` imports `link`, which imports this module.- const [ attachment, { getAttachmentActionGroups } ] = await Promise.all([+ const [ attachment, { getAttachmentActionGroups }, embedItem ] = await Promise.all([froca.getAttachment(attachmentId, true),- import("../services/attachment_actions.js")+ import("../services/attachment_actions.js"),+ getConvertToEmbedItem(e)]);if (!attachment) {return [];}- return getAttachmentActionGroups(attachment).flatMap((group): MenuItem<CommandNames>[] => [+ const groups = getAttachmentActionGroups(attachment);+ const actionItems = groups.flatMap((group): MenuItem<CommandNames>[] => [{ kind: "separator" },...group.map((action) => ({title: action.title,@@ -113,6 +118,33 @@ async function getAttachmentItems(handler: () => void action.run()}))]);++ return embedItem ? [ ...actionItems, embedItem ] : actionItems;+}++/** "Convert link to an embed", for an attachment link in a text note open for editing. */+async function getConvertToEmbedItem(e: ContextMenuEvent): Promise<MenuItem<CommandNames> | null> {+ const link = e.target instanceof Element+ ? e.target.closest<HTMLElement>("a.reference-link")+ : null;+ // Checked first: a note shown read-only has no editor, and asking for one waits for a timeout.+ if (!link?.closest(".ck-editor__editable[contenteditable='true']")) {+ return null;+ }++ const editor = await getTextEditorContaining(link);+ if (!editor?.commands.get("embedAttachmentLink")?.isEnabled) {+ return null;+ }++ return {+ title: t("link_context_menu.convert_link_to_embed"),+ uiIcon: "bx bx-window-alt",+ handler: () => editor.execute("embedAttachmentLink", {+ domElement: link,+ boxSize: options.get("includeNoteDefaultBoxSize")+ })+ };}function getNtxId(e: ContextMenuEvent | GeoMouseEvent) {diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex a4ccb956e6..488de135f0 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -401,6 +401,37 @@ describe("renderIncludedNotes via postProcessRichContent", () => {});});+describe("Attachment embeds", () => {+ it("renders an embedded attachment in place, and links to it one level down", async () => {+ const owner = buildNote({+ title: "Embed owner",+ content: `<section class="include-note" data-attachment-id="embedPic"> </section>`+ });+ new FAttachment(froca, {+ attachmentId: "embedPic",+ ownerId: owner.noteId,+ role: "image",+ mime: "image/png",+ title: "photo.png",+ dateModified: "",+ utcDateModified: "",+ utcDateScheduledForErasureSince: "",+ contentLength: 0+ });++ const contentEl = document.createElement("div");+ await renderText(owner, $(contentEl));+ expect(contentEl.querySelector("section.include-note img")?.getAttribute("src"))+ .toContain("api/attachments/embedPic/image/");++ const nestedEl = document.createElement("div");+ await renderText(owner, $(nestedEl), { includesAsReferenceLinks: true });+ expect(nestedEl.querySelector("section.include-note")).toBeNull();+ expect(nestedEl.querySelector("a.reference-link")?.getAttribute("href"))+ .toBe(`#root/${owner.noteId}?viewMode=attachments&attachmentId=embedPic`);+ });+});+describe("postProcessRichContent with FAttachment", () => {it("adds the attachmentId to seenNoteIds for an attachment owner", async () => {const owner = buildNote({ title: "Owner" });diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex b9108eade6..3e21b79322 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -40,7 +40,7 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere} else if (options.includesAsReferenceLinks) {// This note is itself an included note in display mode: stop after the first level by// degrading its own includes to reference links instead of expanding them.- replaceIncludesWithReferenceLinks($renderedContent[0]);+ await replaceIncludesWithReferenceLinks($renderedContent[0]);} else {await renderIncludedNotes($renderedContent[0], seenNoteIds, options.expandNestedIncludes ?? false);}@@ -93,6 +93,13 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<stri// Render and integrate the notes.for (const includeNoteEl of includeNoteEls) {+ const attachment = await getEmbeddedAttachment(includeNoteEl);+ if (attachment) {+ const { $renderedContent } = await content_renderer.getRenderedContent(attachment);+ includeNoteEl.replaceChildren(...$renderedContent);+ continue;+ }+const noteId = includeNoteEl.getAttribute("data-note-id");if (!noteId) continue;@@ -127,8 +134,19 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<stri* filled in by the reference-link post-processing pass in `postProcessRichContent` (the same pass* that resolves reference links authored in the note), which also batch-prefetches the note.*/-function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {+async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {for (const includeNoteEl of contentEl.querySelectorAll("section.include-note")) {+ const attachment = await getEmbeddedAttachment(includeNoteEl);+ if (attachment) {+ const { ownerId, attachmentId } = attachment;+ const href = `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;+ const referenceLink = document.createElement("a");+ referenceLink.className = "reference-link";+ referenceLink.setAttribute("href", href);+ includeNoteEl.replaceWith(referenceLink);+ continue;+ }+const noteId = includeNoteEl.getAttribute("data-note-id");// Validate the ID against a note-ID allow-list before interpolating it into the href: it// comes from note HTML, and the reference-link pass later reinterprets that href.@@ -141,6 +159,17 @@ function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {}}+/** The attachment an include section embeds, or `null` for an include of a note. */+async function getEmbeddedAttachment(includeNoteEl: Element) {+ const attachmentId = includeNoteEl.getAttribute("data-attachment-id");+ // The ID comes from note HTML, so it is checked before it reaches a request or an href.+ if (!attachmentId || !/^[a-zA-Z0-9_]+$/.test(attachmentId)) {+ return null;+ }++ return await froca.getAttachment(attachmentId, true);+}+/** Rewrite the code block from <pre><code> to <div> in order not to apply a codeblock style to it. */export async function rewriteMermaidDiagramsInContainer(container: HTMLDivElement) {const candidates = container.querySelectorAll("pre:has(code)");diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e89631dc82..88d97f41bd 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3052,7 +3052,8 @@"open_note_in_new_split": "Open note in a new split","open_note_in_other_split": "Open note in the other split","open_note_in_new_window": "Open note in a new window",- "open_note_in_popup": "Quick edit"+ "open_note_in_popup": "Quick edit",+ "convert_link_to_embed": "Convert link to an embed"},"electron_integration": {"desktop-application": "Desktop Application",@@ -4248,6 +4249,7 @@"changes": "Changes","click-on-the-arrow-or-press-0-to-collapse-expand": "Click on the arrow or press %0 to collapse/expand.","collapsible-block": "Collapsible block",+ "convert-to-link": "Convert to link","copy-anchor-reference-link": "Copy anchor reference link","copy-formatting": "Copy formatting","copy-image-to-clipboard": "Copy image to clipboard",diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex f8c50b23fb..fb9fe340cf 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -33,7 +33,13 @@ import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEimport getTemplates, { updateTemplateCache } from "./snippets.js";import linkEmbedService from "../../../services/link_embed";import { usesClassicToolbar } from "./toolbar";-import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";+import {+ getAttachmentHref,+ loadIncludedAttachment,+ loadIncludedNote,+ refreshIncludedNote,+ setupImageOpening+} from "./utils";/*** The editor can operate into two distinct modes:@@ -177,6 +183,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext});},loadIncludedNote,+ loadIncludedAttachment,+ getAttachmentHref,// 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.async fetchLinkMetadata(url: string) {diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex a95e16e92d..50f006481d 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -22,7 +22,12 @@ import { useNoteBlob, useNoteLabel, useSearchTermsConsumer, useSyncedRef, useTriimport { RawHtmlBlock } from "../../react/RawHtml";import { TypeWidgetProps } from "../type_widget";import { applyReferenceLinks } from "./read_only_helper";-import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";+import {+ loadIncludedAttachment,+ loadIncludedNote,+ refreshIncludedNote,+ setupImageOpening+} from "./utils";export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent, isVisible }: TypeWidgetProps) {// The componentId matters: the WS echo of a save made by the editable-text editor in the same@@ -157,9 +162,12 @@ function applyIncludedNotes(container: HTMLDivElement) {const loaded: Promise<unknown>[] = [];const includedNotes = container.querySelectorAll<HTMLElement>("section.include-note");for (const includedNote of includedNotes) {- const noteId = includedNote.dataset.noteId;- if (!noteId) continue;- loaded.push(loadIncludedNote(noteId, $(includedNote)));+ const { attachmentId, noteId } = includedNote.dataset;+ if (attachmentId) {+ loaded.push(loadIncludedAttachment(attachmentId, $(includedNote)));+ } else if (noteId) {+ loaded.push(loadIncludedNote(noteId, $(includedNote)));+ }}return Promise.all(loaded);}diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 5c4deca8be..71a1a3da8d 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -1,9 +1,10 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";vi.mock("../../../services/froca", () => ({- default: { getNote: vi.fn() }+ default: { getNote: vi.fn(), getAttachment: vi.fn() }}));vi.mock("../../../services/link", () => ({default: { createLink: vi.fn() }@@ -15,7 +16,7 @@ vi.mock("../../../services/content_renderer", () => ({import content_renderer from "../../../services/content_renderer";import froca from "../../../services/froca";import link from "../../../services/link";-import { loadIncludedNote } from "./utils";+import { getAttachmentHref, loadIncludedAttachment, loadIncludedNote } from "./utils";const note = { noteId: "noteY" } as unknown as FNote;@@ -71,3 +72,58 @@ describe("loadIncludedNote", () => {expect(content_renderer.disposeInteractiveContent).toHaveBeenCalledWith($el);});});++describe("loadIncludedAttachment", () => {+ const attachment = {+ attachmentId: "att1",+ ownerId: "owner",+ title: "report.pdf"+ } as unknown as FAttachment;++ beforeEach(() => {+ vi.mocked(froca.getAttachment).mockResolvedValue(attachment);+ vi.mocked(link.createLink).mockResolvedValue($('<span><a href="#">report.pdf</a></span>'));+ vi.mocked(content_renderer.getRenderedContent)+ .mockResolvedValue({ $renderedContent: $("<p>body</p>"), type: "pdf" } as never);+ });++ it("fills the box with the attachment, under a title linking to it", async () => {+ const $el = $('<div class="include-note-wrapper">');++ await loadIncludedAttachment("att1", $el, "expandable");++ expect(froca.getAttachment).toHaveBeenCalledWith("att1", true);+ expect(link.createLink).toHaveBeenCalledWith("owner", {+ showTooltip: false,+ showNoteIcon: true,+ viewScope: { viewMode: "attachments", attachmentId: "att1" }+ });+ expect(content_renderer.getRenderedContent)+ .toHaveBeenCalledWith(attachment, { interactive: true, mediaEnvironment: "embedded" });+ expect($el.find("button.include-note-toggle").length).toBe(1);+ expect($el.find(".include-note-content.type-pdf").text()).toBe("body");+ });++ it("leaves the box alone for a deleted attachment", async () => {+ vi.mocked(froca.getAttachment).mockResolvedValue(null);+ vi.mocked(link.createLink).mockClear();+ const $el = $('<div class="include-note-wrapper"><span>kept</span></div>');++ await loadIncludedAttachment("att1", $el, "small");++ expect(link.createLink).not.toHaveBeenCalled();+ expect($el.text()).toBe("kept");+ });+});++describe("getAttachmentHref", () => {+ it("links to the attachment in its note, or to nothing once it is deleted", async () => {+ vi.mocked(froca.getAttachment)+ .mockResolvedValueOnce({ ownerId: "owner" } as unknown as FAttachment)+ .mockResolvedValueOnce(null);++ expect(await getAttachmentHref("att1"))+ .toBe("#root/owner?viewMode=attachments&attachmentId=att1");+ expect(await getAttachmentHref("att1")).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex df0334feaf..dce997e100 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -8,6 +8,57 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,const note = await froca.getNote(noteId);if (!note) return;+ const $link = await link.createLink(note.noteId, {+ showTooltip: false,+ showNoteIcon: true+ });++ // The include widget itself is the first level of inclusion, so the included note's own+ // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).+ await fillIncludeBox($el, boxSize, $link, () => content_renderer.getRenderedContent(note, {+ interactive: true,+ includesAsReferenceLinks: true,+ mediaEnvironment: "embedded"+ }));+}++/** Fills an include box with an embedded attachment, under a title linking to it. */+export async function loadIncludedAttachment(+ attachmentId: string,+ $el: JQuery<HTMLElement>,+ boxSize?: string+) {+ const attachment = await froca.getAttachment(attachmentId, true);+ if (!attachment) return;++ const $link = await link.createLink(attachment.ownerId, {+ showTooltip: false,+ showNoteIcon: true,+ viewScope: { viewMode: "attachments", attachmentId }+ });++ await fillIncludeBox($el, boxSize, $link, () => content_renderer.getRenderedContent(+ attachment,+ { interactive: true, mediaEnvironment: "embedded" }+ ));+}++/** The href of a reference link to the attachment, or `null` once it is deleted. */+export async function getAttachmentHref(attachmentId: string) {+ const attachment = await froca.getAttachment(attachmentId, true);+ if (!attachment) return null;++ return `#root/${attachment.ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;+}++type RenderedContent = Awaited<ReturnType<typeof content_renderer.getRenderedContent>>;++async function fillIncludeBox(+ $el: JQuery<HTMLElement>,+ boxSize: string | undefined,+ $link: JQuery<HTMLElement>,+ renderContent: () => Promise<RenderedContent>+) {// The box size is supplied explicitly by the editing-view downcast; for the other// callers (read-only rendering, script API refresh) fall back to reading it from the DOM.const effectiveBoxSize = boxSize ?? $el.closest('section.include-note').attr('data-box-size');@@ -20,10 +71,6 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,// into it instead of nesting a redundant second `.include-note-wrapper`.const isWrapper = $el.hasClass('include-note-wrapper');const $wrapper = $('<div class="include-note-wrapper">');- const $link = await link.createLink(note.noteId, {- showTooltip: false,- showNoteIcon: true- });if (isExpandable) {// Create expandable structure with toggle@@ -34,9 +81,7 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,$titleRow.append($toggle, $title);$wrapper.append($titleRow);- // The include widget itself is the first level of inclusion, so the included note's own- // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });+ const { $renderedContent, type } = await renderContent();const $content = $(`<div class="include-note-content type-${type}" style="display: none;">`).append($renderedContent);$wrapper.append($content);@@ -52,9 +97,7 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,// Standard display$wrapper.append($('<h4 class="include-note-title">').append($link));- // The include widget itself is the first level of inclusion, so the included note's own- // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });+ const { $renderedContent, type } = await renderContent();$wrapper.append($(`<div class="include-note-content type-${type}">`).append($renderedContent));}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.htmlindex 540ec05ad0..b84a56decf 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html@@ -60,6 +60,23 @@they show, and deleting it removes them from the text notes open for editingat that moment. Converting it into a note turns its links into links tothe new note.</p>+<h2>Embedding an attachment</h2>+<p>An attachment can be shown in the text instead of linked, the way <a+ class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a> shows+ a note: a picture is displayed, and a PDF, a video or a document is previewed.</p>+<ul>+ <li>To embed an attachment, right-click a link to it in a text note being+ edited and select <em>Convert link to an embed</em>, at the end of the menu.+ The embed takes the default box size of included notes.</li>+ <li>To change its size, select the embed and use the box size menu in its+ toolbar.</li>+ <li>To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> <em>Convert to link</em> button+ in its toolbar.</li>+</ul>+<p>An embed follows its attachment like a link does. Converting the attachment+ into a note turns the embed into an included note. In a <a href="#root/_help_R9pX4DGra2Vt">shared note</a>,+ an embedded picture is displayed, and any other attachment appears as a+ link to download it.</p><h2>Converting notes to attachments</h2><p><a class="reference-link" href="#root/_help_W8vYD3Q1zjCR">File</a> notescan be easily converted to attachments of the parent note.</p>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.htmlindex 97923706b3..932e49899a 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,8 @@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 allocatedby default.</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>Included notes in the share functionality</h2><p>If a <a href="#root/_help_R9pX4DGra2Vt">shared note</a> contains one ormore included notes, they will be displayed in the content of the notediff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex c42c44b83f..14963533e7 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -246,6 +246,45 @@ describe("checkImageAttachments", () => {expect(att.save).not.toHaveBeenCalled();});++ it("keeps an attachment alive that only an embed shows", () => {+ const pdf = { title: "report.pdf", role: "file", mime: "application/pdf" };+ const note = buildNote({ title: "Test", attachments: [ pdf ] });+ mockAttachmentSaves(note);+ const [att] = note.getAttachments();++ checkImageAttachments(note, embedOf(att.attachmentId ?? ""));++ expect(att.save).not.toHaveBeenCalled();+ });++ it("points an embed of a foreign attachment at the note's own copy", () => {+ const report = { title: "report.pdf", role: "file", mime: "application/pdf" };+ const source = buildNote({+ title: "Source",+ attachments: [{ id: "foreignAtt2", ...report }]+ });+ const [ foreign ] = source.getAttachments();+ foreign.blobId = "sharedPdfBlob";++ const target = buildNote({+ title: "Target",+ attachments: [{ id: "localAtt2", ...report }]+ });+ mockAttachmentSaves(target);+ const [ local ] = target.getAttachments();+ local.blobId = "sharedPdfBlob";++ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);++ try {+ const { content } = checkImageAttachments(target, embedOf("foreignAtt2"));++ expect(content).toBe(embedOf("localAtt2"));+ } finally {+ getAttachments.mockRestore();+ }+ });});describe("Markdown content", () => {@@ -1059,3 +1098,8 @@ describe("findLlmChatLinks", () => {expect(links).toEqual([]);});});++/** An embed of the attachment, as the text editor saves one. */+function embedOf(attachmentId: string) {+ return `<section class="include-note" data-attachment-id="${attachmentId}">` + "</section>";+}diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.mdindex 35e3e63a95..d62f15a508 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md@@ -35,6 +35,16 @@ Right-clicking a link to an attachment shows the ways to open it, followed by acLinks follow changes to their attachment: renaming it updates the title they show, and deleting it removes them from the text notes open for editing at that moment. Converting it into a note turns its links into links to the new note.+## Embedding an attachment++An attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, and a PDF, a video or a document is previewed.++* To embed an attachment, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu. The embed takes the default box size of included notes.+* To change its size, select the embed and use the box size menu in its toolbar.+* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar.++An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed, and any other attachment appears as a link to download it.+## Converting notes to attachments<a class="reference-link" href="../../Note%20Types/File.md">File</a> notes can be easily converted to attachments of the parent note.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.mdindex be46baf5df..29a6d15f62 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 scriptIn 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.+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).+## Included notes in the share functionalityIf a [shared note](../../Advanced%20Usage/Sharing.md) contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 4ea2c1f5da..84c0265544 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -44,6 +44,13 @@ declare global {loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;+ loadIncludedAttachment(+ attachmentId: string,+ $el: JQuery<HTMLElement>,+ boxSize?: string+ ): void;+ /** The href of a reference link to the attachment, or `null` once it is deleted. */+ getAttachmentHref(attachmentId: string): Promise<string | null>;/*** Reads a page's preview metadata through the host. Never rejects: any failure — network* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` withdiff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.tsindex 601775269f..84315114ce 100644--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.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 IncludeNote from "./includenote.js";+import IncludeNote, { CONVERT_EMBED_TO_LINK_COMMAND } from "./includenote.js";import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";import IncludeNoteToolbar from "./include_note_toolbar.js";import LinkEmbed from "./link_embed/link_embed.js";@@ -93,6 +93,15 @@ describe("IncludeNoteToolbar", () => {expect(requires).toContain(IncludeNoteBoxSizeDropdown);});+ it("offers, next to the box size, the way from an attachment embed back to a link", () => {+ const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {+ _toolbarDefinitions: Map<string, { itemsConfig: string[] }>;+ };++ expect(repository._toolbarDefinitions.get("includeNote")?.itemsConfig)+ .toEqual([ "includeNoteBoxSizeDropdown", CONVERT_EMBED_TO_LINK_COMMAND ]);+ });+it("registers the includeNote toolbar in WidgetToolbarRepository", () => {const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {_toolbarDefinitions: Map<string, unknown>;diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.tsindex 7b330a7827..ccb00bce4d 100644--- a/packages/ckeditor5/src/plugins/include_note_toolbar.ts+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.ts@@ -1,5 +1,5 @@import { Plugin, WidgetToolbarRepository, isWidget, type ViewElement } from "ckeditor5";-import IncludeNote from "./includenote.js";+import IncludeNote, { CONVERT_EMBED_TO_LINK_COMMAND } from "./includenote.js";import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";export default class IncludeNoteToolbar extends Plugin {@@ -14,7 +14,8 @@ export default class IncludeNoteToolbar extends Plugin {widgetToolbarRepository.register("includeNote", {items: [- "includeNoteBoxSizeDropdown"+ "includeNoteBoxSizeDropdown",+ CONVERT_EMBED_TO_LINK_COMMAND],balloonClassName: "ck-toolbar-container include-note-toolbar",getRelatedElement(selection) {diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.tsindex 7d1adf9d1f..2c0f892bd2 100644--- a/packages/ckeditor5/src/plugins/includenote.spec.ts+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts@@ -1,9 +1,13 @@import {+ _getModelData as getModelData,_getViewData as getViewData,_setModelData as setModelData,+ ButtonView,ClassicEditor,Essentials,+ LinkEditing,Paragraph,+ Undo,Widget,type ModelElement} from "ckeditor5";@@ -11,7 +15,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";import { installGlobMock } from "../../test/globals-test-kit.js";-import IncludeNote, { BOX_SIZE_COMMAND_NAME, BOX_SIZES, COMMAND_NAME } from "./includenote.js";+import IncludeNote, {+ BOX_SIZE_COMMAND_NAME,+ BOX_SIZES,+ COMMAND_NAME,+ EMBED_ATTACHMENT_LINK_COMMAND,+ CONVERT_EMBED_TO_LINK_COMMAND+} from "./includenote.js";+import ReferenceLink from "./referencelink.js";describe("IncludeNote", () => {let editor: ClassicEditor;@@ -485,6 +496,150 @@ describe("IncludeNote", () => {});});+describe("IncludeNote with attachments", () => {+ const LINK_HREF = "#root/owner?viewMode=attachments&attachmentId=att1";+ const embedHtml = (attachmentId = "att1") =>+ `<section class="include-note" data-attachment-id="${attachmentId}" data-box-size="small">`+ + "</section>";+ let editor: ClassicEditor;+ let loadIncludedNote: ReturnType<typeof vi.fn>;+ let loadIncludedAttachment: ReturnType<typeof vi.fn>;+ let getAttachmentHref: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ loadIncludedNote = vi.fn();+ loadIncludedAttachment = vi.fn();+ getAttachmentHref = vi.fn(async () => LINK_HREF);+ installGlobMock({+ getComponentByEl: () => ({+ loadIncludedNote,+ loadIncludedAttachment,+ getAttachmentHref,+ loadReferenceLinkTitle: vi.fn(async () => undefined)+ }),+ getReferenceLinkTitleSync: () => "report.pdf"+ });++ editor = await createTestEditor([+ Essentials, Paragraph, Undo, Widget, LinkEditing, ReferenceLink, IncludeNote+ ]);+ });++ /** Querying the DOM root forces the UIElement render callbacks to run. */+ function renderEmbeds() {+ return editor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper");+ }++ function selectEmbed() {+ editor.model.change((writer) => {+ const element = findIncludeNote(editor);+ if (element) {+ writer.setSelection(element, "on");+ }+ });+ }++ it("stores, saves and renders an embed by its attachment", () => {+ editor.setData(embedHtml());++ const element = findIncludeNote(editor);+ expect(element?.getAttribute("attachmentId")).toBe("att1");+ expect(element?.hasAttribute("noteId")).toBe(false);+ expect(editor.getData()).toContain('data-attachment-id="att1"');+ expect(editor.getData()).not.toContain("data-note-id");++ expect(renderEmbeds()).toHaveLength(1);+ expect(loadIncludedNote).not.toHaveBeenCalled();+ expect(loadIncludedAttachment).toHaveBeenCalledTimes(1);+ expect(loadIncludedAttachment.mock.calls[0]?.[0]).toBe("att1");+ expect(loadIncludedAttachment.mock.calls[0]?.[2]).toBe("small");++ selectEmbed();+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "full" });+ expect(loadIncludedAttachment.mock.calls.at(-1)?.[2]).toBe("full");+ });++ it("turns an attachment link into an embed in its place, as one undo step", () => {+ 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" });++ expect(getModelData(editor.model, { withoutSelection: true })).toBe(+ "<paragraph>Before </paragraph>" ++ "<includeNote attachmentId=\"att1\" boxSize=\"expandable\"></includeNote>" ++ "<paragraph> after</paragraph>"+ );++ editor.execute("undo");+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(+ `<paragraph>Before <reference href="${LINK_HREF}"></reference> after</paragraph>`+ );+ });++ it("leaves a link to a note alone", () => {+ editor.setData(`<p>Before <a class="reference-link" href="#root/noteAbc">x</a></p>`);+ const before = getModelData(editor.model, { withoutSelection: true });+ const link = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");++ editor.execute(EMBED_ATTACHMENT_LINK_COMMAND, { domElement: link });++ expect(getModelData(editor.model, { withoutSelection: true })).toBe(before);+ });++ it("turns an attachment embed back into a link, and offers it only for one", async () => {+ const command = editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND);+ const button = editor.ui.componentFactory.create(CONVERT_EMBED_TO_LINK_COMMAND);+ if (!(button instanceof ButtonView)) {+ throw new Error("Expected a button.");+ }+ expect(button.label).toBe("Convert to link");++ insertIncludeNote(editor, "noteX", "small");+ expect(command?.isEnabled).toBe(false);+ expect(button.isVisible).toBe(false);++ editor.setData(embedHtml());+ selectEmbed();+ expect(command?.isEnabled).toBe(true);+ expect(button.isVisible).toBe(true);++ await editor.execute(CONVERT_EMBED_TO_LINK_COMMAND);++ expect(getAttachmentHref).toHaveBeenCalledWith("att1");+ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe(`<paragraph><reference href="${LINK_HREF}"></reference></paragraph>`);+ });++ it("keeps an embed whose attachment has no link to go back to", async () => {+ getAttachmentHref.mockResolvedValue(null);+ editor.setData(embedHtml());+ selectEmbed();++ await editor.execute(CONVERT_EMBED_TO_LINK_COMMAND);++ expect(findIncludeNote(editor)?.getAttribute("attachmentId")).toBe("att1");+ });++ it("redraws the embeds of a changed attachment and removes those of a deleted one", () => {+ editor.setData(embedHtml("att1") + embedHtml("att2"));+ renderEmbeds();+ loadIncludedAttachment.mockClear();++ editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks([+ { attachmentId: "att1", isDeleted: false },+ { attachmentId: "att2", isDeleted: true }+ ]);+ renderEmbeds();++ const redrawn = loadIncludedAttachment.mock.calls.map(([ attachmentId ]) => attachmentId);+ expect(redrawn).toContain("att1");+ expect(redrawn).not.toContain("att2");+ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe("<includeNote attachmentId=\"att1\" boxSize=\"small\"></includeNote>");+ });+});+function findIncludeNote(editor: ClassicEditor): ModelElement | undefined {const root = editor.model.document.getRoot();if (!root) {diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.tsindex 845be08394..90b741f49e 100644--- a/packages/ckeditor5/src/plugins/includenote.ts+++ b/packages/ckeditor5/src/plugins/includenote.ts@@ -1,8 +1,22 @@-import { ButtonView, Command, type Editor, type ModelElement, Plugin, toWidget, type ViewElement, Widget, type Observable } from 'ckeditor5';+import {+ ButtonView,+ Command,+ type Editor,+ IconLink,+ type ModelElement,+ Plugin,+ toWidget,+ type ViewElement,+ Widget,+ type Observable+} from 'ckeditor5';import noteIcon from '../icons/note.svg?raw';+import { getAttachmentId } from './referencelink.js';export const COMMAND_NAME = 'insertIncludeNote';export const BOX_SIZE_COMMAND_NAME = 'includeNoteBoxSize';+export const EMBED_ATTACHMENT_LINK_COMMAND = 'embedAttachmentLink';+export const CONVERT_EMBED_TO_LINK_COMMAND = 'convertEmbedToLink';export const BOX_SIZES = [ 'small', 'medium', 'full', 'expandable' ] as const;@@ -71,6 +85,29 @@ class IncludeNoteUI extends Plugin {return buttonView;} );++ editor.ui.componentFactory.add( CONVERT_EMBED_TO_LINK_COMMAND, locale => {+ const command = editor.commands.get( CONVERT_EMBED_TO_LINK_COMMAND );+ const buttonView = new ButtonView( locale );++ buttonView.set( {+ label: t( 'Convert to link' ),+ icon: IconLink,+ tooltip: true+ } );++ // Shown only on an attachment embed, the one include the command applies to.+ if ( command ) {+ buttonView.bind( 'isEnabled' ).to( command );+ buttonView.bind( 'isVisible' ).to( command, 'isEnabled' );+ }++ this.listenTo( buttonView, 'execute', () => {+ editor.execute( CONVERT_EMBED_TO_LINK_COMMAND );+ } );++ return buttonView;+ } );}}@@ -83,8 +120,12 @@ class IncludeNoteEditing extends Plugin {this._defineSchema();this._defineConverters();- this.editor.commands.add( COMMAND_NAME, new InsertIncludeNoteCommand( this.editor ) );- this.editor.commands.add( BOX_SIZE_COMMAND_NAME, new IncludeNoteBoxSizeCommand( this.editor ) );+ const editor = this.editor;+ const commands = editor.commands;+ commands.add( COMMAND_NAME, new InsertIncludeNoteCommand( editor ) );+ commands.add( BOX_SIZE_COMMAND_NAME, new IncludeNoteBoxSizeCommand( editor ) );+ commands.add( EMBED_ATTACHMENT_LINK_COMMAND, new EmbedAttachmentLinkCommand( editor ) );+ commands.add( CONVERT_EMBED_TO_LINK_COMMAND, new ConvertEmbedToLinkCommand( editor ) );}_defineSchema() {@@ -94,7 +135,8 @@ class IncludeNoteEditing extends Plugin {// Behaves like a self-contained object (e.g. an image).isObject: true,- allowAttributes: [ 'noteId', 'boxSize' ],+ // An include shows either a note or, as an embed, an attachment.+ allowAttributes: [ 'noteId', 'attachmentId', 'boxSize' ],// Allow in places where other blocks are allowed (e.g. directly in the root).allowWhere: '$block'@@ -108,9 +150,13 @@ class IncludeNoteEditing extends Plugin {// <includeNote> convertersconversion.for( 'upcast' ).elementToElement( {model: ( viewElement, { writer: modelWriter } ) => {+ const attachmentId = viewElement.getAttribute( 'data-attachment-id' );+ const included = attachmentId+ ? { attachmentId }+ : { noteId: viewElement.getAttribute( 'data-note-id' ) };return modelWriter.createElement( 'includeNote', {- noteId: viewElement.getAttribute( 'data-note-id' ),+ ...included,boxSize: viewElement.getAttribute( 'data-box-size' ),} );},@@ -125,7 +171,7 @@ class IncludeNoteEditing extends Plugin {// it would make sense here to downcast to <iframe>, with this even HTML export can support note inclusionreturn viewWriter.createContainerElement( 'section', {class: 'include-note',- 'data-note-id': modelElement.getAttribute( 'noteId' ),+ ...getIncludedEntityAttributes( modelElement ),'data-box-size': modelElement.getAttribute( 'boxSize' ),} );}@@ -134,12 +180,11 @@ class IncludeNoteEditing extends Plugin {model: 'includeNote',view: ( modelElement, { writer: viewWriter } ) => {- const noteId = modelElement.getAttribute( 'noteId' ) as string;const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;const section = viewWriter.createContainerElement( 'section', {class: 'include-note box-size-' + boxSize,- 'data-note-id': noteId,+ ...getIncludedEntityAttributes( modelElement ),'data-box-size': boxSize} );@@ -149,10 +194,7 @@ class IncludeNoteEditing extends Plugin {}, function( domDocument ) {const domElement = this.toDomElement( domDocument );- const editorEl = editor.editing.view.getDomRoot();- const component = glob.getComponentByEl<EditorComponent>( editorEl );-- component.loadIncludedNote( noteId, $( domElement ), boxSize );+ loadIncludedContent( editor, modelElement, $( domElement ), boxSize );preventCKEditorHandling( domElement, editor );@@ -224,7 +266,7 @@ class IncludeNoteBoxSizeCommand extends Command {override execute( options: { value: BoxSizeValue } ) {const model = this.editor.model;- const includeNoteElement = this._getSelectedIncludeNote();+ const includeNoteElement = getSelectedIncludeNote( this.editor );if ( includeNoteElement ) {model.change( writer => {@@ -234,23 +276,118 @@ class IncludeNoteBoxSizeCommand extends Command {}override refresh() {- const includeNoteElement = this._getSelectedIncludeNote();+ const includeNoteElement = getSelectedIncludeNote( this.editor );this.isEnabled = !!includeNoteElement;this.value = includeNoteElement?.getAttribute( 'boxSize' ) as BoxSizeValue | null ?? null;}+}++/** Replaces an attachment link with an embed of the attachment, in the same place. */+class EmbedAttachmentLinkCommand 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.+ */+ override execute( { domElement, boxSize }: { domElement: HTMLElement; boxSize?: string } ) {+ const editor = this.editor;+ const viewElement = editor.editing.view.domConverter.mapDomToView( domElement );+ const reference = viewElement?.is( 'element' )+ ? editor.editing.mapper.toModelElement( viewElement )+ : undefined;+ const attachmentId = reference?.is( 'element', 'reference' )+ ? getAttachmentId( reference.getAttribute( 'href' ) )+ : null;+ if ( !reference || !attachmentId ) {+ return;+ }++ editor.model.change( writer => {+ const embed = writer.createElement( 'includeNote', {+ attachmentId,+ boxSize: boxSize ?? 'medium'+ } );+ const range = writer.createRangeOn( reference );+ editor.model.insertObject( embed, range, null, { setSelection: 'on' } );+ } );+ }+}++/** Replaces the selected attachment embed with a link to the attachment. */+class ConvertEmbedToLinkCommand extends Command {+ override refresh() {+ const embed = getSelectedIncludeNote( this.editor );+ const canHoldLink = this.editor.model.schema.isRegistered( 'reference' );++ this.isEnabled = !!embed?.hasAttribute( 'attachmentId' ) && canHoldLink;+ }- private _getSelectedIncludeNote() {- const selection = this.editor.model.document.selection;- const selectedElement = selection.getSelectedElement();+ override async execute() {+ const editor = this.editor;+ const embed = getSelectedIncludeNote( editor );+ const attachmentId = embed?.getAttribute( 'attachmentId' ) as string | undefined;+ if ( !embed || !attachmentId ) {+ return;+ }- if ( selectedElement?.name === 'includeNote' ) {- return selectedElement;+ const editorEl = editor.editing.view.getDomRoot();+ const component = glob.getComponentByEl<EditorComponent>( editorEl );+ const href = await component.getAttachmentHref( attachmentId );++ // The embed can be removed while the host looks the link up.+ const root = embed.root;+ if ( !href || !root.is( 'rootElement' ) || root.rootName === '$graveyard' ) {+ return;}- // Check if we're inside an include note- const firstPosition = selection.getFirstPosition();- return firstPosition?.findAncestor( 'includeNote' ) ?? null;+ editor.model.change( writer => {+ const reference = writer.createElement( 'reference', { href } );+ const paragraph = writer.createElement( 'paragraph' );+ writer.append( reference, paragraph );+ writer.insert( paragraph, writer.createPositionBefore( embed ) );+ writer.remove( embed );+ writer.setSelection( reference, 'after' );+ } );+ }+}++/** The include the selection is on or inside, or `null`. */+function getSelectedIncludeNote( editor: Editor ) {+ const selection = editor.model.document.selection;+ const selectedElement = selection.getSelectedElement();++ if ( selectedElement?.name === 'includeNote' ) {+ return selectedElement;+ }++ return selection.getFirstPosition()?.findAncestor( 'includeNote' ) ?? null;+}++/** The `data-*` attribute naming what an include shows: an attachment, or a note. */+function getIncludedEntityAttributes( element: ModelElement ): Record<string, string> {+ const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;++ return attachmentId+ ? { 'data-attachment-id': attachmentId }+ : { 'data-note-id': element.getAttribute( 'noteId' ) as string };+}++/** Has the host render what an include shows into its wrapper. */+function loadIncludedContent(+ editor: Editor,+ element: ModelElement,+ $wrapper: JQuery<HTMLElement>,+ boxSize: string | undefined+) {+ const editorEl = editor.editing.view.getDomRoot();+ const component = glob.getComponentByEl<EditorComponent>( editorEl );+ const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;+ const noteId = element.getAttribute( 'noteId' ) as string | undefined;++ if ( attachmentId ) {+ component.loadIncludedAttachment( attachmentId, $wrapper, boxSize );+ } else if ( noteId ) {+ component.loadIncludedNote( noteId, $wrapper, boxSize );}}@@ -268,11 +405,9 @@ class IncludeNoteBoxSizeCommand extends Command {function reloadIncludedNote( editor: Editor, viewElement: ViewElement, modelElement: ModelElement, boxSize: string ) {const sectionDom = editor.editing.view.domConverter.mapViewToDom( viewElement );const wrapperDom = sectionDom?.querySelector<HTMLElement>( '.include-note-wrapper' );- const noteId = modelElement.getAttribute( 'noteId' ) as string | undefined;- if ( wrapperDom && noteId ) {- const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );- component.loadIncludedNote( noteId, $( wrapperDom ), boxSize );+ if ( wrapperDom ) {+ loadIncludedContent( editor, modelElement, $( wrapperDom ), boxSize );}}diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.tsindex 4974bdf4fd..4e5b7ba3a2 100644--- a/packages/ckeditor5/src/plugins/referencelink.ts+++ b/packages/ckeditor5/src/plugins/referencelink.ts@@ -76,8 +76,8 @@ export class ReferenceLinkEditing extends Plugin {}/**- * Redraws the links to changed attachments, so they show the current title, and removes the- * links to deleted ones.+ * Redraws the links and embeds of changed attachments, so they show the current state, and+ * removes those of deleted ones.*/updateAttachmentLinks( changes: AttachmentLinkChange[] ) {const editor = this.editor;@@ -89,12 +89,18 @@ export class ReferenceLinkEditing extends Plugin {for ( const root of editor.model.document.getRoots() ) {for ( const { item } of editor.model.createRangeIn( root ) ) {- if ( !item.is( 'element', 'reference' ) ) {+ let attachmentId: unknown;+ if ( item.is( 'element', 'reference' ) ) {+ attachmentId = getAttachmentId( item.getAttribute( 'href' ) );+ } else if ( item.is( 'element', 'includeNote' ) ) {+ attachmentId = item.getAttribute( 'attachmentId' );+ } else {continue;}- const attachmentId = getAttachmentId( item.getAttribute( 'href' ) );- const isDeleted = attachmentId ? isDeletedById.get( attachmentId ) : undefined;+ const isDeleted = typeof attachmentId === 'string'+ ? isDeletedById.get( attachmentId )+ : undefined;if ( isDeleted !== undefined ) {( isDeleted ? deletedLinks : changedLinks ).push( item );}@@ -228,7 +234,7 @@ export class ReferenceLinkEditing extends Plugin {}/** The attachment a reference link points to, or `null` for a link to a note. */-function getAttachmentId( href: unknown ) {+export function getAttachmentId( href: unknown ) {const query = typeof href === 'string' ? href.split( '?' )[ 1 ] : undefined;return query ? new URLSearchParams( query ).get( 'attachmentId' ) : null;}diff --git a/packages/trilium-core/src/becca/entities/battachment.spec.ts b/packages/trilium-core/src/becca/entities/battachment.spec.tsindex c733eabdeb..8340372cbd 100644--- a/packages/trilium-core/src/becca/entities/battachment.spec.ts+++ b/packages/trilium-core/src/becca/entities/battachment.spec.ts@@ -321,6 +321,27 @@ describe("BAttachment (real DB)", () => {expect(unwrapStringOrBuffer(note.getContent())).toBe(parentContent);});+ it("turns an embed of the attachment into an include of the new note", () => {+ const note = createNote({ content: "<p>placeholder</p>" });+ const att = getContext().init(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "embedconv-" + counter,+ content: "file body"+ })+ );+ const section = (attribute: string) =>+ `<section class="include-note" ${attribute}></section>`;+ const embed = section(`data-attachment-id="${att.attachmentId}"`);+ getContext().init(() => note.setContent(embed));++ const { note: created } = getContext().init(() => att.convertToNote());++ expect(unwrapStringOrBuffer(note.getContent()))+ .toBe(section(`data-note-id="${created.noteId}"`));+ });+it("converts an 'image' attachment and rewrites the embedded attachment URL in the parent", () => {const note = createNote({ content: "<p>placeholder</p>" });const att = getContext().init(() =>diff --git a/packages/trilium-core/src/becca/entities/battachment.ts b/packages/trilium-core/src/becca/entities/battachment.tsindex 0ac7edd8b5..a1a6fc9769 100644--- a/packages/trilium-core/src/becca/entities/battachment.ts+++ b/packages/trilium-core/src/becca/entities/battachment.ts@@ -209,6 +209,13 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {new RegExp(`href="[^"]*attachmentId=${escapeRegExp(attachmentId)}[^"]*"`, "g"),`href="#root/${note.noteId}"`);++ // An embed of the attachment becomes an include of the new note.+ fixedContent = replaceAll(+ fixedContent,+ `data-attachment-id="${attachmentId}"`,+ `data-note-id="${note.noteId}"`+ );}if (fixedContent !== origContent) {diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex 4ed3319839..0820adb7a8 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -225,6 +225,43 @@ describe("processNoteContent", () => {expect(content).not.toContain("mapPicture1");});+ it("points an imported embed at its attachment as it was recreated", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "embedNote1",+ title: "Report",+ type: "text",+ mime: "text/html",+ dataFileName: "Report.html",+ attachments: [{+ attachmentId: "embeddedPdf1",+ title: "report.pdf",+ role: "file",+ mime: "application/pdf",+ position: 10,+ dataFileName: "Report_report.pdf"+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Report.html": `<section class="include-note" data-attachment-id="embeddedPdf1">`+ + "</section>",+ "Report_report.pdf": Buffer.from("%PDF-1.4")+ });++ const { importedNote } = await testImportBuffer(zipBuffer);+ const [ pdf ] = importedNote.getAttachments();+ const content = importedNote.getContent() as string;++ expect(pdf.attachmentId).not.toBe("embeddedPdf1");+ expect(content).toContain(`data-attachment-id="${pdf.attachmentId}"`);+ expect(content).not.toContain("embeddedPdf1");+ });+it("restores an embedded mermaid diagram as a note reference, not as a raw attachment", async () => {// The export points the <img> at the mermaid note's generated `mermaid-export.svg`.// On the way back in that has to resolve to `api/images/<noteId>` — which re-renders thediff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 472091c253..9955e1920f 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -467,6 +467,11 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou});+ content = content.replace(+ /data-attachment-id="([a-zA-Z0-9_]+)"/g,+ (_match, id: string) => `data-attachment-id="${getNewAttachmentId(id)}"`+ );+if (noteMeta) {const includeNoteLinks = (noteMeta.attributes || []).filter((attr) => attr.type === "relation" && attr.name === "includeNoteLink");diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex b654869b1d..67ffd8b553 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -529,7 +529,9 @@ export function checkImageAttachments(note: BNote, content: string) {// data-favicon="api/attachments/{id}/image/...">{ pattern: /data-(?:image|favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g, previewPicture: true },// <a href="...attachmentId={id}">- { pattern: /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g }+ { pattern: /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g },+ // <section class="include-note" data-attachment-id="{id}">+ { pattern: /data-attachment-id="([a-zA-Z0-9_]+)"/g }];for (const { pattern, previewPicture } of patterns) {@@ -642,6 +644,12 @@ export function checkImageAttachments(note: BNote, content: string) {new RegExp(`href="[^"]+attachmentId=${unknownAttachment.attachmentId}[^"]*"`, "g"),`href="#root/${localAttachment.ownerId}?viewMode=attachments&attachmentId=${localAttachment.attachmentId}"`);+ // replace embeds+ content = replaceAll(+ content,+ `data-attachment-id="${unknownAttachment.attachmentId}"`,+ `data-attachment-id="${localAttachment.attachmentId}"`+ );}return {diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 3b078773ac..c14da41e34 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -328,6 +328,27 @@ describe("content_renderer", () => {expect(code?.innerHTML).not.toContain("hljs-tag");});+ it("renders an embedded picture as an image, any other attachment as a download", () => {+ const embed = (id: string) =>+ `<section class="include-note" data-attachment-id="${id}"> </section>`;+ const note = buildShareNote({+ content: embed("embedPic1") + embed("embedPdf1") + embed("embedGone"),+ attachments: [+ { id: "embedPic1", role: "image", mime: "image/png", title: "my photo.png" },+ { id: "embedPdf1", role: "file", mime: "application/pdf", title: "report.pdf" }+ ]+ });++ const content = getContent(note).content as string;++ const src = "api/attachments/embedPic1/image/my%20photo.png";+ expect(content).toContain(`<img src="${src}" alt="my photo.png">`);+ expect(content).toContain(`href="api/attachments/embedPdf1/download"`);+ expect(content).toContain("report.pdf");+ expect(content).not.toContain("include-note");+ expect(content).not.toContain("embedGone");+ });+describe("Reference links", () => {it("handles attachment link", () => {const content = trimIndentation`\diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex f2ebb3ee29..b441743ebb 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1,6 +1,6 @@import {- extractYouTubeVideoId, isHttpUrl, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT,- normalizeMimeTypeForCKEditor, safeLinkPreviewHref, safeLinkPreviewImageSrc+ extractYouTubeVideoId, isHttpUrl, isImageAttachmentRole, MIME_TYPE_AUTO, type MimeType,+ MIME_TYPES_DICT, normalizeMimeTypeForCKEditor, safeLinkPreviewHref, safeLinkPreviewImageSrc} from "@triliumnext/commons";import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";@@ -482,9 +482,25 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt// (expandNestedIncludes) keeps expanding recursively. seenNoteIds tracks the current ancestor// path (cloned per descent below) so the recursive path can break cycles without treating a note// included in two sibling sub-trees as circular.+ const getNote: GetNoteFunction = note instanceof BNote+ ? (noteId: string) => becca.getNote(noteId)+ : (noteId: string) => shaca.getNote(noteId);+ const getAttachment = note instanceof BNote+ ? (attachmentId: string) => becca.getAttachment(attachmentId)+ : (attachmentId: string) => shaca.getAttachment(attachmentId);+const seenNoteIds = new Set(options.seenNoteIds);seenNoteIds.add(note.noteId);for (const includeNoteEl of document.querySelectorAll("section.include-note")) {+ const attachmentId = includeNoteEl.getAttribute("data-attachment-id");+ if (attachmentId) {+ const attachment = getAttachment(attachmentId);+ const asLink = !!options.includesAsReferenceLinks;+ const html = attachment ? renderAttachmentEmbed(attachmentId, attachment, asLink) : "";+ includeNoteEl.replaceWith(...parse(html, parseOpts).childNodes);+ continue;+ }+const noteId = includeNoteEl.getAttribute("data-note-id");if (!noteId) continue;@@ -519,13 +535,6 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptresult.isEmpty = document.textContent?.trim().length === 0 && document.querySelectorAll("img").length === 0;- const getNote: GetNoteFunction = note instanceof BNote- ? (noteId: string) => becca.getNote(noteId)- : (noteId: string) => shaca.getNote(noteId);- const getAttachment = note instanceof BNote- ? (attachmentId: string) => becca.getAttachment(attachmentId)- : (attachmentId: string) => shaca.getAttachment(attachmentId);-if (!result.isEmpty) {// Process attachment links.for (const linkEl of document.querySelectorAll("a")) {@@ -563,6 +572,28 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt}}+/**+ * The markup that stands in for an embedded attachment: a picture as an image, anything else as the+ * attachment link that `handleAttachmentLink` then resolves.+ *+ * @param asLink renders a picture as a link too, for an embed below the first level of inclusion.+ */+function renderAttachmentEmbed(+ attachmentId: string,+ attachment: BAttachment | SAttachment,+ asLink: boolean+) {+ const { ownerId, title } = attachment;++ if (!asLink && isImageAttachmentRole(attachment.role)) {+ const src = `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`;+ return `<img src="${src}" alt="${escapeHtml(title)}">`;+ }++ const href = `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;+ return `<a class="reference-link" href="${href}">${escapeHtml(title)}</a>`;+}+function handleAttachmentLink(linkEl: HTMLElement, href: string, getNote: GetNoteFunction, getAttachment: (id: string) => BAttachment | SAttachment | null) {const linkRegExp = /attachmentId=([a-zA-Z0-9_]+)/g;let attachmentMatch;