Skip to content

Build your personal knowledge base with Trilium Notes

feat(options): seamless transition when switching themes

Elian Doran2bcc2a28b4ab
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index 48a463273f..6cf7e8eead 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -1,4 +1,4 @@
-import { getThemeStyle } from "./services/theme";
+import { buildThemeStylesheetRefs, createStylesheetLink, getThemeStyle, StylesheetRef } from "./services/theme";
async function bootstrap() {
showSplash();
@@ -79,67 +79,25 @@ async function loadBootstrapCss() {
}
}
-type StylesheetRef = {
- href: string;
- media?: string;
-};
-
-function getConfiguredThemeStylesheets(stylesheetsPath: string, theme: string, customThemeCssUrl?: string) {
- if (theme === "auto") {
- return [{ href: `${stylesheetsPath}/theme-dark.css`, media: "(prefers-color-scheme: dark)" }];
- }
-
- if (theme === "dark") {
- return [{ href: `${stylesheetsPath}/theme-dark.css` }];
- }
-
- if (theme === "next") {
- return [
- { href: `${stylesheetsPath}/theme-next-light.css` },
- { href: `${stylesheetsPath}/theme-next-dark.css`, media: "(prefers-color-scheme: dark)" }
- ];
- }
-
- if (theme === "next-light") {
- return [{ href: `${stylesheetsPath}/theme-next-light.css` }];
- }
-
- if (theme === "next-dark") {
- return [{ href: `${stylesheetsPath}/theme-next-dark.css` }];
- }
-
- if (theme !== "light" && customThemeCssUrl) {
- return [{ href: customThemeCssUrl }];
- }
-
- return [];
-}
-
function loadStylesheets() {
const { device, assetPath, theme, themeBase, customThemeCssUrl } = window.glob;
- const stylesheetsPath = `${assetPath}/stylesheets`;
-
- const cssToLoad: StylesheetRef[] = [];
- if (device !== "print") {
- cssToLoad.push({ href: `${stylesheetsPath}/ckeditor-theme.css` });
- cssToLoad.push({ href: `api/fonts` });
- cssToLoad.push({ href: `${stylesheetsPath}/theme-light.css` });
- cssToLoad.push(...getConfiguredThemeStylesheets(stylesheetsPath, theme, customThemeCssUrl));
- if (themeBase) {
- cssToLoad.push(...getConfiguredThemeStylesheets(stylesheetsPath, themeBase));
- }
- cssToLoad.push({ href: `${stylesheetsPath}/style.css` });
+ if (device === "print") {
+ return;
}
- for (const { href, media } of cssToLoad) {
- const linkEl = document.createElement("link");
- linkEl.href = href;
- linkEl.rel = "stylesheet";
- if (media) {
- linkEl.media = media;
- }
- document.head.appendChild(linkEl);
+ const stylesheetsPath = `${assetPath}/stylesheets`;
+ appendStylesheet({ href: `${stylesheetsPath}/ckeditor-theme.css` });
+ appendStylesheet({ href: `api/fonts` });
+ // The light theme is always loaded as the baseline and acts as the anchor for live theme swapping.
+ appendStylesheet({ href: `${stylesheetsPath}/theme-light.css` }, { base: true });
+ for (const ref of buildThemeStylesheetRefs(theme, customThemeCssUrl, themeBase)) {
+ appendStylesheet(ref, { theme: true });
}
+ appendStylesheet({ href: `${stylesheetsPath}/style.css` });
+}
+
+function appendStylesheet(ref: StylesheetRef, opts?: { base?: boolean; theme?: boolean }) {
+ document.head.appendChild(createStylesheetLink(ref, opts));
}
function loadIcons() {
diff --git a/apps/client/src/services/theme.spec.ts b/apps/client/src/services/theme.spec.ts
index a31fd1c19b..e74a0f6341 100644
--- a/apps/client/src/services/theme.spec.ts
+++ b/apps/client/src/services/theme.spec.ts
@@ -1,6 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { getEffectiveThemeStyle, getThemeStyle } from "./theme.js";
+import { applyTheme, buildThemeStylesheetRefs, getConfiguredThemeStylesheets, getEffectiveThemeStyle, getThemeStyle } from "./theme.js";
+
+const STYLESHEETS_PATH = "/assets/stylesheets";
type ThemeValue = string | undefined;
@@ -113,3 +115,127 @@ describe("getEffectiveThemeStyle", () => {
expect(getEffectiveThemeStyle()).toBe("light");
});
});
+
+describe("getConfiguredThemeStylesheets", () => {
+ it("resolves each built-in theme to its stylesheets", () => {
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "light")).toEqual([]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "dark")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-dark.css` }
+ ]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "auto")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-dark.css`, media: "(prefers-color-scheme: dark)" }
+ ]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "next")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-next-light.css` },
+ { href: `${STYLESHEETS_PATH}/theme-next-dark.css`, media: "(prefers-color-scheme: dark)" }
+ ]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "next-light")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-next-light.css` }
+ ]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "next-dark")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-next-dark.css` }
+ ]);
+ });
+
+ it("uses the custom CSS URL for non-built-in themes, but never for the light baseline", () => {
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "my-theme", "api/notes/download/abc123")).toEqual([
+ { href: "api/notes/download/abc123" }
+ ]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "light", "api/notes/download/abc123")).toEqual([]);
+ expect(getConfiguredThemeStylesheets(STYLESHEETS_PATH, "my-theme")).toEqual([]);
+ });
+});
+
+describe("buildThemeStylesheetRefs", () => {
+ beforeEach(() => {
+ setTheme(undefined);
+ win.glob = { ...(win.glob ?? {}), assetPath: "/assets" };
+ });
+
+ it("appends the base theme stylesheets underneath a custom theme", () => {
+ expect(buildThemeStylesheetRefs("my-theme", "api/notes/download/abc123", "next-dark")).toEqual([
+ { href: "api/notes/download/abc123" },
+ { href: `${STYLESHEETS_PATH}/theme-next-dark.css` }
+ ]);
+ });
+
+ it("omits base stylesheets when no base is configured", () => {
+ expect(buildThemeStylesheetRefs("dark")).toEqual([
+ { href: `${STYLESHEETS_PATH}/theme-dark.css` }
+ ]);
+ });
+});
+
+describe("applyTheme", () => {
+ beforeEach(() => {
+ win.glob = { ...(win.glob ?? {}), assetPath: "/assets" };
+ document.head.innerHTML = "";
+ document.body.removeAttribute("data-theme-id");
+ // Baseline light theme link acts as the insertion anchor for swapped themes.
+ const base = document.createElement("link");
+ base.rel = "stylesheet";
+ base.href = `${STYLESHEETS_PATH}/theme-light.css`;
+ base.setAttribute("data-theme-base", "true");
+ document.head.appendChild(base);
+ });
+
+ afterEach(() => {
+ document.head.innerHTML = "";
+ });
+
+ it("swaps the active theme stylesheets and only removes the old ones once the new ones load", async () => {
+ applyTheme("dark");
+ fireLoadOnPendingThemeLinks();
+ await Promise.resolve();
+ expect(themeStylesheetHrefs()).toEqual([`${STYLESHEETS_PATH}/theme-dark.css`]);
+
+ // Switching to next adds the new links before the old dark link is removed.
+ applyTheme("next");
+ expect(themeStylesheetHrefs()).toEqual([
+ `${STYLESHEETS_PATH}/theme-dark.css`,
+ `${STYLESHEETS_PATH}/theme-next-light.css`,
+ `${STYLESHEETS_PATH}/theme-next-dark.css`
+ ]);
+
+ fireLoadOnPendingThemeLinks();
+ await Promise.resolve();
+ expect(themeStylesheetHrefs()).toEqual([
+ `${STYLESHEETS_PATH}/theme-next-light.css`,
+ `${STYLESHEETS_PATH}/theme-next-dark.css`
+ ]);
+ expect(document.body.getAttribute("data-theme-id")).toBe("next");
+ });
+
+ it("removes theme stylesheets when switching to the bare light baseline", async () => {
+ applyTheme("dark");
+ fireLoadOnPendingThemeLinks();
+ expect(themeStylesheetHrefs()).toHaveLength(1);
+
+ applyTheme("light");
+ // No new links to wait for, so the swap finalizes on the next microtask.
+ await Promise.resolve();
+ expect(themeStylesheetHrefs()).toHaveLength(0);
+ expect(document.body.getAttribute("data-theme-id")).toBe("light");
+ // The baseline light link is preserved.
+ expect(document.head.querySelector("link[data-theme-base]")).not.toBeNull();
+ });
+
+ it("updates window.glob so the active theme metadata stays current", () => {
+ applyTheme("my-theme", "api/notes/download/abc123", "next-dark");
+ expect(win.glob?.theme).toBe("my-theme");
+ expect(win.glob?.customThemeCssUrl).toBe("api/notes/download/abc123");
+ expect(win.glob?.themeBase).toBe("next-dark");
+ });
+});
+
+function themeStylesheetHrefs() {
+ return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-theme-stylesheet]"))
+ .map((link) => link.getAttribute("href"));
+}
+
+/** happy-dom does not fetch stylesheets, so emulate the pending links finishing loading. */
+function fireLoadOnPendingThemeLinks() {
+ for (const link of document.head.querySelectorAll<HTMLLinkElement>("link[data-theme-stylesheet]")) {
+ link.dispatchEvent(new Event("load"));
+ }
+}
diff --git a/apps/client/src/services/theme.ts b/apps/client/src/services/theme.ts
index 9aa42c22ba..793c693efb 100644
--- a/apps/client/src/services/theme.ts
+++ b/apps/client/src/services/theme.ts
@@ -1,3 +1,5 @@
+import { readCssVar } from "../utils/css-var.js";
+
export function getThemeStyle(): "auto" | "light" | "dark" {
const configuredTheme = window.glob?.theme;
if (configuredTheme === "auto" || configuredTheme === "next") {
@@ -33,3 +35,165 @@ export function getEffectiveThemeStyle(): "light" | "dark" {
return themeStyle === "dark" ? "dark" : "light";
}
+
+export interface StylesheetRef {
+ href: string;
+ media?: string;
+}
+
+type ThemeBase = "next" | "next-light" | "next-dark";
+
+/** Built-in themes whose stylesheets can be resolved purely on the client, without a server lookup. */
+const BUILTIN_THEMES = new Set([ "auto", "light", "dark", "next", "next-light", "next-dark" ]);
+
+/** Marks the always-present baseline `theme-light.css` link, used as the insertion anchor when swapping themes. */
+const THEME_BASE_ATTR = "data-theme-base";
+
+/** Marks the swappable theme stylesheet links so they can be replaced when the theme changes. */
+const THEME_STYLESHEET_ATTR = "data-theme-stylesheet";
+
+export function getConfiguredThemeStylesheets(stylesheetsPath: string, theme: string, customThemeCssUrl?: string): StylesheetRef[] {
+ if (theme === "auto") {
+ return [{ href: `${stylesheetsPath}/theme-dark.css`, media: "(prefers-color-scheme: dark)" }];
+ }
+
+ if (theme === "dark") {
+ return [{ href: `${stylesheetsPath}/theme-dark.css` }];
+ }
+
+ if (theme === "next") {
+ return [
+ { href: `${stylesheetsPath}/theme-next-light.css` },
+ { href: `${stylesheetsPath}/theme-next-dark.css`, media: "(prefers-color-scheme: dark)" }
+ ];
+ }
+
+ if (theme === "next-light") {
+ return [{ href: `${stylesheetsPath}/theme-next-light.css` }];
+ }
+
+ if (theme === "next-dark") {
+ return [{ href: `${stylesheetsPath}/theme-next-dark.css` }];
+ }
+
+ if (theme !== "light" && customThemeCssUrl) {
+ return [{ href: customThemeCssUrl }];
+ }
+
+ return [];
+}
+
+/** Resolves every swappable stylesheet for the given theme (the theme itself plus an optional `next` base). */
+export function buildThemeStylesheetRefs(theme: string, customThemeCssUrl?: string, themeBase?: string): StylesheetRef[] {
+ const stylesheetsPath = `${window.glob.assetPath}/stylesheets`;
+ const refs = getConfiguredThemeStylesheets(stylesheetsPath, theme, customThemeCssUrl);
+ if (themeBase) {
+ refs.push(...getConfiguredThemeStylesheets(stylesheetsPath, themeBase));
+ }
+ return refs;
+}
+
+export function createStylesheetLink(ref: StylesheetRef, opts?: { base?: boolean; theme?: boolean }): HTMLLinkElement {
+ const linkEl = document.createElement("link");
+ linkEl.href = ref.href;
+ linkEl.rel = "stylesheet";
+ if (ref.media) {
+ linkEl.media = ref.media;
+ }
+ if (opts?.base) {
+ linkEl.setAttribute(THEME_BASE_ATTR, "true");
+ }
+ if (opts?.theme) {
+ linkEl.setAttribute(THEME_STYLESHEET_ATTR, "true");
+ }
+ return linkEl;
+}
+
+/** Toggles the `light-theme`/`dark-theme` body classes to match the active theme's `--theme-style`. */
+export function updateColorSchemeClasses() {
+ const colorScheme = readCssVar(document.body, "theme-style").asString();
+ document.body.classList.toggle("light-theme", colorScheme === "light");
+ document.body.classList.toggle("dark-theme", colorScheme === "dark");
+}
+
+/** Reads the current `theme` option and applies it live, resolving custom-theme metadata from the server if needed. */
+export async function applyThemeFromOptions() {
+ // Imported lazily because this module is loaded by the entry point before jQuery is initialized;
+ // a static import would pull options -> server -> i18n into the boot graph and crash on `$`.
+ const { default: options } = await import("./options.js");
+ const theme = options.get("theme");
+ if (BUILTIN_THEMES.has(theme)) {
+ applyTheme(theme);
+ return;
+ }
+
+ // Custom theme — resolve its note to build the CSS URL and the optional `next` base.
+ const { default: server } = await import("./server.js");
+ const userThemes = await server.get<CustomThemeInfo[]>("options/user-themes");
+ const match = userThemes.find((userTheme) => userTheme.val === theme);
+ applyTheme(
+ theme,
+ match ? `api/notes/download/${match.noteId}` : undefined,
+ match?.appThemeBase
+ );
+}
+
+interface CustomThemeInfo {
+ val: string;
+ noteId: string;
+ appThemeBase?: ThemeBase;
+}
+
+/**
+ * Swaps the active theme stylesheets without reloading the page. The new stylesheets are appended first and the
+ * previous ones removed only once the new ones have loaded, so the swap stays free of a flash of unstyled content.
+ */
+export function applyTheme(theme: string, customThemeCssUrl?: string, themeBase?: string) {
+ window.glob.theme = theme;
+ window.glob.customThemeCssUrl = customThemeCssUrl;
+ window.glob.themeBase = themeBase as ThemeBase | undefined;
+
+ const refs = buildThemeStylesheetRefs(theme, customThemeCssUrl, themeBase);
+ const oldLinks = Array.from(document.head.querySelectorAll<HTMLLinkElement>(`link[${THEME_STYLESHEET_ATTR}]`));
+ const anchor: HTMLElement | null = oldLinks.at(-1) ?? document.head.querySelector<HTMLLinkElement>(`link[${THEME_BASE_ATTR}]`);
+
+ let insertAfter = anchor;
+ const newLinks = refs.map((ref) => {
+ const link = createStylesheetLink(ref, { theme: true });
+ if (insertAfter) {
+ insertAfter.after(link);
+ } else {
+ document.head.appendChild(link);
+ }
+ insertAfter = link;
+ return link;
+ });
+
+ void waitForStylesheets(newLinks).then(() => {
+ for (const oldLink of oldLinks) {
+ oldLink.remove();
+ }
+ document.body.setAttribute("data-theme-id", theme);
+ updateColorSchemeClasses();
+ });
+}
+
+function waitForStylesheets(links: HTMLLinkElement[]): Promise<void> {
+ if (links.length === 0) {
+ return Promise.resolve();
+ }
+
+ return new Promise((resolve) => {
+ let remaining = links.length;
+ const onSettled = () => {
+ remaining--;
+ if (remaining <= 0) {
+ resolve();
+ }
+ };
+ for (const link of links) {
+ link.addEventListener("load", onSettled, { once: true });
+ link.addEventListener("error", onSettled, { once: true });
+ }
+ });
+}
diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.ts
index 403ef01678..eb1163c604 100644
--- a/apps/client/src/widgets/containers/root_container.ts
+++ b/apps/client/src/widgets/containers/root_container.ts
@@ -3,6 +3,7 @@ import { LOCALES } from "@triliumnext/commons";
import { EventData } from "../../components/app_context.js";
import { getEnabledExperimentalFeatureIds } from "../../services/experimental_features.js";
import options from "../../services/options.js";
+import { applyThemeFromOptions, updateColorSchemeClasses } from "../../services/theme.js";
import utils, { isIOS, isMobile } from "../../services/utils.js";
import { readCssVar } from "../../utils/css-var.js";
import type BasicWidget from "../basic_widget.js";
@@ -51,6 +52,10 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
}
entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
+ if (loadResults.isOptionReloaded("theme")) {
+ void applyThemeFromOptions();
+ }
+
if (loadResults.isOptionReloaded("motionEnabled")) {
this.#setMotion();
}
@@ -71,7 +76,7 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
}
#initTheme() {
- const colorSchemeChangeObserver = matchMedia("(prefers-color-scheme: dark)")
+ const colorSchemeChangeObserver = matchMedia("(prefers-color-scheme: dark)");
colorSchemeChangeObserver.addEventListener("change", () => this.#updateColorScheme());
this.#updateColorScheme();
@@ -79,10 +84,7 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
}
#updateColorScheme() {
- const colorScheme = readCssVar(document.body, "theme-style").asString();
-
- document.body.classList.toggle("light-theme", colorScheme === "light");
- document.body.classList.toggle("dark-theme", colorScheme === "dark");
+ updateColorSchemeClasses();
}
#onMobileResize() {
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsx
index 003e9f937e..16f3491fad 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx
@@ -146,7 +146,7 @@ export default function AppearanceSettings() {
}
function UserInterface() {
- const [ theme, setTheme ] = useTriliumOption("theme", true);
+ const [ theme, setTheme ] = useTriliumOption("theme");
const [ customThemes, setCustomThemes ] = useState<CustomTheme[]>([]);
const [ newLayout, setNewLayout ] = useTriliumOptionBool("newLayout");
const [ layoutOrientation, setLayoutOrientation ] = useTriliumOption("layoutOrientation", true);
diff --git a/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.tsx b/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.tsx
index 370a9f59d1..68113cd867 100644
--- a/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.tsx
@@ -2,45 +2,34 @@ import "./SettingsNavigation.css";
import clsx from "clsx";
-import NoteContext from "../../../../components/note_context";
import { useChildNotes } from "../../../react/hooks";
interface SettingsNavigationProps {
/** Note ID of the settings page currently being displayed (e.g. `_optionsAppearance`). */
activeNoteId: string;
- /** The context the selector lives in, used to switch pages in place (e.g. inside the quick-edit popup). */
- noteContext: NoteContext | undefined;
}
/**
* In-content selector for the settings pages, rendered alongside the active options page.
*
* It mirrors the list of pages otherwise reached through the note tree, reading them straight from
- * the `_options` subtree so titles, icons and ordering stay in sync. Clicking an entry switches the
- * page within the current context — including the quick-edit popup, which has no note tree — while
- * keeping the popup open. Modified clicks (ctrl/middle/shift) fall through to the global link handler
- * so the page can still be opened in a new tab or window.
+ * the `_options` subtree so titles, icons and ordering stay in sync. Each entry is a plain internal
+ * link; navigation within the quick-edit popup is handled by the popup's own link interceptor, while
+ * modified clicks (ctrl/middle/shift) fall through to the global handler to open a new tab/window.
*/
-export default function SettingsNavigation({ activeNoteId, noteContext }: SettingsNavigationProps) {
+export default function SettingsNavigation({ activeNoteId }: SettingsNavigationProps) {
const pages = useChildNotes("_options");
return (
<nav className="settings-navigation">
{pages.map((page) => {
const isActive = page.noteId === activeNoteId;
- const notePath = `root/_hidden/_options/${page.noteId}`;
return (
<a
key={page.noteId}
- href={`#${notePath}`}
+ href={`#root/_hidden/_options/${page.noteId}`}
className={clsx("settings-navigation-item no-tooltip-preview", { active: isActive })}
aria-current={isActive ? "page" : undefined}
- onClick={(e) => {
- if (!noteContext || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
- e.preventDefault();
- e.stopPropagation();
- void noteContext.setNote(notePath, { keepActiveDialog: true });
- }}
>
<span className={page.getIcon()} />
<span className="settings-navigation-title">{page.title}</span>
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index d160ae9388..ba87b16687 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -17,6 +17,7 @@ interface UserTheme {
title: string; // title of the theme, displayed in the UI
noteId: string; // ID of the note containing the theme
icon: string; // icon class of the note
+ appThemeBase?: "next" | "next-light" | "next-dark"; // optional base theme to load underneath the custom theme
}
// options allowed to be updated directly in the Options dialog
@@ -239,7 +240,8 @@ function getUserThemes() {
val: value,
title,
noteId: note.noteId,
- icon: note.getIcon()
+ icon: note.getIcon(),
+ appThemeBase: (note.getLabelValue("appThemeBase") ?? undefined) as "next" | "next-light" | "next-dark" | undefined
});
}