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
fix(render): scope a render note's CSS to its own container (closes #10765)
Elian Doran3c7362888ad3
diff --git a/apps/client/src/services/render.spec.tsx b/apps/client/src/services/render.spec.tsxindex 79d3bbf21d..ff7f2b09b0 100644--- a/apps/client/src/services/render.spec.tsx+++ b/apps/client/src/services/render.spec.tsx@@ -20,6 +20,7 @@ import utils from "../services/utils.js";import { buildNote } from "../test/easy-froca";import froca from "./froca.js";import renderDefault, { render, renderIfJsx } from "./render.js";+import { RENDER_SCOPE_CLASS } from "./render_css_scope.js";import server from "./server.js";const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));@@ -112,6 +113,29 @@ describe("render", () => {expect((containerArg as JQuery<HTMLElement>)[0]).toBe($container[0]);});+ it("scopes the note's own stylesheet to its container so it cannot restyle the app", async () => {+ server.postWithSilentInternalServerError = vi.fn(async () => ({+ script: "",+ html: "<style>body { max-width: 980px } @keyframes spin { from { opacity: 0 } }</style><p>hi</p>",+ noteId: "scriptNote",+ allNoteIds: []+ })) as typeof server.postWithSilentInternalServerError;+ const target = buildNote({ title: "Target" });+ const note = buildNote({ title: "Host", "~renderNote": target.noteId });+ const $el = $("<div>");++ await render(note, $el);++ const $container = $el.children();+ expect($container.hasClass(RENDER_SCOPE_CLASS)).toBe(true);+ const css = $container.find("style").text();+ expect(css).toContain(`@scope (.${RENDER_SCOPE_CLASS})`);+ expect(css).toContain(":scope { max-width: 980px }");+ expect(css).not.toMatch(/(^|\s)body\s*\{/);+ // Named at-rules are document-global either way, so they stay outside the wrapper.+ expect(css.indexOf("@keyframes")).toBeLessThan(css.indexOf("@scope"));+ });+it("loops over every renderNote relation: one container + bundle fetch + execution per target", async () => {const target1 = buildNote({ title: "Target A" });const target2 = buildNote({ title: "Target B" });diff --git a/apps/client/src/services/render.tsx b/apps/client/src/services/render.tsxindex ae16a33fd0..771deb4315 100644--- a/apps/client/src/services/render.tsx+++ b/apps/client/src/services/render.tsx@@ -4,6 +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 server from "./server.js";/**@@ -27,10 +28,11 @@ export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: Erthrow new Error(`Script note '${renderNoteId}' could not be loaded. It may be protected and require an active protected session.`);}- const $scriptContainer = $("<div>");+ const $scriptContainer = $("<div>").addClass(RENDER_SCOPE_CLASS);$el.append($scriptContainer);$scriptContainer.append(bundle.html);+ scopeOwnStyles($scriptContainer);// async so that scripts cannot block trilium executionexecuteBundleWithoutErrorHandling(bundle, note, $scriptContainer)@@ -90,6 +92,16 @@ export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<HrenderReactWidgetAtElement(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.tsnew file mode 100644index 0000000000..dfa743fcda--- /dev/null+++ b/apps/client/src/services/render_css_scope.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";++import { 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) {+ return scopeRenderNoteCss(css).replace(/\s+/g, " ").trim();+}++const OPEN = `@scope (.${RENDER_SCOPE_CLASS}) {`;++describe("scopeRenderNoteCss", () => {+ it("wraps rules and leaves ordinary selectors alone", () => {+ expect(scope(".card { color: red }")).toBe(`${OPEN} .card { color: red } }`);+ expect(scope("#id .card > a:hover { color: red }")).toBe(`${OPEN} #id .card > a:hover { color: red } }`);+ expect(scope("")).toBe("");+ });++ it("rewrites selectors that address the document root", () => {+ expect(scope("body { max-width: 980px }")).toBe(`${OPEN} :scope { max-width: 980px } }`);+ expect(scope("html { color: red }")).toBe(`${OPEN} :scope { color: red } }`);+ expect(scope(":root { --x: 1 }")).toBe(`${OPEN} :scope { --x: 1 } }`);+ expect(scope("html body { color: red }")).toBe(`${OPEN} :scope { color: red } }`);+ expect(scope("html > body .card { color: red }")).toBe(`${OPEN} :scope .card { color: red } }`);+ expect(scope("body.dark { color: red }")).toBe(`${OPEN} :scope.dark { color: red } }`);+ expect(scope("body + .x { color: red }")).toBe(`${OPEN} :scope + .x { color: red } }`);+ });++ it("does not mistake other identifiers for the document root", () => {+ expect(scope("bodyguard { color: red }")).toBe(`${OPEN} bodyguard { color: red } }`);+ expect(scope("[data-body] { color: red }")).toBe(`${OPEN} [data-body] { color: red } }`);+ expect(scope(".x body { color: red }")).toBe(`${OPEN} .x body { color: red } }`);+ });++ it("rewrites every selector in a list, splitting only on top-level commas", () => {+ expect(scope("body, .x { color: red }")).toBe(`${OPEN} :scope, .x { color: red } }`);+ expect(scope(":is(a, body) { color: red }")).toBe(`${OPEN} :is(a, body) { color: red } }`);+ expect(scope("[title=\"a,b\"], body { color: red }")).toBe(`${OPEN} [title="a,b"], :scope { color: red } }`);+ });++ it("recurses into grouping at-rules, which stay scoped", () => {+ expect(scope("@media (min-width: 1px) { body { color: red } .x { color: blue } }"))+ .toBe(`${OPEN} @media (min-width: 1px) { :scope { color: red } .x { color: blue } } }`);+ expect(scope("@supports (display: grid) { body { color: red } }"))+ .toBe(`${OPEN} @supports (display: grid) { :scope { color: red } } }`);+ });++ it("hoists at-rules that define document-global names or must stay at the top level", () => {+ expect(scope("@keyframes spin { from { opacity: 0 } } body { color: red }"))+ .toBe(`@keyframes spin { from { opacity: 0 } } ${OPEN} :scope { color: red } }`);+ expect(scope("@font-face { font-family: X } .a { color: red }"))+ .toBe(`@font-face { font-family: X } ${OPEN} .a { color: red } }`);+ expect(scope("@import url(\"x.css\"); .a { color: red }"))+ .toBe(`@import url("x.css"); ${OPEN} .a { color: red } }`);+ // Nothing left to scope, so no empty wrapper is emitted.+ expect(scope("@font-face { font-family: X }")).toBe("@font-face { font-family: X }");+ });++ it("survives braces and commas that are not structural", () => {+ expect(scope("a::after { content: \"}\" } .b { color: red }"))+ .toBe(`${OPEN} a::after { content: "}" } .b { color: red } }`);+ expect(scope("/* } */ body { color: red }")).toBe(`${OPEN} :scope { color: red } }`);+ expect(scope("body { color: red /* } */ }")).toBe(`${OPEN} :scope { color: red /* } */ } }`);+ });++ it("recovers from an unterminated rule rather than dropping the stylesheet", () => {+ expect(scope(".a { color: red")).toBe(`${OPEN} .a { color: red} }`);+ expect(scope("body { color: red } .b {")).toBe(`${OPEN} :scope { color: red } .b {} }`);+ });+});diff --git a/apps/client/src/services/render_css_scope.ts b/apps/client/src/services/render_css_scope.tsnew file mode 100644index 0000000000..a1b6972a74--- /dev/null+++ b/apps/client/src/services/render_css_scope.ts@@ -0,0 +1,220 @@+/**+ * Class applied to the element a render note's markup is mounted into. It doubles as the root that+ * the note's own stylesheets are scoped to, so the two must stay in sync.+ */+export const RENDER_SCOPE_CLASS = "render-note-scope";++/**+ * Confines a render note's stylesheet to the note's own container.+ *+ * A `<style>` element applies to the whole document however deeply it is nested, so a standalone+ * HTML document's `body { max-width: … }` restyles the app. Wrapping the rules in `@scope` stops+ * that. Selectors that address the document root are rewritten to `:scope`, so they keep+ * styling the note instead of silently matching nothing.+ *+ * At-rules that define named resources (`@keyframes`, `@font-face`) stay outside the wrapper: they+ * are global by nature, and nesting them changes whether they parse at all.+ */+export function scopeRenderNoteCss(css: string): string {+ const hoisted: string[] = [];+ const scoped: string[] = [];++ for (const node of parseNodes(css)) {+ if (node.atName && HOISTED_AT_RULES.has(node.atName)) {+ hoisted.push(serialize(node, false));+ } else {+ scoped.push(serialize(node, true));+ }+ }++ const prefix = hoisted.length ? `${hoisted.join("\n")}\n` : "";+ if (!scoped.length) {+ return prefix.trimEnd();+ }++ return `${prefix}@scope (.${RENDER_SCOPE_CLASS}) {\n${scoped.join("\n")}\n}`;+}++/** 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",+ "font-face", "font-feature-values", "font-palette-values",+ "keyframes", "-webkit-keyframes", "-moz-keyframes",+ "property", "counter-style", "page"+]);++/** At-rules that wrap style rules, whose selectors still need rewriting. */+const GROUPING_AT_RULES = new Set([ "media", "supports", "container", "layer", "starting-style" ]);++/**+ * A leading run of `html` / `body` / `:root`, which addresses the document rather than the note.+ * Combinators are consumed with it, so `html > body .card` scopes down to `:scope .card`.+ */+const DOCUMENT_ROOT_PREFIX = /^\s*(?:html|body|:root)\b(?:\s*[>+~]?\s*(?:html|body|:root)\b)*/;++const COMMENT = /\/\*[\s\S]*?\*\//g;++interface CssNode {+ /** The at-rule name without its `@`, or undefined for a style rule. */+ atName?: string;+ /** Everything before the block: the selector, or the at-rule name and its condition. */+ prelude: string;+ /** The block contents, or undefined for a statement at-rule such as `@import …;`. */+ block?: string;+}++/**+ * Splits CSS into top-level nodes. Braces inside strings and comments are ignored, so a declaration+ * such as `content: "}"` does not end the rule early. Unbalanced input is consumed to the end+ * rather than rejected, which is how a browser recovers from it.+ */+function parseNodes(css: string): CssNode[] {+ const nodes: CssNode[] = [];+ let index = 0;+ let preludeStart = 0;++ while (index < css.length) {+ const char = css[index];++ if (char === "/" && css[index + 1] === "*") {+ index = skipComment(css, index);+ } else if (char === "\"" || char === "'") {+ index = skipString(css, index);+ } else if (char === ";") {+ addNode(nodes, css.slice(preludeStart, index));+ index++;+ preludeStart = index;+ } else if (char === "{") {+ const blockEnd = findBlockEnd(css, index);+ addNode(nodes, css.slice(preludeStart, index), css.slice(index + 1, blockEnd));+ index = blockEnd + 1;+ preludeStart = index;+ } else {+ index++;+ }+ }++ addNode(nodes, css.slice(preludeStart));+ return nodes;+}++function addNode(nodes: CssNode[], rawPrelude: string, block?: string) {+ // A comment ahead of the selector would otherwise hide the `body` that needs rewriting.+ const prelude = rawPrelude.replace(COMMENT, " ").trim();+ if (!prelude) {+ return;+ }++ const atName = /^@([\w-]+)/.exec(prelude)?.[1]?.toLowerCase();+ nodes.push({ atName, prelude, block });+}++function serialize(node: CssNode, rewrite: boolean): string {+ if (node.block === undefined) {+ return `${node.prelude};`;+ }++ if (node.atName) {+ // Grouping at-rules hold style rules of their own; anything else keeps its body verbatim.+ const body = rewrite && GROUPING_AT_RULES.has(node.atName)+ ? parseNodes(node.block).map((child) => serialize(child, true)).join("\n")+ : node.block;+ return `${node.prelude} {\n${body}\n}`;+ }++ const selector = rewrite ? rewriteSelector(node.prelude) : node.prelude;+ return `${selector} {${node.block}}`;+}++/** Rewrites document-root selectors to `:scope`, leaving every other selector untouched. */+function rewriteSelector(selector: string): string {+ return splitSelectorList(selector)+ .map((part) => part.replace(DOCUMENT_ROOT_PREFIX, ":scope"))+ .join(", ");+}++/** Splits a selector list on its top-level commas, ignoring those inside `:is(…)` or strings. */+function splitSelectorList(selector: string): string[] {+ const parts: string[] = [];+ let depth = 0;+ let start = 0;+ let index = 0;++ while (index < selector.length) {+ const char = selector[index];++ if (char === "\"" || char === "'") {+ index = skipString(selector, index);+ continue;+ }++ if (char === "(" || char === "[") {+ depth++;+ } else if (char === ")" || char === "]") {+ depth--;+ } else if (char === "," && depth === 0) {+ parts.push(selector.slice(start, index).trim());+ start = index + 1;+ }++ index++;+ }++ parts.push(selector.slice(start).trim());+ return parts.filter((part) => part);+}++function findBlockEnd(css: string, openIndex: number): number {+ let depth = 0;+ let index = openIndex;++ while (index < css.length) {+ const char = css[index];++ if (char === "/" && css[index + 1] === "*") {+ index = skipComment(css, index);+ continue;+ }++ if (char === "\"" || char === "'") {+ index = skipString(css, index);+ continue;+ }++ if (char === "{") {+ depth++;+ } else if (char === "}") {+ depth--;+ if (depth === 0) {+ return index;+ }+ }++ index++;+ }++ return css.length;+}++function skipComment(css: string, index: number): number {+ const end = css.indexOf("*/", index + 2);+ return end === -1 ? css.length : end + 2;+}++function skipString(css: string, index: number): number {+ const quote = css[index];+ let cursor = index + 1;++ while (cursor < css.length) {+ if (css[cursor] === "\\") {+ cursor += 2;+ continue;+ }+ if (css[cursor] === quote) {+ return cursor + 1;+ }+ cursor++;+ }++ return css.length;+}