Skip to content

Build your personal knowledge base with Trilium Notes

fix(render): keep scoping a render note's CSS as its script adds more

Elian Doran975f54b44e6b
diff --git a/apps/client/src/services/render.tsx b/apps/client/src/services/render.tsx
index 771deb4315..b5d07abe3b 100644
--- a/apps/client/src/services/render.tsx
+++ b/apps/client/src/services/render.tsx
@@ -4,7 +4,7 @@ import type FNote from "../entities/fnote.js";
import { renderReactWidgetAtElement } from "../widgets/react/react_utils.jsx";
import { type Bundle, executeBundleWithoutErrorHandling } from "./bundle.js";
import froca from "./froca.js";
-import { RENDER_SCOPE_CLASS, scopeRenderNoteCss } from "./render_css_scope.js";
+import { keepStylesScoped, RENDER_SCOPE_CLASS } from "./render_css_scope.js";
import server from "./server.js";
/**
@@ -32,7 +32,7 @@ export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: Er
$el.append($scriptContainer);
$scriptContainer.append(bundle.html);
- scopeOwnStyles($scriptContainer);
+ keepStylesScoped($scriptContainer[0]);
// async so that scripts cannot block trilium execution
executeBundleWithoutErrorHandling(bundle, note, $scriptContainer)
@@ -92,16 +92,6 @@ export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<H
renderReactWidgetAtElement(closestComponent, el, $el[0]);
}
-/**
- * Confines the note's own stylesheets to its container, so that a document-level rule such as
- * `body { max-width: … }` cannot restyle the application around it.
- */
-function scopeOwnStyles($container: JQuery<HTMLElement>) {
- for (const style of $container.find("style")) {
- style.textContent = scopeRenderNoteCss(style.textContent ?? "");
- }
-}
-
export default {
render
};
diff --git a/apps/client/src/services/render_css_scope.spec.ts b/apps/client/src/services/render_css_scope.spec.ts
index 03f3f4519e..b0a389b58b 100644
--- a/apps/client/src/services/render_css_scope.spec.ts
+++ b/apps/client/src/services/render_css_scope.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { RENDER_SCOPE_CLASS, scopeRenderNoteCss } from "./render_css_scope.js";
+import { keepStylesScoped, RENDER_SCOPE_CLASS, scopeRenderNoteCss } from "./render_css_scope.js";
/** Collapses whitespace, so assertions read as CSS rather than as the serializer's exact layout. */
function scope(css: string) {
@@ -86,3 +86,74 @@ describe("scopeRenderNoteCss", () => {
expect(computed("#outside").color).not.toBe("rgb(255, 0, 0)");
});
});
+
+describe("keepStylesScoped", () => {
+ /** Mutation records are delivered on a microtask, so give the observer a turn to run. */
+ const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+ function mount(html = "") {
+ document.body.innerHTML = `<div class="${RENDER_SCOPE_CLASS}">${html}</div>`;
+ const container = document.querySelector<HTMLElement>(`.${RENDER_SCOPE_CLASS}`);
+ if (!container) {
+ throw new Error("container was not mounted");
+ }
+ keepStylesScoped(container);
+ return container;
+ }
+
+ function addStyle(parent: Element, css: string) {
+ const style = document.createElement("style");
+ style.textContent = css;
+ parent.appendChild(style);
+ return style;
+ }
+
+ it("scopes the stylesheets already present", () => {
+ const container = mount("<style>body { color: red }</style>");
+
+ expect(container.querySelector("style")?.textContent).toContain(`@scope (.${RENDER_SCOPE_CLASS})`);
+ });
+
+ it("scopes a stylesheet a script appends after mount, however deeply", async () => {
+ const container = mount("<div class=\"panel\"></div>");
+ const direct = addStyle(container, "body { color: red }");
+ const nested = addStyle(container.querySelector(".panel") as Element, "body { color: blue }");
+
+ await flush();
+
+ expect(direct.textContent).toContain(`@scope (.${RENDER_SCOPE_CLASS})`);
+ expect(nested.textContent).toContain(`@scope (.${RENDER_SCOPE_CLASS})`);
+ });
+
+ it("scopes a subtree that arrives with a stylesheet inside it", async () => {
+ const container = mount();
+ const panel = document.createElement("div");
+ panel.innerHTML = "<style>body { color: red }</style><p>hi</p>";
+ container.appendChild(panel);
+
+ await flush();
+
+ expect(panel.querySelector("style")?.textContent).toContain(`@scope (.${RENDER_SCOPE_CLASS})`);
+ });
+
+ it("re-scopes a stylesheet whose contents are replaced", async () => {
+ const container = mount("<style>body { color: red }</style>");
+ const style = container.querySelector("style") as HTMLStyleElement;
+
+ style.textContent = "body { color: blue }";
+ await flush();
+
+ expect(style.textContent).toContain(":scope { color: blue }");
+ expect(style.textContent).not.toContain("color: red");
+ });
+
+ it("does not wrap its own output again", async () => {
+ const container = mount("<style>body { color: red }</style>");
+ const style = container.querySelector("style") as HTMLStyleElement;
+
+ await flush();
+ await flush();
+
+ expect(style.textContent?.match(/@scope/g)).toHaveLength(1);
+ });
+});
diff --git a/apps/client/src/services/render_css_scope.ts b/apps/client/src/services/render_css_scope.ts
index a1b6972a74..896af86c3d 100644
--- a/apps/client/src/services/render_css_scope.ts
+++ b/apps/client/src/services/render_css_scope.ts
@@ -4,6 +4,39 @@
*/
export const RENDER_SCOPE_CLASS = "render-note-scope";
+/**
+ * Scopes every stylesheet the note has in `container`, and keeps scoping the ones it adds later.
+ *
+ * A render note's script can build its markup after the bundle's HTML is inserted, so the sheet
+ * that has to be confined does not necessarily exist yet. Assigning to a style element's
+ * `textContent` swaps its child text node, so watching `childList` over the subtree catches a
+ * rewritten stylesheet as well as a newly appended one.
+ *
+ * Rules a script adds through `CSSStyleSheet.insertRule()` never touch the DOM and so cannot be
+ * caught here, and neither can a stylesheet it appends to `document.head` instead.
+ */
+export function keepStylesScoped(container: HTMLElement) {
+ scopeStyleElements(container.querySelectorAll("style"));
+
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ if (record.target instanceof HTMLStyleElement) {
+ scopeStyleElements([ record.target ]);
+ }
+
+ for (const node of record.addedNodes) {
+ if (node instanceof HTMLStyleElement) {
+ scopeStyleElements([ node ]);
+ } else if (node instanceof Element) {
+ scopeStyleElements(node.querySelectorAll("style"));
+ }
+ }
+ }
+ });
+
+ observer.observe(container, { childList: true, subtree: true });
+}
+
/**
* Confines a render note's stylesheet to the note's own container.
*
@@ -35,6 +68,25 @@ export function scopeRenderNoteCss(css: string): string {
return `${prefix}@scope (.${RENDER_SCOPE_CLASS}) {\n${scoped.join("\n")}\n}`;
}
+/**
+ * The CSS this module last wrote into a style element. Rewriting `textContent` is itself a
+ * mutation, so without this the observer would see its own work and wrap the rules a second time.
+ */
+const scopedOutput = new WeakMap<HTMLStyleElement, string>();
+
+function scopeStyleElements(styles: Iterable<HTMLStyleElement>) {
+ for (const style of styles) {
+ const css = style.textContent ?? "";
+ if (scopedOutput.get(style) === css) {
+ continue;
+ }
+
+ const scoped = scopeRenderNoteCss(css);
+ scopedOutput.set(style, scoped);
+ style.textContent = scoped;
+ }
+}
+
/** At-rules defining document-global named resources, or that are only valid at the top level. */
const HOISTED_AT_RULES = new Set([
"charset", "import", "namespace",