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
fix(desktop): background effects not properly restored after changing theme
Elian Doran93d8bb7b5225
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.tsindex 03986abf1b..12eba31ec8 100644--- a/apps/client/src/desktop.ts+++ b/apps/client/src/desktop.ts@@ -7,9 +7,9 @@ import electronContextMenu from "./menus/electron_context_menu.js";import bundleService from "./services/bundle.js";import glob from "./services/glob.js";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 options from "./services/options.js";import toastService from "./services/toast.js";import utils from "./services/utils.js";@@ -55,78 +55,18 @@ function initOnElectron() {win.onGlobalShortcut(async (actionName) => appContext.triggerCommand(actionName as CommandNames));win.onOpenInSameTab(async (noteId) => appContext.tabManager.openInSameTab(noteId));- const style = window.getComputedStyle(document.body);-- initDarkOrLightMode(win);- initTransparencyEffects(win, style);+ syncNativeWindowWithTheme();initFullScreenDetection(win);- if (options.get("nativeTitleBarVisible") !== "true") {- initTitleBarButtons(win, style);- }+ // 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);// Clear navigation history on frontend refresh.api.navigation.clearNavigationHistory();}-function initTitleBarButtons(win: ElectronWindowApi, style: CSSStyleDeclaration) {- if (window.glob.platform === "win32") {- const applyWindowsOverlay = () => {- const color = style.getPropertyValue("--native-titlebar-background");- const symbolColor = style.getPropertyValue("--native-titlebar-foreground");- if (color && symbolColor) {- win.setTitleBarOverlay({ color, symbolColor });- }- };-- applyWindowsOverlay();-- // Register for changes to the native title bar colors.- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyWindowsOverlay);- }-- if (window.glob.platform === "darwin") {- const xOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-x-offset"), 10);- const yOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-y-offset"), 10);- win.setWindowButtonPosition({ x: xOffset, y: yOffset });- }-}-function initFullScreenDetection(win: ElectronWindowApi) {win.onEnterFullScreen(() => document.body.classList.add("full-screen"));win.onLeaveFullScreen(() => document.body.classList.remove("full-screen"));}--function initTransparencyEffects(win: ElectronWindowApi, style: CSSStyleDeclaration) {- const material = style.getPropertyValue("--background-material").trim();- if (window.glob.platform === "win32") {- const bgMaterialOptions = ["auto", "none", "mica", "acrylic", "tabbed"] as const;- const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);- if (foundBgMaterialOption) {- win.setBackgroundMaterial(foundBgMaterialOption);- }- }-- if (window.glob.platform === "darwin") {- const bgMaterialOptions = [ "popover", "tooltip", "titlebar", "selection", "menu", "sidebar", "header", "sheet", "window", "hud", "fullscreen-ui", "content", "under-window", "under-page" ] as const;- const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);- if (foundBgMaterialOption) {- win.setVibrancy(foundBgMaterialOption);- }- }-}--/**- * Informs Electron that we prefer a dark or light theme. Apart from changing prefers-color-scheme at CSS level which is a side effect,- * this fixes color issues with background effects or native title bars.- */-function initDarkOrLightMode(win: ElectronWindowApi) {- let themeSource: "system" | "light" | "dark" = "system";-- const themeStyle = window.glob.getThemeStyle();- if (themeStyle !== "auto") {- themeSource = themeStyle;- }-- win.setNativeThemeSource(themeSource);-}diff --git a/apps/client/src/services/native_window.ts b/apps/client/src/services/native_window.tsnew file mode 100644index 0000000000..d3cb1f0d7b--- /dev/null+++ b/apps/client/src/services/native_window.ts@@ -0,0 +1,81 @@+import type { ElectronWindowApi } from "@triliumnext/commons";++import options from "./options.js";+import { getThemeStyle } from "./theme.js";++/**+ * Pushes the theme-derived part of the native window configuration to Electron: the preferred+ * light/dark mode (which drives the tint of background effects such as Mica on Windows), the+ * window background material and the native title bar colors and button position.+ *+ * These all come from the active theme's CSS variables, which Electron cannot observe itself, so+ * this runs at startup, after every live theme change (see `applyTheme`) and when the OS color+ * scheme changes. No-op outside Electron.+ */+export function syncNativeWindowWithTheme() {+ const win = window.electronApi?.window;+ if (!win) {+ return;+ }++ const style = window.getComputedStyle(document.body);++ applyDarkOrLightMode(win);+ applyTransparencyEffects(win, style);++ // The title bar overlay only exists when the native title bar is hidden; setting it otherwise throws.+ if (options.get("nativeTitleBarVisible") !== "true") {+ applyTitleBarButtons(win, style);+ }+}++/**+ * Informs Electron that we prefer a dark or light theme. Apart from changing prefers-color-scheme at CSS level which is a side effect,+ * this fixes color issues with background effects or native title bars.+ */+function applyDarkOrLightMode(win: ElectronWindowApi) {+ let themeSource: "system" | "light" | "dark" = "system";++ const themeStyle = getThemeStyle();+ if (themeStyle !== "auto") {+ themeSource = themeStyle;+ }++ win.setNativeThemeSource(themeSource);+}++/** Window effects (Mica on Windows and Vibrancy on macOS), driven by the theme's `--background-material`. */+function applyTransparencyEffects(win: ElectronWindowApi, style: CSSStyleDeclaration) {+ const material = style.getPropertyValue("--background-material").trim();+ if (window.glob.platform === "win32") {+ const bgMaterialOptions = ["auto", "none", "mica", "acrylic", "tabbed"] as const;+ const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);+ if (foundBgMaterialOption) {+ win.setBackgroundMaterial(foundBgMaterialOption);+ }+ }++ if (window.glob.platform === "darwin") {+ const bgMaterialOptions = [ "popover", "tooltip", "titlebar", "selection", "menu", "sidebar", "header", "sheet", "window", "hud", "fullscreen-ui", "content", "under-window", "under-page" ] as const;+ const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);+ if (foundBgMaterialOption) {+ win.setVibrancy(foundBgMaterialOption);+ }+ }+}++function applyTitleBarButtons(win: ElectronWindowApi, style: CSSStyleDeclaration) {+ if (window.glob.platform === "win32") {+ const color = style.getPropertyValue("--native-titlebar-background");+ const symbolColor = style.getPropertyValue("--native-titlebar-foreground");+ if (color && symbolColor) {+ win.setTitleBarOverlay({ color, symbolColor });+ }+ }++ if (window.glob.platform === "darwin") {+ const xOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-x-offset"), 10);+ const yOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-y-offset"), 10);+ win.setWindowButtonPosition({ x: xOffset, y: yOffset });+ }+}diff --git a/apps/client/src/services/theme.ts b/apps/client/src/services/theme.tsindex 95b98c74a9..aa7d28ab7c 100644--- a/apps/client/src/services/theme.ts+++ b/apps/client/src/services/theme.ts@@ -116,6 +116,14 @@ export function updateColorSchemeClasses() {document.body.classList.toggle("dark-theme", colorScheme === "dark");}+/** Toggles the `theme-supports-background-effects` body class to match the active theme's `--allow-background-effects`. */+export function updateThemeCapabilities() {+ const useBgfx = readCssVar(document.documentElement, "allow-background-effects")+ .asBoolean(false);++ document.body.classList.toggle("theme-supports-background-effects", useBgfx);+}+/** 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;@@ -182,6 +190,14 @@ export function applyTheme(theme: string, customThemeCssUrl?: string, themeBase?}document.body.setAttribute("data-theme-id", theme);updateColorSchemeClasses();+ updateThemeCapabilities();++ // 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+ // module stays loadable from the early boot entry point (see `applyThemeFromOptions`).+ if (window.electronApi) {+ void import("./native_window.js").then(({ syncNativeWindowWithTheme }) => syncNativeWindowWithTheme());+ }});}diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.tsindex 5af300419d..e0a5c0855b 100644--- a/apps/client/src/widgets/containers/root_container.ts+++ b/apps/client/src/widgets/containers/root_container.ts@@ -4,9 +4,8 @@ import { EventData } from "../../components/app_context.js";import { getEnabledExperimentalFeatureIds } from "../../services/experimental_features.js";import { applyFontsFromOptions } from "../../services/font.js";import options from "../../services/options.js";-import { applyThemeFromOptions, updateColorSchemeClasses } from "../../services/theme.js";+import { applyThemeFromOptions, updateColorSchemeClasses, updateThemeCapabilities } 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";import FlexContainer from "./flex_container.js";@@ -53,7 +52,7 @@ export default class RootContainer extends FlexContainer<BasicWidget> {this.#setMotion();this.#setShadows();this.#setBackdropEffects();- this.#setThemeCapabilities();+ updateThemeCapabilities();this.#setLocaleAndDirection(options.get("locale"));this.#setExperimentalFeatures();this.#initPWATopbarColor();@@ -134,15 +133,6 @@ export default class RootContainer extends FlexContainer<BasicWidget> {document.body.classList.toggle("backdrop-effects-disabled", !enabled);}- #setThemeCapabilities() {- // Supports background effects-- const useBgfx = readCssVar(document.documentElement, "allow-background-effects")- .asBoolean(false);-- document.body.classList.toggle("theme-supports-background-effects", useBgfx);- }-#setExperimentalFeatures() {for (const featureId of getEnabledExperimentalFeatureIds()) {document.body.classList.add(`experimental-feature-${featureId}`);