Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): choose between light, dark and the system theme

Elian Doran1f976284a233
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index 9cff7c87ae..0c0f1bc117 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -9,13 +9,16 @@ class="image">
<h2>Features, interaction and limitations</h2>
<ul>
<li>Searching by note title.</li>
- <li>Automatic dark/light mode based on the user's browser settings.</li>
+ <li>Light and dark mode, following the visitor's system setting by default,
+ also while the page is open. The visitor can pick <em>Light</em>, <em>Dark</em> or <em>System</em> with
+ the buttons next to <em>Site Theme</em> at the top of the navigation pane,
+ or on narrow screens with the button in the header, which cycles through
+ the three; the choice is remembered by the browser.</li>
<li>A layout centered on wide screens, with the navigation tree and the table
of contents at either side of the content, and a mobile-friendly layout
with sliding panes on narrow ones.</li>
<li>Collapsible tree with the same note icons as the application.</li>
<li>Customizable logo.</li>
- <li>Toggle button for dark/light mode, which also stores the user preferences.</li>
<li>Quick navigation buttons (previous and next note).</li>
<li>Displaying the date of the last update of the note, written out in the
application's language.</li>
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 4767bd1b89..5a7acdf80a 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -448,6 +448,10 @@
},
"share_theme": {
"site-theme": "Site Theme",
+ "theme-light": "Light",
+ "theme-dark": "Dark",
+ "theme-system": "System",
+ "theme-current": "Site Theme: {{- theme}}",
"search_placeholder": "Search...",
"image_alt": "Article Image",
"last-updated": "Last updated on {{- date}}",
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 183efc5d2a..92d5ee3a22 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -6,11 +6,10 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
## Features, interaction and limitations
* Searching by note title.
-* Automatic dark/light mode based on the user's browser settings.
+* Light and dark mode, following the visitor's system setting by default, also while the page is open. The visitor can pick _Light_, _Dark_ or _System_ with the buttons next to _Site Theme_ at the top of the navigation pane, or on narrow screens with the button in the header, which cycles through the three; the choice is remembered by the browser.
* A layout centered on wide screens, with the navigation tree and the table of contents at either side of the content, and a mobile-friendly layout with sliding panes on narrow ones.
* Collapsible tree with the same note icons as the application.
* Customizable logo.
-* Toggle button for dark/light mode, which also stores the user preferences.
* Quick navigation buttons (previous and next note).
* Displaying the date of the last update of the note, written out in the application's language.
* Marking the page with the application's language and its text direction, and the content of the note with its own [content language](../Note%20Types/Text/Content%20language%20%26%20Right-to-left%20support.md), for screen readers and right-to-left text.
diff --git a/packages/share-theme/src/base.css b/packages/share-theme/src/base.css
index 6f47b6d163..838de9c562 100644
--- a/packages/share-theme/src/base.css
+++ b/packages/share-theme/src/base.css
@@ -73,6 +73,15 @@ a:hover {
display: inline-block;
}
+.visually-hidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
+
pre, code, kbd, samp {
font-family: JetBrainsLight, ui-monospace, monospace;
}
diff --git a/packages/share-theme/src/page/header.css b/packages/share-theme/src/page/header.css
index fa29f4240f..530c75154b 100644
--- a/packages/share-theme/src/page/header.css
+++ b/packages/share-theme/src/page/header.css
@@ -5,7 +5,8 @@ html {
#header {
background: var(--background-secondary);
display: none;
- justify-content: space-between;
+ grid-template-columns: 1fr auto 1fr;
+ justify-items: start;
align-items: center;
height: var(--header-height);
padding: 0 12px;
@@ -55,13 +56,27 @@ html {
background-color: var(--background-highlight);
}
+.header-button:focus-visible {
+ outline: 2px solid var(--link-focus-outline-color);
+ outline-offset: 1px;
+}
+
.header-button-placeholder {
width: 32px;
}
+#header > :last-child {
+ justify-self: end;
+}
+
+.header-actions {
+ display: flex;
+ gap: 4px;
+}
+
@media (max-width: 48em) {
#header {
- display: flex;
+ display: grid;
}
#site-logo {
diff --git a/packages/share-theme/src/page/theme_switch.css b/packages/share-theme/src/page/theme_switch.css
index 349c6404a6..2b65c60acd 100644
--- a/packages/share-theme/src/page/theme_switch.css
+++ b/packages/share-theme/src/page/theme_switch.css
@@ -88,3 +88,59 @@ input:focus + .slider {
right: 5px;
color: var(--background-highlight);
}
+
+.theme-options {
+ display: flex;
+ gap: 2px;
+ padding: 2px;
+ border-radius: 8px;
+ background: var(--background-highlight);
+}
+
+.theme-option {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 26px;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--text-menu);
+ font-size: 18px;
+ cursor: pointer;
+ transition: background-color 150ms ease, color 150ms ease;
+}
+
+.theme-option:hover {
+ color: var(--text-primary);
+}
+
+.theme-option:focus-visible {
+ outline: 2px solid var(--link-focus-outline-color);
+ outline-offset: 1px;
+}
+
+.theme-preference-light .theme-option[data-theme="light"],
+.theme-preference-dark .theme-option[data-theme="dark"],
+.theme-preference-system .theme-option[data-theme="system"] {
+ background: var(--background-primary);
+ color: var(--text-primary);
+}
+
+.theme-cycle-option {
+ display: none;
+}
+
+.theme-preference-light .theme-cycle-option[data-theme="light"],
+.theme-preference-dark .theme-cycle-option[data-theme="dark"],
+.theme-preference-system .theme-cycle-option[data-theme="system"] {
+ display: flex;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .theme-option {
+ transition: none;
+ }
+}
diff --git a/packages/share-theme/src/page/theme_switch.spec.ts b/packages/share-theme/src/page/theme_switch.spec.ts
index 43f92b1aa4..f7b7e19205 100644
--- a/packages/share-theme/src/page/theme_switch.spec.ts
+++ b/packages/share-theme/src/page/theme_switch.spec.ts
@@ -1,17 +1,100 @@
// @vitest-environment happy-dom
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import setupThemeSelector from "./theme_switch.js";
+const OPTIONS = `
+ <div class="theme-options">
+ <button class="theme-option" data-theme="light"></button>
+ <button class="theme-option" data-theme="dark"></button>
+ <button class="theme-option" data-theme="system"></button>
+ </div>
+ <button id="theme-cycle-button"></button>`;
+
describe("setupThemeSelector", () => {
+ let systemDark: ReturnType<typeof mockSystemTheme>;
+
+ beforeEach(() => {
+ systemDark = mockSystemTheme(false);
+ });
+
afterEach(() => {
+ vi.unstubAllGlobals();
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";
+ it("applies, marks and stores the chosen theme, or forgets it for the system", () => {
+ document.body.innerHTML = OPTIONS;
+ setupThemeSelector();
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-system" ]);
+ expect(pressed()).toStrictEqual([ "system" ]);
+
+ clickOption("dark");
+ expect(rootClasses()).toStrictEqual([ "theme-dark", "theme-preference-dark" ]);
+ expect(pressed()).toStrictEqual([ "dark" ]);
+ expect(localStorage.getItem("theme")).toBe("dark");
+
+ clickOption("light");
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-light" ]);
+ expect(localStorage.getItem("theme")).toBe("light");
+
+ clickOption("system");
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-system" ]);
+ expect(localStorage.getItem("theme")).toBeNull();
+ });
+
+ it("cycles light, dark and system from the header button", () => {
+ localStorage.setItem("theme", "light");
+ document.body.innerHTML = OPTIONS;
+ setupThemeSelector();
+ const cycle = document.getElementById("theme-cycle-button");
+ expect(cycle).not.toBeNull();
+
+ const preferences = [];
+ for (let i = 0; i < 3; i++) {
+ cycle?.click();
+ preferences.push(localStorage.getItem("theme"));
+ }
+ expect(preferences).toStrictEqual([ "dark", null, "light" ]);
+ expect(pressed()).toStrictEqual([ "light" ]);
+ });
+
+ it("follows a change of the system theme only while the preference is the system's", () => {
+ document.body.innerHTML = OPTIONS;
+ setupThemeSelector();
+
+ systemDark.change(true);
+ expect(rootClasses()).toStrictEqual([ "theme-dark", "theme-preference-system" ]);
+
+ clickOption("light");
+ systemDark.change(false);
+ systemDark.change(true);
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-light" ]);
+ });
+
+ it("ignores an unknown stored value and works when storage is blocked", () => {
+ localStorage.setItem("theme", "sepia");
+ systemDark = mockSystemTheme(true);
+ document.body.innerHTML = OPTIONS;
+ setupThemeSelector();
+ expect(rootClasses()).toStrictEqual([ "theme-dark", "theme-preference-system" ]);
+
+ const blocked = () => {
+ throw new Error("Storage is blocked.");
+ };
+ vi.stubGlobal("localStorage", { getItem: blocked, setItem: blocked, removeItem: blocked });
+ document.body.innerHTML = OPTIONS;
+ setupThemeSelector();
+ expect(rootClasses()).toStrictEqual([ "theme-dark", "theme-preference-system" ]);
+
+ clickOption("light");
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-light" ]);
+ });
+
+ it("keeps the switch of a custom template copied from an earlier page.ejs working", () => {
+ localStorage.setItem("theme", "dark");
document.body.innerHTML = `<div class="theme-selection"><input type="checkbox"></div>`;
const input = document.querySelector<HTMLInputElement>(".theme-selection input");
if (!input) {
@@ -23,16 +106,48 @@ describe("setupThemeSelector", () => {
input.checked = false;
input.dispatchEvent(new Event("change"));
- expect(document.documentElement.className).toBe("theme-light");
+ expect(rootClasses()).toStrictEqual([ "theme-light", "theme-preference-light" ]);
expect(localStorage.getItem("theme")).toBe("light");
input.checked = true;
input.dispatchEvent(new Event("change"));
- expect(document.documentElement.className).toBe("theme-dark");
expect(localStorage.getItem("theme")).toBe("dark");
});
- it("does nothing on a page without the switch", () => {
+ it("does nothing on a page without the controls", () => {
expect(() => setupThemeSelector()).not.toThrow();
});
});
+
+/** Replaces `matchMedia` with a system theme the spec can change. */
+function mockSystemTheme(matches: boolean) {
+ const listeners: (() => void)[] = [];
+ const query = {
+ matches,
+ addEventListener: (_type: string, listener: () => void) => listeners.push(listener)
+ };
+ vi.stubGlobal("matchMedia", () => query);
+ return {
+ change(dark: boolean) {
+ query.matches = dark;
+ for (const listener of listeners) {
+ listener();
+ }
+ }
+ };
+}
+
+function rootClasses() {
+ return [ ...document.documentElement.classList ].sort();
+}
+
+function pressed() {
+ return [ ...document.querySelectorAll<HTMLElement>(".theme-option[aria-pressed=true]") ]
+ .map((button) => button.dataset.theme);
+}
+
+function clickOption(theme: string) {
+ const button = document.querySelector<HTMLButtonElement>(`.theme-option[data-theme=${theme}]`);
+ expect(button).not.toBeNull();
+ button?.click();
+}
diff --git a/packages/share-theme/src/page/theme_switch.ts b/packages/share-theme/src/page/theme_switch.ts
index bd8bc54480..e6634ebb80 100644
--- a/packages/share-theme/src/page/theme_switch.ts
+++ b/packages/share-theme/src/page/theme_switch.ts
@@ -1,32 +1,88 @@
import "./theme_switch.css";
+type ThemePreference = "light" | "dark" | "system";
+
+/** The order of the buttons, and the order in which the header button cycles. */
+const PREFERENCES: ThemePreference[] = [ "light", "dark", "system" ];
+const STORAGE_KEY = "theme";
+
const themeRootEl = document.documentElement;
/**
- * 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.
+ * Wires the theme buttons of the left pane and the header button, which cycles through the same
+ * choices. `boot_script.ejs` applies the theme and its `theme-preference-*` class before the first
+ * paint, and the controls are styled from that class, so this only syncs `aria-pressed`, switches
+ * the theme on click and follows the system theme while the preference is "system".
*/
export default function setupThemeSelector() {
- const themeSwitch = document.querySelector<HTMLInputElement>(".theme-selection input");
- if (!themeSwitch) {
- return;
- }
+ const systemDark = window.matchMedia("(prefers-color-scheme: dark)");
+ const optionButtons = document.querySelectorAll<HTMLButtonElement>(".theme-option");
+ // The checkbox of custom templates copied from an earlier `page.ejs`.
+ const legacySwitch = document.querySelector<HTMLInputElement>(
+ ".theme-selection input[type=checkbox]");
+ let preference = readPreference();
+
+ const apply = () => {
+ const isDark = preference === "system" ? systemDark.matches : preference === "dark";
+ themeRootEl.classList.toggle("theme-dark", isDark);
+ themeRootEl.classList.toggle("theme-light", !isDark);
+ for (const option of PREFERENCES) {
+ themeRootEl.classList.toggle(`theme-preference-${option}`, option === preference);
+ }
+ for (const button of optionButtons) {
+ button.setAttribute("aria-pressed", String(button.dataset.theme === preference));
+ }
+ if (legacySwitch) {
+ legacySwitch.checked = isDark;
+ }
+ };
- themeSwitch.checked = themeRootEl.classList.contains("theme-dark");
- themeSwitch.addEventListener("change", () => {
- const theme = themeSwitch.checked ? "dark" : "light";
- setTheme(theme);
- localStorage.setItem("theme", theme);
+ const choose = (newPreference: ThemePreference) => {
+ preference = newPreference;
+ writePreference(preference);
+ apply();
+ };
+
+ for (const button of optionButtons) {
+ button.addEventListener("click", () => choose(parsePreference(button.dataset.theme)));
+ }
+ document.getElementById("theme-cycle-button")?.addEventListener("click", () => {
+ choose(PREFERENCES[(PREFERENCES.indexOf(preference) + 1) % PREFERENCES.length]);
});
+ legacySwitch?.addEventListener("change", () => choose(legacySwitch.checked ? "dark" : "light"));
+ systemDark.addEventListener("change", () => {
+ if (preference === "system") {
+ apply();
+ }
+ });
+
+ apply();
}
-function setTheme(theme: string) {
- if (theme === "dark") {
- themeRootEl.classList.add("theme-dark");
- themeRootEl.classList.remove("theme-light");
- } else {
- themeRootEl.classList.remove("theme-dark");
- themeRootEl.classList.add("theme-light");
+function parsePreference(value: string | null | undefined): ThemePreference {
+ return value === "light" || value === "dark" ? value : "system";
+}
+
+function readPreference() {
+ try {
+ return parsePreference(localStorage.getItem(STORAGE_KEY));
+ } catch {
+ return "system";
+ }
+}
+
+/**
+ * Stores an explicit theme; the system preference is stored as no value, as `boot_script.ejs`
+ * reads it.
+ */
+function writePreference(preference: ThemePreference) {
+ try {
+ if (preference === "system") {
+ localStorage.removeItem(STORAGE_KEY);
+ } else {
+ localStorage.setItem(STORAGE_KEY, preference);
+ }
+ } catch {
+ // The choice still applies to this page.
}
}
diff --git a/packages/share-theme/src/templates/boot_script.ejs b/packages/share-theme/src/templates/boot_script.ejs
index ad9605bfd8..8ddf6bc89c 100644
--- a/packages/share-theme/src/templates/boot_script.ejs
+++ b/packages/share-theme/src/templates/boot_script.ejs
@@ -12,8 +12,10 @@
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}`);
+ const stored = read("theme");
+ const preference = stored === "light" || stored === "dark" ? stored : "system";
+ const theme = preference === "system" ? (prefersDark ? "dark" : "light") : preference;
+ root.classList.add(`theme-${theme}`, `theme-preference-${preference}`);
window.glob = {
isStatic: <%= !!isStatic %>,
diff --git a/packages/share-theme/src/templates/boot_script.spec.ts b/packages/share-theme/src/templates/boot_script.spec.ts
index fc3b923f0e..0b5477a942 100644
--- a/packages/share-theme/src/templates/boot_script.spec.ts
+++ b/packages/share-theme/src/templates/boot_script.spec.ts
@@ -10,14 +10,18 @@ describe("boot_script.ejs", () => {
"theme": "dark"
});
- expect([ ...classes ]).toStrictEqual([ "theme-dark" ]);
+ expect([ ...classes ]).toStrictEqual([ "theme-dark", "theme-preference-dark" ]);
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("follows the system theme when storage holds no theme or cannot be read", () => {
+ expect([ ...runBootScript({}, true).classes ])
+ .toStrictEqual([ "theme-dark", "theme-preference-system" ]);
+ expect([ ...runBootScript(null, false).classes ])
+ .toStrictEqual([ "theme-light", "theme-preference-system" ]);
+ expect([ ...runBootScript({ theme: "sepia" }, true).classes ])
+ .toStrictEqual([ "theme-dark", "theme-preference-system" ]);
});
it("leaves no inline script in the page template besides the boot script", () => {
@@ -42,7 +46,17 @@ function runBootScript(stored: Record<string, string> | null, prefersDark = fals
}
},
matchMedia: () => ({ matches: prefersDark }),
- document: { documentElement: { classList: { add: (name: string) => classes.add(name) } } }
+ document: {
+ documentElement: {
+ classList: {
+ add(...names: string[]) {
+ for (const name of names) {
+ classes.add(name);
+ }
+ }
+ }
+ }
+ }
});
context.window = context;
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index c0fbcb500b..5c1c4e06f7 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -30,25 +30,29 @@
<div id="header">
<button aria-label="<%= t("share_theme.toggle-navigation") %>" id="left-pane-toggle-button" class="header-button"><span class="tn-icon bx bx-menu" aria-hidden="true"></span></button>
<%- include("site_logo", { id: "header-logo" }) %>
- <% if (headings.length > 1) { %>
- <button aria-label="<%= t("share_theme.toggle-toc") %>" id="toc-pane-toggle-button" class="header-button"><span class="tn-icon bx bx-list-ul" aria-hidden="true"></span></button>
- <% } else { %>
- <div class="header-button-placeholder"></div>
- <% } %>
+ <div class="header-actions">
+ <button type="button" id="theme-cycle-button" class="header-button">
+ <span class="theme-cycle-option" data-theme="light" title="<%= t("share_theme.theme-light") %>"><span class="tn-icon bx bx-sun" aria-hidden="true"></span><span class="visually-hidden"><%= t("share_theme.theme-current", { theme: t("share_theme.theme-light") }) %></span></span>
+ <span class="theme-cycle-option" data-theme="dark" title="<%= t("share_theme.theme-dark") %>"><span class="tn-icon bx bx-moon" aria-hidden="true"></span><span class="visually-hidden"><%= t("share_theme.theme-current", { theme: t("share_theme.theme-dark") }) %></span></span>
+ <span class="theme-cycle-option" data-theme="system" title="<%= t("share_theme.theme-system") %>"><span class="tn-icon bx bx-desktop" aria-hidden="true"></span><span class="visually-hidden"><%= t("share_theme.theme-current", { theme: t("share_theme.theme-system") }) %></span></span>
+ </button>
+ <% if (headings.length > 1) { %>
+ <button aria-label="<%= t("share_theme.toggle-toc") %>" id="toc-pane-toggle-button" class="header-button"><span class="tn-icon bx bx-list-ul" aria-hidden="true"></span></button>
+ <% } %>
+ </div>
</div>
<div id="split-pane">
<div id="left-pane">
<div id="navigation">
<div id="site-header">
<%- include("site_logo", { id: "site-logo" }) %>
- <div class="theme-selection">
+ <div class="theme-selection" role="group" aria-labelledby="sitetheme">
<span id="sitetheme"><%= t("share_theme.site-theme") %></span>
- <label class="switch">
- <input type="checkbox" aria-labelledby="sitetheme">
- <span class="slider"></span>
- <span class="dark-icon tn-icon bx bx-moon" aria-hidden="true"></span>
- <span class="light-icon tn-icon bx bx-sun" aria-hidden="true"></span>
- </label>
+ <div class="theme-options">
+ <button type="button" class="theme-option" data-theme="light" aria-label="<%= t("share_theme.theme-light") %>" title="<%= t("share_theme.theme-light") %>"><span class="tn-icon bx bx-sun" aria-hidden="true"></span></button>
+ <button type="button" class="theme-option" data-theme="dark" aria-label="<%= t("share_theme.theme-dark") %>" title="<%= t("share_theme.theme-dark") %>"><span class="tn-icon bx bx-moon" aria-hidden="true"></span></button>
+ <button type="button" class="theme-option" data-theme="system" aria-label="<%= t("share_theme.theme-system") %>" title="<%= t("share_theme.theme-system") %>"><span class="tn-icon bx bx-desktop" aria-hidden="true"></span></button>
+ </div>
</div>
<% if (navigation.length) { %>
<div class="search-item">