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
client/refactor: add an event for theme/color scheme change
Adorian Doranb08a3e32b3e9
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex f44b192743..eb0609c209 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -432,6 +432,12 @@ type EventMappings = {activeScreenChanged: {activeScreen: Screen;};+ /** Triggered when the active theme changes (theme option swap or, for auto themes, the OS light/dark flip),+ * once the new stylesheet is applied. Lets widgets that read CSS variables in JS (e.g. canvas renderers)+ * re-read them. Consume with {@link useTriliumEvent}("themeChanged") or the {@link useColorScheme} hook. */+ themeChanged: {+ themeStyle: "light" | "dark";+ };activeContextChanged: {noteContext: NoteContext;};diff --git a/apps/client/src/index.ts b/apps/client/src/index.tsindex 8abf3992e3..9f7ef0aafd 100644--- a/apps/client/src/index.ts+++ b/apps/client/src/index.ts@@ -1,5 +1,5 @@import { createFontStylesheetLink } from "./services/font";-import { buildThemeStylesheetRefs, createStylesheetLink, getThemeStyle, StylesheetRef } from "./services/theme";+import { buildThemeStylesheetRefs, createStylesheetLink, getThemeStyle, initThemeChangeNotifier, StylesheetRef } from "./services/theme";async function bootstrap() {showSplash();@@ -9,6 +9,7 @@ async function bootstrap() {loadBootstrapCss()]);loadStylesheets();+ initThemeChangeNotifier();loadIcons();setBodyAttributes();await loadScripts();diff --git a/apps/client/src/services/theme.spec.ts b/apps/client/src/services/theme.spec.tsindex b895760309..fd3b40d9db 100644--- a/apps/client/src/services/theme.spec.ts+++ b/apps/client/src/services/theme.spec.ts@@ -1,6 +1,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { applyTheme, buildThemeStylesheetRefs, getConfiguredThemeStylesheets, getEffectiveThemeStyle, getThemeStyle } from "./theme.js";+import { applyTheme, buildThemeStylesheetRefs, getConfiguredThemeStylesheets, getEffectiveThemeStyle, getThemeStyle, initThemeChangeNotifier } 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.+const { triggerEvent } = vi.hoisted(() => ({ triggerEvent: vi.fn() }));+vi.mock("../components/app_context.js", () => ({ default: { triggerEvent } }));const STYLESHEETS_PATH = "/assets/stylesheets";@@ -27,10 +32,14 @@ function setTheme(theme: ThemeValue) {win.glob = { ...(win.glob ?? {}), theme };}-afterEach(() => {+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.+ await new Promise((resolve) => setTimeout(resolve));win.getComputedStyle = originalGetComputedStyle;win.matchMedia = originalMatchMedia;win.glob = originalGlob;+ triggerEvent.mockClear();vi.restoreAllMocks();});@@ -232,6 +241,24 @@ describe("applyTheme", () => {expect(win.glob?.themeBase).toBe("next-dark");});+ it("emits themeChanged once the new stylesheet has loaded", async () => {+ applyTheme("dark");+ fireLoadOnPendingThemeLinks();+ await vi.waitFor(() => expect(triggerEvent).toHaveBeenCalledWith("themeChanged", { themeStyle: "dark" }));+ });++ it("does not emit themeChanged when the swap rolls back", async () => {+ applyTheme("dark");+ fireLoadOnPendingThemeLinks();+ await vi.waitFor(() => expect(triggerEvent).toHaveBeenCalled());+ triggerEvent.mockClear();++ applyTheme("my-theme", "api/notes/download/missing");+ document.head.querySelector(`link[href="api/notes/download/missing"]`)?.dispatchEvent(new Event("error"));+ await new Promise((resolve) => setTimeout(resolve));+ expect(triggerEvent).not.toHaveBeenCalled();+ });+it("keeps the previous theme when a new stylesheet fails to load", async () => {applyTheme("dark");fireLoadOnPendingThemeLinks();@@ -264,6 +291,46 @@ describe("applyTheme", () => {});});+describe("initThemeChangeNotifier", () => {+ beforeEach(() => {+ setTheme(undefined);+ stubComputedStyle({});+ triggerEvent.mockClear();+ });++ /** Fake MediaQueryList whose `matches` is mutable and whose `change` listener we can fire by hand. */+ function installMatchMedia(matches: boolean) {+ const state: { matches: boolean; listener?: () => void } = { matches, listener: undefined };+ win.matchMedia = vi.fn(() => ({+ get matches() { return state.matches; },+ addEventListener: (_type: string, listener: () => void) => { state.listener = listener; },+ removeEventListener: vi.fn()+ })) as unknown as typeof window.matchMedia;+ return state;+ }++ it("emits themeChanged on an OS light/dark flip while an auto theme follows the OS", async () => {+ setTheme("auto");+ const mql = installMatchMedia(false);+ initThemeChangeNotifier();++ mql.matches = true;+ mql.listener?.();+ await vi.waitFor(() => expect(triggerEvent).toHaveBeenCalledWith("themeChanged", { themeStyle: "dark" }));+ });++ it("ignores OS flips for a fixed theme that does not follow the OS", async () => {+ setTheme("dark");+ const mql = installMatchMedia(false);+ initThemeChangeNotifier();++ mql.matches = true;+ mql.listener?.();+ await new Promise((resolve) => setTimeout(resolve));+ expect(triggerEvent).not.toHaveBeenCalled();+ });+});+function themeStylesheetHrefs() {return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-theme-stylesheet]")).map((link) => link.getAttribute("href"));diff --git a/apps/client/src/services/theme.ts b/apps/client/src/services/theme.tsindex 2cea976ac7..51c1983903 100644--- a/apps/client/src/services/theme.ts+++ b/apps/client/src/services/theme.ts@@ -225,6 +225,7 @@ export function applyTheme(theme: string, customThemeCssUrl?: string, themeBase?document.body.setAttribute("data-theme-id", theme);updateColorSchemeClasses();updateThemeCapabilities();+ notifyThemeChanged();// The stylesheet swap is invisible to Electron, whose window configuration (Mica tint,// background material, title bar colors) derives from the theme. Imported lazily so this@@ -235,6 +236,38 @@ 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;++/** 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 });+ });+}++/**+ * 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.+ */+export function initThemeChangeNotifier() {+ if (!window.matchMedia) {+ return;+ }+ 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();+ }+ });+}+/** Resolves once every link has settled, with `true` only if all of them loaded successfully. */function waitForStylesheets(links: HTMLLinkElement[]): Promise<boolean> {if (links.length === 0) {diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex b05827ffe9..5f44244e39 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -21,6 +21,7 @@ import protected_session_holder from "../../services/protected_session_holder";import server from "../../services/server";import shortcuts, { Handler, removeIndividualBinding } from "../../services/shortcuts";import SpacedUpdate, { type StateCallback } from "../../services/spaced_update";+import { getEffectiveThemeStyle } from "../../services/theme";import toast, { ToastOptions } from "../../services/toast";import tree from "../../services/tree";import utils, { escapeRegExp, getErrorMessage, randomString, reloadFrontendApp } from "../../services/utils";@@ -1752,21 +1753,12 @@ export function useGetContextDataFrom<K extends keyof NoteContextDataMap>(return data;}+/** The effective light/dark style, updated on any theme change — a theme-option swap or, for auto themes, the+ * OS light/dark flip (both delivered via the global `themeChanged` event). */export function useColorScheme() {- const themeStyle = window.glob.getThemeStyle();- const defaultValue = themeStyle === "auto" ? (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) : themeStyle === "dark";- const [ prefersDark, setPrefersDark ] = useState(defaultValue);-- useEffect(() => {- if (themeStyle !== "auto") return;- const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");- const listener = (e: MediaQueryListEvent) => setPrefersDark(e.matches);-- mediaQueryList.addEventListener("change", listener);- return () => mediaQueryList.removeEventListener("change", listener);- }, [ themeStyle ]);-- return prefersDark ? "dark" : "light";+ const [ themeStyle, setThemeStyle ] = useState(getEffectiveThemeStyle);+ useTriliumEvent("themeChanged", ({ themeStyle }) => setThemeStyle(themeStyle));+ return themeStyle;}/**diff --git a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsxindex a1009c69b1..7b545aceed 100644--- a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx+++ b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx@@ -4,6 +4,7 @@ import { RefObject } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n";+import { useTriliumEvent } from "../../react/hooks";import { formatTime } from "./MediaPlayer";/** Below this normalized amplitude a bucket is considered silence and painted with the silence color. */@@ -61,12 +62,15 @@ export function WaveformSeekBar({ mediaRef, peaks }: { mediaRef: RefObject<HTMLVreturn () => observer.disconnect();}, []);- // Resolve the theme's waveform colors once on mount and cache them — the draw runs up to ~60 times/second- // during the morph, so it must not force a style recalculation each frame.- useEffect(() => {+ // Resolve the theme's waveform colors and cache them — the draw runs up to ~60 times/second during the+ // morph, so it must not force a style recalculation each frame. Re-resolved on mount and whenever the theme+ // changes (option swap or OS light/dark flip).+ const refreshColors = useCallback(() => {const canvas = canvasRef.current;if (canvas) setColors(readColors(canvas));}, []);+ useEffect(refreshColors, [ refreshColors ]);+ useTriliumEvent("themeChanged", refreshColors);// Animate flat → analyzed once the peaks are available. While they are null (loading or undecodable) morph// stays at 0 and the bars hold the flat placeholder.