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/include notes: prevent the content render to be invoked while in tiny layout
Adorian Doranc739da519108
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 80b07702b2..e0f0615c05 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -7,6 +7,7 @@ import DOMPurify from "dompurify";import { beforeEach, describe, expect, it, vi } from "vitest";import FAttachment from "../entities/fattachment";+import content_renderer from "./content_renderer";import froca from "./froca";import server from "./server";import { buildNote } from "../test/easy-froca";@@ -80,7 +81,7 @@ describe("Text content renderer", () => {expect(contentEl.querySelectorAll("section.include-note p").length).toBe(1);});- it("renders the caption of an embed after its content, unless Tiny or nested", async () => {+ it("renders the caption of an embed after its content, unless nested", async () => {const contentEl = document.createElement("div");const figure = (noteId: string, boxSize: string, caption: string) =>`<figure class="include-note" data-note-id="${noteId}" data-box-size="${boxSize}">`@@ -93,18 +94,56 @@ describe("Text content renderer", () => {const note = buildNote({title: "New note",content: figure(embeddedNote.noteId, "medium", "A <strong>caption</strong>")- + figure(embeddedNote.noteId, "tiny", "Tiny caption")});await renderText(note, $(contentEl));- const [ embed, tinyEmbed ] = contentEl.querySelectorAll(".ck-content > .include-note");+ const [ embed ] = contentEl.querySelectorAll(".ck-content > .include-note");expect(embed.querySelector("p")?.textContent).toBe("Included.");expect(embed.lastElementChild?.outerHTML).toBe("<figcaption>A <strong>caption</strong></figcaption>");expect(embed.querySelectorAll("figcaption")).toHaveLength(1);- expect(tinyEmbed.querySelector("p")?.textContent).toBe("Included.");- expect(tinyEmbed.querySelector("figcaption")).toBeNull();+ });++ it("renders a Tiny embed as a link, without rendering what it shows", async () => {+ const embeddedNote = buildNote({ title: "Tiny note", content: "<p>Not rendered.</p>" });+ const owner = buildNote({+ title: "Tiny owner",+ content: `<figure class="include-note" data-note-id="${embeddedNote.noteId}"`+ + ` data-box-size="tiny"><figcaption>Tiny caption</figcaption></figure>`+ + `<figure class="include-note" data-attachment-id="tinyPic" data-box-size="tiny">`+ + "</figure>"+ });+ new FAttachment(froca, {+ attachmentId: "tinyPic",+ ownerId: owner.noteId,+ role: "image",+ mime: "image/png",+ title: "photo.png",+ dateModified: "",+ utcDateModified: "",+ utcDateScheduledForErasureSince: "",+ contentLength: 0+ });+ const getRenderedContent = vi.spyOn(content_renderer, "getRenderedContent");++ try {+ const contentEl = document.createElement("div");+ await renderText(owner, $(contentEl));++ expect(getRenderedContent).not.toHaveBeenCalled();+ expect(contentEl.querySelector(".include-note")).toBeNull();+ expect(contentEl.querySelector("img")).toBeNull();+ expect(contentEl.textContent).not.toContain("Not rendered.");+ expect(contentEl.textContent).not.toContain("Tiny caption");+ const links = Array.from(contentEl.querySelectorAll("a.reference-link"));+ expect(links.map((link) => link.getAttribute("href"))).toEqual([+ `#root/${embeddedNote.noteId}`,+ `#root/${owner.noteId}?viewMode=attachments&attachmentId=tinyPic`+ ]);+ } finally {+ getRenderedContent.mockRestore();+ }});it("skips rendering embedded note", async () => {diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex 7f05bad082..daca0762ba 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -93,6 +93,12 @@ async function renderContentEmbeds(contentEl: HTMLElement, seenNoteIds: Set<stri// Render and integrate the notes.for (const embedEl of embedEls) {+ // A Tiny embed shows only a title, so it links to what it shows instead of rendering it.+ if (embedEl.getAttribute("data-box-size") === "tiny") {+ await replaceEmbedWithReferenceLink(embedEl);+ continue;+ }+const attachment = await getEmbeddedAttachment(embedEl);if (attachment) {const { $renderedContent } = await content_renderer.getRenderedContent(attachment);@@ -151,27 +157,32 @@ export function getEmbedCaption(embedEl: Element) {*/async function replaceEmbedsWithReferenceLinks(contentEl: HTMLElement) {for (const embedEl of contentEl.querySelectorAll(".include-note")) {- const attachment = await getEmbeddedAttachment(embedEl);- 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);- embedEl.replaceWith(referenceLink);- continue;- }-- const noteId = embedEl.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.- if (!noteId || !/^[a-zA-Z0-9_]+$/.test(noteId)) continue;+ await replaceEmbedWithReferenceLink(embedEl);+ }+}+/** Replaces `embedEl` with a bare reference link to the note or attachment it shows. */+async function replaceEmbedWithReferenceLink(embedEl: Element) {+ const attachment = await getEmbeddedAttachment(embedEl);+ 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", `#root/${noteId}`);+ referenceLink.setAttribute("href", href);embedEl.replaceWith(referenceLink);+ return;}++ const noteId = embedEl.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.+ if (!noteId || !/^[a-zA-Z0-9_]+$/.test(noteId)) return;++ const referenceLink = document.createElement("a");+ referenceLink.className = "reference-link";+ referenceLink.setAttribute("href", `#root/${noteId}`);+ embedEl.replaceWith(referenceLink);}/** The attachment an embed shows, or `null` for an embed of a note. */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 71cdfcc4c2..f9e3270933 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@@ -98,8 +98,8 @@</ul><p>An embed follows its attachment like a link does. Converting the attachmentinto a note turns the embed into an included note. In a <a href="#root/_help_R9pX4DGra2Vt">shared note</a>,- an embedded picture is displayed with its caption, and any other attachment- appears as a link to download it.</p>+ an embedded picture is displayed with its caption, and any other attachment,+ or a picture in a <em>Tiny</em> embed, 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 2657994dda..94b29ed936 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@@ -14,7 +14,9 @@<ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon,its title with the path to the note above it, and buttons to act on the- note.</li>+ note. The included note is never rendered, so wherever the note is shown+ outside the editor, such as in print, in a tooltip or on a shared page,+ a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height.Text scrolls inside the box, while a picture, a diagram or a video is scaleddown to fit it.</li>@@ -94,7 +96,8 @@<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 noteas if they were part of the note itself. The caption of an include is shown- under the included content.</p>+ under the included content. A <em>Tiny</em> include is shown as a link to+ the included note instead.</p><p>For this to work, the included notes must also be shared, otherwise theywill not be shown. However, the included notes can still be hidden fromthe note tree via <code>#shareHiddenFromTree</code>.</p>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 0d56150377..06a6a5e16b 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@@ -49,7 +49,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref* To show an embed of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.* 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. _Convert to link_ also ends the menu that right-clicking the title row of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button opens.-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 with its caption, and any other attachment appears as a link to download it.+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 with its caption, and any other attachment, or a picture in a _Tiny_ embed, appears as a link to download it.## Converting notes to attachmentsdiff --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 25f77c1b42..62d0642799 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@@ -13,7 +13,7 @@ An [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) caThe box size sets how much of the included note is shown.-* _Tiny_ shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note.+* _Tiny_ shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a _Tiny_ include appears as a link to the included note.* _Small_ and _Medium_ show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.* _Full_ shows the whole content.* _Expandable_ shows only the title until its <span class="tn-icon bx bx-chevron-right"></span> arrow is pressed.@@ -64,7 +64,7 @@ To replace an include with a link to the included note, select it and press the## Included notes in the share functionality-If 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. The caption of an include is shown under the included content.+If 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. The caption of an include is shown under the included content. A _Tiny_ include is shown as a link to the included note instead.For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via `#shareHiddenFromTree`.diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 15cb60967e..e5feab41f2 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -68,23 +68,50 @@ describe("content_renderer", () => {`);});- it("keeps the caption of an embed under its content, except on a Tiny one", () => {+ it("keeps the caption of an embed under its content", () => {buildShareNotes([ { id: "subnote1", content: `<p>Foo</p>` } ]);- const embed = (boxSize: string) =>- `<figure class="include-note" data-note-id="subnote1" data-box-size="${boxSize}">`- + `<figcaption>A <strong>caption</strong></figcaption></figure>`;const note = buildShareNote({id: "note1",- content: embed("medium") + embed("tiny")+ content: `<figure class="include-note" data-note-id="subnote1"`+ + ` data-box-size="medium"><figcaption>A <strong>caption</strong></figcaption>`+ + `</figure>`});expect(getContent(note).content).toStrictEqual(`<figure class="include-note" data-note-id="subnote1" data-box-size="medium">`+ `<p>Foo</p><figcaption>A <strong>caption</strong></figcaption></figure>`- + `<p>Foo</p>`);});+ it("renders a Tiny embed as a link, without the content it shows", () => {+ buildShareNotes([+ { id: "tinyNote1", title: "Tiny note", content: "<p>Not rendered</p>" }+ ]);+ const note = buildShareNote({+ content: `<figure class="include-note" data-note-id="tinyNote1"`+ + ` data-box-size="tiny"><figcaption>Tiny caption</figcaption></figure>`+ + `<figure class="include-note" data-attachment-id="tinyPic1"`+ + ` data-box-size="tiny"></figure>`,+ attachments: [+ { id: "tinyPic1", role: "image", mime: "image/png", title: "my photo.png" }+ ]+ });+ const tinyNote = shaca.getNote("tinyNote1");+ if (!tinyNote) throw new Error("Expected the embedded note.");+ const getNoteContent = vi.spyOn(tinyNote, "getContent");++ const content = getContent(note).content as string;++ expect(getNoteContent).not.toHaveBeenCalled();+ expect(content).not.toContain("include-note");+ expect(content).not.toContain("Not rendered");+ expect(content).not.toContain("Tiny caption");+ expect(content).not.toContain("<img");+ expect(content).toContain("reference-link");+ expect(content).toContain("Tiny note");+ expect(content).toContain(`href="api/attachments/tinyPic1/download"`);+ });+it("renders only the first level of nested embeds on the share view (nested embed becomes a reference link)", () => {buildShareNote({ id: "nestC2", title: "Note C", content: "<p>C body</p>" });buildShareNote({diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 5894037015..1e26828ea6 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -492,10 +492,12 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptconst seenNoteIds = new Set(options.seenNoteIds);seenNoteIds.add(note.noteId);for (const embedEl of document.querySelectorAll(".include-note")) {+ // A Tiny embed shows only a title, so it links to what it shows instead of rendering it.+ const asLink = !!options.embedsAsReferenceLinks+ || embedEl.getAttribute("data-box-size") === "tiny";const attachmentId = embedEl.getAttribute("data-attachment-id");if (attachmentId) {const attachment = getAttachment(attachmentId);- const asLink = !!options.embedsAsReferenceLinks;const html = attachment ? renderAttachmentEmbed(attachmentId, attachment, asLink) : "";const embed = parse(html, parseOpts).childNodes;if (attachment && !asLink && isImageAttachmentRole(attachment.role)) {@@ -520,9 +522,9 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptcontinue;}- // Deeper-than-first-level embeds (and any cycle in the recursive path) degrade to a- // reference link that the link-processing passes below resolve to the shared note.- if (options.embedsAsReferenceLinks || seenNoteIds.has(noteId)) {+ // Tiny embeds, deeper-than-first-level embeds and any cycle in the recursive path degrade+ // to a reference link that the link-processing passes below resolve to the shared note.+ if (asLink || seenNoteIds.has(noteId)) {embedEl.replaceWith(...parse(`<a class="reference-link" href="#root/${escapeHtml(noteId)}">${escapeHtml(embeddedNote.title)}</a>`, parseOpts).childNodes);continue;}@@ -577,20 +579,13 @@ 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 embedding.- *//*** Puts `content` in place of an embed. An embed with a caption stays a `<figure>`, holding* `content` and then the caption.*/function replaceEmbedContent(embedEl: HTMLElement, content: ParsedNode[]) {- const caption = embedEl.getAttribute("data-box-size") !== "tiny"- && embedEl.childNodes.find((child) =>- child instanceof HTMLElement && child.tagName === "FIGCAPTION");+ const caption = embedEl.childNodes.find((child) =>+ child instanceof HTMLElement && child.tagName === "FIGCAPTION");if (caption) {embedEl.set_content([ ...content, caption ]);} else {@@ -598,6 +593,13 @@ function replaceEmbedContent(embedEl: HTMLElement, content: ParsedNode[]) {}}+/**+ * 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 a Tiny embed or one below the first level of+ * embedding.+ */function renderAttachmentEmbed(attachmentId: string,attachment: BAttachment | SAttachment,