Skip to content

Build your personal knowledge base with Trilium Notes

fix(theme): recover an OS light/dark switch missed while hidden (closes #11267)

Elian Doranb387bbf5ba70
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.ts
index e7dfc8b17c..5d6e9c6852 100644
--- a/apps/client/src/desktop.ts
+++ b/apps/client/src/desktop.ts
@@ -11,7 +11,7 @@ import { t } from "./services/i18n.js";
import { syncNativeWindowWithTheme } from "./services/native_window.js";
import noteAutocompleteService from "./services/note_autocomplete.js";
import noteTooltipService from "./services/note_tooltip.js";
-import { setBackgroundEffectsSuspended } from "./services/theme.js";
+import { onEffectiveThemeStyleChange, setBackgroundEffectsSuspended } from "./services/theme.js";
import toastService from "./services/toast.js";
import utils from "./services/utils.js";
import { preloadCommonNoteTypes } from "./widgets/note_types.js";
@@ -77,7 +77,7 @@ function initOnElectron() {
// With an "auto" theme the effective colors of background effects and the native title bar
// follow the OS color scheme.
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", syncNativeWindowWithTheme);
+ onEffectiveThemeStyleChange(() => syncNativeWindowWithTheme());
// Clear navigation history on frontend refresh.
api.navigation.clearNavigationHistory();
diff --git a/apps/client/src/services/syntax_highlight.spec.ts b/apps/client/src/services/syntax_highlight.spec.ts
index e980c29e12..3ea3e3a266 100644
--- a/apps/client/src/services/syntax_highlight.spec.ts
+++ b/apps/client/src/services/syntax_highlight.spec.ts
@@ -45,6 +45,20 @@ vi.mock("@triliumnext/highlightjs", () => {
};
});
+// Capture the color-scheme subscription so tests can fire it directly, keeping the rest of theme.ts real
+// (getEffectiveCodeBlockTheme resolves the light/dark choice through getEffectiveThemeStyle).
+const themeSubscription = vi.hoisted(() => ({ listeners: [] as Array<() => void> }));
+vi.mock("./theme.js", async (orig) => {
+ const actual = (await orig()) as Record<string, unknown>;
+ return {
+ ...actual,
+ onEffectiveThemeStyleChange: (listener: () => void) => {
+ themeSubscription.listeners.push(listener);
+ return () => {};
+ }
+ };
+});
+
// Spy on the clipboard helpers so we can assert which copy path the click handlers take
// (copyTextWithToast in-app vs copyText in share mode). Persists across vi.resetModules().
const clip = vi.hoisted(() => ({
@@ -106,7 +120,8 @@ describe("syntax_highlight", () => {
hl.loadTheme.mockClear().mockImplementation(async () => {});
hl.highlight.mockClear().mockImplementation(() => ({ value: "HL" }));
hl.highlightAuto.mockClear().mockImplementation(() => ({ value: "AUTO" }));
- // matchMedia is required by the color-scheme listener.
+ themeSubscription.listeners.length = 0;
+ // matchMedia backs getEffectiveThemeStyle, which picks the light or dark code-block theme.
(window as any).matchMedia = vi.fn(() => ({
matches: false,
addEventListener: vi.fn(),
@@ -387,7 +402,7 @@ describe("syntax_highlight", () => {
});
describe("color scheme listener + cache eviction", () => {
- it("registers a matchMedia listener once and re-applies theme on change", async () => {
+ it("subscribes to the effective color scheme once and re-applies the theme on change", async () => {
const mod = await freshModule();
setOptions({
codeBlockThemeMatchesApp: "true",
@@ -396,53 +411,41 @@ describe("syntax_highlight", () => {
codeNotesMimeTypes: "[]"
});
- let changeHandler: (() => void) | undefined;
- const addEventListener = vi.fn((_evt: string, cb: () => void) => {
- changeHandler = cb;
- });
- (window as any).matchMedia = vi.fn(() => ({ matches: true, addEventListener }));
+ (window as any).matchMedia = vi.fn(() => ({ matches: true, addEventListener: vi.fn() }));
(window as any).glob = { isMainWindow: true, theme: "auto" };
// first ensure registers the listener and marks highlightingLoaded
await mod.ensureMimeTypesForHighlighting("text-css");
- expect(addEventListener).toHaveBeenCalledTimes(1);
+ expect(themeSubscription.listeners).toHaveLength(1);
hl.loadTheme.mockClear();
- // OS scheme change with matchesApp=true + highlightingLoaded -> re-load theme
+ // Scheme change with matchesApp=true + highlightingLoaded -> re-load theme
// (the handler resolves highlight.js via a dynamic import, hence the waitFor)
- changeHandler!();
+ themeSubscription.listeners[0]?.();
await vi.waitFor(() => expect(hl.loadTheme).toHaveBeenCalledTimes(1));
- // a second ensure must NOT register the listener again
+ // a second ensure must NOT subscribe again
await mod.ensureMimeTypesForHighlighting("text-x-csrc");
- expect(addEventListener).toHaveBeenCalledTimes(1);
+ expect(themeSubscription.listeners).toHaveLength(1);
});
- it("registers the matchMedia listener at most once (idempotent)", async () => {
+ it("subscribes at most once (idempotent)", async () => {
const mod = await freshModule();
- const addEventListener = vi.fn();
- (window as any).matchMedia = vi.fn(() => ({ matches: false, addEventListener }));
mod.ensureColorSchemeListener();
mod.ensureColorSchemeListener(); // second call hits the early-return
- expect(addEventListener).toHaveBeenCalledTimes(1);
+ expect(themeSubscription.listeners).toHaveLength(1);
});
it("does not re-apply the theme on change when matchesApp is false", async () => {
const mod = await freshModule();
setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs", codeNotesMimeTypes: "[]" });
- let changeHandler: (() => void) | undefined;
- const addEventListener = vi.fn((_evt: string, cb: () => void) => {
- changeHandler = cb;
- });
- (window as any).matchMedia = vi.fn(() => ({ matches: false, addEventListener }));
-
await mod.ensureMimeTypesForHighlighting("text-css");
hl.loadTheme.mockClear();
setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
- changeHandler!();
+ themeSubscription.listeners[0]?.();
expect(hl.loadTheme).not.toHaveBeenCalled();
});
diff --git a/apps/client/src/services/syntax_highlight.ts b/apps/client/src/services/syntax_highlight.ts
index d87c7b704c..6218603287 100644
--- a/apps/client/src/services/syntax_highlight.ts
+++ b/apps/client/src/services/syntax_highlight.ts
@@ -7,7 +7,7 @@ import { copyText, copyTextWithToast } from "./clipboard_ext.js";
import { t } from "./i18n.js";
import mime_types from "./mime_types.js";
import options from "./options.js";
-import { getEffectiveThemeStyle } from "./theme.js";
+import { getEffectiveThemeStyle, onEffectiveThemeStyleChange } from "./theme.js";
import { isShare } from "./utils.js";
let highlightingLoaded = false;
@@ -20,14 +20,14 @@ function getEffectiveCodeBlockTheme(): string {
return String(options.get("codeBlockTheme"));
}
-// Re-apply the highlight.js theme when the OS color scheme changes, so that
+// Re-apply the highlight.js theme when the effective color scheme changes, so that
// "match app appearance" reacts in real time.
let colorSchemeListenerRegistered = false;
export function ensureColorSchemeListener() {
if (colorSchemeListenerRegistered) return;
colorSchemeListenerRegistered = true;
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
+ onEffectiveThemeStyleChange(() => {
if (highlightingLoaded && options.get("codeBlockThemeMatchesApp") === "true") {
loadHighlightingTheme(getEffectiveCodeBlockTheme());
}
diff --git a/apps/client/src/services/theme.spec.ts b/apps/client/src/services/theme.spec.ts
index fd3b40d9db..53931ff815 100644
--- a/apps/client/src/services/theme.spec.ts
+++ b/apps/client/src/services/theme.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { applyTheme, buildThemeStylesheetRefs, getConfiguredThemeStylesheets, getEffectiveThemeStyle, getThemeStyle, initThemeChangeNotifier } from "./theme.js";
+import { applyTheme, buildThemeStylesheetRefs, getConfiguredThemeStylesheets, getEffectiveThemeStyle, getThemeStyle, initThemeChangeNotifier, onEffectiveThemeStyleChange } from "./theme.js";
// theme.ts lazily imports the app context to emit `themeChanged`; mock it so the tests capture the emission
// without pulling the whole app graph into happy-dom.
@@ -32,6 +32,11 @@ function setTheme(theme: ThemeValue) {
win.glob = { ...(win.glob ?? {}), theme };
}
+/** happy-dom models no window visibility, so `document.hidden` is shadowed on the instance. */
+function setDocumentHidden(hidden: boolean) {
+ Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden });
+}
+
afterEach(async () => {
// Let any pending `themeChanged` dynamic import settle before teardown, so a late emit can't leak into the
// next test, then clear the captured calls.
@@ -39,6 +44,7 @@ afterEach(async () => {
win.getComputedStyle = originalGetComputedStyle;
win.matchMedia = originalMatchMedia;
win.glob = originalGlob;
+ Reflect.deleteProperty(document, "hidden");
triggerEvent.mockClear();
vi.restoreAllMocks();
});
@@ -329,6 +335,57 @@ describe("initThemeChangeNotifier", () => {
await new Promise((resolve) => setTimeout(resolve));
expect(triggerEvent).not.toHaveBeenCalled();
});
+
+ /** Chromium withholds the `change` event while the window is hidden and never replays it (#11267). */
+ function flipWithoutEventWhileHidden(mql: { matches: boolean }) {
+ setDocumentHidden(true);
+ mql.matches = true;
+ setDocumentHidden(false);
+ document.dispatchEvent(new Event("visibilitychange"));
+ }
+
+ it("recovers an OS flip that arrived with no change event while the window was hidden", async () => {
+ setTheme("auto");
+ const mql = installMatchMedia(false);
+ initThemeChangeNotifier();
+
+ flipWithoutEventWhileHidden(mql);
+
+ await vi.waitFor(() => expect(triggerEvent).toHaveBeenCalledWith("themeChanged", { themeStyle: "dark" }));
+ });
+
+ it("notifies subscribers of a flip recovered on becoming visible, exactly once", async () => {
+ setTheme("auto");
+ const mql = installMatchMedia(false);
+ const listener = vi.fn();
+ const unsubscribe = onEffectiveThemeStyleChange(listener);
+ initThemeChangeNotifier();
+
+ flipWithoutEventWhileHidden(mql);
+ expect(listener).toHaveBeenCalledExactlyOnceWith("dark");
+
+ // Becoming visible again with nothing changed must stay quiet.
+ document.dispatchEvent(new Event("visibilitychange"));
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ mql.matches = false;
+ mql.listener?.();
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ it("stays quiet while the window is still hidden", async () => {
+ setTheme("auto");
+ const mql = installMatchMedia(false);
+ initThemeChangeNotifier();
+
+ setDocumentHidden(true);
+ mql.matches = true;
+ document.dispatchEvent(new Event("visibilitychange"));
+
+ await new Promise((resolve) => setTimeout(resolve));
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
});
function themeStylesheetHrefs() {
diff --git a/apps/client/src/services/theme.ts b/apps/client/src/services/theme.ts
index 51c1983903..db1bfb2485 100644
--- a/apps/client/src/services/theme.ts
+++ b/apps/client/src/services/theme.ts
@@ -236,35 +236,68 @@ export function applyTheme(theme: string, customThemeCssUrl?: string, themeBase?
});
}
-/** Last effective light/dark style broadcast via `themeChanged`, so the OS-preference listener only fires when
- * the style actually flips (an auto theme following the OS) rather than on every preference change. */
-let lastNotifiedThemeStyle: "light" | "dark" | null = null;
+/** Last effective light/dark style the subscribers and `themeChanged` were told about, so an OS-preference
+ * change only propagates when the style actually flips (an auto theme following the OS). */
+let lastKnownThemeStyle: "light" | "dark" | null = null;
-/** Broadcasts the global `themeChanged` event. `appContext` is imported lazily because this module is loaded by
- * the boot entry point before the app context (and jQuery) exist; the import resolves later, when an actual
- * theme change occurs. */
-function notifyThemeChanged() {
- const themeStyle = getEffectiveThemeStyle();
- lastNotifiedThemeStyle = themeStyle;
- void import("../components/app_context.js").then(({ default: appContext }) => {
- void appContext.triggerEvent("themeChanged", { themeStyle });
- });
+/** Callbacks registered through {@link onEffectiveThemeStyleChange}. */
+const themeStyleListeners = new Set<(themeStyle: "light" | "dark") => void>();
+
+/**
+ * Subscribes to changes of the effective light/dark style, whether they come from the OS preference or from
+ * an explicit theme swap. Returns a function that removes the subscription.
+ *
+ * Prefer this over a private `matchMedia("(prefers-color-scheme: dark)")` listener: this one also fires for
+ * a theme-option swap, and it recovers the OS switches Chromium drops (see {@link initThemeChangeNotifier}).
+ */
+export function onEffectiveThemeStyleChange(listener: (themeStyle: "light" | "dark") => void) {
+ themeStyleListeners.add(listener);
+ return () => themeStyleListeners.delete(listener);
}
/**
- * Installs a listener so that, while an auto theme follows the OS, a system light/dark switch also emits
- * `themeChanged` — explicit theme-option swaps already emit from {@link applyTheme}. Call once at startup.
+ * Installs the listeners that keep the effective light/dark style current while an auto theme follows the OS;
+ * explicit theme-option swaps notify from {@link applyTheme}. Call once at startup.
+ *
+ * Chromium withholds `prefers-color-scheme` change events from a hidden window and does not replay them when
+ * it is shown again, so an OS switch made while the window sat in the tray stays unapplied until restart
+ * (#11267). Reconciling on `visibilitychange` recovers that missed edge; the media query alone cannot.
*/
export function initThemeChangeNotifier() {
- if (!window.matchMedia) {
- return;
+ lastKnownThemeStyle = getEffectiveThemeStyle();
+
+ // A module-level reference, so a repeated init cannot stack duplicate listeners.
+ document.addEventListener("visibilitychange", reconcileOnceVisible);
+
+ window.matchMedia?.("(prefers-color-scheme: dark)")
+ .addEventListener("change", reconcileEffectiveThemeStyle);
+}
+
+/** Reads the effective style again once the window is back on screen, where a dropped OS switch shows up. */
+function reconcileOnceVisible() {
+ if (!document.hidden) {
+ reconcileEffectiveThemeStyle();
}
- lastNotifiedThemeStyle = getEffectiveThemeStyle();
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
- // A fixed light/dark theme ignores the OS preference, so only emit when the effective style truly flips.
- if (getEffectiveThemeStyle() !== lastNotifiedThemeStyle) {
- notifyThemeChanged();
- }
+}
+
+/** Notifies only when the style truly flips — a fixed light/dark theme ignores the OS preference. */
+function reconcileEffectiveThemeStyle() {
+ if (getEffectiveThemeStyle() !== lastKnownThemeStyle) {
+ notifyThemeChanged();
+ }
+}
+
+/** Broadcasts to the subscribers and the global `themeChanged` event. `appContext` is imported lazily because
+ * this module is loaded by the boot entry point before the app context (and jQuery) exist; the import
+ * resolves later, when an actual theme change occurs. */
+function notifyThemeChanged() {
+ const themeStyle = getEffectiveThemeStyle();
+ lastKnownThemeStyle = themeStyle;
+ for (const listener of themeStyleListeners) {
+ listener(themeStyle);
+ }
+ void import("../components/app_context.js").then(({ default: appContext }) => {
+ void appContext.triggerEvent("themeChanged", { themeStyle });
});
}
diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.ts
index 00da4e3eb0..9b14afd806 100644
--- a/apps/client/src/widgets/containers/root_container.ts
+++ b/apps/client/src/widgets/containers/root_container.ts
@@ -5,7 +5,7 @@ import { getEnabledExperimentalFeatureIds } from "../../services/experimental_fe
import { applyCustomFontsFromOptions, hasCustomFontContentChanged } from "../../services/custom_fonts.js";
import { applyFontsFromOptions } from "../../services/font.js";
import options from "../../services/options.js";
-import { applyThemeFromOptions, updateColorSchemeClasses, updateThemeCapabilities } from "../../services/theme.js";
+import { applyThemeFromOptions, onEffectiveThemeStyleChange, updateColorSchemeClasses, updateThemeCapabilities } from "../../services/theme.js";
import utils, { isIOS, isMobile } from "../../services/utils.js";
import type BasicWidget from "../basic_widget.js";
import FlexContainer from "./flex_container.js";
@@ -106,10 +106,9 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
}
#initTheme() {
- const colorSchemeChangeObserver = matchMedia("(prefers-color-scheme: dark)");
- colorSchemeChangeObserver.addEventListener("change", () => this.#updateColorScheme());
+ onEffectiveThemeStyleChange(() => this.#updateColorScheme());
this.#updateColorScheme();
-
+
document.body.setAttribute("data-theme-id", options.get("theme"));
}
diff --git a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
index 5e05e96f04..fdad094da7 100644
--- a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
@@ -1,6 +1,7 @@
import type { HTMLAttributes, RefObject } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";
+import { onEffectiveThemeStyleChange } from "../../../services/theme";
import { useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
interface FontDefinition {
@@ -90,9 +91,7 @@ function useStyleInjection(iframeRef: RefObject<HTMLIFrameElement>, disableSelec
styleRef.current!.textContent = cssVarsToString(getRootCssVariables());
};
- const media = window.matchMedia("(prefers-color-scheme: dark)");
- media.addEventListener("change", listener);
- return () => media.removeEventListener("change", listener);
+ return onEffectiveThemeStyleChange(listener);
}, [ iframeRef ]);
return onLoad;