Skip to content

Build your personal knowledge base with Trilium Notes

fix(render): preserve script modal context (closes #11847)

tollenceld2cce30580135
diff --git a/apps/client/src/widgets/react/Modal.spec.tsx b/apps/client/src/widgets/react/Modal.spec.tsx
index 2ba5c894dc..d0e1c475d1 100644
--- a/apps/client/src/widgets/react/Modal.spec.tsx
+++ b/apps/client/src/widgets/react/Modal.spec.tsx
@@ -88,6 +88,8 @@ describe("Modal", () => {
return <button onClick={onClick}>{useContext(Context)}</button>;
}
+ container.classList.add("note-detail-render-content");
+ container.dataset.ntxId = "source-pane";
container.style.contain = "size";
container.style.overflow = "auto";
await act(async () => {
@@ -99,12 +101,14 @@ describe("Modal", () => {
});
const dialog = document.querySelector<HTMLElement>(".script-dialog");
- expect(dialog?.parentElement).toBe(document.body);
+ expect(dialog?.parentElement?.parentElement).toBe(document.body);
+ expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(true);
expect(container.contains(dialog)).toBe(false);
expect(mocks.openDialog).toHaveBeenCalledWith(expect.anything(), true, { focus: true }, undefined);
const button = dialog?.querySelector<HTMLButtonElement>(".modal-body button");
expect(button?.textContent).toBe("from render note");
+ expect(button?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("source-pane");
await act(async () => button?.click());
expect(onClick).toHaveBeenCalledOnce();
@@ -113,6 +117,35 @@ describe("Modal", () => {
expect(mocks.hide).toHaveBeenCalled();
});
+ it("keeps a script modal's pane without applying render-note styles outside a render note", async () => {
+ container.dataset.ntxId = "script-pane";
+
+ await act(async () => {
+ render(<ScriptModal className="script-dialog" size="md" show onHidden={() => {}}>body</ScriptModal>, container);
+ });
+
+ const dialog = document.querySelector<HTMLElement>(".script-dialog");
+ expect(dialog?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("script-pane");
+ expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(false);
+ });
+
+ it("carries the render-note scope and pane into a nested script modal", async () => {
+ container.classList.add("note-detail-render-content");
+ container.dataset.ntxId = "nested-source-pane";
+
+ await act(async () => {
+ render(<ScriptModal className="outer-script" size="md" show onHidden={() => {}}>
+ <ScriptModal className="inner-script" size="sm" show stackable onHidden={() => {}}>nested</ScriptModal>
+ </ScriptModal>, container);
+ });
+
+ for (const className of [ "outer-script", "inner-script" ]) {
+ const dialog = document.querySelector<HTMLElement>(`.${className}`);
+ expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(true);
+ expect(dialog?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("nested-source-pane");
+ }
+ });
+
/**
* The bug this pins: `modalRef.current` stood among the effect's dependencies, and a ref holds
* nothing while the render that names them runs and the element by the time the effect does —
diff --git a/apps/client/src/widgets/react/Modal.tsx b/apps/client/src/widgets/react/Modal.tsx
index 3f00a2719c..6a677ba12e 100644
--- a/apps/client/src/widgets/react/Modal.tsx
+++ b/apps/client/src/widgets/react/Modal.tsx
@@ -3,11 +3,12 @@ import "./Modal.css";
import { Modal as BootstrapModal } from "bootstrap";
import clsx from "clsx";
import { ComponentChildren, createPortal, CSSProperties, RefObject } from "preact";
-import { useEffect, useLayoutEffect, useMemo, useRef } from "preact/hooks";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context";
import { openDialog } from "../../services/dialog";
import { t } from "../../services/i18n";
+import { RENDER_SCOPE_CLASS } from "../../services/render_css_scope";
import { openInAppHelpFromUrl } from "../../services/utils";
import { useSyncedRef } from "./hooks";
import { suspendModalFocusTraps } from "./modal_focustrap";
@@ -107,11 +108,6 @@ export interface ModalProps {
ariaLabel?: string;
}
-/** Mounts a modal opened by a script alongside Bootstrap's body-level backdrop. */
-export function ScriptModal(props: ModalProps) {
- return createPortal(<Modal {...props} />, document.body);
-}
-
export default function Modal({ children, className, size, title, customTitleBarButtons: titleBarButtons, header, footer, footerStyle, footerAlignment, onShown, onSubmit, helpPageId, minWidth, maxWidth, zIndex, scrollable, onHidden, modalRef: externalModalRef, formRef, bodyStyle, show, stackable, keepInDom, noFocus, sidebar, hideSidebarHeader, isFullPageOnMobile, ariaLabel }: ModalProps) {
const modalRef = useSyncedRef<HTMLDivElement>(externalModalRef);
const modalInstanceRef = useRef<BootstrapModal | undefined>(undefined);
@@ -331,6 +327,23 @@ export default function Modal({ children, className, size, title, customTitleBar
);
}
+/** Mounts a script modal beside Bootstrap's body-level backdrop while retaining its source context. */
+export function ScriptModal(props: ModalProps) {
+ const [ origin, setOrigin ] = useState<HTMLTemplateElement | null>(null);
+ const ntxId = origin?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id");
+ const isRenderNote = !!origin?.closest(`.note-detail-render-content, .${RENDER_SCOPE_CLASS}`);
+
+ return <>
+ <template ref={setOrigin} />
+ {origin && createPortal(
+ <div className={isRenderNote ? RENDER_SCOPE_CLASS : undefined} data-ntx-id={ntxId} style={{ display: "contents" }}>
+ <Modal {...props} />
+ </div>,
+ document.body
+ )}
+ </>;
+}
+
/** The classes a host asked for, as `classList` takes them. */
function splitClasses(className: string) {
return className.split(" ").filter((cls) => cls !== "");
diff --git a/apps/client/src/widgets/type_widgets/Render.spec.tsx b/apps/client/src/widgets/type_widgets/Render.spec.tsx
new file mode 100644
index 0000000000..9f8e2fb4d6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/Render.spec.tsx
@@ -0,0 +1,54 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const renderNote = vi.hoisted(() => vi.fn());
+
+vi.mock("../../services/render", () => ({ default: { render: renderNote } }));
+vi.mock("../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../react/hooks")>()),
+ useNoteRelation: (_note: unknown, name: string) => name === "renderNote" ? [ {} ] : [],
+ useTriliumEvent: () => {}
+}));
+
+import type FNote from "../../entities/fnote";
+import * as reactUtils from "../react/react_utils";
+import Render from "./Render";
+import type { TypeWidgetProps } from "./type_widget";
+
+const container = document.createElement("div");
+document.body.appendChild(container);
+
+afterEach(async () => {
+ await act(async () => render(null, container));
+ renderNote.mockClear();
+});
+
+describe("Render content", () => {
+ it("aborts the previous render on note change and on unmount", async () => {
+ const dispose = vi.spyOn(reactUtils, "disposeReactWidget");
+ const first = { noteId: "first" } as FNote;
+ const second = { noteId: "second" } as FNote;
+ const props = (note: FNote) => ({ note, ntxId: "pane", noteContext: null }) as unknown as TypeWidgetProps;
+
+ await act(async () => render(<Render {...props(first)} />, container));
+ expect(renderNote).toHaveBeenCalledTimes(1);
+ expect(renderNote.mock.calls[0][0]).toBe(first);
+ const firstContainer = container.querySelector(".note-detail-render-content");
+ const firstSignal = renderNote.mock.calls[0][3] as AbortSignal;
+ expect(firstSignal.aborted).toBe(false);
+
+ await act(async () => render(<Render {...props(second)} />, container));
+ expect(firstSignal.aborted).toBe(true);
+ expect(dispose).toHaveBeenCalledWith(firstContainer);
+ expect(renderNote).toHaveBeenCalledTimes(2);
+ const secondContainer = container.querySelector(".note-detail-render-content");
+ const secondSignal = renderNote.mock.calls[1][3] as AbortSignal;
+ expect(secondSignal.aborted).toBe(false);
+
+ await act(async () => render(null, container));
+ expect(secondSignal.aborted).toBe(true);
+ expect(dispose).toHaveBeenCalledWith(secondContainer);
+ dispose.mockRestore();
+ });
+});