Skip to content

Instantly share code, notes, and snippets.

@BHznJNs
Created July 28, 2025 07:58
Show Gist options
  • Select an option

  • Save BHznJNs/15b37ecf68995ef26a3be7d576a51f03 to your computer and use it in GitHub Desktop.

Select an option

Save BHznJNs/15b37ecf68995ef26a3be7d576a51f03 to your computer and use it in GitHub Desktop.
A rust module for tauri applications that provides a trait which can let window background color automatically adapts to the configurated theme.
use dark_light;
use tauri::{
AppHandle,
Manager,
Theme,
WebviewWindowBuilder,
};
use crate::app_state::AppState;
enum ConfigTheme { System, Light, Dark }
impl From<&str> for ConfigTheme {
fn from(s: &str) -> Self {
match s {
"dark" => ConfigTheme::Dark,
"light" => ConfigTheme::Light,
_ => ConfigTheme::System,
}
}
}
pub trait ApplyTheme {
fn apply_theme(self, app_handle: &AppHandle) -> Self;
}
impl<'a, R: tauri::Runtime, M: Manager<R>> ApplyTheme for WebviewWindowBuilder<'a, R, M> {
fn apply_theme(self, app_handle: &AppHandle) -> Self {
let app_state = app_handle.state::<AppState>();
let theme = match app_state.config.lock() {
Ok(config) => config.theme.clone(),
Err(_) => "system".to_string(),
};
let config_theme = ConfigTheme::from(theme.as_str());
// set window frame theme
let builder = match config_theme {
ConfigTheme::Dark => self.theme(Some(Theme::Dark)),
ConfigTheme::Light => self.theme(Some(Theme::Light)),
ConfigTheme::System => self.theme(None),
};
// apply proper webview window background color
let Ok(system_mode) = dark_light::detect() else {
return builder;
};
let dark_background_color = "#121212".parse().unwrap();
let light_background_color = "#ffffff".parse().unwrap();
let builder = match config_theme {
ConfigTheme::Dark => builder.background_color(dark_background_color),
ConfigTheme::Light => builder.background_color(light_background_color),
ConfigTheme::System => match system_mode {
dark_light::Mode::Dark => builder.background_color(dark_background_color),
dark_light::Mode::Light => builder.background_color(light_background_color),
dark_light::Mode::Unspecified => builder,
},
};
return builder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment