Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): keep the page's inline scripts out of the global scope

Elian Doran53ca5a1c0a71
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.json
index ae143126d7..1da95d13ad 100644
--- a/packages/share-theme/package.json
+++ b/packages/share-theme/package.json
@@ -27,6 +27,8 @@
"devDependencies": {
"@triliumnext/ckeditor5": "workspace:*",
"@triliumnext/highlightjs": "workspace:*",
+ "@types/ejs": "3.1.5",
+ "ejs": "7.0.1",
"esbuild": "0.28.2",
"happy-dom": "20.14.5",
"sass": "1.105.1",
diff --git a/packages/share-theme/src/page/theme_switch.css b/packages/share-theme/src/page/theme_switch.css
index ecb8eca802..75fe670799 100644
--- a/packages/share-theme/src/page/theme_switch.css
+++ b/packages/share-theme/src/page/theme_switch.css
@@ -36,7 +36,7 @@
z-index: 2;
}
-input:checked + .slider {
+.theme-dark .slider {
background-color: var(--background-highlight);
}
@@ -44,7 +44,7 @@ input:focus + .slider {
box-shadow: 0 0 1px var(--background-highlight);
}
-input:checked + .slider:before {
+.theme-dark .slider::before {
transform: translateX(33px);
}
@@ -69,11 +69,11 @@ input:checked + .slider:before {
width: 24px;
}
-input:not(:checked) ~ .light-icon {
+.theme-light .light-icon {
opacity: 1;
}
-input:checked ~ .dark-icon {
+.theme-dark .dark-icon {
opacity: 1;
}
diff --git a/packages/share-theme/src/page/theme_switch.spec.ts b/packages/share-theme/src/page/theme_switch.spec.ts
new file mode 100644
index 0000000000..3b154fb6ed
--- /dev/null
+++ b/packages/share-theme/src/page/theme_switch.spec.ts
@@ -0,0 +1,29 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it } from "vitest";
+
+import setupThemeSelector from "./theme_switch.js";
+
+describe("setupThemeSelector", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ document.documentElement.className = "";
+ localStorage.clear();
+ });
+
+ it("checks the switch for the dark theme and switches and stores the theme on change", () => {
+ document.documentElement.className = "theme-dark";
+ document.body.innerHTML = `<div class="theme-selection"><input type="checkbox"></div>`;
+ const input = document.querySelector<HTMLInputElement>(".theme-selection input");
+ if (!input) {
+ throw new Error("The switch is missing.");
+ }
+
+ setupThemeSelector();
+ expect(input.checked).toBe(true);
+
+ input.checked = false;
+ input.dispatchEvent(new Event("change"));
+ expect(document.documentElement.className).toBe("theme-light");
+ expect(localStorage.getItem("theme")).toBe("light");
+ });
+});
diff --git a/packages/share-theme/src/page/theme_switch.ts b/packages/share-theme/src/page/theme_switch.ts
index 56e6c25aaf..bd8bc54480 100644
--- a/packages/share-theme/src/page/theme_switch.ts
+++ b/packages/share-theme/src/page/theme_switch.ts
@@ -3,15 +3,18 @@ import "./theme_switch.css";
const themeRootEl = document.documentElement;
/**
- * Note:
- *
- * - Setting of the .theme-dark or .theme-light is done in the share template's <head> to avoid a flash.
- * - Setting of the value of the checkbox is also done in the template, near the definition of the input box.
+ * Wires the dark mode switch. `boot_script.ejs` applies the theme class before the first paint, and
+ * the switch is styled from that class, so this only syncs the checkbox for assistive technologies
+ * and switches the theme on change.
*/
-
export default function setupThemeSelector() {
- const themeSwitch: HTMLInputElement = document.querySelector(".theme-selection input")!;
- themeSwitch?.addEventListener("change", () => {
+ const themeSwitch = document.querySelector<HTMLInputElement>(".theme-selection input");
+ if (!themeSwitch) {
+ return;
+ }
+
+ themeSwitch.checked = themeRootEl.classList.contains("theme-dark");
+ themeSwitch.addEventListener("change", () => {
const theme = themeSwitch.checked ? "dark" : "light";
setTheme(theme);
localStorage.setItem("theme", theme);
diff --git a/packages/share-theme/src/templates/boot_script.ejs b/packages/share-theme/src/templates/boot_script.ejs
index 2c68a89001..8a512cfd71 100644
--- a/packages/share-theme/src/templates/boot_script.ejs
+++ b/packages/share-theme/src/templates/boot_script.ejs
@@ -1,20 +1,26 @@
<script>
- // Load dark/light theme as soon as possible to avoid color flashes.
- let theme = localStorage.getItem("theme");
- if (!theme) {
- theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light";
- }
- document.documentElement.classList.add(`theme-${theme}`);
+ // Applies the theme and the collapsed panes before the first paint, to avoid color flashes. The
+ // function keeps its names out of the global scope, which `~shareHtml` snippets share.
+ (function () {
+ function read(key) {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+ }
- window.glob = {
- isStatic: <%= !!isStatic %>,
- theme
- };
+ const root = document.documentElement;
+ const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
+ const theme = read("theme") || (prefersDark ? "dark" : "light");
+ root.classList.add(`theme-${theme}`);
- (function() {
- const leftCollapsed = localStorage.getItem("left-pane-collapsed") === "true";
- const tocCollapsed = localStorage.getItem("toc-pane-collapsed") === "true";
- if (leftCollapsed) document.documentElement.classList.add("left-pane-collapsed");
- if (tocCollapsed) document.documentElement.classList.add("toc-pane-collapsed");
+ window.glob = {
+ isStatic: <%= !!isStatic %>,
+ theme
+ };
+
+ if (read("left-pane-collapsed") === "true") root.classList.add("left-pane-collapsed");
+ if (read("toc-pane-collapsed") === "true") root.classList.add("toc-pane-collapsed");
})();
</script>
diff --git a/packages/share-theme/src/templates/boot_script.spec.ts b/packages/share-theme/src/templates/boot_script.spec.ts
new file mode 100644
index 0000000000..7ec5329132
--- /dev/null
+++ b/packages/share-theme/src/templates/boot_script.spec.ts
@@ -0,0 +1,54 @@
+/// <reference types="node" />
+import ejs from "ejs";
+import { readFileSync } from "node:fs";
+import { createContext, runInContext } from "node:vm";
+import { describe, expect, it } from "vitest";
+
+describe("boot_script.ejs", () => {
+ it("applies the stored theme and panes without leaving global names behind", () => {
+ const { context, classes } = runBootScript({
+ "theme": "dark",
+ "left-pane-collapsed": "true"
+ });
+
+ expect([ ...classes ]).toStrictEqual([ "theme-dark", "left-pane-collapsed" ]);
+ expect(context.glob).toEqual({ isStatic: true, theme: "dark" });
+ expect(() => runInContext(`const el = 1; let theme = 2; let root = 3;`, context)).not.toThrow();
+ });
+
+ it("follows the system theme when storage holds none or cannot be read", () => {
+ expect([ ...runBootScript({}, true).classes ]).toStrictEqual([ "theme-dark" ]);
+ expect([ ...runBootScript(null, false).classes ]).toStrictEqual([ "theme-light" ]);
+ });
+
+ it("leaves no inline script in the page template besides the boot script", () => {
+ const page = readFileSync(new URL("page.ejs", import.meta.url), "utf8");
+ expect(page.match(/<script>/g)).toBeNull();
+ });
+});
+
+/**
+ * Runs the rendered boot script in a sandbox, with `stored` as the local storage (`null` for
+ * storage that throws) and `prefersDark` as the system theme.
+ */
+function runBootScript(stored: Record<string, string> | null, prefersDark = false) {
+ const classes = new Set<string>();
+ const context = createContext({
+ localStorage: {
+ getItem(key: string) {
+ if (!stored) {
+ throw new Error("Storage is blocked.");
+ }
+ return stored[key] ?? null;
+ }
+ },
+ matchMedia: () => ({ matches: prefersDark }),
+ document: { documentElement: { classList: { add: (name: string) => classes.add(name) } } }
+ });
+ context.window = context;
+
+ const html = ejs.render(readFileSync(new URL("boot_script.ejs", import.meta.url), "utf8"),
+ { isStatic: true });
+ runInContext(html.replace(/<\/?script>/g, ""), context);
+ return { context, classes };
+}
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index a86b7407fb..857810c9bd 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -52,10 +52,6 @@
<svg class="dark-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M20.742 13.045a8.088 8.088 0 0 1-2.077.271c-2.135 0-4.14-.83-5.646-2.336a8.025 8.025 0 0 1-2.064-7.723A1 1 0 0 0 9.73 2.034a10.014 10.014 0 0 0-4.489 2.582c-3.898 3.898-3.898 10.243 0 14.143a9.937 9.937 0 0 0 7.072 2.93 9.93 9.93 0 0 0 7.07-2.929 10.007 10.007 0 0 0 2.583-4.491 1.001 1.001 0 0 0-1.224-1.224zm-2.772 4.301a7.947 7.947 0 0 1-5.656 2.343 7.953 7.953 0 0 1-5.658-2.344c-3.118-3.119-3.118-8.195 0-11.314a7.923 7.923 0 0 1 2.06-1.483 10.027 10.027 0 0 0 2.89 7.848 9.972 9.972 0 0 0 7.848 2.891 8.036 8.036 0 0 1-1.484 2.059z"></path></svg>
<svg class="light-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M6.993 12c0 2.761 2.246 5.007 5.007 5.007s5.007-2.246 5.007-5.007S14.761 6.993 12 6.993 6.993 9.239 6.993 12zM12 8.993c1.658 0 3.007 1.349 3.007 3.007S13.658 15.007 12 15.007 8.993 13.658 8.993 12 10.342 8.993 12 8.993zM10.998 19h2v3h-2zm0-17h2v3h-2zm-9 9h3v2h-3zm17 0h3v2h-3zM4.219 18.363l2.12-2.122 1.415 1.414-2.12 2.122zM16.24 6.344l2.122-2.122 1.414 1.414-2.122 2.122zM6.342 7.759 4.22 5.637l1.415-1.414 2.12 2.122zm13.434 10.605-1.414 1.414-2.122-2.122 1.414-1.414z"></path></svg>
</label>
- <script>
- const el = document.querySelector(".theme-selection input");
- el.checked = (glob.theme === "dark");
- </script>
</div>
<% if (hasTree) { %>
<div class="search-item">
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 67c70cc70a..1d2d8cd346 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1370,6 +1370,12 @@ importers:
'@triliumnext/highlightjs':
specifier: workspace:*
version: link:../highlightjs
+ '@types/ejs':
+ specifier: 3.1.5
+ version: 3.1.5
+ ejs:
+ specifier: 7.0.1
+ version: 7.0.1
esbuild:
specifier: 0.28.2
version: 0.28.2