Skip to content

A local-first personal finance app

[AI] Fix theme colour ordering and custom theme refresh (#8922)

Tim353e5dd26aa9
diff --git a/packages/desktop-client/src/hooks/useMetaThemeColor.test.ts b/packages/desktop-client/src/hooks/useMetaThemeColor.test.ts
index a4b867e9d2..e16cee17af 100644
--- a/packages/desktop-client/src/hooks/useMetaThemeColor.test.ts
+++ b/packages/desktop-client/src/hooks/useMetaThemeColor.test.ts
@@ -1,6 +1,9 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { resetTestProviders, TestProviders } from '#mocks';
+import { mergeGlobalPrefs } from '#prefs/prefsSlice';
+import { useStore } from '#redux';
import { usePreferredDarkTheme, useTheme } from '#style/theme';
import { useMetaThemeColor } from './useMetaThemeColor';
@@ -8,6 +11,16 @@ import { useMetaThemeColor } from './useMetaThemeColor';
const DEFAULT_THEME_COLOR = '#5c3dbb';
const originalMatchMedia = window.matchMedia;
+function renderThemeColor(color?: string) {
+ return renderHook(
+ () => {
+ useMetaThemeColor(color);
+ return useStore();
+ },
+ { wrapper: TestProviders },
+ );
+}
+
vi.mock('#style/theme', () => ({
useTheme: vi.fn(),
usePreferredDarkTheme: vi.fn(),
@@ -31,6 +44,7 @@ function clearCssVar(name: string) {
}
beforeEach(() => {
+ resetTestProviders();
vi.mocked(useTheme).mockReturnValue(['light', vi.fn()]);
vi.mocked(usePreferredDarkTheme).mockReturnValue(['dark', vi.fn()]);
document.body.style.backgroundColor = '';
@@ -51,19 +65,19 @@ afterEach(() => {
describe('useMetaThemeColor', () => {
describe('when color is undefined', () => {
it('does not set theme-color meta tag', () => {
- renderHook(() => useMetaThemeColor(undefined));
+ renderThemeColor(undefined);
expect(getThemeColorMeta()).toBeNull();
});
it('does not set body background-color', () => {
- renderHook(() => useMetaThemeColor(undefined));
+ renderThemeColor(undefined);
expect(document.body.style.backgroundColor).toBe('');
});
});
describe('when color is a literal hex value', () => {
it('sets theme-color meta content and body background to that color', () => {
- renderHook(() => useMetaThemeColor('#1a2b3c'));
+ renderThemeColor('#1a2b3c');
expect(getThemeColorMeta()).toBe('#1a2b3c');
// jsdom normalizes assigned hex to rgb()
expect(document.body.style.backgroundColor).toBe('rgb(26, 43, 60)');
@@ -71,7 +85,7 @@ describe('useMetaThemeColor', () => {
it('creates theme-color meta tag if missing', () => {
expect(getThemeColorMeta()).toBeNull();
- renderHook(() => useMetaThemeColor('#abc'));
+ renderThemeColor('#abc');
expect(getThemeColorMeta()).toBe('#abc');
});
});
@@ -81,7 +95,7 @@ describe('useMetaThemeColor', () => {
setCssVar('--color-mobileViewTheme', ' #fedcba ');
const getComputedStyleSpy = vi.spyOn(window, 'getComputedStyle');
- renderHook(() => useMetaThemeColor('var(--color-mobileViewTheme)'));
+ renderThemeColor('var(--color-mobileViewTheme)');
expect(getComputedStyleSpy).toHaveBeenCalledWith(
document.documentElement,
@@ -91,7 +105,7 @@ describe('useMetaThemeColor', () => {
});
it('uses default when resolved var is empty', () => {
- renderHook(() => useMetaThemeColor('var(--color-mobileViewTheme)'));
+ renderThemeColor('var(--color-mobileViewTheme)');
expect(getThemeColorMeta()).toBe(DEFAULT_THEME_COLOR);
expect(document.body.style.backgroundColor).toBe('rgb(92, 61, 187)');
@@ -101,9 +115,7 @@ describe('useMetaThemeColor', () => {
describe('theme reactivity', () => {
it('re-runs effect when activeTheme changes', () => {
setCssVar('--color-mobileViewTheme', '#111');
- const { rerender } = renderHook(() =>
- useMetaThemeColor('var(--color-mobileViewTheme)'),
- );
+ const { rerender } = renderThemeColor('var(--color-mobileViewTheme)');
expect(document.body.style.backgroundColor).toBe('rgb(17, 17, 17)');
setCssVar('--color-mobileViewTheme', '#222');
@@ -114,9 +126,7 @@ describe('useMetaThemeColor', () => {
it('re-runs effect when darkThemePreference changes', () => {
setCssVar('--color-mobileViewTheme', '#aaa');
- const { rerender } = renderHook(() =>
- useMetaThemeColor('var(--color-mobileViewTheme)'),
- );
+ const { rerender } = renderThemeColor('var(--color-mobileViewTheme)');
expect(document.body.style.backgroundColor).toBe('rgb(170, 170, 170)');
setCssVar('--color-mobileViewTheme', '#bbb');
@@ -125,6 +135,29 @@ describe('useMetaThemeColor', () => {
expect(document.body.style.backgroundColor).toBe('rgb(187, 187, 187)');
});
+ it('refreshes meta colour and body background when customCssOverride changes while mounted', () => {
+ setCssVar('--color-mobileViewTheme', '#111');
+ const { result } = renderThemeColor('var(--color-mobileViewTheme)');
+ expect(getThemeColorMeta()).toBe('#111');
+ expect(document.body.style.backgroundColor).toBe('rgb(17, 17, 17)');
+
+ act(() => {
+ // Supply the updated CSS; the preference subscription must trigger
+ // the colour refresh without remounting or changing the hook argument.
+ setCssVar('--color-mobileViewTheme', '#222');
+ result.current.dispatch(
+ mergeGlobalPrefs({
+ customCssOverride: ':root { --color-mobileViewTheme: #222; }',
+ }),
+ );
+ });
+
+ expect({
+ meta: getThemeColorMeta(),
+ background: document.body.style.backgroundColor,
+ }).toEqual({ meta: '#222', background: 'rgb(34, 34, 34)' });
+ });
+
it('re-runs effect when system color scheme changes', async () => {
let matches = false;
const listeners = new Set<() => void>();
@@ -151,7 +184,7 @@ describe('useMetaThemeColor', () => {
});
setCssVar('--color-mobileViewTheme', '#111');
- renderHook(() => useMetaThemeColor('var(--color-mobileViewTheme)'));
+ renderThemeColor('var(--color-mobileViewTheme)');
expect(document.body.style.backgroundColor).toBe('rgb(17, 17, 17)');
expect(listeners.size).toBe(1);
diff --git a/packages/desktop-client/src/hooks/useMetaThemeColor.ts b/packages/desktop-client/src/hooks/useMetaThemeColor.ts
index b189227553..ad6184031e 100644
--- a/packages/desktop-client/src/hooks/useMetaThemeColor.ts
+++ b/packages/desktop-client/src/hooks/useMetaThemeColor.ts
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
+import { useGlobalPref } from '#hooks/useGlobalPref';
import { usePreferredDarkTheme, useTheme } from '#style/theme';
const VAR_STRING_REGEX = /^var\((--.*)\)$/;
@@ -8,12 +9,17 @@ const DEFAULT_THEME_COLOR = '#5c3dbb';
/**
* Sets the theme-color meta tag (for browsers that use it) and document.body
* background-color (for Safari 26+, which derives status bar tint from body).
- * Re-runs when theme or system color scheme changes so the status bar follows
- * the app theme.
+ * Re-runs when built-in/custom themes, CSS overrides, or the system color
+ * scheme change so the status bar follows the app theme.
*/
export function useMetaThemeColor(color?: string) {
const [activeTheme] = useTheme();
const [darkThemePreference] = usePreferredDarkTheme();
+ const [installedCustomLightTheme] = useGlobalPref(
+ 'installedCustomLightTheme',
+ );
+ const [installedCustomDarkTheme] = useGlobalPref('installedCustomDarkTheme');
+ const [customCssOverride] = useGlobalPref('customCssOverride');
const systemColorScheme = useSystemColorScheme();
useEffect(() => {
@@ -25,7 +31,15 @@ export function useMetaThemeColor(color?: string) {
ensureThemeColorMetaTag();
setThemeColorMetaContent(resolved);
document.body.style.backgroundColor = resolved;
- }, [color, activeTheme, darkThemePreference, systemColorScheme]);
+ }, [
+ color,
+ activeTheme,
+ darkThemePreference,
+ installedCustomLightTheme,
+ installedCustomDarkTheme,
+ customCssOverride,
+ systemColorScheme,
+ ]);
}
function useSystemColorScheme() {
diff --git a/packages/desktop-client/src/style/customThemes.ts b/packages/desktop-client/src/style/customThemes.ts
index 9d1dccfc2f..1ed7b3625d 100644
--- a/packages/desktop-client/src/style/customThemes.ts
+++ b/packages/desktop-client/src/style/customThemes.ts
@@ -5,6 +5,10 @@
export const BASE_THEME_OPTIONS = ['light', 'dark', 'midnight'] as const;
export type BaseTheme = (typeof BASE_THEME_OPTIONS)[number];
+export function isBaseTheme(value: string): value is BaseTheme {
+ return (BASE_THEME_OPTIONS as readonly string[]).includes(value);
+}
+
export type CatalogTheme = {
name: string;
repo: string;
@@ -674,11 +678,9 @@ export function parseInstalledTheme(
};
if (
typeof parsed.baseTheme === 'string' &&
- BASE_THEME_OPTIONS.includes(
- parsed.baseTheme as (typeof BASE_THEME_OPTIONS)[number],
- )
+ isBaseTheme(parsed.baseTheme)
) {
- result.baseTheme = parsed.baseTheme as BaseTheme;
+ result.baseTheme = parsed.baseTheme;
}
return result;
}
diff --git a/packages/desktop-client/src/style/theme.tsx b/packages/desktop-client/src/style/theme.tsx
index 9fdb9fba8e..31578516ed 100644
--- a/packages/desktop-client/src/style/theme.tsx
+++ b/packages/desktop-client/src/style/theme.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo } from 'react';
import darkThemeCss from '@actual-app/components/themes/dark.css?inline';
import lightThemeCss from '@actual-app/components/themes/light.css?inline';
@@ -9,21 +9,19 @@ import type { DarkTheme, Theme } from '@actual-app/core/types/prefs';
import { useGlobalPref } from '#hooks/useGlobalPref';
import {
+ isBaseTheme,
migrateLegacyOverride,
parseInstalledTheme,
validateThemeCss,
} from './customThemes';
-import type { BaseTheme } from './customThemes';
const themes = {
light: { name: 'Light', colors: lightThemeCss },
dark: { name: 'Dark', colors: darkThemeCss },
midnight: { name: 'Midnight', colors: midnightThemeCss },
- auto: { name: 'System default', colors: darkThemeCss },
+ auto: { name: 'System default' },
} as const;
-type ThemeKey = keyof typeof themes;
-
export const themeOptions = Object.entries(themes).map(
([key, { name }]) => [key, name] as [Theme, string],
);
@@ -88,8 +86,11 @@ function useMigrateLegacyOverride() {
]);
}
-function getBaseThemeColors(baseTheme: BaseTheme) {
- return themes[baseTheme]?.colors;
+function getBaseThemeColors(baseTheme: string | undefined) {
+ // Theme prefs are untrusted strings; unknown values resolve to undefined.
+ return baseTheme !== undefined && isBaseTheme(baseTheme)
+ ? themes[baseTheme].colors
+ : undefined;
}
export function ThemeStyle() {
@@ -101,74 +102,38 @@ export function ThemeStyle() {
const [installedCustomDarkThemeJson] = useGlobalPref(
'installedCustomDarkTheme',
);
- const [themeColors, setThemeColors] = useState<string | undefined>(undefined);
-
- useEffect(() => {
- if (activeTheme === 'auto') {
- const installedLight = parseInstalledTheme(installedCustomLightThemeJson);
- const installedDark = parseInstalledTheme(installedCustomDarkThemeJson);
-
- const lightColors =
- (installedLight?.baseTheme &&
- getBaseThemeColors(installedLight.baseTheme)) ||
- themes['light'].colors;
- const darkColors =
- (installedDark?.baseTheme &&
- getBaseThemeColors(installedDark.baseTheme)) ||
- themes[darkThemePreference].colors;
-
- function darkThemeMediaQueryListener(event: MediaQueryListEvent) {
- if (event.matches) {
- setThemeColors(darkColors);
- } else {
- setThemeColors(lightColors);
- }
- }
- const darkThemeMediaQuery = window.matchMedia(
- '(prefers-color-scheme: dark)',
- );
- darkThemeMediaQuery.addEventListener(
- 'change',
- darkThemeMediaQueryListener,
- );
+ // Rendered rather than injected from an effect so the CSS variables exist
+ // in the same commit as any consumer effect that reads them.
+ const themeColors =
+ getBaseThemeColors(
+ parseInstalledTheme(installedCustomLightThemeJson)?.baseTheme,
+ ) ?? getBaseThemeColors(activeTheme === 'auto' ? 'light' : activeTheme);
- if (darkThemeMediaQuery.matches) {
- setThemeColors(darkColors);
- } else {
- setThemeColors(lightColors);
- }
+ if (!themeColors) return null;
- return () => {
- darkThemeMediaQuery.removeEventListener(
- 'change',
- darkThemeMediaQueryListener,
- );
- };
- } else {
- const installedTheme = parseInstalledTheme(installedCustomLightThemeJson);
- if (installedTheme?.baseTheme) {
- setThemeColors(
- getBaseThemeColors(installedTheme.baseTheme) ??
- themes[activeTheme as ThemeKey]?.colors,
- );
- } else {
- setThemeColors(themes[activeTheme as ThemeKey]?.colors);
- }
- }
- }, [
- activeTheme,
- darkThemePreference,
- installedCustomLightThemeJson,
- installedCustomDarkThemeJson,
- ]);
+ if (activeTheme !== 'auto') {
+ return (
+ <>
+ <style>{paletteCss}</style>
+ <style>{themeColors}</style>
+ </>
+ );
+ }
- if (!themeColors) return null;
+ // Let the browser pick the sheet so system theme changes need no re-render.
+ const darkColors =
+ getBaseThemeColors(
+ parseInstalledTheme(installedCustomDarkThemeJson)?.baseTheme,
+ ) ??
+ getBaseThemeColors(darkThemePreference) ??
+ themes.dark.colors;
return (
<>
<style>{paletteCss}</style>
- <style>{themeColors}</style>
+ <style media="(prefers-color-scheme: light)">{themeColors}</style>
+ <style media="(prefers-color-scheme: dark)">{darkColors}</style>
</>
);
}
diff --git a/upcoming-release-notes/fix-theme-color-ordering.md b/upcoming-release-notes/fix-theme-color-ordering.md
new file mode 100644
index 0000000000..733524afe7
--- /dev/null
+++ b/upcoming-release-notes/fix-theme-color-ordering.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [tim-smart]
+---
+
+Fix the browser theme colour staying at its fallback on startup or lagging behind theme changes.