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: port the include note component to Preact
Adorian Doran9326daecc0a6
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex bf67139f73..3a7b05f629 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1594,28 +1594,12 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tflex-grow: 1;}-.include-note-toggle,-.include-note-open,-.include-note-fullscreen,-.include-note-menu {- background: none;- border: none;- padding: 2px;- cursor: pointer;- font-size: 1.2em;- color: var(--muted-text-color);- transition: transform 0.2s ease;- display: flex;- align-items: center;- justify-content: center;+.include-note-title-row > .icon-action {flex-shrink: 0;}-.include-note-toggle:hover,-.include-note-open:hover,-.include-note-fullscreen:hover,-.include-note-menu:hover {- color: var(--main-link-color);+.include-note-toggle {+ transition: transform 0.2s ease;}.include-note-toggle.expanded {diff --git a/apps/client/src/widgets/react/ActionButton.tsx b/apps/client/src/widgets/react/ActionButton.tsxindex 459ca575e2..fe31672739 100644--- a/apps/client/src/widgets/react/ActionButton.tsx+++ b/apps/client/src/widgets/react/ActionButton.tsx@@ -8,7 +8,10 @@ import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_dimport { isMobile } from "../../services/utils";import { useStaticTooltip } from "./hooks";-export interface ActionButtonProps extends Pick<HTMLAttributes<HTMLButtonElement>, "onClick" | "onAuxClick" | "onContextMenu" | "onBlur" | "style"> {+export interface ActionButtonProps extends Pick<+ HTMLAttributes<HTMLButtonElement>,+ "onClick" | "onAuxClick" | "onContextMenu" | "onBlur" | "style" | "aria-expanded"+> {text: string;titlePosition?: "top" | "right" | "bottom" | "left";/** Extra class applied to the tooltip popup (e.g. `tooltip-top` to raise its z-index above modals). */diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex f35f59e810..4e4a84851a 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -39,7 +39,8 @@ import {loadIncludedAttachment,loadIncludedNote,refreshIncludedNote,- setupImageOpening+ setupImageOpening,+ watchIncludedNotes} from "./utils";/**@@ -55,6 +56,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextconst contentNoteIdRef = useRef<string>();const pendingAttachmentChangesRef = useRef<PendingAttachmentChanges>();const watchdogRef = useRef<EditorWatchdog>(null);+ const stopWatchingIncludesRef = useRef<() => void>();const editorApiRef = useRef<CKEditorApi>(null);/** The open icon picker request and its balloon container, or `null` when none is open. */const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerOpts & { container: HTMLElement } | null>(null);@@ -289,6 +291,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextrefreshIncludedNote(containerRef.current, noteId);});+ useEffect(() => () => stopWatchingIncludesRef.current?.(), []);+useTriliumEvent("entitiesReloaded", ({ loadResults }) => {const editor = watchdogRef.current?.editor as CKTextEditor | null | undefined;if (editor && note) {@@ -530,6 +534,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextonEditorInitialized={(editor) => {if (containerRef.current) {setupImageOpening(containerRef.current, false);+ stopWatchingIncludesRef.current?.();+ stopWatchingIncludesRef.current = watchIncludedNotes(containerRef.current);}editor.plugins.get("FileUploadEditing")diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx b/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsxnew file mode 100644index 0000000000..2bd9a6599d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx@@ -0,0 +1,244 @@+import { Tooltip } from "bootstrap";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const {+ openTabWithNoteWithHoisting,+ openContextMenu,+ disposeInteractiveContent+} = vi.hoisted(() => ({+ openTabWithNoteWithHoisting: vi.fn(),+ openContextMenu: vi.fn(),+ disposeInteractiveContent: vi.fn()+}));++vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));+vi.mock("../../../components/app_context", () => ({+ default: { tabManager: { openTabWithNoteWithHoisting } }+}));+vi.mock("../../../menus/link_context_menu", () => ({ default: { openContextMenu } }));+vi.mock("../../../services/content_renderer", () => ({ default: { disposeInteractiveContent } }));++import IncludeNote, { type IncludeNoteProps } from "./IncludeNote";++const ATTACHMENT_SCOPE = { viewMode: "attachments", attachmentId: "att1" } as const;++let container: HTMLElement;++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement("div");+ document.body.appendChild(container);+});++afterEach(() => {+ act(() => render(null, container));+ container.remove();+ for (const tooltip of document.querySelectorAll(".tooltip")) {+ tooltip.remove();+ }+});++function element(html: string) {+ const template = document.createElement("template");+ template.innerHTML = html;+ const first = template.content.firstElementChild;+ if (!(first instanceof HTMLElement)) {+ throw new Error(`Expected an element in: ${html}`);+ }+ return first;+}++function renderBox(props: Partial<IncludeNoteProps> = {}) {+ const boxProps: IncludeNoteProps = {+ title: element(`<span><a href="#root/noteA">Note A</a></span>`),+ content: element(`<div class="rendered-content"><p>body</p></div>`),+ contentType: "text",+ notePath: "noteA",+ ...props+ };+ act(() => render(<IncludeNote {...boxProps} />, container));+ return boxProps;+}++/** The include-note-* class of each element in the title row, in order. */+function titleRow() {+ return [ ...container.querySelectorAll(".include-note-title-row > *") ]+ .map((child) => [ ...child.classList ].find((name) => name.startsWith("include-note-")));+}++function button(className: string) {+ const found = container.querySelector<HTMLButtonElement>(`button.${className}`);+ if (!found) {+ throw new Error(`Expected a button.${className}.`);+ }+ return found;+}++function contentBox() {+ const found = container.querySelector<HTMLElement>(".include-note-content");+ if (!found) {+ throw new Error("Expected the content box.");+ }+ return found;+}++function tooltipOf(target: HTMLElement) {+ const tooltip = Tooltip.getInstance(target);+ act(() => tooltip?.show());+ const text = document.querySelector(".tooltip-inner")?.textContent;+ act(() => tooltip?.hide());+ return text;+}++/** Clicks `target` and tells whether the click was kept from what surrounds the box. */+function click(target: HTMLElement) {+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });+ const stopPropagation = vi.spyOn(event, "stopPropagation");+ act(() => {+ target.dispatchEvent(event);+ });+ return { event, isStopped: stopPropagation.mock.calls.length > 0 };+}++describe("IncludeNote", () => {+ it("lays out the title row for each box size", () => {+ const plain = [ "title", "open", "menu" ];+ const withFullscreen = [ "title", "open", "fullscreen", "menu" ];+ const layouts: [ string | undefined, boolean, string[] ][] = [+ [ undefined, false, plain ],+ [ "small", true, plain ],+ [ "medium", false, plain ],+ [ "medium", true, withFullscreen ],+ [ "full", true, withFullscreen ],+ [ "expandable", true, [ "toggle", "title", "open", "menu" ] ]+ ];++ for (const [ boxSize, isFullscreenOffered, expected ] of layouts) {+ act(() => render(null, container));+ renderBox({ boxSize, isFullscreenOffered });+ expect(titleRow(), `${boxSize} ${isFullscreenOffered}`)+ .toEqual(expected.map((name) => `include-note-${name}`));+ }+ });++ it("shows its title and content, and swaps them on a new render", () => {+ const titleChildren = () => [+ ...container.querySelector("h4.include-note-title")?.childNodes ?? []+ ];+ const first = renderBox({ contentType: "pdf" });+ const box = contentBox();+ expect(titleChildren()).toEqual([ first.title ]);+ expect(box.className).toBe("include-note-content type-pdf");+ expect(first.content.parentElement).toBe(box);++ const second = renderBox({ contentType: "image" });+ expect(titleChildren()).toEqual([ second.title ]);+ expect(contentBox()).toBe(box);+ expect(box.className).toBe("include-note-content type-image");+ expect([ ...box.children ]).toEqual([ second.content ]);+ expect(first.content.isConnected).toBe(false);+ expect(disposeInteractiveContent).toHaveBeenCalledOnce();+ expect(disposeInteractiveContent.mock.calls[0][0][0]).toBe(first.content);+ });++ it("disposes its content when unmounted", () => {+ const { content } = renderBox();++ act(() => render(null, container));++ expect(content.isConnected).toBe(false);+ expect(disposeInteractiveContent.mock.calls.map(([ $content ]) => $content[0]))+ .toEqual([ content ]);+ });++ it("keeps the content of an expandable box hidden until its toggle opens it", () => {+ renderBox({ boxSize: "expandable" });+ const toggle = button("include-note-toggle");+ expect(contentBox().hidden).toBe(true);+ expect(toggle.getAttribute("aria-expanded")).toBe("false");+ expect(Tooltip.getInstance(toggle)).toBeNull();++ expect(click(toggle).isStopped).toBe(true);+ expect(contentBox().hidden).toBe(false);+ expect(toggle.getAttribute("aria-expanded")).toBe("true");+ expect(toggle.classList.contains("expanded")).toBe(true);++ click(toggle);+ expect(contentBox().hidden).toBe(true);+ expect(toggle.classList.contains("expanded")).toBe(false);++ act(() => render(null, container));+ renderBox({ boxSize: "full" });+ expect(contentBox().hidden).toBe(false);+ });++ it("opens the note in a new tab, and its context menu, from the title row", () => {+ renderBox({ notePath: "owner", viewScope: ATTACHMENT_SCOPE });+ const open = button("include-note-open");+ const menu = button("include-note-menu");+ expect(open.className).toContain("bx-link-external");+ expect(menu.className).toContain("bx-dots-vertical-rounded");+ expect(tooltipOf(open)).toBe("common.open_in_new_tab");+ expect(tooltipOf(menu)).toBe("common.more_actions");++ expect(click(open).isStopped).toBe(true);+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledWith("owner", {+ viewScope: ATTACHMENT_SCOPE,+ activate: true,+ placement: "afterCurrent"+ });++ const { event, isStopped } = click(menu);+ expect(isStopped).toBe(true);+ expect(openContextMenu).toHaveBeenCalledWith("owner", event, ATTACHMENT_SCOPE);+ });++ it("gives its content the screen, and takes it back from the overlay button", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const exitFullscreen = vi.fn<() => Promise<void>>(async () => {});+ Object.defineProperty(document, "exitFullscreen", {+ value: exitFullscreen,+ configurable: true+ });+ renderBox({ boxSize: "medium", isFullscreenOffered: true });+ const box = contentBox();+ box.requestFullscreen = vi.fn(async () => {});++ const fullscreen = button("include-note-fullscreen");+ expect(fullscreen.className).toContain("bx-fullscreen");+ expect(tooltipOf(fullscreen)).toBe("common.fullscreen");+ expect(click(fullscreen).isStopped).toBe(true);+ expect(box.requestFullscreen).toHaveBeenCalledOnce();++ const group = box.querySelector<HTMLElement>(+ ":scope > .include-note-fullscreen-controls > .tn-overlay-control-group"+ );+ const exit = group?.querySelector("button");+ expect(group?.classList.contains("include-note-exit-fullscreen")).toBe(true);+ expect(group?.dataset.placement).toBe("top-end");+ expect(exit?.textContent).toBe("common.exit_fullscreen");+ expect(exit?.querySelector(".bx.bx-exit")).not.toBeNull();+ if (!exit) return;+ expect(click(exit).isStopped).toBe(true);+ expect(exitFullscreen).toHaveBeenCalledOnce();++ // Refused requests are logged rather than left unhandled.+ box.requestFullscreen = vi.fn(async () => {+ throw new Error("Denied");+ });+ exitFullscreen.mockRejectedValueOnce(new Error("Not in fullscreen"));+ click(fullscreen);+ click(exit);+ await vi.waitFor(() => expect(warn).toHaveBeenCalledTimes(2));++ warn.mockRestore();+ Reflect.deleteProperty(document, "exitFullscreen");+ });++ it("leaves the fullscreen controls out of a box that offers no fullscreen", () => {+ renderBox({ boxSize: "full" });+ expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx b/apps/client/src/widgets/type_widgets/text/IncludeNote.tsxnew file mode 100644index 0000000000..de31689706--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx@@ -0,0 +1,127 @@+import clsx from "clsx";+import { useLayoutEffect, useRef, useState } from "preact/hooks";++import appContext from "../../../components/app_context";+import linkContextMenu from "../../../menus/link_context_menu";+import content_renderer from "../../../services/content_renderer";+import { t } from "../../../services/i18n";+import type { ViewScope } from "../../../services/link";+import ActionButton from "../../react/ActionButton";+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";++export interface IncludeNoteProps {+ boxSize?: string;+ /** The link to the included note or attachment, shown as the title. */+ title: HTMLElement;+ /** The rendered note or attachment. */+ content: HTMLElement;+ contentType: string;+ /** The note opened by the buttons in the title row. */+ notePath: string;+ viewScope?: ViewScope;+ /** Whether a medium or full box offers to show its content in fullscreen. */+ isFullscreenOffered?: boolean;+}++/** The title row and the content of an included note or embedded attachment. */+export default function IncludeNote({+ boxSize, title, content, contentType, notePath, viewScope, isFullscreenOffered+}: IncludeNoteProps) {+ const titleRef = useRef<HTMLHeadingElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);+ const [ isExpanded, setIsExpanded ] = useState(false);+ const isExpandable = boxSize === "expandable";+ const hasFullscreen = !!isFullscreenOffered && (boxSize === "medium" || boxSize === "full");++ useLayoutEffect(() => {+ titleRef.current?.replaceChildren(title);+ }, [ title ]);++ useLayoutEffect(() => {+ contentRef.current?.append(content);+ return () => {+ content_renderer.disposeInteractiveContent($(content));+ content.remove();+ };+ }, [ content ]);++ return (+ <>+ <div className="include-note-title-row">+ {isExpandable && (+ <ActionButton+ className={clsx("include-note-toggle", isExpanded && "expanded")}+ icon="bx bx-chevron-right"+ text=""+ aria-expanded={isExpanded}+ onClick={(e) => {+ e.stopPropagation();+ setIsExpanded(!isExpanded);+ }}+ />+ )}+ <h4 ref={titleRef} className="include-note-title" />+ <ActionButton+ className="include-note-open"+ icon="bx bx-link-external"+ text={t("common.open_in_new_tab")}+ onClick={(e) => {+ e.stopPropagation();+ void appContext.tabManager.openTabWithNoteWithHoisting(notePath, {+ viewScope,+ activate: true,+ placement: "afterCurrent"+ });+ }}+ />+ {hasFullscreen && (+ <ActionButton+ className="include-note-fullscreen"+ icon="bx bx-fullscreen"+ text={t("common.fullscreen")}+ onClick={(e) => {+ e.stopPropagation();+ contentRef.current?.requestFullscreen().catch((error: unknown) => {+ console.warn("Could not show the include in fullscreen:", error);+ });+ }}+ />+ )}+ <ActionButton+ className="include-note-menu"+ icon="bx bx-dots-vertical-rounded"+ text={t("common.more_actions")}+ onClick={(e) => {+ e.stopPropagation();+ void linkContextMenu.openContextMenu(notePath, e, viewScope);+ }}+ />+ </div>+ <div+ ref={contentRef}+ className={`include-note-content type-${contentType}`}+ hidden={isExpandable && !isExpanded}+ >+ {hasFullscreen && (+ <div className="include-note-fullscreen-controls">+ <OverlayControlGroup+ placement="top-end"+ className="include-note-exit-fullscreen"+ >+ <OverlayControlButton+ icon="bx-exit"+ text={t("common.exit_fullscreen")}+ onClick={(e) => {+ e.stopPropagation();+ document.exitFullscreen().catch((error: unknown) => {+ console.warn("Could not leave fullscreen:", error);+ });+ }}+ />+ </OverlayControlGroup>+ </div>+ )}+ </div>+ </>+ );+}diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 94001ff9d9..387a78ffbb 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@ -33,6 +33,15 @@ import ReadOnlyText from "./ReadOnlyText";// Imported by ReadOnlyText only for its content styles; irrelevant (and heavy) in happy-dom.vi.mock("@triliumnext/ckeditor5", () => ({}));+const { watchIncludedNotes, stopWatchingIncludes } = vi.hoisted(() => {+ const stop = vi.fn();+ return { watchIncludedNotes: vi.fn(() => stop), stopWatchingIncludes: stop };+});+vi.mock("./utils", async (importOriginal) => ({+ ...await importOriginal<typeof import("./utils")>(),+ watchIncludedNotes+}));+vi.stubGlobal("logError", vi.fn());vi.stubGlobal("logInfo", vi.fn());@@ -270,3 +279,22 @@ describe("ReadOnlyText text direction", () => {expect((await mountWithLanguage(undefined))?.getAttribute("dir")).toBe("ltr");});});++describe("ReadOnlyText included notes", () => {+ it("watches its content for include boxes until it unmounts", async () => {+ watchIncludedNotes.mockClear();+ stopWatchingIncludes.mockClear();+ const harness = setupHarness({ isVisible: true });++ await harness.mount();++ const content = harness.container.querySelector(".note-detail-readonly-text-content");+ expect(content).not.toBeNull();+ expect(watchIncludedNotes.mock.calls).toEqual([ [ content ] ]);+ expect(stopWatchingIncludes).not.toHaveBeenCalled();++ await act(async () => render(null, harness.container));+ harness.container.remove();+ expect(stopWatchingIncludes).toHaveBeenCalledOnce();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 50f006481d..b5cee427e5 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -26,7 +26,8 @@ import {loadIncludedAttachment,loadIncludedNote,refreshIncludedNote,- setupImageOpening+ setupImageOpening,+ watchIncludedNotes} from "./utils";export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent, isVisible }: TypeWidgetProps) {@@ -124,6 +125,11 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: esetupImageOpening(container, true);}, [ html, ntxId, contentRef ]);+ useEffect(() => {+ if (!contentRef.current) return;+ return watchIncludedNotes(contentRef.current);+ }, [ contentRef ]);+// React to included note changes.useTriliumEvent("refreshIncludedNote", ({ noteId }) => {if (!contentRef.current) return;diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex ef321cf934..2f1aef56a6 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -1,5 +1,5 @@import type { VNode } from "preact";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";@@ -10,289 +10,219 @@ vi.mock("../../../services/froca", () => ({vi.mock("../../../services/link", () => ({default: { createLink: vi.fn() }}));-vi.mock("../../../services/content_renderer", async () => {- const { render } = await import("preact");- return {- default: {- getRenderedContent: vi.fn(),- disposeInteractiveContent: vi.fn(),- mountInteractiveWidget: vi.fn(async (vnode: VNode, container: HTMLElement) => {- render(vnode, container);- })- }- };-});-vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));-const { openTabWithNoteWithHoisting, openContextMenu } = vi.hoisted(() => ({- openTabWithNoteWithHoisting: vi.fn(),- openContextMenu: vi.fn()-}));-vi.mock("../../../components/app_context", () => ({- default: { tabManager: { openTabWithNoteWithHoisting } }+vi.mock("../../../services/content_renderer", () => ({+ default: {+ getRenderedContent: vi.fn(),+ disposeInteractiveContent: vi.fn(),+ mountInteractiveWidget: vi.fn()+ }}));-vi.mock("../../../menus/link_context_menu", () => ({ default: { openContextMenu } }));+vi.mock("./IncludeNote", () => ({ default: () => null }));import content_renderer from "../../../services/content_renderer";import froca from "../../../services/froca";import link from "../../../services/link";-import { getAttachmentHref, loadIncludedAttachment, loadIncludedNote } from "./utils";+import IncludeNote, { type IncludeNoteProps } from "./IncludeNote";+import {+ getAttachmentHref,+ loadIncludedAttachment,+ loadIncludedNote,+ watchIncludedNotes+} from "./utils";const note = { noteId: "noteY" } as unknown as FNote;+const attachment = { attachmentId: "att1", ownerId: "owner" } as unknown as FAttachment;+const ATTACHMENT_SCOPE = { viewMode: "attachments", attachmentId: "att1" };++let title: HTMLElement;+let content: HTMLElement;++beforeEach(() => {+ vi.clearAllMocks();+ title = document.createElement("span");+ content = document.createElement("div");+ vi.mocked(froca.getNote).mockResolvedValue(note);+ vi.mocked(froca.getAttachment).mockResolvedValue(attachment);+ vi.mocked(link.createLink).mockResolvedValue($(title));+ vi.mocked(content_renderer.getRenderedContent)+ .mockResolvedValue({ $renderedContent: $(content), type: "pdf" } as never);+});-describe("loadIncludedNote", () => {- beforeEach(() => {- vi.mocked(froca.getNote).mockResolvedValue(note);- vi.mocked(link.createLink).mockResolvedValue($('<span class="link"><a href="#">noteY</a></span>'));- vi.mocked(content_renderer.getRenderedContent).mockResolvedValue({ $renderedContent: $("<p>body</p>"), type: "text" } as never);- vi.mocked(content_renderer.disposeInteractiveContent).mockReset();- });-- it("reuses the wrapper element without nesting a second one (editing-view path)", async () => {- // The editing-view downcast hands us the `.include-note-wrapper` element itself.- const $el = $('<div class="include-note-wrapper">');-- await loadIncludedNote("noteY", $el, "small");-- const wrappers = $el.find(".include-note-wrapper");- expect(wrappers.length).toBe(0);- expect($el.children(".include-note-title-row").children(".include-note-title").length)- .toBe(1);- expect($el.children(".include-note-content").length).toBe(1);- });-- it("builds a single wrapper inside the section (read-only / refresh path)", async () => {- // The read-only and refresh paths hand us the outer `section.include-note`.- const $el = $('<section class="include-note" data-note-id="noteY">');-- await loadIncludedNote("noteY", $el, "small");-- const wrappers = $el.find(".include-note-wrapper");- expect(wrappers.length).toBe(1);- expect(wrappers.children(".include-note-title-row").children(".include-note-title").length)- .toBe(1);- expect(wrappers.children(".include-note-content").length).toBe(1);- });+/** The include box mounted last, and the element it was mounted in. */+function lastMount() {+ const call = vi.mocked(content_renderer.mountInteractiveWidget).mock.lastCall;+ if (!call) {+ throw new Error("Expected a mounted include box.");+ }+ const vnode = call[0] as VNode<IncludeNoteProps>;+ return { type: vnode.type, props: vnode.props, container: call[1] };+}- it("builds an expandable include (toggle) and degrades the note's own includes to reference links", async () => {- const $el = $('<div class="include-note-wrapper">');+function createWrapper() {+ const wrapper = document.createElement("div");+ wrapper.className = "include-note-wrapper";+ return wrapper;+}- await loadIncludedNote("noteY", $el, "expandable");+describe("loadIncludedNote", () => {+ it("mounts a box with the note, its own includes reduced to reference links", async () => {+ const wrapper = createWrapper();- // The expandable branch adds a title row with a toggle button.- expect($el.children(".include-note-title-row").length).toBe(1);- expect($el.find("button.include-note-toggle").length).toBe(1);- // The included note is rendered with its own includes reduced to reference links.- expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });- });+ await loadIncludedNote("noteY", $(wrapper), "medium");- it("offers no fullscreen button at any box size", async () => {- for (const boxSize of [ "small", "medium", "full", "expandable" ]) {- const $el = $('<div class="include-note-wrapper">');- await loadIncludedNote("noteY", $el, boxSize);- expect($el.find(".include-note-fullscreen, .include-note-fullscreen-controls"))- .toHaveLength(0);- }+ expect(link.createLink).toHaveBeenCalledWith("noteY", {+ showTooltip: false,+ showNoteIcon: true+ });+ expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note, {+ interactive: true,+ includesAsReferenceLinks: true,+ mediaEnvironment: "embedded"+ });+ const mount = lastMount();+ expect(mount.type).toBe(IncludeNote);+ expect(mount.container).toBe(wrapper);+ expect(mount.props).toEqual({+ boxSize: "medium",+ title,+ content,+ contentType: "pdf",+ notePath: "noteY"+ });});- it("disposes interactive content of a previous render before replacing it", async () => {- const $el = $('<div class="include-note-wrapper">');+ it("leaves the box alone for a note that no longer exists", async () => {+ vi.mocked(froca.getNote).mockResolvedValue(null);- await loadIncludedNote("noteY", $el, "small");+ await loadIncludedNote("noteY", $(createWrapper()), "small");- expect(content_renderer.disposeInteractiveContent).toHaveBeenCalledWith($el);+ expect(link.createLink).not.toHaveBeenCalled();+ expect(content_renderer.mountInteractiveWidget).not.toHaveBeenCalled();});});describe("loadIncludedAttachment", () => {- const attachment = {- attachmentId: "att1",- ownerId: "owner",- title: "report.pdf"- } as unknown as FAttachment;-- beforeEach(() => {- vi.mocked(froca.getAttachment).mockResolvedValue(attachment);- vi.mocked(link.createLink).mockResolvedValue($('<span><a href="#">report.pdf</a></span>'));- vi.mocked(content_renderer.getRenderedContent)- .mockResolvedValue({ $renderedContent: $("<p>body</p>"), type: "pdf" } as never);- });-- it("fills the box with the attachment, under a title linking to it", async () => {- const $el = $('<div class="include-note-wrapper">');+ it("mounts a box with the attachment, opened in its note and offered fullscreen", async () => {+ const wrapper = createWrapper();- await loadIncludedAttachment("att1", $el, "expandable");+ await loadIncludedAttachment("att1", $(wrapper), "full");expect(froca.getAttachment).toHaveBeenCalledWith("att1", true);expect(link.createLink).toHaveBeenCalledWith("owner", {showTooltip: false,showNoteIcon: true,- viewScope: { viewMode: "attachments", attachmentId: "att1" }+ viewScope: ATTACHMENT_SCOPE});expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(attachment, { interactive: true, mediaEnvironment: "embedded" });- expect($el.find("button.include-note-toggle").length).toBe(1);- expect($el.find(".include-note-content.type-pdf").text()).toBe("body");- });-- it("offers fullscreen from the end of a medium or full box's title row", async () => {- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- // The read-only path reads the box size from the section rather than taking it.- const boxes: [ JQuery<HTMLElement>, string | undefined ][] = [- [ $('<div class="include-note-wrapper">'), "medium" ],- [ $('<section class="include-note" data-box-size="full">'), undefined ]- ];-- for (const [ $el, boxSize ] of boxes) {- await loadIncludedAttachment("att1", $el, boxSize);-- const $row = $el.find(".include-note-title-row");- const button = $row.children("button.include-note-fullscreen.bx-fullscreen")[0];- expect($row.children().map((_, child) => child.className).get()).toEqual([- "include-note-title",- "include-note-open bx bx-link-external",- "include-note-fullscreen bx bx-fullscreen",- "include-note-menu bx bx-dots-vertical-rounded"- ]);- expect(button.title).toBe("common.fullscreen");-- const content = $el.find(".include-note-content")[0];- content.requestFullscreen = vi.fn(async () => {});- const click = new MouseEvent("click", { bubbles: true });- const stopPropagation = vi.spyOn(click, "stopPropagation");- button.dispatchEvent(click);- expect(content.requestFullscreen).toHaveBeenCalledOnce();- expect(stopPropagation).toHaveBeenCalled();- }-- // A refused request is logged rather than left unhandled.- const content = boxes[1][0].find(".include-note-content")[0];- content.requestFullscreen = vi.fn(async () => {- throw new Error("Denied");- });- boxes[1][0].find("button.include-note-fullscreen")[0].click();- await vi.waitFor(() => expect(warn).toHaveBeenCalled());- warn.mockRestore();-- for (const boxSize of [ "small", "expandable" ]) {- const $el = $('<div class="include-note-wrapper">');- await loadIncludedAttachment("att1", $el, boxSize);- expect($el.find(".include-note-fullscreen, .include-note-fullscreen-controls"))- .toHaveLength(0);- }- });-- it("puts a labeled button leaving fullscreen over the top end of the content", async () => {- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- const exitFullscreen = vi.fn<() => Promise<void>>(async () => {});- Object.defineProperty(document, "exitFullscreen", {- value: exitFullscreen,- configurable: true+ const mount = lastMount();+ expect(mount.type).toBe(IncludeNote);+ expect(mount.container).toBe(wrapper);+ expect(mount.props).toEqual({+ boxSize: "full",+ title,+ content,+ contentType: "pdf",+ notePath: "owner",+ viewScope: ATTACHMENT_SCOPE,+ isFullscreenOffered: true});- const $el = $('<div class="include-note-wrapper">');-- await loadIncludedAttachment("att1", $el, "full");-- const controls = $el.children(".include-note-content")[0].firstElementChild;- const group = controls?.querySelector<HTMLElement>(".tn-overlay-control-group");- const button = group?.querySelector("button");- expect(controls?.className).toBe("include-note-fullscreen-controls");- expect(group?.className).toContain("include-note-exit-fullscreen");- expect(group?.dataset.placement).toBe("top-end");- expect(button?.textContent).toBe("common.exit_fullscreen");- expect(button?.querySelector(".bx.bx-exit")).not.toBeNull();-- const click = new MouseEvent("click", { bubbles: true });- const stopPropagation = vi.spyOn(click, "stopPropagation");- button?.dispatchEvent(click);- expect(exitFullscreen).toHaveBeenCalledOnce();- expect(stopPropagation).toHaveBeenCalled();-- // A refused request is logged rather than left unhandled.- exitFullscreen.mockRejectedValueOnce(new Error("Not in fullscreen"));- button?.click();- await vi.waitFor(() => expect(warn).toHaveBeenCalled());-- warn.mockRestore();- Reflect.deleteProperty(document, "exitFullscreen");});it("leaves the box alone for a deleted attachment", async () => {vi.mocked(froca.getAttachment).mockResolvedValue(null);- vi.mocked(link.createLink).mockClear();- const $el = $('<div class="include-note-wrapper"><span>kept</span></div>');- await loadIncludedAttachment("att1", $el, "small");+ await loadIncludedAttachment("att1", $(createWrapper()), "small");expect(link.createLink).not.toHaveBeenCalled();- expect($el.text()).toBe("kept");+ expect(content_renderer.mountInteractiveWidget).not.toHaveBeenCalled();+ });+});++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 = " ";++ await loadIncludedNote("noteY", $(section));++ const { container, props } = lastMount();+ expect([ ...section.childNodes ]).toEqual([ container ]);+ 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");+ 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 () => {+ const section = document.createElement("section");+ section.className = "include-note ck-widget";+ section.dataset.boxSize = "full";+ const wrapper = createWrapper();+ const typeAround = document.createElement("div");+ section.append(wrapper, typeAround);++ await loadIncludedAttachment("att1", $(section));++ expect(lastMount().container).toBe(wrapper);+ expect(lastMount().props.boxSize).toBe("full");+ expect([ ...section.children ]).toEqual([ wrapper, typeAround ]);});});-describe("the buttons after the title of an include", () => {- const attachmentScope = { viewMode: "attachments", attachmentId: "att1" };+describe("watchIncludedNotes", () => {+ let container: HTMLElement;beforeEach(() => {- openTabWithNoteWithHoisting.mockClear();- openContextMenu.mockClear();- vi.mocked(froca.getNote).mockResolvedValue(note);- vi.mocked(froca.getAttachment).mockResolvedValue(- { attachmentId: "att1", ownerId: "owner" } as unknown as FAttachment- );- vi.mocked(link.createLink)- .mockImplementation(async () => $('<span><a href="#">x</a></span>'));- vi.mocked(content_renderer.getRenderedContent).mockImplementation(async () => (- { $renderedContent: $("<p>body</p>"), type: "text" } as never- ));+ container = document.createElement("div");+ container.innerHTML = `<p>text</p><section class="include-note"></section>`+ + `<blockquote><section class="include-note"></section></blockquote>`;+ document.body.appendChild(container);});- /** A note box and an attachment box of each size, with the note and view scope each shows. */- async function loadEveryBox() {- const boxes: [ JQuery<HTMLElement>, string, object | undefined ][] = [];- for (const boxSize of [ "small", "medium", "full", "expandable" ]) {- const $note = $('<div class="include-note-wrapper">');- const $attachment = $('<div class="include-note-wrapper">');- await loadIncludedNote("noteY", $note, boxSize);- await loadIncludedAttachment("att1", $attachment, boxSize);- boxes.push([ $note, "noteY", undefined ], [ $attachment, "owner", attachmentScope ]);- }- return boxes;+ afterEach(() => {+ container.remove();+ });++ function disposed() {+ return vi.mocked(content_renderer.disposeInteractiveContent).mock.calls+ .map(([ $element ]) => $element[0]);}- function click(button: HTMLElement) {- const event = new MouseEvent("click", { bubbles: true });- const stopPropagation = vi.spyOn(event, "stopPropagation");- button.dispatchEvent(event);- return { event, stopPropagation };+ function flush() {+ return new Promise((resolve) => setTimeout(resolve, 0));}- it("opens the note or attachment in a new tab, from right after the title", async () => {- for (const [ $el, notePath, viewScope ] of await loadEveryBox()) {- const $button = $el.find(".include-note-title").next();- expect($button.attr("class")).toBe("include-note-open bx bx-link-external");- expect($button.attr("title")).toBe("common.open_in_new_tab");-- const { stopPropagation } = click($button[0]);- expect(openTabWithNoteWithHoisting).toHaveBeenLastCalledWith(notePath, {- viewScope,- activate: true,- placement: "afterCurrent"- });- expect(stopPropagation).toHaveBeenCalled();- }- expect(openTabWithNoteWithHoisting).toHaveBeenCalledTimes(8);+ 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 ];++ section.remove();+ quote.remove();+ container.append(quote);+ paragraph.firstChild?.remove();+ await flush();++ expect(disposed()).toEqual([ section ]);+ stop();});- it("opens the context menu of the note or attachment from the end of the row", async () => {- for (const [ $el, notePath, viewScope ] of await loadEveryBox()) {- const $button = $el.find(".include-note-title-row").children().last();- expect($button.attr("class")).toBe("include-note-menu bx bx-dots-vertical-rounded");- expect($button.attr("title")).toBe("common.more_actions");-- const { event, stopPropagation } = click($button[0]);- expect(openContextMenu).toHaveBeenLastCalledWith(notePath, event, viewScope);- expect(stopPropagation).toHaveBeenCalled();- }- expect(openContextMenu).toHaveBeenCalledTimes(8);+ it("unmounts what is left on stop, and stops watching", async () => {+ const stop = watchIncludedNotes(container);+ const section = container.querySelector("section");+ section?.remove();++ stop();+ expect(disposed()).toEqual([ section, container ]);++ container.querySelector("blockquote")?.remove();+ await flush();+ expect(disposed()).toHaveLength(2);});});diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 8ca057428c..b010fa64ca 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -1,13 +1,11 @@import { h } from "preact";import appContext from "../../../components/app_context";-import linkContextMenu from "../../../menus/link_context_menu";import content_renderer from "../../../services/content_renderer";import froca from "../../../services/froca";-import { t } from "../../../services/i18n";import link, { ViewScope } from "../../../services/link";import utils from "../../../services/utils";-import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";+import IncludeNote, { type IncludeNoteProps } from "./IncludeNote";export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {const note = await froca.getNote(noteId);@@ -20,11 +18,19 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,// The include widget itself is the first level of inclusion, so the included note's own// includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).- await fillIncludeBox($el, boxSize, $link, () => content_renderer.getRenderedContent(note, {+ const { $renderedContent, type } = await content_renderer.getRenderedContent(note, {interactive: true,includesAsReferenceLinks: true,mediaEnvironment: "embedded"- }), { notePath: note.noteId });+ });++ await mountIncludeNote($el[0], {+ boxSize,+ title: $link[0],+ content: $renderedContent[0],+ contentType: type,+ notePath: note.noteId+ });}/** Fills an include box with an embedded attachment, under a title linking to it. */@@ -42,164 +48,82 @@ export async function loadIncludedAttachment(showNoteIcon: true,viewScope});-- await fillIncludeBox($el, boxSize, $link, () => content_renderer.getRenderedContent(+ const { $renderedContent, type } = await content_renderer.getRenderedContent(attachment,{ interactive: true, mediaEnvironment: "embedded" }- ), { notePath: attachment.ownerId, viewScope, offersFullscreen: true });-}--/** The href of a reference link to the attachment, or `null` once it is deleted. */-export async function getAttachmentHref(attachmentId: string) {- const attachment = await froca.getAttachment(attachmentId, true);- if (!attachment) return null;-- return `#root/${attachment.ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;+ );++ await mountIncludeNote($el[0], {+ boxSize,+ title: $link[0],+ content: $renderedContent[0],+ contentType: type,+ notePath: attachment.ownerId,+ viewScope,+ isFullscreenOffered: true+ });}-type RenderedContent = Awaited<ReturnType<typeof content_renderer.getRenderedContent>>;--interface IncludeBoxOptions {- /** The note that the box's button opens in a new tab. */- notePath: string;- /** The view of that note to open, such as one of its attachments. */- viewScope?: ViewScope;- /** Whether a medium or full box ends its title row with a fullscreen button. */- offersFullscreen?: boolean;+/**+ * Mounts an include box in `el`: the `.include-note-wrapper` the editor renders, or a+ * `section.include-note`, whose wrapper is reused or created. Without a box size of its own, the+ * box takes the one of its section.+ */+async function mountIncludeNote(el: HTMLElement, props: IncludeNoteProps) {+ const boxSize = props.boxSize+ ?? el.closest<HTMLElement>("section.include-note")?.dataset.boxSize;+ const box = h(IncludeNote, { ...props, boxSize });+ await content_renderer.mountInteractiveWidget(box, getWrapper(el));}-async function fillIncludeBox(- $el: JQuery<HTMLElement>,- boxSize: string | undefined,- $link: JQuery<HTMLElement>,- renderContent: () => Promise<RenderedContent>,- { notePath, viewScope, offersFullscreen = false }: IncludeBoxOptions-) {- // The box size is supplied explicitly by the editing-view downcast; for the other- // callers (read-only rendering, script API refresh) fall back to reading it from the DOM.- const effectiveBoxSize = boxSize ?? $el.closest('section.include-note').attr('data-box-size');- const isExpandable = effectiveBoxSize === 'expandable';-- // The editing-view downcast passes the `.include-note-wrapper` element itself as $el, whereas the- // read-only and refresh paths pass the outer `section.include-note`. Build the content in a- // detached wrapper either way (so the old content stays visible during the async render — no- // flicker), then swap it in; when $el is already the wrapper we move the built children straight- // into it instead of nesting a redundant second `.include-note-wrapper`.- const isWrapper = $el.hasClass('include-note-wrapper');- const $wrapper = $('<div class="include-note-wrapper">');-- if (isExpandable) {- // Create expandable structure with toggle- const $titleRow = $('<div class="include-note-title-row">');- const $toggle = $('<button class="include-note-toggle bx bx-chevron-right" aria-expanded="false">');- const $title = $('<h4 class="include-note-title">').append($link);-- $titleRow.append(- $toggle,- $title,- createOpenInNewTabButton(notePath, viewScope),- createMenuButton(notePath, viewScope)- );- $wrapper.append($titleRow);-- const { $renderedContent, type } = await renderContent();- const $content = $(`<div class="include-note-content type-${type}" style="display: none;">`).append($renderedContent);- $wrapper.append($content);-- // Add toggle functionality- $toggle.on('click', (e) => {- e.stopPropagation();- const isExpanded = $toggle.attr('aria-expanded') === 'true';- $toggle.attr('aria-expanded', String(!isExpanded));- $toggle.toggleClass('expanded');- $content.slideToggle(200);- });- } else {- const $title = $('<h4 class="include-note-title">').append($link);- const { $renderedContent, type } = await renderContent();- const $content = $(`<div class="include-note-content type-${type}">`)- .append($renderedContent);- const $titleRow = $('<div class="include-note-title-row">')- .append($title, createOpenInNewTabButton(notePath, viewScope));-- if (offersFullscreen && (effectiveBoxSize === "medium" || effectiveBoxSize === "full")) {- $titleRow.append(createFullscreenButton($content[0]));- await mountExitFullscreenControls($content);- }-- $titleRow.append(createMenuButton(notePath, viewScope));- $wrapper.append($titleRow, $content);+function getWrapper(el: HTMLElement) {+ if (el.classList.contains("include-note-wrapper")) {+ return el;}- // Unmount any interactive widgets from a previous render of this include (e.g. on a box-size- // change or refreshIncludedNote) before $el.empty() discards their DOM — otherwise their- // standalone Preact roots (collections, web views) would leak.- content_renderer.disposeInteractiveContent($el);- $el.empty().append(isWrapper ? $wrapper.children() : $wrapper);-}+ const existing = el.querySelector<HTMLElement>(":scope > .include-note-wrapper");+ if (existing) {+ return existing;+ }-/** A button opening a note in a new tab after the current one and switching to it. */-function createOpenInNewTabButton(notePath: string, viewScope: ViewScope | undefined) {- return $('<button type="button" class="include-note-open bx bx-link-external">')- .attr({ title: t("common.open_in_new_tab") })- .on("click", (e) => {- e.stopPropagation();- void appContext.tabManager.openTabWithNoteWithHoisting(notePath, {- viewScope,- activate: true,- placement: "afterCurrent"- });- });+ const wrapper = document.createElement("div");+ wrapper.className = "include-note-wrapper";+ el.replaceChildren(wrapper);+ return wrapper;}-/** A button opening the context menu that right-clicking the title of an include box opens. */-function createMenuButton(notePath: string, viewScope: ViewScope | undefined) {- return $('<button type="button" class="include-note-menu bx bx-dots-vertical-rounded">')- .attr({ title: t("common.more_actions") })- .on("click", (e) => {- e.stopPropagation();- if (e.originalEvent) {- void linkContextMenu.openContextMenu(notePath, e.originalEvent, viewScope);- }- });-}+/** The href of a reference link to the attachment, or `null` once it is deleted. */+export async function getAttachmentHref(attachmentId: string) {+ const attachment = await froca.getAttachment(attachmentId, true);+ if (!attachment) return null;-/** A button giving `content` the whole screen. */-function createFullscreenButton(content: HTMLElement) {- return $('<button type="button" class="include-note-fullscreen bx bx-fullscreen">')- .attr({ title: t("common.fullscreen") })- .on("click", (e) => {- e.stopPropagation();- content.requestFullscreen().catch((error: unknown) => {- console.warn("Could not show the included content in fullscreen:", error);- });- });+ return `#root/${attachment.ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;}/**- * Mounts the button leaving fullscreen at the start of `$content`. The stylesheet shows it only- * while `$content` has the screen.+ * Unmounts the include boxes, and what they show, once they leave `container`. The returned+ * function stops watching and unmounts the boxes still in it.*/-async function mountExitFullscreenControls($content: JQuery<HTMLElement>) {- const container = document.createElement("div");- container.className = "include-note-fullscreen-controls";- $content.prepend(container);+export function watchIncludedNotes(container: HTMLElement) {+ const observer = new MutationObserver(disposeRemoved);+ observer.observe(container, { childList: true, subtree: true });++ return () => {+ disposeRemoved(observer.takeRecords());+ observer.disconnect();+ content_renderer.disposeInteractiveContent($(container));+ };+}- const exitButton = h(OverlayControlButton, {- icon: "bx-exit",- text: t("common.exit_fullscreen"),- onClick: (e) => {- e.stopPropagation();- document.exitFullscreen().catch((error: unknown) => {- console.warn("Could not leave fullscreen:", error);- });+function disposeRemoved(records: MutationRecord[]) {+ for (const record of records) {+ for (const node of record.removedNodes) {+ // A node moved elsewhere in the document is still in use.+ if (node instanceof HTMLElement && !node.isConnected) {+ content_renderer.disposeInteractiveContent($(node));+ }}- });- await content_renderer.mountInteractiveWidget(h(OverlayControlGroup, {- placement: "top-end",- className: "include-note-exit-fullscreen",- children: exitButton- }), container);+ }}export function refreshIncludedNote(container: HTMLDivElement, noteId: string) {