feat(windows): the tray theme item cycles System, Light and Dark

The item said "Toggle Dark/Light" and flipped between two states, so a
reader who had ever chosen Light or Dark could not get back to following
the system, which is the only setting the mac has at all. It steps
System, Light, Dark now and names the state it moves to, because a menu
item reads as a verb. The popover's More menu runs the same cycle from
the same wording, so the two can never disagree.

The choice is written to the settings file from Rust rather than asked of
the popover, which means the item works with no popover on screen, and
every window retints from the broadcast that already exists. That made
the resolved-theme state in the popover dead, and the media listener that
kept it, so both are gone.

One bug had to go first. A tray's on_menu_event handler is registered
globally rather than against that tray, so registering it on both the
logo and the badge icon ran every menu item twice: the cycle skipped a
step, and Show Capacity Dock had been toggling itself straight back.
This commit is contained in:
iamtoruk 2026-09-02 00:03:52 -07:00
parent 6ed5b8f2fd
commit 8a227ef87d
3 changed files with 95 additions and 27 deletions

View file

@ -37,6 +37,8 @@ use tauri::{
static DOCK_MENU_ITEM: std::sync::OnceLock<CheckMenuItem<tauri::Wry>> = std::sync::OnceLock::new();
#[cfg(not(target_os = "linux"))]
static USAGE_MENU_ITEM: std::sync::OnceLock<MenuItem<tauri::Wry>> = std::sync::OnceLock::new();
#[cfg(not(target_os = "linux"))]
static THEME_MENU_ITEM: std::sync::OnceLock<MenuItem<tauri::Wry>> = std::sync::OnceLock::new();
use crate::cli::CodeburnCli;
use crate::config::CurrencyConfig;
@ -209,7 +211,13 @@ fn build_tray_tauri(app: &AppHandle) -> tauri::Result<()> {
let usage = MenuItem::with_id(app, "usage", "Today", false, None::<&str>)?;
let open = MenuItem::with_id(app, "open", "Open CodeBurn", true, None::<&str>)?;
let refresh = MenuItem::with_id(app, "refresh", "Refresh", true, None::<&str>)?;
let theme = MenuItem::with_id(app, "toggle_theme", "Toggle Dark/Light", true, None::<&str>)?;
let theme = MenuItem::with_id(
app,
"toggle_theme",
theme_menu_text(&theme_choice()),
true,
None::<&str>,
)?;
let settings = MenuItem::with_id(app, "settings", "Settings...", true, None::<&str>)?;
let dock_settings = MenuItem::with_id(
app,
@ -252,10 +260,15 @@ fn build_tray_tauri(app: &AppHandle) -> tauri::Result<()> {
// checkmark in step with the persisted state and the usage row in step with the payload.
let _ = DOCK_MENU_ITEM.set(capacity_dock);
let _ = USAGE_MENU_ITEM.set(usage);
let _ = THEME_MENU_ITEM.set(theme);
tray.set_menu(Some(menu.clone()))?;
tray.set_show_menu_on_left_click(false)?;
let _ = tray.set_tooltip(Some("CodeBurn"));
// A tray's menu handler is registered globally, not against that tray, so this one
// answers for both icons and the badge below must not register a second copy: two
// copies ran every item twice, which skipped a step of the theme cycle and left the
// Capacity Dock item toggling itself back.
tray.on_menu_event(on_tray_menu_event);
tray.on_tray_icon_event(on_tray_icon_event);
@ -271,7 +284,6 @@ fn build_tray_tauri(app: &AppHandle) -> tauri::Result<()> {
.tooltip("CodeBurn")
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(on_tray_menu_event)
.on_tray_icon_event(on_tray_icon_event)
.build(app)?
.set_visible(false)?;
@ -292,11 +304,7 @@ fn on_tray_menu_event(app: &AppHandle, event: tauri::menu::MenuEvent) {
let _ = window.emit("codeburn://refresh", ());
}
}
"toggle_theme" => {
if let Some(window) = app.get_webview_window(POPOVER_LABEL) {
let _ = window.emit("codeburn://toggle-theme", ());
}
}
"toggle_theme" => cycle_theme(app),
"toggle_dock" => set_dock_enabled(app, !dock::is_enabled()),
// Deep links into the settings window: General, General scrolled to its Capacity
// Dock section, and About, exactly as the mac's three menu items land.
@ -496,6 +504,64 @@ fn apply_tray_tint(app: &AppHandle, tint: Option<[u8; 3]>) -> Result<(), String>
Ok(())
}
/// System, then Light, then Dark, then back. The mac has no counterpart: its windows follow
/// the system appearance and offer no choice at all.
fn next_theme(current: &str) -> &'static str {
match current {
"light" => "dark",
"dark" => "system",
_ => "light",
}
}
/// The item names the state it moves to rather than the one it is in, because a menu item
/// reads as a verb.
fn theme_menu_text(current: &str) -> String {
match next_theme(current) {
"light" => "Switch to Light Theme".into(),
"dark" => "Switch to Dark Theme".into(),
_ => "Switch to System Theme".into(),
}
}
fn theme_choice() -> String {
settings::read()
.get("theme")
.and_then(serde_json::Value::as_str)
.filter(|choice| matches!(*choice, "system" | "light" | "dark"))
.unwrap_or("system")
.to_owned()
}
/// Writing the preference rather than asking the popover to flip its own is what makes the
/// item work with no popover on screen: every window renders from the broadcast.
fn cycle_theme(app: &AppHandle) {
let mut patch = serde_json::Map::new();
patch.insert(
"theme".into(),
serde_json::json!(next_theme(&theme_choice())),
);
match settings::patch(patch) {
Ok(merged) => {
settings::broadcast(app, &merged);
sync_theme_menu_item();
}
Err(err) => eprintln!("codeburn: failed to persist the theme: {err}"),
}
}
/// Keeps the item honest when the theme changed somewhere else: the popover's More menu or
/// the settings window.
#[cfg(not(target_os = "linux"))]
pub fn sync_theme_menu_item() {
if let Some(item) = THEME_MENU_ITEM.get() {
let _ = item.set_text(theme_menu_text(&theme_choice()));
}
}
#[cfg(target_os = "linux")]
pub fn sync_theme_menu_item() {}
#[cfg(not(target_os = "linux"))]
fn set_tray_usage_text(text: &str) {
if let Some(item) = USAGE_MENU_ITEM.get() {
@ -1005,6 +1071,7 @@ mod commands {
) -> Result<Value, String> {
let merged = crate::settings::patch(patch).map_err(|e| e.to_string())?;
crate::settings::broadcast(&app, &merged);
crate::sync_theme_menu_item();
Ok(Value::Object(merged))
}

View file

@ -7,9 +7,9 @@ import type { CurrencyState } from './lib/currency'
import { USD, formatCurrency, formatTokens, plural, trayBadgeText } from './lib/currency'
import { PayloadCache, sameSelection, selectionKey, type Selection } from './lib/cache'
import { relativePast } from './lib/dates'
import { applyTheme, currentTheme, readSetting, writeSetting } from './lib/settings'
import { applyTheme, readSetting, writeSetting } from './lib/settings'
import {
DEFAULT_SETTINGS, MENUBAR_PERIODS, MENUBAR_SUFFIX, cacheThemeAndAccent, subscribeSettings,
DEFAULT_SETTINGS, MENUBAR_PERIODS, MENUBAR_SUFFIX, cacheThemeAndAccent, nextTheme, subscribeSettings, themeCycleLabel,
writeSettings, type AppSettings, type ThemeChoice,
} from './lib/appSettings'
import { TRAY_BADGE_SUPPORTED } from './lib/platform'
@ -122,7 +122,6 @@ export function App() {
const [cliChecking, setCliChecking] = useState(false)
const [version, setVersion] = useState('')
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
const [theme, setTheme] = useState(() => currentTheme())
const [quota, setQuota] = useState<QuotaState>(EMPTY_QUOTA)
// The window starts hidden and is shown by a tray click, which emits `codeburn://shown`.
const [popoverVisible, setPopoverVisible] = useState(false)
@ -321,7 +320,6 @@ export function App() {
if (cadence.current === 0) return
refreshAll({ includeOptimize: false, showOverlay: false })
})
const unlistenTheme = listen('codeburn://toggle-theme', () => toggleTheme())
const unlistenBudget = listen<Budgets>('codeburn://budget-changed', event => {
if (event.payload) setBudgets(event.payload)
})
@ -333,7 +331,6 @@ export function App() {
unlistenShown.then(fn => fn())
unlistenHidden.then(fn => fn())
unlistenWake.then(fn => fn())
unlistenTheme.then(fn => fn())
unlistenBudget.then(fn => fn())
unlistenCurrency.then(fn => fn())
}
@ -346,7 +343,6 @@ export function App() {
setSettings(next)
applyAccent(accentById(next.accent))
applyTheme(next.theme === 'system' ? null : next.theme)
setTheme(currentTheme())
cacheThemeAndAccent(next)
}), [])
@ -393,15 +389,6 @@ export function App() {
// with the page. A manual Refresh asks it for a fresh answer too.
useEffect(() => subscribeQuota(setQuota), [])
// The stored theme is applied by the settings subscription; this only follows the system
// while the choice is System.
useEffect(() => {
const media = window.matchMedia('(prefers-color-scheme: dark)')
const onChange = () => setTheme(currentTheme())
media.addEventListener('change', onChange)
return () => media.removeEventListener('change', onChange)
}, [])
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') invoke('hide_popover').catch(() => {})
@ -473,12 +460,11 @@ export function App() {
const chooseTheme = (choice: ThemeChoice) => {
applyTheme(choice === 'system' ? null : choice)
setTheme(currentTheme())
void writeSettings({ theme: choice })
}
const toggleTheme = () => {
chooseTheme(currentTheme() === 'dark' ? 'light' : 'dark')
const cycleTheme = () => {
chooseTheme(nextTheme(settings.theme))
}
const setTrayBadgePref = (on: boolean) => {
@ -677,9 +663,9 @@ export function App() {
onRefresh={userRefresh}
onExport={format => openTerminal(['export', '-f', format])}
onOpenReport={() => openTerminal(['report'])}
onToggleTheme={toggleTheme}
onToggleTheme={cycleTheme}
onQuit={() => invoke('quit_app').catch(() => {})}
themeLabel={theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'}
themeLabel={themeCycleLabel(settings.theme)}
trayBadge={trayBadge}
onToggleTrayBadge={() => setTrayBadgePref(!trayBadge)}
onOpenSettings={openSettingsWindow}

View file

@ -47,6 +47,21 @@ export type MenubarScope = 'local' | 'combined'
export type ThemeChoice = 'system' | 'light' | 'dark'
/// System, then Light, then Dark, then back. The tray item and the popover's More menu both
/// step through this, and both name the state they move to rather than the one they are in.
/// Kept in step by hand with `next_theme` in src-tauri/src/lib.rs, which the tray reads
/// before any webview exists.
export function nextTheme(current: ThemeChoice): ThemeChoice {
return current === 'light' ? 'dark' : current === 'dark' ? 'system' : 'light'
}
export function themeCycleLabel(current: ThemeChoice): string {
const next = nextTheme(current)
if (next === 'light') return 'Switch to Light Theme'
if (next === 'dark') return 'Switch to Dark Theme'
return 'Switch to System Theme'
}
/// UsageRefreshCadence. Auto is the adaptive default, manual never auto-spawns.
export const USAGE_CADENCES: Array<{ id: number; label: string }> = [
// The mac's label promises "less on battery", which is the adaptive refresh that comes