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: add support for captions (similar to images)
Adorian Doranc858be34a371
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex 36f19fa4dc..bd8c3ac59a 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -197,7 +197,7 @@ function getConvertToLinkItem(editor: CKTextEditor | null): MenuItem<CommandNames> | null {const titleRow = getTarget(e)?.closest<HTMLElement>(".include-note-title-row");- if (!titleRow?.closest("section.include-note[data-attachment-id]")+ if (!titleRow?.closest(".include-note[data-attachment-id]")|| !editor?.plugins.has("IncludeNote") || !editor.commands.get("convertEmbedToLink")) {return null;}diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex e627f2b207..45c8aa3254 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -41,14 +41,14 @@ export interface RenderOptions {/** If enabled, it will prevent rendering of included notes. */noIncludedNotes?: boolean;/**- * Keep expanding include-note sections recursively at every depth. Used for printing/export,+ * Keep expanding includes recursively at every depth. Used for printing/export,* which preserves full nesting. When false (the default for on-screen display), only the first- * level of inclusion is rendered and deeper include-note sections are replaced with a reference+ * level of inclusion is rendered and deeper includes are replaced with a reference* link (see {@link includesAsReferenceLinks}).*/expandNestedIncludes?: boolean;/**- * Internal: render this note's own include-note sections as reference links instead of expanding+ * Internal: render this note's own includes as reference links instead of expanding* them. Set when rendering a note that is itself already an included note in display mode, so that* inclusion stops after the first level.*/diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 488de135f0..49b5745ad9 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -80,6 +80,33 @@ describe("Text content renderer", () => {expect(contentEl.querySelectorAll("section.include-note p").length).toBe(1);});+ it("renders the caption of an include after its content, unless Tiny or 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}">`+ + `<figcaption>${caption}</figcaption></figure>`;+ const nestedNote = buildNote({ title: "Nested note", content: "<p>Nested.</p>" });+ const includedNote = buildNote({+ title: "Included note",+ content: `<p>Included.</p>${figure(nestedNote.noteId, "medium", "Nested caption")}`+ });+ const note = buildNote({+ title: "New note",+ content: figure(includedNote.noteId, "medium", "A <strong>caption</strong>")+ + figure(includedNote.noteId, "tiny", "Tiny caption")+ });++ await renderText(note, $(contentEl));++ const [ include, tinyInclude ] = contentEl.querySelectorAll(".ck-content > .include-note");+ expect(include.querySelector("p")?.textContent).toBe("Included.");+ expect(include.lastElementChild?.outerHTML)+ .toBe("<figcaption>A <strong>caption</strong></figcaption>");+ expect(include.querySelectorAll("figcaption")).toHaveLength(1);+ expect(tinyInclude.querySelector("p")?.textContent).toBe("Included.");+ expect(tinyInclude.querySelector("figcaption")).toBeNull();+ });+it("skips rendering included note", async () => {const contentEl = document.createElement("div");const includedNote = buildNote({diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex 3e21b79322..e2048414ad 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -27,7 +27,7 @@ export default async function renderText(note: FNote | FAttachment, $renderedCon/*** Apply the post-render passes that make CKEditor-compatible HTML fully- * interactive: expand `<section class="include-note">`, render inline math and+ * interactive: expand `<figure class="include-note">`, render inline math and* Mermaid diagrams, rewrite reference-link titles, and highlight code blocks.* Assumes the caller has already appended the HTML inside a `.ck-content` child* of `$renderedContent`.@@ -36,7 +36,7 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendereconst seenNoteIds = options.seenNoteIds ?? new Set<string>();seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);if (options.noIncludedNotes) {- $renderedContent.find("section.include-note").remove();+ $renderedContent.find(".include-note").remove();} 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.@@ -77,7 +77,7 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendereasync function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>, expandNested: boolean) {// TODO: Consider duplicating with server's share/content_renderer.ts.- const includeNoteEls = contentEl.querySelectorAll("section.include-note");+ const includeNoteEls = contentEl.querySelectorAll(".include-note");// Gather the list of items to load.const noteIds: string[] = [];@@ -96,7 +96,7 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<striconst attachment = await getEmbeddedAttachment(includeNoteEl);if (attachment) {const { $renderedContent } = await content_renderer.getRenderedContent(attachment);- includeNoteEl.replaceChildren(...$renderedContent);+ replaceIncludeContent(includeNoteEl, $renderedContent.toArray());continue;}@@ -123,19 +123,34 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<stri? { seenNoteIds: new Set(seenNoteIds), expandNestedIncludes: true }: { seenNoteIds: new Set(seenNoteIds), includesAsReferenceLinks: true })).$renderedContent;- includeNoteEl.replaceChildren(...renderedContent);+ replaceIncludeContent(includeNoteEl, renderedContent.toArray());}}+/** Puts `content` in an include, followed by the include's caption. */+function replaceIncludeContent(includeNoteEl: Element, content: Node[]) {+ const caption = getIncludeCaption(includeNoteEl);+ includeNoteEl.replaceChildren(...content, ...(caption ? [ caption ] : []));+}++/** The caption of an include, or `null` for a Tiny include, which shows none. */+export function getIncludeCaption(includeNoteEl: Element) {+ if (includeNoteEl.getAttribute("data-box-size") === "tiny") {+ return null;+ }++ return includeNoteEl.querySelector<HTMLElement>(":scope > figcaption");+}+/**- * Replace each `section.include-note` in the given content with a bare reference link to the+ * Replace each `.include-note` in the given content with a bare reference link to the* included note, without expanding it. Used on display to stop inclusion after the first level so a* note's transitive include graph is not rendered inline. The link's title, icon and colour are* 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.*/async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {- for (const includeNoteEl of contentEl.querySelectorAll("section.include-note")) {+ for (const includeNoteEl of contentEl.querySelectorAll(".include-note")) {const attachment = await getEmbeddedAttachment(includeNoteEl);if (attachment) {const { ownerId, attachmentId } = attachment;@@ -159,7 +174,7 @@ async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {}}-/** The attachment an include section embeds, or `null` for an include of a note. */+/** The attachment an include 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.diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex 7841e5eeec..c7393a4f41 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -217,9 +217,11 @@ describe("isHtmlEmpty", () => {expect(isHtmlEmpty("<p> </p>")).toBe(true);});- it("detects content via img / section / link-mention", () => {+ it("detects content via img / section / include / link-mention", () => {expect(isHtmlEmpty("<IMG src='x'>")).toBe(false);expect(isHtmlEmpty("<SECTION></section>")).toBe(false);+ expect(isHtmlEmpty("<figure class=\"include-note\" data-note-id=\"n1\"> </figure>"))+ .toBe(false);expect(isHtmlEmpty("<span class='link-mention'></span>")).toBe(false);});diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex fc30f22082..316afb93a3 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -397,6 +397,7 @@ export function isHtmlEmpty(html: string) {return (!html.includes("<img") &&!html.includes("<section") &&+ !html.includes("include-note") &&!html.includes("link-mention") &&// the line below will actually attempt to load images so better to check for images first$("<div>").html(html).text().trim().length === 0diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 3f2b1f01b5..2fec442409 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1433,16 +1433,28 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t}.include-note {- margin-bottom: 10px;+ margin: 0 0 10px;border-radius: var(--_include-note-top-border-radius, 8px)var(--_include-note-top-border-radius, 8px)var(--_include-note-bottom-border-radius, 8px)var(--_include-note-bottom-border-radius, 8px);background-color: var(--card-background-color, var(--accented-background-color));display: flex; /* see https://github.com/zadam/trilium/issues/1590 */+ flex-direction: column;transition: background-color 200ms ease-out;}+/* On the wrapper: the editor gives the caption a border of its own for the focus ring. */+.include-note-wrapper:has(+ figcaption) {+ border-bottom: 2px solid var(--main-background-color);+}++.include-note > figcaption {+ padding: 6px 1rem;+ font-size: .8em;+ text-align: center;+}+/* Includes in a series share flush edges, as link previews and collapsible blocks do. */.include-note + .include-note {--_include-note-top-border-radius: 0;@@ -1533,6 +1545,27 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-theight: 20em;}+/* Pictures, diagrams and players fit the box height, where text scrolls in it. */+.include-note[data-box-size="small"] {+ --include-note-media-max-height: 10em;+}++.include-note[data-box-size="medium"] {+ --include-note-media-max-height: 20em;+}++.include-note[data-box-size] .include-note-content:is(+ .type-image, .type-canvas, .type-mindMap, .type-spreadsheet, .type-mermaid, .type-video+) {+ max-height: none;+}++.include-note-content:not(:fullscreen) :is(+ .rendered-content > img, .rendered-content > svg, .video-preview+) {+ max-height: var(--include-note-media-max-height, none);+}+.include-note-wrapper {width: 100%;display: flex;diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.cssindex 5754154a26..900610eb51 100644--- a/apps/client/src/stylesheets/theme-next/notes/text.css+++ b/apps/client/src/stylesheets/theme-next/notes/text.css@@ -734,6 +734,10 @@ html .note-detail-editable-text > :not(figure, .include-note, hr):first-child {overflow: hidden;}+.include-note:has(> figcaption) .include-note-content.type-video .video-preview-wrapper {+ border-radius: 0;+}+.ck.ck-editor__editable pre[data-language]::after {--ck-color-code-block-label-background: rgba(128, 128, 128, 0.5);border-radius: 0 0 5px 5px;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ed4f3b2805..f98f14a026 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4255,6 +4255,7 @@"attach-file-as-a-link": "Attach file as a link","box-size": "Box size","bulleted-list": "Bulleted list",+ "caption-for-the-included-note": "Caption for the included note","card": "Card","caution": "Caution","changes": "Changes",@@ -4282,6 +4283,7 @@"edit-task-states": "Edit task states","edit-title": "Edit title","embed": "Embed",+ "enter-caption": "Enter caption","enter-the-anchor-name-without-spaces": "Enter the anchor name without spaces.","equation-preview": "Equation preview","error-rendering-equation": "Error rendering equation",diff --git a/apps/client/src/widgets/highlights_list.spec.ts b/apps/client/src/widgets/highlights_list.spec.tsindex 72fb6e67fb..01d8df83c9 100644--- a/apps/client/src/widgets/highlights_list.spec.ts+++ b/apps/client/src/widgets/highlights_list.spec.ts@@ -11,12 +11,12 @@ describe("getHighlightList", () => {it("supports old italics", async () => {const highlights = await widget.getHighlightList("This is <i>italic</i> text", [ "italic" ]);expect(highlights.$highlightsList.html()).toBe("<li><i>italic</i></li>");- expect(highlights.findSubStr).toContain("i:not(section.include-note i)");+ expect(highlights.findSubStr).toContain("i:not(.include-note-wrapper i)");});it("supports new italics", async () => {const highlights = await widget.getHighlightList("This is <em>italic</em> text", [ "italic" ]);expect(highlights.$highlightsList.html()).toBe("<li><em>italic</em></li>");- expect(highlights.findSubStr).toContain("em:not(section.include-note em)");+ expect(highlights.findSubStr).toContain("em:not(.include-note-wrapper em)");});})diff --git a/apps/client/src/widgets/highlights_list.ts b/apps/client/src/widgets/highlights_list.tsindex 25dd63dec0..a15af64493 100644--- a/apps/client/src/widgets/highlights_list.ts+++ b/apps/client/src/widgets/highlights_list.ts@@ -170,24 +170,25 @@ export default class HighlightsListWidget extends RightPanelWidget {let findSubStr = "",combinedRegexStr = "";if (optionsHighlightsList.includes("bgColor")) {- findSubStr += `,span[style*="background-color"]:not(section.include-note span[style*="background-color"])`;+ findSubStr += `,span[style*="background-color"]`+ + `:not(.include-note-wrapper span[style*="background-color"])`;combinedRegexStr += `|${regex1.source}`;}if (optionsHighlightsList.includes("color")) {- findSubStr += `,span[style*="color"]:not(section.include-note span[style*="color"])`;+ findSubStr += `,span[style*="color"]:not(.include-note-wrapper span[style*="color"])`;combinedRegexStr += `|${regex2.source}`;}if (optionsHighlightsList.includes("italic")) {- findSubStr += `,i:not(section.include-note i)`;- findSubStr += `,em:not(section.include-note em)`;+ findSubStr += `,i:not(.include-note-wrapper i)`;+ findSubStr += `,em:not(.include-note-wrapper em)`;combinedRegexStr += `|${regex3.source}`;}if (optionsHighlightsList.includes("bold")) {- findSubStr += `,strong:not(section.include-note strong)`;+ findSubStr += `,strong:not(.include-note-wrapper strong)`;combinedRegexStr += `|${regex4.source}`;}if (optionsHighlightsList.includes("underline")) {- findSubStr += `,u:not(section.include-note u)`;+ findSubStr += `,u:not(.include-note-wrapper u)`;combinedRegexStr += `|${regex5.source}`;}diff --git a/apps/client/src/widgets/toc.ts b/apps/client/src/widgets/toc.tsindex 15358135aa..c07734bd3a 100644--- a/apps/client/src/widgets/toc.ts+++ b/apps/client/src/widgets/toc.ts@@ -425,7 +425,8 @@ export default class TocWidget extends RightPanelWidget {}}- const headingElement = $container?.find(":header:not(section.include-note :header)")?.[headingIndex];+ const headingElement = $container+ ?.find(":header:not(.include-note :header)")?.[headingIndex];headingElement?.scrollIntoView({ behavior: "smooth" });}diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsxindex 49dc5ac310..63c69dd48e 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx@@ -377,7 +377,7 @@ function useTextCommands(parentComponent: TypeWidgetProps["parentComponent"], edparentComponent?.triggerCommand("showIncludeNoteDialog", {editorApi: {addIncludeNote(noteId: string, boxSize?: string) {- insertText(editorView, `<section class="include-note" data-note-id="${noteId}" data-box-size="${boxSize ?? "full"}"></section>\n`);+ insertText(editorView, `<figure class="include-note" data-note-id="${noteId}" data-box-size="${boxSize ?? "full"}"></figure>\n`);editorView.focus();},async addImage(noteId: string) {diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex b5cee427e5..fbea07e36f 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -166,7 +166,7 @@ function useNoteLanguage(note: FNote) {function applyIncludedNotes(container: HTMLDivElement) {const loaded: Promise<unknown>[] = [];- const includedNotes = container.querySelectorAll<HTMLElement>("section.include-note");+ const includedNotes = container.querySelectorAll<HTMLElement>(".include-note");for (const includedNote of includedNotes) {const { attachmentId, noteId } = includedNote.dataset;if (attachmentId) {diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex cce820969b..c054810d0b 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -43,6 +43,7 @@ import {getAttachmentHref,loadIncludedAttachment,loadIncludedNote,+ refreshIncludedNote,watchIncludedNotes} from "./utils";@@ -126,14 +127,15 @@ describe("loadIncludedNote", () => {expect(content_renderer.mountInteractiveWidget).not.toHaveBeenCalled();});- it("mounts a tiny box with the note's path, without rendering the note", async () => {+ it("mounts a tiny box with the note's path, without the note or a caption", async () => {const actions = [ action("edit"), action("open") ];vi.mocked(getNoteActions).mockReturnValue(actions);- const section = document.createElement("section");- section.className = "include-note";- section.dataset.boxSize = "tiny";+ const figure = document.createElement("figure");+ figure.className = "include-note";+ figure.dataset.boxSize = "tiny";+ figure.innerHTML = "<figcaption>Caption</figcaption>";- await loadIncludedNote("noteY", $(section));+ await loadIncludedNote("noteY", $(figure));expect(link.createLink).toHaveBeenCalledWith("noteY", {showTooltip: false,@@ -143,7 +145,7 @@ describe("loadIncludedNote", () => {expect(getNoteActions).toHaveBeenCalledWith("noteY");const mount = lastMount();expect(mount.type).toBe(TinyIncludeNote);- expect(mount.container.parentElement).toBe(section);+ expect([ ...figure.childNodes ]).toEqual([ mount.container ]);expect(mount.props).toEqual({icon: "bx bx-note",title,@@ -219,38 +221,71 @@ describe("loadIncludedAttachment", () => {});describe("the element an include box is mounted in", () => {- it("is a wrapper created in a read-only section, which gives the box size", async () => {- const section = document.createElement("section");- section.className = "include-note";- section.dataset.boxSize = "expandable";- section.innerHTML = " ";+ it("is a wrapper created in a read-only include ahead of its caption", async () => {+ const figure = document.createElement("figure");+ figure.className = "include-note";+ figure.dataset.boxSize = "expandable";+ figure.innerHTML = " <figcaption>Caption</figcaption>";+ const caption = figure.querySelector("figcaption");- await loadIncludedNote("noteY", $(section));+ await loadIncludedNote("noteY", $(figure));const { container, props } = lastMount();- expect([ ...section.childNodes ]).toEqual([ container ]);+ expect(caption).not.toBeNull();+ expect([ ...figure.childNodes ]).toEqual([ container, caption ]);expect(container.className).toBe("include-note-wrapper");expect(props.boxSize).toBe("expandable");// Loading again, as a refresh does, reuses the wrapper.- await loadIncludedNote("noteY", $(section), "small");+ await loadIncludedNote("noteY", $(figure), "small");expect(lastMount().container).toBe(container);expect(lastMount().props.boxSize).toBe("small");});- it("is the wrapper an editor section holds, leaving the editor's own elements", async () => {+ it("is a wrapper created in a legacy <section> include", async () => {const section = document.createElement("section");- section.className = "include-note ck-widget";- section.dataset.boxSize = "full";+ section.className = "include-note";+ section.dataset.boxSize = "medium";++ await loadIncludedNote("noteY", $(section));++ expect([ ...section.childNodes ]).toEqual([ lastMount().container ]);+ expect(lastMount().props.boxSize).toBe("medium");+ });++ it("is the wrapper an editor include holds, leaving the editor's own elements", async () => {+ const figure = document.createElement("figure");+ figure.className = "include-note ck-widget";+ figure.dataset.boxSize = "full";const wrapper = createWrapper();+ const caption = document.createElement("figcaption");const typeAround = document.createElement("div");- section.append(wrapper, typeAround);+ figure.append(wrapper, caption, typeAround);- await loadIncludedAttachment("att1", $(section));+ await loadIncludedAttachment("att1", $(figure));expect(lastMount().container).toBe(wrapper);expect(lastMount().props.boxSize).toBe("full");- expect([ ...section.children ]).toEqual([ wrapper, typeAround ]);+ expect([ ...figure.children ]).toEqual([ wrapper, caption, typeAround ]);+ });+});++describe("refreshIncludedNote", () => {+ it("reloads every include of the note, of either element", async () => {+ const container = document.createElement("div");+ container.innerHTML = `<figure class="include-note" data-note-id="noteY"></figure>`+ + `<section class="include-note" data-note-id="noteY"></section>`+ + `<figure class="include-note" data-note-id="other"></figure>`;+ const [ figure, section ] = [ ...container.children ];++ refreshIncludedNote(container, "noteY");++ await vi.waitFor(() => {+ expect(content_renderer.mountInteractiveWidget).toHaveBeenCalledTimes(2);+ });+ const mountedIn = vi.mocked(content_renderer.mountInteractiveWidget).mock.calls+ .map(([ , wrapper ]) => wrapper.parentElement);+ expect(mountedIn).toEqual([ figure, section ]);});});@@ -259,8 +294,8 @@ describe("watchIncludedNotes", () => {beforeEach(() => {container = document.createElement("div");- container.innerHTML = `<p>text</p><section class="include-note"></section>`- + `<blockquote><section class="include-note"></section></blockquote>`;+ container.innerHTML = `<p>text</p><figure class="include-note"></figure>`+ + `<blockquote><figure class="include-note"></figure></blockquote>`;document.body.appendChild(container);});@@ -279,25 +314,25 @@ describe("watchIncludedNotes", () => {it("unmounts what is removed from the container, but not what is moved within it", async () => {const stop = watchIncludedNotes(container);- const [ paragraph, section, quote ] = [ ...container.children ];+ const [ paragraph, include, quote ] = [ ...container.children ];- section.remove();+ include.remove();quote.remove();container.append(quote);paragraph.firstChild?.remove();await flush();- expect(disposed()).toEqual([ section ]);+ expect(disposed()).toEqual([ include ]);stop();});it("unmounts what is left on stop, and stops watching", async () => {const stop = watchIncludedNotes(container);- const section = container.querySelector("section");- section?.remove();+ const include = container.querySelector("figure");+ include?.remove();stop();- expect(disposed()).toEqual([ section, container ]);+ expect(disposed()).toEqual([ include, container ]);container.querySelector("blockquote")?.remove();await flush();diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 8df6567387..f25b79cae5 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -3,6 +3,7 @@ import { h } from "preact";import appContext from "../../../components/app_context";import content_renderer from "../../../services/content_renderer";+import { getIncludeCaption } from "../../../services/content_renderer_text";import froca from "../../../services/froca";import link, { ViewScope } from "../../../services/link";import utils from "../../../services/utils";@@ -10,14 +11,14 @@ import IncludeNote, { getNoteActions, TinyIncludeNote } from "./IncludeNote";/*** Fills an include box with a note. Without a box size of its own, the box takes the one of its- * section.+ * include.*/export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {const note = await froca.getNote(noteId);if (!note) return;const el = $el[0];- const size = boxSize ?? getSectionBoxSize(el);+ const size = boxSize ?? getIncludeBoxSize(el);if (size === "tiny") {const $link = await link.createLink(note.noteId, {showTooltip: false,@@ -58,7 +59,7 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,/*** Fills an include box with an embedded attachment, under a title linking to it. Without a box- * size of its own, the box takes the one of its section.+ * size of its own, the box takes the one of its include.*/export async function loadIncludedAttachment(attachmentId: string,@@ -69,7 +70,7 @@ export async function loadIncludedAttachment(if (!attachment) return;const el = $el[0];- const size = boxSize ?? getSectionBoxSize(el);+ const size = boxSize ?? getIncludeBoxSize(el);const viewScope: ViewScope = { viewMode: "attachments", attachmentId };if (size === "tiny") {// `attachment_actions` is imported on demand: it imports the image compression dialog.@@ -110,13 +111,14 @@ export async function loadIncludedAttachment(await content_renderer.mountInteractiveWidget(box, getWrapper(el));}-function getSectionBoxSize(el: HTMLElement) {- return el.closest<HTMLElement>("section.include-note")?.dataset.boxSize;+function getIncludeBoxSize(el: HTMLElement) {+ return el.closest<HTMLElement>(".include-note")?.dataset.boxSize;}/*** The element an include box is mounted in: `el` when it is the `.include-note-wrapper` the- * editor renders, otherwise the wrapper of the `section.include-note`, reused or created.+ * editor renders, otherwise the wrapper of the `.include-note`, reused or created ahead of the+ * caption.*/function getWrapper(el: HTMLElement) {if (el.classList.contains("include-note-wrapper")) {@@ -130,7 +132,8 @@ function getWrapper(el: HTMLElement) {const wrapper = document.createElement("div");wrapper.className = "include-note-wrapper";- el.replaceChildren(wrapper);+ const caption = getIncludeCaption(el);+ el.replaceChildren(wrapper, ...(caption ? [ caption ] : []));return wrapper;}@@ -169,7 +172,7 @@ function disposeRemoved(records: MutationRecord[]) {}export function refreshIncludedNote(container: HTMLDivElement, noteId: string) {- const includedNotes = container.querySelectorAll(`section[data-note-id="${noteId}"]`);+ const includedNotes = container.querySelectorAll(`.include-note[data-note-id="${noteId}"]`);for (const includedNote of includedNotes) {loadIncludedNote(noteId, $(includedNote as HTMLElement));}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 44a7058d27..4ad801c4d8 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@@ -78,6 +78,7 @@<li>An embed gets the box size that suits the attachment, as a new includednote does (see <em>Box sizes</em> there). To change its size, select theembed and use the box size menu in its toolbar.</li>+ <li>An embed can have a caption, as an included note can (see <em>Caption</em> there).</li><li>To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> <em>Open in new tab</em> buttonat the end of the embed's title.</li><li>An embed of size <em>Tiny</em> shows only the title of the attachment and@@ -94,8 +95,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, and any other attachment appears as a- link to download it.</p>+ an embedded picture is displayed with its caption, 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/Markdown.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.htmlindex 291c9baf93..b2a9125424 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html@@ -61,10 +61,14 @@</li><li><p><a class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a> (no- built-in Markdown syntax, but HTML syntax works just fine):</p><pre><code class="language-text-html"><section class="include-note" data-note-id="vJDjQm0VK8Na" data-box-size="expandable">- &nbsp;-</section></code></pre>+ built-in Markdown syntax, but HTML syntax works just fine):</p><pre><code class="language-text-html"><figure class="include-note" data-note-id="vJDjQm0VK8Na" data-box-size="expandable">+ <figcaption>An optional caption, with <strong>HTML</strong> formatting</figcaption>+</figure></code></pre><ul>+ <li>The caption is optional. Markdown is not processed inside the HTML block,+ so format the caption with HTML tags.</li>+ <li>Includes written as <code><section class="include-note"></code>,+ the syntax of earlier versions, still work.</li><li>These can also be quickly created via the <code>/include</code> commandor via a dedicated keyboard shortcut (not assigned by default).</li></ul>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 ac443872a6..2b1716f310 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@@ -15,8 +15,9 @@<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 thenote.</li>- <li><em>Small</em> and <em>Medium</em> show the content in a box of limited height,- which scrolls.</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 scaled+ down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class="tn-icon bx bx-chevron-right"></span> arrowis pressed.</li>@@ -32,6 +33,21 @@<p>The dialog that includes a note selects that size once the note is picked,and you can choose another one there. To change the size later, selectthe include and use the <em>Box size</em> menu in its toolbar.</p>+<h2>Caption</h2>+<p>An include can have a caption, shown centered at the bottom of its box.+ The caption is part of the text note, so it can be formatted like the rest+ of the text, for example in bold or with a link.</p>+<ul>+ <li>To add a caption, select the include, press the <span class="tn-icon cke cke-caption"></span> <em>Toggle caption on</em> button+ in its toolbar and type the caption.</li>+ <li>To remove the caption, press the same button again. Pressing it once more+ brings back the text it had, as long as the note stays open.</li>+ <li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes+ its caption, and switching it back to a larger size restores the caption,+ as long as the note stays open.</li>+ <li>An <em>Expandable</em> include shows its caption under the title while the+ content is collapsed, and under the content once it is expanded.</li>+</ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> <em>Open in new tab</em> buttonat the end of its title. An embedded attachment has the same button.</p>@@ -56,7 +72,8 @@<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 note- as if they were part of the note itself.</p>+ as if they were part of the note itself. The caption of an include is shown+ under the included content.</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/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex 14963533e7..7de3bae488 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -750,6 +750,25 @@ describe("saveLinks", () => {expect(imageLink.markAsDeleted).not.toHaveBeenCalled();});+ it("keeps the includeNoteLink relations of a text note's includes, of either element", () => {+ const note = buildNote({ title: "Test" });+ const [ figureTarget, sectionTarget, staleTarget ] = [ "Figure", "Section", "Stale" ]+ .map((title) => buildNote({ title }));+ const [ figureLink, sectionLink, staleLink ] = [ figureTarget, sectionTarget, staleTarget ]+ .map((target) => makeLinkRelation(note.noteId, "includeNoteLink", target.noteId));+ note.getRelations = () => [ figureLink, sectionLink, staleLink ];+ note.getAttachments = () => [];++ saveLinks(note, `<figure class="include-note" data-note-id="${figureTarget.noteId}"`+ + ` data-box-size="medium"><figcaption>Caption</figcaption></figure>`+ + `<section class="include-note" data-note-id="${sectionTarget.noteId}"`+ + ` data-box-size="small"> </section>`);++ expect(figureLink.markAsDeleted).not.toHaveBeenCalled();+ expect(sectionLink.markAsDeleted).not.toHaveBeenCalled();+ expect(staleLink.markAsDeleted).toHaveBeenCalled();+ });+it("does not delete existing internalLink relations on markdown notes using #root links", () => {const note = buildNote({ title: "Test", type: "code", mime: "text/x-markdown" });const targetNote = buildNote({ title: "Other Note" });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 0b4a006002..c9309c5824 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@@ -42,12 +42,13 @@ An attachment can be shown in the text instead of linked, the way <a class="ref* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.* To embed an attachment that is already linked, 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.* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar.+* An embed can have a caption, as an included note can (see _Caption_ there).* To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of the embed's title.* An embed of size _Tiny_ shows only the title of the attachment and its size, in a single row. Its buttons are <span class="tn-icon bx bx-file-find"></span> _Open externally_ and <span class="tn-icon bx bx-download"></span> _Download_.* 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 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, 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 appears as a link to download it.## Converting notes to attachmentsdiff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.mdindex f1d0f753b6..040631dda3 100644--- a/docs/User Guide/User Guide/Note Types/Markdown.md+++ b/docs/User Guide/User Guide/Note Types/Markdown.md@@ -36,11 +36,13 @@ The following features are supported by Trilium's Markdown format and will show* <a class="reference-link" href="Text/Include%20Note.md">Include Note</a> (no built-in Markdown syntax, but HTML syntax works just fine):```html- <section class="include-note" data-note-id="vJDjQm0VK8Na" data-box-size="expandable">- - </section>+ <figure class="include-note" data-note-id="vJDjQm0VK8Na" data-box-size="expandable">+ <figcaption>An optional caption, with <strong>HTML</strong> formatting</figcaption>+ </figure>```+ * The caption is optional. Markdown is not processed inside the HTML block, so format the caption with HTML tags.+ * Includes written as `<section class="include-note">`, the syntax of earlier versions, still work.* These can also be quickly created via the `/include` command or via a dedicated keyboard shortcut (not assigned by default).* <a class="reference-link" href="Text/Links/Internal%20(reference)%20links.md">Internal (reference) links</a> via its HTML syntax, or through a _Wikilinks_\-like format (only <a class="reference-link" href="../Advanced%20Usage/Note%20ID.md">Note ID</a>):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 464bf1ada2..429edbafc6 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@@ -14,7 +14,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.-* _Small_ and _Medium_ show the content in a box of limited height, which scrolls.+* _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.@@ -27,6 +27,15 @@ A new include gets the size that suits what it shows:The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar.+## Caption++An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.++* To add a caption, select the include, press the <span class="tn-icon cke cke-caption"></span> _Toggle caption on_ button in its toolbar and type the caption.+* To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.+* A _Tiny_ include has no caption. Switching an include to _Tiny_ removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.+* An _Expandable_ include shows its caption under the title while the content is collapsed, and under the content once it is expanded.+## Opening an included noteTo open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of its title. An embedded attachment has the same button.@@ -42,7 +51,7 @@ A _Tiny_ include has these buttons instead, followed by the same _More actions_## 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.+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.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/ckeditor5/src/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.tsindex 84315114ce..8a5a090278 100644--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts@@ -3,14 +3,16 @@ 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, { CONVERT_EMBED_TO_LINK_COMMAND } from "./includenote.js";+import IncludeNote, {+ CONVERT_EMBED_TO_LINK_COMMAND,+ TOGGLE_CAPTION_COMMAND_NAME+} 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";// ----------------------------------------------------------------------------// Minimal inline plugin that registers a section widget WITHOUT a class-// attribute, allowing us to exercise the `|| ""` branch in isIncludeNoteWidget.+// Minimal inline plugin that registers a widget without a class attribute.// ---------------------------------------------------------------------------class SectionNoClassWidget extends Plugin {@@ -41,7 +43,6 @@ class SectionNoClassWidget extends Plugin {editor.conversion.for("editingDowncast").elementToElement({model: "sectionNoClass",view: (_modelEl, { writer }) => {- // Intentionally no class attribute — exercises the `|| ""` branch.const section = writer.createContainerElement("section", {});return toWidget(section, writer, { label: "section no class widget" });}@@ -66,6 +67,9 @@ function getRelatedElementFn(ed: ClassicEditor): (selection: unknown) => unknownreturn def.getRelatedElement;}+/** A selection on nothing, standing in for the view selection. */+const EMPTY_SELECTION = { getSelectedElement: () => null, getFirstPosition: () => null };+// ---------------------------------------------------------------------------// Suite 1: basic plugin registration (IncludeNote only, no LinkEmbed)// ---------------------------------------------------------------------------@@ -93,20 +97,16 @@ describe("IncludeNoteToolbar", () => {expect(requires).toContain(IncludeNoteBoxSizeDropdown);});- it("offers, next to the box size, the way from an attachment embed back to a link", () => {+ it("offers the box size, the caption, and turning an attachment embed into 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>;- };- expect(repository._toolbarDefinitions.has("includeNote")).toBe(true);+ expect(repository._toolbarDefinitions.get("includeNote")?.itemsConfig).toEqual([+ "includeNoteBoxSizeDropdown",+ TOGGLE_CAPTION_COMMAND_NAME,+ CONVERT_EMBED_TO_LINK_COMMAND+ ]);});describe("getRelatedElement", () => {@@ -130,6 +130,23 @@ describe("IncludeNoteToolbar", () => {expect(result).not.toBeNull();});+ it("stays on the include while its caption is edited", () => {+ editor.setData("<figure class=\"include-note\" data-note-id=\"n1\""+ + " data-box-size=\"medium\"><figcaption>Caption</figcaption></figure>");+ editor.model.change((writer) => {+ const include = editor.model.document.getRoot()?.getChild(0);+ const caption = include?.is("element") ? include.getChild(0) : null;+ if (!caption?.is("element", "caption")) {+ throw new Error("Expected a caption.");+ }+ writer.setSelection(caption, 2);+ });++ const result = getRelatedElementFn(editor)(editor.editing.view.document.selection);++ expect(result).toBe(editor.editing.view.document.getRoot()?.getChild(0));+ });+it("returns null when selection is inside a plain paragraph (not an include-note widget)", () => {setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");@@ -139,20 +156,17 @@ describe("IncludeNoteToolbar", () => {expect(result).toBeNull();});- it("returns null when getSelectedElement returns null", () => {- const fn = getRelatedElementFn(editor);- const fakeSelection = { getSelectedElement: () => null };- const result = fn(fakeSelection);- expect(result).toBeNull();+ it("returns null when the selection is on nothing", () => {+ expect(getRelatedElementFn(editor)(EMPTY_SELECTION)).toBeNull();});});});// ----------------------------------------------------------------------------// Suite 2: || "" fallback branch (line 43) — widget section with no class attr+// Suite 2: a widget without a class attribute// ----------------------------------------------------------------------------describe("isIncludeNoteWidget — section widget without a class attribute (|| '' branch)", () => {+describe("isIncludeNoteWidget — widget without a class attribute", () => {let editor: ClassicEditor;beforeEach(async () => {@@ -164,13 +178,7 @@ describe("isIncludeNoteWidget — section widget without a class attribute (|| 'editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, SectionNoClassWidget]);});- it("returns null for a section widget that has no class attribute (exercises the || '' fallback at line 43)", () => {- // The SectionNoClassWidget editing downcast creates a real CKEditor widget (toWidget)- // wrapping a <section> element with NO class attribute. When that widget is selected:- // isWidget(element) → true (real widget marker)- // element.is("element","section") → true- // element.getAttribute("class") → null/undefined → || "" → ""- // "".includes("include-note") → false → return false+ it("returns null for a selected widget that has no class attribute", () => {editor.model.change((writer) => {const root = editor.model.document.getRoot();if (!root) {@@ -183,18 +191,15 @@ describe("isIncludeNoteWidget — section widget without a class attribute (|| 'const fn = getRelatedElementFn(editor);const viewSelection = editor.editing.view.document.selection;- const result = fn(viewSelection);- // No "include-note" class → must return null.- expect(result).toBeNull();+ expect(fn(viewSelection)).toBeNull();});});// ----------------------------------------------------------------------------// Suite 3: isIncludeNoteWidget branches — uses LinkEmbed to get real widgets-// that pass isWidget() but are NOT include-note sections.+// Suite 3: real widgets that are not includes// ----------------------------------------------------------------------------describe("isIncludeNoteWidget — real non-include-note widgets (branch coverage)", () => {+describe("isIncludeNoteWidget — real non-include-note widgets", () => {let editor: ClassicEditor;beforeEach(async () => {@@ -220,29 +225,22 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverageeditor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, LinkEmbed]);});- it("returns null when getSelectedElement returns a non-widget element (covers the !isWidget branch at line 35-36)", () => {- // To hit `return false` at line 36 in isIncludeNoteWidget we need a non-null- // selected element for which isWidget() returns false. A plain JS object- // that looks like a ViewElement but lacks the CKEditor widget marker is sufficient.- const fn = getRelatedElementFn(editor);-- // Fake element: is("element","section") would be true, getAttribute returns- // "include-note", but isWidget() checks for an internal custom property symbol- // that is absent here → isWidget returns false → isIncludeNoteWidget returns false.+ it("returns null when the selected element is not a widget", () => {+ // isWidget() checks for a custom property that this lookalike lacks.const fakeNonWidget = {- is: (type: string, name: string) => type === "element" && name === "section",- getAttribute: (attr: string) => attr === "class" ? "include-note" : null,+ is: (type: string) => type === "element",+ hasClass: (className: string) => className === "include-note",getCustomProperty: (_key: unknown) => undefined};- const result = fn({ getSelectedElement: () => fakeNonWidget });+ const result = getRelatedElementFn(editor)({+ ...EMPTY_SELECTION,+ getSelectedElement: () => fakeNonWidget+ });expect(result).toBeNull();});- it("returns null for a span.link-mention widget (isWidget=true but element is not a section — covers line 39-40)", () => {- // span.link-mention is a real CKEditor inline widget wrapping a <span>.- // isWidget() returns true for it, but element.is("element", "section") is false →- // isIncludeNoteWidget returns false at line 40.+ it("returns null for a selected span.link-mention widget", () => {editor.setData('<p><span class="link-mention" data-url="https://example.com">example</span></p>');editor.model.change((writer) => {@@ -263,16 +261,10 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverageconst fn = getRelatedElementFn(editor);const viewSelection = editor.editing.view.document.selection;- const result = fn(viewSelection);- // span.link-mention passes isWidget() but is not a section → returns null.- expect(result).toBeNull();+ expect(fn(viewSelection)).toBeNull();});- it("returns null for a section.link-embed widget (isWidget=true, is section, but class lacks 'include-note' — covers line 43-44)", () => {- // section.link-embed is a real CKEditor block widget wrapping a <section>.- // isWidget() returns true, element.is("element", "section") is true, but the class- // attribute is "link-embed" which does NOT include "include-note" →- // isIncludeNoteWidget returns false at line 44.+ it("returns null for a selected section.link-embed widget", () => {editor.setData('<section class="link-embed" data-url="https://example.com" data-embed-type="opengraph"></section>');@@ -291,10 +283,7 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverageconst fn = getRelatedElementFn(editor);const viewSelection = editor.editing.view.document.selection;- const result = fn(viewSelection);- // section.link-embed passes isWidget() and is a section, but the class- // does not contain "include-note" → returns null.- expect(result).toBeNull();+ expect(fn(viewSelection)).toBeNull();});it("returns the include-note element when a real include-note widget is selected (full happy path)", () => {@@ -313,7 +302,6 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverageconst fn = getRelatedElementFn(editor);const viewSelection = editor.editing.view.document.selection;- const result = fn(viewSelection);- expect(result).not.toBeNull();+ expect(fn(viewSelection)).not.toBeNull();});});diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.tsindex ccb00bce4d..e21dea1bab 100644--- a/packages/ckeditor5/src/plugins/include_note_toolbar.ts+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.ts@@ -1,5 +1,8 @@import { Plugin, WidgetToolbarRepository, isWidget, type ViewElement } from "ckeditor5";-import IncludeNote, { CONVERT_EMBED_TO_LINK_COMMAND } from "./includenote.js";+import IncludeNote, {+ CONVERT_EMBED_TO_LINK_COMMAND,+ TOGGLE_CAPTION_COMMAND_NAME+} from "./includenote.js";import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";export default class IncludeNoteToolbar extends Plugin {@@ -15,6 +18,7 @@ export default class IncludeNoteToolbar extends Plugin {widgetToolbarRepository.register("includeNote", {items: ["includeNoteBoxSizeDropdown",+ TOGGLE_CAPTION_COMMAND_NAME,CONVERT_EMBED_TO_LINK_COMMAND],balloonClassName: "ck-toolbar-container include-note-toolbar",@@ -25,6 +29,13 @@ export default class IncludeNoteToolbar extends Plugin {return selectedElement;}+ // The toolbar stays on the include while its caption is edited.+ for (const ancestor of selection.getFirstPosition()?.getAncestors() ?? []) {+ if (ancestor.is("element") && isIncludeNoteWidget(ancestor)) {+ return ancestor;+ }+ }+return null;}});@@ -33,15 +44,5 @@ export default class IncludeNoteToolbar extends Plugin {}function isIncludeNoteWidget(element: ViewElement): boolean {- if (!isWidget(element)) {- return false;- }-- if (!element.is("element", "section")) {- return false;- }-- /* v8 ignore next -- isWidget() only matches toWidget()-wrapped elements, which always carry the ck-widget class, so getAttribute("class") is never falsy here */- const classes = element.getAttribute("class") || "";- return typeof classes === "string" && classes.includes("include-note");+ return isWidget(element) && element.hasClass("include-note");}diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.tsindex f1f73e4c72..b343a6048e 100644--- a/packages/ckeditor5/src/plugins/includenote.spec.ts+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts@@ -2,6 +2,7 @@ import {_getModelData as getModelData,_getViewData as getViewData,_setModelData as setModelData,+ Bold,ButtonView,ClassicEditor,Essentials,@@ -20,7 +21,8 @@ import IncludeNote, {BOX_SIZES,COMMAND_NAME,EMBED_ATTACHMENT_LINK_COMMAND,- CONVERT_EMBED_TO_LINK_COMMAND+ CONVERT_EMBED_TO_LINK_COMMAND,+ TOGGLE_CAPTION_COMMAND_NAME} from "./includenote.js";import ReferenceLink from "./referencelink.js";@@ -81,29 +83,22 @@ describe("IncludeNote", () => {// Conversion: upcast / data downcast / editing downcast// ------------------------------------------------------------------------ it("upcasts a <section class=\"include-note\"> into an includeNote model element", () => {- editor.setData(- '<section class="include-note" data-note-id="abc123" data-box-size="medium"></section>'- );-- const element = findIncludeNote(editor);- expect(element).toBeDefined();- expect(element?.getAttribute("noteId")).toBe("abc123");- expect(element?.getAttribute("boxSize")).toBe("medium");- });-- it("data-downcasts an includeNote back to a <section class=\"include-note\"> with data attributes", () => {- insertIncludeNote(editor, "noteX", "full");+ it("loads a <figure> include and a legacy <section>, and saves a <figure>", () => {+ for (const tag of [ "figure", "section" ]) {+ editor.setData(`<${tag} class="include-note" data-note-id="abc123"`+ + ` data-box-size="medium"></${tag}>`);- const data = editor.getData();- expect(data).toContain('class="include-note"');- expect(data).toContain('data-note-id="noteX"');- expect(data).toContain('data-box-size="full"');+ const element = findIncludeNote(editor);+ expect(element?.getAttribute("noteId")).toBe("abc123");+ expect(element?.getAttribute("boxSize")).toBe("medium");+ expect(editor.getData()).toBe("<figure class=\"include-note\" data-note-id=\"abc123\" "+ + "data-box-size=\"medium\"> </figure>");+ }});it("editing-downcasts to a widget and invokes loadIncludedNote when the UIElement renders", () => {editor.setData(- '<section class="include-note" data-note-id="noteY" data-box-size="small"></section>'+ '<figure class="include-note" data-note-id="noteY" data-box-size="small"></figure>');const view = getViewData(editor.editing.view);@@ -129,14 +124,14 @@ describe("IncludeNote", () => {insertIncludeNote(editor, "noteZ", "small");const domRoot = editor.editing.view.getDomRoot();- const section = domRoot?.querySelector("section.include-note");- expect(section?.classList.contains("box-size-small")).toBe(true);+ const figure = domRoot?.querySelector("figure.include-note");+ expect(figure?.classList.contains("box-size-small")).toBe(true);editor.execute(BOX_SIZE_COMMAND_NAME, { value: "full" });- expect(section?.classList.contains("box-size-small")).toBe(false);- expect(section?.classList.contains("box-size-full")).toBe(true);- expect(section?.getAttribute("data-box-size")).toBe("full");+ expect(figure?.classList.contains("box-size-small")).toBe(false);+ expect(figure?.classList.contains("box-size-full")).toBe(true);+ expect(figure?.getAttribute("data-box-size")).toBe("full");});it("re-renders the included note content with the new size on a genuine box-size change", () => {@@ -165,9 +160,9 @@ describe("IncludeNote", () => {});const domRoot = editor.editing.view.getDomRoot();- const section = domRoot?.querySelector("section.include-note");- expect(section?.classList.contains("box-size-medium")).toBe(true);- expect(section?.getAttribute("data-box-size")).toBe("medium");+ const figure = domRoot?.querySelector("figure.include-note");+ expect(figure?.classList.contains("box-size-medium")).toBe(true);+ expect(figure?.getAttribute("data-box-size")).toBe("medium");});it("ignores a boxSize change cleared to an empty value (no new class to add)", () => {@@ -178,10 +173,10 @@ describe("IncludeNote", () => {});const domRoot = editor.editing.view.getDomRoot();- const section = domRoot?.querySelector("section.include-note");+ const figure = domRoot?.querySelector("figure.include-note");// Old class removed, no new class added because the new value is empty.- expect(section?.classList.contains("box-size-small")).toBe(false);- expect(section?.classList.contains("box-size-")).toBe(false);+ expect(figure?.classList.contains("box-size-small")).toBe(false);+ expect(figure?.classList.contains("box-size-")).toBe(false);});// -----------------------------------------------------------------------@@ -443,7 +438,7 @@ describe("IncludeNote", () => {expect(keyStop).toHaveBeenCalled();});- it("does nothing on a mousedown when the wrapper has no enclosing include-note section", () => {+ it("does nothing on a mousedown when the wrapper has no enclosing include", () => {insertIncludeNote(editor, "noteDetached", "small");const domRoot = editor.editing.view.getDomRoot();@@ -454,7 +449,7 @@ describe("IncludeNote", () => {}// Detach the wrapper (which carries the capture-phase mousedown handler) from its- // section so that domElement.closest("section.include-note") returns null. The handler+ // include so that domElement.closest(".include-note") returns null. The handler// still fires because it is bound to the wrapper element itself.const holder = document.createElement("div");document.body.appendChild(holder);@@ -467,7 +462,7 @@ describe("IncludeNote", () => {expect(true).toBe(true);});- it("does nothing on a mousedown when the section is not mapped to a view element", () => {+ it("does nothing on a mousedown when the include is not mapped to a view element", () => {insertIncludeNote(editor, "noteUnmapped", "small");const domRoot = editor.editing.view.getDomRoot();@@ -477,35 +472,35 @@ describe("IncludeNote", () => {return;}- // Move the wrapper into a hand-built section.include-note that the editor's- // DomConverter knows nothing about. closest() then finds this fake section, but+ // Move the wrapper into a hand-built figure.include-note that the editor's+ // DomConverter knows nothing about. closest() then finds this fake include, but// mapDomToView() returns nothing for it, so selectIncludeNoteWidget returns early.- const fakeSection = document.createElement("section");- fakeSection.className = "include-note";- document.body.appendChild(fakeSection);- fakeSection.appendChild(wrapper);+ const fakeFigure = document.createElement("figure");+ fakeFigure.className = "include-note";+ document.body.appendChild(fakeFigure);+ fakeFigure.appendChild(wrapper);wrapper.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));- fakeSection.remove();+ fakeFigure.remove();expect(true).toBe(true);});- it("does nothing on a mousedown when the section view element has no mapped model element", () => {+ it("does nothing on a mousedown when the include's view maps to no model element", () => {insertIncludeNote(editor, "noteNoModel", "small");const domRoot = editor.editing.view.getDomRoot();const wrapper = domRoot?.querySelector("div.include-note-wrapper");- const section = domRoot?.querySelector<HTMLElement>("section.include-note");+ const figure = domRoot?.querySelector<HTMLElement>("figure.include-note");expect(wrapper).not.toBeNull();- expect(section).not.toBeNull();- if (!wrapper || !section) {+ expect(figure).not.toBeNull();+ if (!wrapper || !figure) {return;}// The DOM->view mapping stays intact (mapDomToView succeeds), but we break the// view->model mapping so selectIncludeNoteWidget returns at the !modelElement guard.- const viewElement = editor.editing.view.domConverter.mapDomToView(section);+ const viewElement = editor.editing.view.domConverter.mapDomToView(figure);expect(viewElement).toBeDefined();if (viewElement && viewElement.is("element")) {editor.editing.mapper.unbindViewElement(viewElement);@@ -518,8 +513,8 @@ describe("IncludeNote", () => {it("selects the include that a DOM element is part of, for a context menu opened on it", () => {editor.setData("<p>foo</p>"- + "<section class=\"include-note\" data-note-id=\"noteMenu\" data-box-size=\"small\">"- + "</section>");+ + "<figure class=\"include-note\" data-note-id=\"noteMenu\" data-box-size=\"small\">"+ + "</figure>");const domRoot = editor.editing.view.getDomRoot();const wrapper = domRoot?.querySelector("div.include-note-wrapper");const paragraph = domRoot?.querySelector("p");@@ -542,7 +537,9 @@ describe("IncludeNote", () => {// Exercise the falsy `if (command)` branch in IncludeNoteUI: when the command lookup// returns undefined, the button must still be created (just without the binding).const realGet = editor.commands.get.bind(editor.commands);- const absent: string[] = [ COMMAND_NAME, CONVERT_EMBED_TO_LINK_COMMAND ];+ const absent: string[] = [+ COMMAND_NAME, CONVERT_EMBED_TO_LINK_COMMAND, TOGGLE_CAPTION_COMMAND_NAME+ ];const getSpy = vi.spyOn(editor.commands, "get").mockImplementation((name) => (absent.includes(name) ? undefined : realGet(name)));@@ -552,6 +549,8 @@ describe("IncludeNote", () => {expect(view.label).toBe("Include note");const convert = editor.ui.componentFactory.create(CONVERT_EMBED_TO_LINK_COMMAND);expect((convert as unknown as { label: string }).label).toBe("Convert to link");+ const caption = editor.ui.componentFactory.create(TOGGLE_CAPTION_COMMAND_NAME);+ expect((caption as unknown as { label: string }).label).toBe("Toggle caption on");} finally {getSpy.mockRestore();}@@ -561,8 +560,8 @@ 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>";+ `<figure class="include-note" data-attachment-id="${attachmentId}" data-box-size="small">`+ + "</figure>";let editor: ClassicEditor;let loadIncludedNote: ReturnType<typeof vi.fn>;let loadIncludedAttachment: ReturnType<typeof vi.fn>;@@ -635,17 +634,24 @@ describe("IncludeNote with attachments", () => {expect(loadIncludedAttachment).not.toHaveBeenCalled();expect(loadIncludedNote).not.toHaveBeenCalled();const data = editor.getData();- expect(data).toContain("<section class=\"include-note\" data-box-size=\"small\">");+ expect(data).toContain("<figure class=\"include-note\" data-box-size=\"small\">");expect(data).not.toMatch(/data-(note|attachment)-id/);- editor.model.change((writer) => {- const element = findIncludeNote(editor);- if (element) {- writer.setAttribute("attachmentId", "att1", element);- writer.removeAttribute("uploadFileName", element);- }- });- renderEmbeds();+ const element = findIncludeNote(editor);+ if (!element) {+ throw new Error("Expected the embed.");+ }++ // The two steps of `FileUploadEditing` once the upload ends.+ editor.model.change((writer) => writer.setAttribute("attachmentId", "att1", element));+ expect(wrapper?.querySelector(".include-note-title")?.textContent).toBe("report.pdf");+ expect(loadIncludedAttachment).not.toHaveBeenCalled();++ editor.model.change((writer) => writer.removeAttribute("uploadFileName", element));+ expect(renderEmbeds()?.[0]).toBe(wrapper);+ expect(wrapper?.querySelector(".include-note-title")).toBeNull();+ expect(wrapper?.parentElement?.getAttribute("data-attachment-id")).toBe("att1");+ expect(loadIncludedAttachment).toHaveBeenCalledTimes(1);expect(loadIncludedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");});@@ -687,7 +693,7 @@ describe("IncludeNote with attachments", () => {});it("loads an include that names nothing, as one saved mid-upload, as an empty box", () => {- editor.setData("<section class=\"include-note\" data-box-size=\"small\"></section>");+ editor.setData("<figure class=\"include-note\" data-box-size=\"small\"></figure>");expect(renderEmbeds()).toHaveLength(1);expect(loadIncludedNote).not.toHaveBeenCalled();@@ -787,6 +793,173 @@ describe("IncludeNote with attachments", () => {});});+describe("IncludeNote captions", () => {+ const CAPTIONED = "<figure class=\"include-note\" data-note-id=\"n1\" data-box-size=\"medium\">"+ + "<figcaption>A <strong>bold</strong> caption</figcaption></figure>";+ let editor: ClassicEditor;+ let loadIncludedNote: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ loadIncludedNote = vi.fn();+ installGlobMock({+ getComponentByEl: () => ({ loadIncludedNote })+ });++ editor = await createTestEditor([ Essentials, Paragraph, Bold, Undo, Widget, IncludeNote ]);+ });++ function getCommand() {+ const command = editor.commands.get(TOGGLE_CAPTION_COMMAND_NAME);+ if (!command) {+ throw new Error("Expected the caption command.");+ }+ return command;+ }++ function selectInclude() {+ editor.model.change((writer) => {+ const include = findIncludeNote(editor);+ if (include) {+ writer.setSelection(include, "on");+ }+ });+ }++ /** The caption the editing view renders, after checking that it follows the content. */+ function getRenderedCaption() {+ const figcaption = editor.editing.view.getDomRoot()+ ?.querySelector("figure.include-note > figcaption");+ expect(figcaption?.previousElementSibling?.classList.contains("include-note-wrapper"))+ .toBe(true);+ return figcaption;+ }++ function isSelectionInCaption() {+ const position = editor.model.document.selection.getFirstPosition();+ return !!position?.parent.is("element", "caption");+ }++ it("loads and saves a formatted caption, and renders it editable after the content", () => {+ editor.setData(CAPTIONED);++ expect(getModelData(editor.model, { withoutSelection: true })).toBe(+ "<includeNote boxSize=\"medium\" noteId=\"n1\">"+ + "<caption>A <$text bold=\"true\">bold</$text> caption</caption></includeNote>"+ );+ expect(editor.getData()).toBe(CAPTIONED);+ expect(getRenderedCaption()?.getAttribute("contenteditable")).toBe("true");+ });++ it("toggles a caption on after the content and off again, keeping its text", () => {+ insertIncludeNote(editor, "n1", "medium");+ const command = getCommand();+ expect(command.isEnabled).toBe(true);+ expect(command.value).toBe(false);++ editor.execute(TOGGLE_CAPTION_COMMAND_NAME, { focusCaptionOnShow: true });+ expect(command.value).toBe(true);+ expect(isSelectionInCaption()).toBe(true);+ expect(getRenderedCaption()).not.toBeNull();++ editor.model.change((writer) => {+ const position = editor.model.document.selection.getFirstPosition();+ if (position) {+ writer.insertText("Caption", position);+ }+ });+ editor.execute(TOGGLE_CAPTION_COMMAND_NAME);+ expect(command.value).toBe(false);+ expect(editor.getData()).not.toContain("figcaption");+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("includeNote");++ editor.execute(TOGGLE_CAPTION_COMMAND_NAME);+ expect(editor.getData()).toContain("<figcaption>Caption</figcaption>");+ expect(isSelectionInCaption()).toBe(false);+ });++ it("keeps the rendered content while the caption is toggled and edited", () => {+ insertIncludeNote(editor, "n1", "medium");+ const wrapper = editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper");+ expect(wrapper).not.toBeNull();+ expect(loadIncludedNote).toHaveBeenCalledTimes(1);++ editor.execute(TOGGLE_CAPTION_COMMAND_NAME, { focusCaptionOnShow: true });+ editor.model.change((writer) => {+ const position = editor.model.document.selection.getFirstPosition();+ if (position) {+ writer.insertText("Caption", position);+ }+ });+ editor.execute(TOGGLE_CAPTION_COMMAND_NAME);+ editor.execute(TOGGLE_CAPTION_COMMAND_NAME);++ expect(getRenderedCaption()?.textContent).toBe("Caption");+ expect(editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper"))+ .toBe(wrapper);+ expect(loadIncludedNote).toHaveBeenCalledTimes(1);+ });++ it("is disabled with no include selected and on a Tiny include", () => {+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ expect(getCommand().isEnabled).toBe(false);++ insertIncludeNote(editor, "n1", "tiny");+ expect(getCommand().isEnabled).toBe(false);+ expect(getCommand().value).toBe(false);+ });++ it("labels its toolbar button by whether the caption shows", () => {+ const button = editor.ui.componentFactory.create(TOGGLE_CAPTION_COMMAND_NAME);+ if (!(button instanceof ButtonView)) {+ throw new Error("Expected a button.");+ }+ insertIncludeNote(editor, "n1", "medium");+ expect(button.label).toBe("Toggle caption on");+ expect(button.isOn).toBe(false);++ button.fire("execute");++ expect(button.label).toBe("Toggle caption off");+ expect(button.isOn).toBe(true);+ expect(isSelectionInCaption()).toBe(true);+ });++ it("removes the caption of a Tiny include and restores it on a larger size, undoably", () => {+ editor.setData(CAPTIONED);+ selectInclude();++ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });+ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe("<includeNote boxSize=\"tiny\" noteId=\"n1\"></includeNote>");++ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "small" });+ expect(editor.getData()).toBe(CAPTIONED.replace("medium", "small"));+ expect(getRenderedCaption()).not.toBeNull();++ editor.execute("undo");+ editor.execute("undo");+ expect(editor.getData()).toBe(CAPTIONED);+ });++ it("leaves a caption hidden with the toggle hidden when the include leaves Tiny", () => {+ editor.setData(CAPTIONED);+ selectInclude();++ editor.execute(TOGGLE_CAPTION_COMMAND_NAME);+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });++ expect(editor.getData()).not.toContain("figcaption");+ });++ it("drops the caption of a Tiny include it loads", () => {+ editor.setData(CAPTIONED.replace("medium", "tiny"));++ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe("<includeNote boxSize=\"tiny\" noteId=\"n1\"></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 3891b5b205..089c978c37 100644--- a/packages/ckeditor5/src/plugins/includenote.ts+++ b/packages/ckeditor5/src/plugins/includenote.ts@@ -1,11 +1,21 @@import {ButtonView,Command,+ type DowncastConversionApi,type Editor,+ enableViewPlaceholder,+ IconCaption,IconLink,- type ModelElement,+ type MapperModelToViewPositionEvent,+ ModelElement,+ type ModelNode,+ type ModelDocumentFragment,+ type ModelWriter,+ type PlaceholderableViewElement,Plugin,toWidget,+ toWidgetEditable,+ type ViewEditableElement,type ViewElement,Widget,type Observable@@ -17,6 +27,7 @@ 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 TOGGLE_CAPTION_COMMAND_NAME = 'toggleIncludeNoteCaption';export const BOX_SIZES = [ 'tiny', 'small', 'medium', 'full', 'expandable' ] as const;@@ -131,6 +142,31 @@ class IncludeNoteUI extends Plugin {return buttonView;} );++ editor.ui.componentFactory.add( TOGGLE_CAPTION_COMMAND_NAME, locale => {+ const command = editor.commands.get( TOGGLE_CAPTION_COMMAND_NAME );+ const buttonView = new ButtonView( locale );++ buttonView.set( {+ label: t( 'Toggle caption on' ),+ icon: IconCaption,+ tooltip: true,+ isToggleable: true+ } );++ if ( command ) {+ buttonView.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );+ buttonView.bind( 'label' ).to( command, 'value', value =>+ value ? t( 'Toggle caption off' ) : t( 'Toggle caption on' ) );+ }++ this.listenTo( buttonView, 'execute', () => {+ editor.execute( TOGGLE_CAPTION_COMMAND_NAME, { focusCaptionOnShow: true } );+ editor.editing.view.focus();+ } );++ return buttonView;+ } );}}@@ -139,6 +175,16 @@ class IncludeNoteEditing extends Plugin {return [ Widget ];}+ static get pluginName() {+ return 'IncludeNoteEditing' as const;+ }++ /** The captions that were hidden or that a Tiny box size removed, by include. */+ private readonly savedCaptions = new WeakMap<ModelElement, unknown>();++ /** The includes whose saved caption a Tiny box size removed. */+ private readonly tinyIncludes = new WeakSet<ModelElement>();+init() {this._defineSchema();this._defineConverters();@@ -149,6 +195,26 @@ class IncludeNoteEditing extends Plugin {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 ) );+ commands.add( TOGGLE_CAPTION_COMMAND_NAME, new ToggleIncludeNoteCaptionCommand( editor ) );++ editor.model.document.registerPostFixer( writer => this.removeTinyCaptions( writer ) );+ }++ /** Keeps a copy of `caption`, for `include` to show again. */+ saveCaption( include: ModelElement, caption: ModelElement ) {+ this.savedCaptions.set( include, caption.toJSON() );+ this.tinyIncludes.delete( include );+ }++ /** A copy of the caption last saved for `include`, or `null`. */+ getSavedCaption( include: ModelElement ): ModelElement | null {+ const json = this.savedCaptions.get( include );+ return json ? ModelElement.fromJSON( json ) : null;+ }++ /** A copy of the caption that a Tiny box size removed from `include`, or `null`. */+ takeTinyCaption( include: ModelElement ): ModelElement | null {+ return this.tinyIncludes.delete( include ) ? this.getSavedCaption( include ) : null;}_defineSchema() {@@ -167,11 +233,23 @@ class IncludeNoteEditing extends Plugin {// Allow in places where other blocks are allowed (e.g. directly in the root).allowWhere: '$block'} );++ // `ImageCaptionEditing` and `TableCaptionEditing` share the same `caption` element.+ if ( schema.isRegistered( 'caption' ) ) {+ schema.extend( 'caption', { allowIn: 'includeNote' } );+ } else {+ schema.register( 'caption', {+ allowIn: 'includeNote',+ allowContentOf: '$block',+ isLimit: true+ } );+ }}_defineConverters() {const editor = this.editor;const conversion = editor.conversion;+ const t = editor.t;// <includeNote> convertersconversion.for( 'upcast' ).elementToElement( {@@ -186,16 +264,16 @@ class IncludeNoteEditing extends Plugin {boxSize: viewElement.getAttribute( 'data-box-size' ),} );},+ // Includes saved before captions existed are `<section>` elements.view: {- name: 'section',+ name: /^(?:figure|section)$/,classes: 'include-note'}} );conversion.for( 'dataDowncast' ).elementToElement( {model: 'includeNote',view: ( modelElement, { writer: viewWriter } ) => {- // it would make sense here to downcast to <iframe>, with this even HTML export can support note inclusion- return viewWriter.createContainerElement( 'section', {+ return viewWriter.createContainerElement( 'figure', {class: 'include-note',...getIncludedEntityAttributes( modelElement ),'data-box-size': modelElement.getAttribute( 'boxSize' ),@@ -203,16 +281,12 @@ class IncludeNoteEditing extends Plugin {}} );conversion.for( 'editingDowncast' ).elementToElement( {- // Redraws an uploading embed when its upload sets `attachmentId` and clears- // `uploadFileName`.- model: { name: 'includeNote', attributes: [ 'attachmentId', 'uploadFileName' ] },+ model: 'includeNote',view: ( modelElement, { writer: viewWriter } ) => {const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;- const uploadFileName = modelElement.getAttribute( 'uploadFileName' ) as- string | undefined;- const section = viewWriter.createContainerElement( 'section', {+ const figure = viewWriter.createContainerElement( 'figure', {class: 'include-note box-size-' + boxSize,...getIncludedEntityAttributes( modelElement ),'data-box-size': boxSize@@ -224,24 +298,22 @@ class IncludeNoteEditing extends Plugin {}, function( domDocument ) {const domElement = this.toDomElement( domDocument );- if ( uploadFileName ) {- domElement.append( createUploadTitle( domDocument, uploadFileName ) );- } else {- loadIncludedContent( editor, modelElement, $( domElement ), boxSize );- }-+ showIncludedContent( editor, modelElement, domElement );preventCKEditorHandling( domElement, editor );return domElement;} );- viewWriter.insert( viewWriter.createPositionAt( section, 0 ), includedNoteWrapper );+ viewWriter.insert( viewWriter.createPositionAt( figure, 0 ), includedNoteWrapper );// hasSelectionHandle gives the block widget CKEditor's own drag grip so it moves// atomically, instead of the browser's native drag tearing the embedded note apart.// The label is announced by screen readers; lowercase to match the "image widget" /// "table widget" labels CKEditor gives its own widgets.- return toWidget( section, viewWriter, { label: editor.t('include note widget'), hasSelectionHandle: true } );+ return toWidget( figure, viewWriter, {+ label: editor.t( 'include note widget' ),+ hasSelectionHandle: true+ } );}} );@@ -273,7 +345,99 @@ class IncludeNoteEditing extends Plugin {reloadIncludedNote( editor, viewElement, data.item as ModelElement, newBoxSize );}} );++ // Redraws the content in place when an upload ends. A converter that lists+ // `attributes` also reconverts the include on every change of its children, such as+ // a caption toggle.+ for ( const attribute of [ 'attachmentId', 'uploadFileName' ] ) {+ dispatcher.on( `attribute:${ attribute }:includeNote`, ( _evt, data, api ) => {+ redrawIncludedEntity( editor, data.item as ModelElement, api );+ } );+ }+ } );++ // <caption> converters, for the caption of an include only+ conversion.for( 'upcast' ).elementToElement( {+ view: element => isIncludeNoteCaptionView( element ) ? { name: true } : null,+ model: 'caption'+ } );+ conversion.for( 'dataDowncast' ).elementToElement( {+ model: 'caption',+ view: ( modelElement, { writer: viewWriter } ) => isIncludeNote( modelElement.parent )+ ? viewWriter.createContainerElement( 'figcaption' )+ : null+ } );+ conversion.for( 'editingDowncast' ).elementToElement( {+ model: 'caption',+ view: ( modelElement, { writer: viewWriter } ) => {+ if ( !isIncludeNote( modelElement.parent ) ) {+ return null;+ }++ const figcaption: ViewEditableElement & PlaceholderableViewElement =+ viewWriter.createEditableElement( 'figcaption' );+ figcaption.placeholder = t( 'Enter caption' );+ enableViewPlaceholder( {+ view: editor.editing.view,+ element: figcaption,+ keepOnFocus: true+ } );++ return toWidgetEditable( figcaption, viewWriter, {+ label: t( 'Caption for the included note' )+ } );+ }} );++ // The default mapping places model offset 0 before the content wrapper, which has no model+ // length. The caption goes after it.+ editor.editing.mapper.on<MapperModelToViewPositionEvent>(+ 'modelToViewPosition',+ ( _evt, data ) => {+ const parent = data.modelPosition.parent;+ const viewElement = parent.is( 'element', 'includeNote' )+ ? data.mapper.toViewElement( parent )+ : undefined;+ const wrapperIndex = viewElement ? getWrapperIndex( viewElement ) : null;+ if ( !viewElement || wrapperIndex === null ) {+ return;+ }++ const offset = wrapperIndex + 1 + data.modelPosition.offset;+ data.viewPosition = editor.editing.view.createPositionAt(+ viewElement, Math.min( offset, viewElement.childCount ) );+ }+ );+ }++ /**+ * Removes the caption of every Tiny include that a change touched, keeping a copy for when+ * the include gets a larger box size.+ */+ private removeTinyCaptions( writer: ModelWriter ) {+ const includes = new Set<ModelElement>();+ for ( const change of this.editor.model.document.differ.getChanges() ) {+ if ( change.type === 'attribute' && change.attributeKey === 'boxSize' ) {+ addIncludeNotes( includes, change.range.start.nodeAfter );+ } else if ( change.type === 'insert' && change.name === 'caption' ) {+ addIncludeNotes( includes, change.position.parent );+ } else if ( change.type === 'insert' && change.name !== '$text' ) {+ addIncludeNotes( includes, change.position.nodeAfter );+ }+ }++ let isChanged = false;+ for ( const include of includes ) {+ const caption = getCaption( include );+ if ( caption && include.getAttribute( 'boxSize' ) === 'tiny' ) {+ this.saveCaption( include, caption );+ this.tinyIncludes.add( include );+ writer.remove( caption );+ isChanged = true;+ }+ }++ return isChanged;}}@@ -298,13 +462,28 @@ class InsertIncludeNoteCommand extends Command {class IncludeNoteBoxSizeCommand extends Command {declare value: BoxSizeValue | null;+ /**+ * Sets the box size of the selected include. Tiny takes the caption away, and a larger size+ * shows it again.+ */override execute( options: { value: BoxSizeValue } ) {- const model = this.editor.model;- const includeNoteElement = getSelectedIncludeNote( this.editor );+ const editor = this.editor;+ const includeNoteElement = getSelectedIncludeNote( editor );if ( includeNoteElement ) {- model.change( writer => {+ editor.model.change( writer => {+ const wasTiny = includeNoteElement.getAttribute( 'boxSize' ) === 'tiny';writer.setAttribute( 'boxSize', options.value, includeNoteElement );++ if ( options.value === 'tiny' ) {+ writer.setSelection( includeNoteElement, 'on' );+ } else if ( wasTiny && !getCaption( includeNoteElement ) ) {+ const caption = editor.plugins.get( IncludeNoteEditing )+ .takeTinyCaption( includeNoteElement );+ if ( caption ) {+ writer.append( caption, includeNoteElement );+ }+ }} );}}@@ -317,6 +496,48 @@ class IncludeNoteBoxSizeCommand extends Command {}}+/** Shows or hides the caption of the selected include. A Tiny include has none. */+export class ToggleIncludeNoteCaptionCommand extends Command {+ declare value: boolean;++ override refresh() {+ const include = getSelectedIncludeNote( this.editor );++ this.isEnabled = !!include && include.getAttribute( 'boxSize' ) !== 'tiny'+ && this.editor.model.schema.checkChild( include, 'caption' );+ this.value = !!include && !!getCaption( include );+ }++ /**+ * @param options.focusCaptionOnShow whether a caption that the command shows takes the+ * selection.+ */+ override execute( { focusCaptionOnShow = false }: { focusCaptionOnShow?: boolean } = {} ) {+ const editor = this.editor;+ const include = getSelectedIncludeNote( editor );+ if ( !include ) {+ return;+ }++ const editing = editor.plugins.get( IncludeNoteEditing );+ editor.model.change( writer => {+ const caption = getCaption( include );+ if ( caption ) {+ editing.saveCaption( include, caption );+ writer.setSelection( include, 'on' );+ writer.remove( caption );+ return;+ }++ const shown = editing.getSavedCaption( include ) ?? writer.createElement( 'caption' );+ writer.append( shown, include );+ if ( focusCaptionOnShow ) {+ writer.setSelection( shown, 'in' );+ }+ } );+ }+}+/** Replaces an attachment link with an embed of the attachment, in the same place. */class EmbedAttachmentLinkCommand extends Command {/**@@ -399,9 +620,9 @@ function getSelectedIncludeNote( editor: Editor ) {/** The include whose rendering contains `domElement`, or `null`. */function getIncludeNoteAt( editor: Editor, domElement: Element ) {- const sectionElement = domElement.closest<HTMLElement>( 'section.include-note' );- const viewElement = sectionElement- && editor.editing.view.domConverter.mapDomToView( sectionElement );+ const includeElement = domElement.closest<HTMLElement>( '.include-note' );+ const viewElement = includeElement+ && editor.editing.view.domConverter.mapDomToView( includeElement );if ( !viewElement?.is( 'element' ) ) {return null;}@@ -409,6 +630,53 @@ function getIncludeNoteAt( editor: Editor, domElement: Element ) {return editor.editing.mapper.toModelElement( viewElement ) ?? null;}+function isIncludeNote( node: ModelNode | ModelDocumentFragment | null ): node is ModelElement {+ return !!node?.is( 'element', 'includeNote' );+}++/** The caption of `include`, or `null`. */+function getCaption( include: ModelElement ) {+ for ( const child of include.getChildren() ) {+ if ( child.is( 'element', 'caption' ) ) {+ return child;+ }+ }++ return null;+}++/** Whether `element` is the `<figcaption>` of an include. */+function isIncludeNoteCaptionView( element: ViewElement ) {+ const parent = element.parent;+ return element.name === 'figcaption' && !!parent?.is( 'element' )+ && parent.hasClass( 'include-note' );+}++/** The index of the content wrapper among the children of an include's view, or `null`. */+function getWrapperIndex( viewElement: ViewElement ) {+ for ( const [ index, child ] of Array.from( viewElement.getChildren() ).entries() ) {+ if ( child.is( 'uiElement' ) && child.hasClass( 'include-note-wrapper' ) ) {+ return index;+ }+ }++ return null;+}++/** Adds `node`, when it is an include, and every include inside it to `includes`. */+function addIncludeNotes(+ includes: Set<ModelElement>,+ node: ModelNode | ModelDocumentFragment | null+) {+ if ( isIncludeNote( node ) ) {+ includes.add( node );+ } else if ( node?.is( 'element' ) ) {+ for ( const descendant of node.getChildren() ) {+ addIncludeNotes( includes, descendant );+ }+ }+}+/*** The `data-*` attribute naming what an include shows: an attachment, or a note. An embed whose* upload has not ended names nothing.@@ -437,6 +705,66 @@ function createUploadTitle( domDocument: Document, fileName: string ) {return title;}+/** What each content wrapper shows, so that it is drawn again only when that changes. */+const shownContents = new WeakMap<HTMLElement, string>();++/**+ * Draws what an include shows into its content wrapper: the file name while an upload is under+ * way, then the attachment or note.+ */+function showIncludedContent( editor: Editor, element: ModelElement, wrapper: HTMLElement ) {+ const uploadFileName = element.getAttribute( 'uploadFileName' ) as string | undefined;+ const shown = uploadFileName+ ? `upload:${ uploadFileName }`+ : JSON.stringify( getIncludedEntityAttributes( element ) );+ const previous = shownContents.get( wrapper );+ if ( previous === shown ) {+ return;+ }+ shownContents.set( wrapper, shown );++ if ( uploadFileName ) {+ wrapper.replaceChildren( createUploadTitle( wrapper.ownerDocument, uploadFileName ) );+ return;+ }++ if ( previous?.startsWith( 'upload:' ) ) {+ wrapper.replaceChildren();+ }+ const boxSize = element.getAttribute( 'boxSize' ) as string | undefined;+ loadIncludedContent( editor, element, $( wrapper ), boxSize );+}++/** Updates the `data-*` attribute of an include's view to what it shows, and redraws it. */+function redrawIncludedEntity(+ editor: Editor,+ include: ModelElement,+ conversionApi: DowncastConversionApi+) {+ const viewElement = conversionApi.mapper.toViewElement( include );+ if ( !viewElement ) {+ return;+ }++ const viewWriter = conversionApi.writer;+ viewWriter.removeAttribute( 'data-attachment-id', viewElement );+ viewWriter.removeAttribute( 'data-note-id', viewElement );+ for ( const [ key, value ] of Object.entries( getIncludedEntityAttributes( include ) ) ) {+ viewWriter.setAttribute( key, value, viewElement );+ }++ const wrapper = getWrapperDom( editor, viewElement );+ if ( wrapper ) {+ showIncludedContent( editor, include, wrapper );+ }+}++/** The content wrapper of a rendered include, or `null` before the include is rendered. */+function getWrapperDom( editor: Editor, viewElement: ViewElement ) {+ return editor.editing.view.domConverter.mapViewToDom( viewElement )+ ?.querySelector<HTMLElement>( ':scope > .include-note-wrapper' ) ?? null;+}+/** Has the host render what an include shows into its wrapper. */function loadIncludedContent(editor: Editor,@@ -468,8 +796,7 @@ function loadIncludedContent(* performs that first paint instead. It only does work on a subsequent, genuine box-size change.*/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 wrapperDom = getWrapperDom( editor, viewElement );if ( wrapperDom ) {loadIncludedContent( editor, modelElement, $( wrapperDom ), boxSize );@@ -505,7 +832,7 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {evt.stopPropagation();- // Suppress the browser's native caret on non-interactive areas. The widget's <section> is+ // Suppress the browser's native caret on non-interactive areas. The widget's <figure> is// contenteditable=false inside an editable root, so the default mousedown action drops a caret// next to it that visibly moves as the user clicks around.evt.preventDefault();@@ -578,4 +905,8 @@ declare module 'ckeditor5' {interface PluginsMap {[ IncludeNote.pluginName ]: IncludeNote;}++ interface CommandsMap {+ toggleIncludeNoteCaption: ToggleIncludeNoteCaptionCommand;+ }}diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.cssindex 20bbf614d3..a781074022 100644--- a/packages/share-theme/src/styles/content.css+++ b/packages/share-theme/src/styles/content.css@@ -173,3 +173,16 @@ body.type-webView {max-width: 100%;object-fit: contain;}++/* An include with a caption: the included content, then the caption. */+.ck-content figure.include-note {+ margin: 1em 0;+}++.ck-content .include-note > figcaption {+ margin-top: .5em;+ border-top: 1px solid var(--background-active);+ padding-top: .5em;+ font-size: .9em;+ text-align: center;+}diff --git a/packages/trilium-core/src/services/app_info.spec.ts b/packages/trilium-core/src/services/app_info.spec.tsindex 96c581a619..1d3746e029 100644--- a/packages/trilium-core/src/services/app_info.spec.ts+++ b/packages/trilium-core/src/services/app_info.spec.ts@@ -19,7 +19,7 @@ describe("app_info", () => {it("exposes the fixed sync and clipper protocol versions", () => {// These are protocol constants; bumping them is a deliberate,// breaking change, so they are locked here as a regression guard.- expect(appInfo.syncVersion).toBe(39);+ expect(appInfo.syncVersion).toBe(40);expect(appInfo.clipperProtocolVersion).toBe("1.0");});diff --git a/packages/trilium-core/src/services/app_info.ts b/packages/trilium-core/src/services/app_info.tsindex 70d5251f19..846893bcff 100644--- a/packages/trilium-core/src/services/app_info.ts+++ b/packages/trilium-core/src/services/app_info.ts@@ -3,7 +3,7 @@ import packageJson from "../../package.json" with { type: "json" };import { AppInfo } from "@triliumnext/commons";import { getMaxMigrationVersion } from "../migrations/migrations.js";-const SYNC_VERSION = 39;+const SYNC_VERSION = 40;const CLIPPER_PROTOCOL_VERSION = "1.0";const appInfo: AppInfo = {diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex 2b14e922e0..c178815825 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -566,6 +566,17 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("preserves an include note figure, with or without its caption", () => {+ const start = `<figure class="include-note" data-note-id="i4A5g9iOg9I0"`+ + ` data-box-size="full">`;+ const blank = `${start} </figure>`;+ const captioned = `${start}<figcaption>A <strong>caption</strong></figcaption></figure>`;++ expect(markdownExportService.toMarkdown(blank)).toBe(blank);+ expect(markdownExportService.toMarkdown(`<p>Before</p>${captioned}<p>After</p>`))+ .toBe(`Before\n\n${captioned}\n\nAfter`);+ });+it("exports todo lists properly", () => {const html = trimIndentation/*html*/`\<ul class="todo-list">diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex f7b2cec646..14587aab79 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -61,7 +61,7 @@ function toMarkdown(content: string, options: ToMarkdownOptions = {}) {codeBlockStyle: "fenced",headerlessTables,blankReplacement(_content, node) {- if (node.nodeName === "SECTION" && node.classList.contains("include-note")) {+ if (isIncludeNote(node)) {return node.outerHTML;}@@ -293,8 +293,8 @@ function buildInlineLinkFilter(): Rule {function buildFigureFilter(): Rule {return {filter(node, options) {- return node.nodeName === 'FIGURE'- && node.classList.contains("image");+ return (node.nodeName === "FIGURE" && node.classList.contains("image"))+ || isIncludeNote(node);},replacement(content, node) {return (node as HTMLElement).outerHTML;@@ -302,6 +302,12 @@ function buildFigureFilter(): Rule {};}+/** Whether `node` is an include. Includes saved before captions existed are `<section>`s. */+function isIncludeNote(node: Pick<LinkPreviewNodeLike, "nodeName" | "classList">) {+ return (node.nodeName === "FIGURE" || node.nodeName === "SECTION")+ && node.classList.contains("include-note");+}+/*** Link previews (block `<section class="link-embed">`, inline `<span class="link-mention">`) keep* all their metadata in data attributes on an empty element, so without special handling turndowndiff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 67ffd8b553..4f9e5f0051 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -530,7 +530,7 @@ export function checkImageAttachments(note: BNote, content: string) {{ 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 },- // <section class="include-note" data-attachment-id="{id}">+ // <figure class="include-note" data-attachment-id="{id}">{ pattern: /data-attachment-id="([a-zA-Z0-9_]+)"/g }];@@ -851,7 +851,8 @@ export function findLlmChatLinks(content: string, foundLinks: FoundLink[]) {}function findIncludeNoteLinks(content: string, foundLinks: FoundLink[]) {- const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;+ // Includes saved before captions existed are `<section>` elements.+ const re = /<(?:figure|section) class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;let match;while ((match = re.exec(content))) {diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex c14da41e34..8a7c579295 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -68,6 +68,23 @@ describe("content_renderer", () => {`);});+ it("keeps the caption of an include under its content, except on a Tiny one", () => {+ buildShareNotes([ { id: "subnote1", content: `<p>Foo</p>` } ]);+ const include = (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: include("medium") + include("tiny")+ });++ 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 only the first level of nested includes on the share view (nested include 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 b441743ebb..68f1c13ec7 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -8,7 +8,7 @@ import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumneimport ejs from "ejs";import escapeHtml from "escape-html";import { t } from "i18next";-import { HTMLElement, Options, parse, TextNode } from "node-html-parser";+import { HTMLElement, type Node as ParsedNode, Options, parse, TextNode } from "node-html-parser";import becca from "../becca/becca.js";import type BAttachment from "../becca/entities/battachment.js";@@ -310,13 +310,13 @@ export type CanAccessInclude = (note: SNote) => boolean;export interface ShareRenderOptions {/**- * Keep expanding include-note sections recursively at every depth. Used for static export, which+ * Keep expanding includes recursively at every depth. Used for static export, which* preserves full nesting. When false (the default for the on-screen share view), only the first- * level of inclusion is rendered and deeper include-note sections are replaced with a reference+ * level of inclusion is rendered and deeper includes are replaced with a reference* link.*/expandNestedIncludes?: boolean;- /** Internal: render this note's own include-note sections as reference links instead of expanding. */+ /** Internal: render this note's own includes as reference links instead of expanding. */includesAsReferenceLinks?: boolean;/** Internal: note IDs already rendered on the current include path, used as a recursion cycle guard. */seenNoteIds?: Set<string>;@@ -491,13 +491,18 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptconst seenNoteIds = new Set(options.seenNoteIds);seenNoteIds.add(note.noteId);- for (const includeNoteEl of document.querySelectorAll("section.include-note")) {+ for (const includeNoteEl of document.querySelectorAll(".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);+ const embed = parse(html, parseOpts).childNodes;+ if (attachment && !asLink && isImageAttachmentRole(attachment.role)) {+ replaceIncludeContent(includeNoteEl, embed);+ } else {+ includeNoteEl.replaceWith(...embed);+ }continue;}@@ -529,7 +534,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptconst includedDocument = parse(includedResult.content, parseOpts).childNodes;if (includedDocument) {- includeNoteEl.replaceWith(...includedDocument);+ replaceIncludeContent(includeNoteEl, includedDocument);}}@@ -578,6 +583,21 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt** @param asLink renders a picture as a link too, for an embed below the first level of inclusion.*/+/**+ * Puts `content` in place of an include. An include with a caption stays a `<figure>`, holding+ * `content` and then the caption.+ */+function replaceIncludeContent(includeNoteEl: HTMLElement, content: ParsedNode[]) {+ const caption = includeNoteEl.getAttribute("data-box-size") !== "tiny"+ && includeNoteEl.childNodes.find((child) =>+ child instanceof HTMLElement && child.tagName === "FIGCAPTION");+ if (caption) {+ includeNoteEl.set_content([ ...content, caption ]);+ } else {+ includeNoteEl.replaceWith(...content);+ }+}+function renderAttachmentEmbed(attachmentId: string,attachment: BAttachment | SAttachment,